Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/blog-platform/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@veriworkly/blog-platform",
"version": "3.10.0",
"version": "3.10.2",
"private": true,
"scripts": {
"dev": "next dev",
Expand Down
2 changes: 1 addition & 1 deletion apps/docs-platform/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@veriworkly/docs-platform",
"version": "3.10.0",
"version": "3.10.2",
"private": true,
"scripts": {
"dev": "next dev",
Expand Down
2 changes: 1 addition & 1 deletion apps/server/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@veriworkly/server",
"version": "3.10.0",
"version": "3.10.2",
"description": "VeriWorkly Resume Backend API",
"main": "dist/index.js",
"type": "module",
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/controllers/apiKeyController.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Request, Response, NextFunction } from "express";
import type { NextFunction, Request, Response } from "express";

import { requireAuthUser } from "#middleware/auth";

Expand Down
55 changes: 38 additions & 17 deletions apps/server/src/controllers/shareController.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { NextFunction, Request, Response } from "express";

import { z } from "zod";
import { NextFunction, Request, Response } from "express";

import { PublicShareLink } from "#types/api";

Expand Down Expand Up @@ -91,14 +92,17 @@ export class ShareController {
body,
);

await cacheDelByPrefix(`share:list:${user.id}:${documentId}:`);
await cacheDelByPrefix(`share:shared-document-ids:${user.id}:`);

if (previousSlug)
await cacheDel(`share:public-readable:${shareLink.username}:${previousSlug}`);

await cacheDel(`share:public-readable:${shareLink.username}:${shareLink.documentSlug}`);
await cacheDel(`share:public-readable:${shareLink.username}:${shareLink.slug}`);
await Promise.all([
cacheDelByPrefix(`share:list:${user.id}:${documentId}:`),
cacheDelByPrefix(`share:shared-document-ids:${user.id}:`),
cacheDel(`profile:${user.id}`),
cacheDel(`user:profile:v2:${user.id}`),
...(previousSlug
? [cacheDel(`share:public-readable:${shareLink.username}:${previousSlug}`)]
: []),
cacheDel(`share:public-readable:${shareLink.username}:${shareLink.documentSlug}`),
cacheDel(`share:public-readable:${shareLink.username}:${shareLink.slug}`),
]);

res
.status(201)
Expand Down Expand Up @@ -164,9 +168,8 @@ export class ShareController {

const cached = await cacheGet<unknown>(cacheKey);

if (cached) {
if (cached)
return res.json(createSuccessResponse(cached, "Shared document ids fetched from cache"));
}

const documentIds = await ShareService.listSharedDocumentIds(user.id, ids);
const response = { documentIds };
Expand Down Expand Up @@ -197,9 +200,13 @@ export class ShareController {
const revoked = await ShareService.revokeShareLink(user.id, documentId, shareLinkId);

// Invalidate caches
await cacheDelByPrefix(`share:list:${user.id}:${documentId}:`);
await cacheDelByPrefix(`share:shared-document-ids:${user.id}:`);
await cacheDel(`share:public-readable:${revoked.username}:${revoked.slug}`);
await Promise.all([
cacheDelByPrefix(`share:list:${user.id}:${documentId}:`),
cacheDelByPrefix(`share:shared-document-ids:${user.id}:`),
cacheDel(`profile:${user.id}`),
cacheDel(`user:profile:v2:${user.id}`),
cacheDel(`share:public-readable:${revoked.username}:${revoked.slug}`),
]);

res.json(createSuccessResponse(null, "Share link revoked successfully"));
} catch (error) {
Expand All @@ -225,16 +232,29 @@ export class ShareController {

if (!shareLink) {
shareLink = await ShareService.getPublicShareLinkByUsernameAndSlug(username, slug);
await cacheSet(cacheKey, shareLink, 3600);
let ttl = 3600;

if (shareLink.expiresAt) {
const msLeft = new Date(shareLink.expiresAt).getTime() - Date.now();

if (msLeft > 0) {
ttl = Math.min(3600, Math.ceil(msLeft / 1000));
} else {
ttl = 0;
}
}

if (ttl > 0) await cacheSet(cacheKey, shareLink, ttl);
}

if (!shareLink) throw new ApiError(404, "Link not found");

if (shareLink.passwordHash) {
if (ShareService.isExpired(shareLink.expiresAt)) throw new ApiError(410, "Link expired");

if (shareLink.passwordHash)
return res.json(
createSuccessResponse(buildPublicSharePayload(shareLink, false), "Password required"),
);
}

ShareService.recordShareView(shareLink.id, req.ip, req.headers["user-agent"]).catch((err) =>
console.error("View tracking failed:", err),
Expand All @@ -248,6 +268,7 @@ export class ShareController {
);
} catch (error) {
if (error instanceof z.ZodError) return next(handleValidationError(error));

next(error);
}
}
Expand Down
21 changes: 13 additions & 8 deletions apps/server/src/jobs/usageMetricsJob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { config } from "#config";
import { logger } from "#utils/logger";
import { getRedis } from "#utils/redis";

import { flushUsageMetricsForDate } from "#services/analyticsService";
import { flushUsageMetricsForDate, getPendingUsageMetricDates } from "#services/analyticsService";

let job: ScheduledTask | null = null;

Expand All @@ -13,9 +13,9 @@ let job: ScheduledTask | null = null;
* This ensures we only flush complete day cycles.
*/

function getYesterdayUtcDate() {
function getTodayUtcDate() {
const now = new Date();
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - 1));
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
}

/**
Expand Down Expand Up @@ -45,16 +45,21 @@ async function runFlush(reason: "startup" | "cron") {
return;
}

const targetDate = getYesterdayUtcDate();
const result = await flushUsageMetricsForDate(targetDate);
const todayKey = getTodayUtcDate().toISOString().slice(0, 10);
const dateKeys = (await getPendingUsageMetricDates()).filter((dateKey) => dateKey < todayKey);

if (dateKeys.length === 0) {
logger.info(`Usage metrics flush (${reason}) skipped: no completed days pending`);
return;
}

for (const dateKey of dateKeys) {
const result = await flushUsageMetricsForDate(new Date(`${dateKey}T00:00:00.000Z`));

if (result.flushedEvents > 0) {
logger.info(`Usage metrics flush (${reason}) completed`, {
dateKey: result.dateKey,
flushedEvents: result.flushedEvents,
});
} else {
logger.info(`Usage metrics flush (${reason}) skipped: no data for ${result.dateKey}`);
}
} catch (error) {
logger.error(`Usage metrics flush (${reason}) failed`, {
Expand Down
23 changes: 15 additions & 8 deletions apps/server/src/middleware/apiKeyRateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ import { createErrorResponse } from "#utils/errors";
const WINDOW_MS = 15 * 60 * 1000;
const MAX_REQUESTS = 20;

const INCREMENT_WITH_EXPIRY_SCRIPT = `
local count = redis.call("INCR", KEYS[1])
if count == 1 then
redis.call("PEXPIRE", KEYS[1], ARGV[1])
end
return count
`;

/**
* Rate limiter middleware for API keys.
* Expects apiKey object to be present on req (from apiKeyAuth middleware).
Expand All @@ -27,15 +35,14 @@ export const apiKeyRateLimit = async (req: Request, res: Response, next: NextFun
try {
const redis = getRedis();

if (!redis.isOpen) {
throw new Error("Redis not connected");
}

const count = await redis.incr(redisKey);
if (!redis.isOpen) throw new Error("Redis not connected");

if (count === 1) {
await redis.pExpire(redisKey, WINDOW_MS);
}
const count = Number(
await redis.eval(INCREMENT_WITH_EXPIRY_SCRIPT, {
keys: [redisKey],
arguments: [String(WINDOW_MS)],
}),
);

const limit = apiKey.rateLimit || MAX_REQUESTS;

Expand Down
6 changes: 5 additions & 1 deletion apps/server/src/middleware/cors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ export const corsMiddleware = cors({
return;
}

if (config.allowedOrigins.includes(origin)) {
const trustedPortfolioOrigin =
/^https:\/\/[a-z0-9-]+\.veriworkly\.com$/i.test(origin) ||
/^http:\/\/[a-z0-9-]+\.localhost:3004$/i.test(origin);

if (config.allowedOrigins.includes(origin) || trustedPortfolioOrigin) {
callback(null, true);
} else {
callback(new ApiError(403, "Not allowed by CORS"));
Expand Down
35 changes: 26 additions & 9 deletions apps/server/src/middleware/rateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ function pruneExpiredEntries() {
const cleanupInterval = setInterval(pruneExpiredEntries, 10 * 60 * 1000);
cleanupInterval.unref();

const INCREMENT_WITH_EXPIRY_SCRIPT = `
local count = redis.call("INCR", KEYS[1])
if count == 1 then
redis.call("PEXPIRE", KEYS[1], ARGV[1])
end
return count
`;

export const rateLimitMiddleware = (req: Request, res: Response, next: NextFunction) => {
if (config.nodeEnv === "development") {
return next();
Expand All @@ -79,13 +87,12 @@ export const rateLimitMiddleware = (req: Request, res: Response, next: NextFunct

if (!redis.isOpen) throw new Error("Redis not open");

const count = await redis.incr(redisKey);

if (count === 1) {
await redis.pExpire(redisKey, windowMs);
}

return count;
return Number(
await redis.eval(INCREMENT_WITH_EXPIRY_SCRIPT, {
keys: [redisKey],
arguments: [String(windowMs)],
}),
);
} catch {
const current = bucket.get(redisKey);

Expand All @@ -99,6 +106,7 @@ export const rateLimitMiddleware = (req: Request, res: Response, next: NextFunct
}

bucket.set(redisKey, { count: 1, resetAt: now + windowMs });

return 1;
}

Expand All @@ -108,15 +116,24 @@ export const rateLimitMiddleware = (req: Request, res: Response, next: NextFunct
};

checkWithFallback()
.then((count) => {
.then(async (count) => {
if (count <= maxRequests) {
next();
return;
}

logger.warn(`Rate limit exceeded for IP: ${key}`);

const retryAfter = Math.ceil((windowMs - (now % windowMs)) / 1000);
let retryAfter = Math.ceil(windowMs / 1000);

try {
const ttl = await getRedis().pTTL(redisKey);
if (ttl > 0) retryAfter = Math.ceil(ttl / 1000);
} catch {
const resetAt = bucket.get(redisKey)?.resetAt;
if (resetAt) retryAfter = Math.max(1, Math.ceil((resetAt - now) / 1000));
}

res.set("Retry-After", String(retryAfter));
res.status(429).json(createErrorResponse(429, "Too many requests. Please try again later."));
})
Expand Down
Loading
Loading