fix: close TOCTOU race + missing checks in tier limits, add AI rate limits, patch CVEs (v0.60.0)

Security audit fixes (see SECURITY_AUDIT.md):
- lib/tiers.ts: checkAndIncrementTierLimit's recipe/storage branches did a
  live count/sum check with no lock tying it to the later write, so two
  concurrent requests near the cap could both pass and both write past the
  limit. Added checkTierLimitInTransaction — holds a per-user Postgres
  advisory lock for the duration of the caller's transaction, so the check
  and the write are atomic together. Applied to every recipe/storage write
  path (recipes create/update, fork, rate, avatar, and 7 AI recipe-creation
  routes).
- Adversarial re-verification of that fix caught a bigger gap in the same
  area: four AI routes (photo import, idea generation, batch-cook,
  translate-to-new-draft) had no recipe-limit check at all. Fixed.
- Added missing per-user rate limits to 5 AI endpoints (adapt, drinks,
  pairings, translate, variations) that had none, unlike their siblings.
- search page now checks for a session server-side, matching every other
  page under (app)/ — defense in depth; the underlying API was already
  public by design and proxy.ts already blocked unauthenticated requests.
- admin/settings route now uses the shared requireAdmin instead of a local
  duplicate.
- Documented two admin support-ticket endpoints missing from the OpenAPI
  spec; verified full route/OpenAPI parity otherwise.
- Bumped drizzle-orm to fix a SQL-identifier-escaping CVE, and overrode two
  transitive deps (esbuild, postcss) with known CVEs. pnpm audit is clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-20 22:21:51 +02:00
parent 623e5bcd34
commit 7626f1b496
31 changed files with 561 additions and 509 deletions
+16 -1
View File
@@ -1,5 +1,5 @@
// Mirrors CHANGELOG.md at the repo root — update both together.
export const APP_VERSION = "0.59.0";
export const APP_VERSION = "0.60.0";
export type ChangelogEntry = {
version: string;
@@ -11,6 +11,21 @@ export type ChangelogEntry = {
};
export const CHANGELOG: ChangelogEntry[] = [
{
version: "0.60.0",
date: "2026-07-20 22:15",
security: [
"Closed a race in recipe/storage tier-limit checks — two concurrent requests near the cap could both pass a live count check and both write, exceeding the lifetime limit. Now locked per-user inside the same transaction as the write.",
"Fixed four AI recipe-creation routes (photo import, idea generation, batch-cook, translate-to-new-draft) that had no recipe-limit check at all, letting any tier create unlimited recipes through them.",
"Added missing per-user rate limits to 5 AI endpoints (adapt, drinks, pairings, translate, variations).",
"Search page now checks for a session server-side, matching every other page (defense-in-depth — the underlying API was already public by design and the edge proxy already blocked unauthenticated access).",
"Upgraded drizzle-orm to fix a SQL-identifier-escaping vulnerability, and overrode two transitive dependencies (esbuild, postcss) with known CVEs — pnpm audit is now clean.",
],
fixed: [
"Admin settings endpoint now uses the shared admin-auth check instead of a local duplicate.",
"Documented two admin support-ticket endpoints that were missing from the OpenAPI spec.",
],
},
{
version: "0.59.0",
date: "2026-07-20 21:15",
+16 -1
View File
@@ -630,6 +630,18 @@ export function generateOpenApiSpec(): object {
registry.registerPath({ method: "post", path: "/api/v1/support", summary: "Submit a bug report, suggestion, or question", description: "Best-effort opens a matching issue on the configured Gitea repo (see giteaIssueUrl/giteaError) — this never blocks ticket creation. Sends a confirmation email. Attach files by presigning each one first via POST /api/v1/support/attachments/presign, uploading to the returned URL, then passing the keys here.", security, request: { body: { content: { "application/json": { schema: CreateSupportTicketRef } }, required: true } }, responses: { 201: { description: "Created", content: { "application/json": { schema: SupportTicketRef } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/support/attachments/presign", summary: "Get a presigned upload URL for a support ticket attachment", description: "Rate-limited: 20 req/hour. Accepts images, PDF, plain text, JSON, or zip, up to 10MB. Upload the file as multipart form data to the returned url+fields, then include the returned key when submitting the ticket.", security, request: { body: { content: { "application/json": { schema: PresignSupportAttachmentRef } }, required: true } }, responses: { 200: { description: "Presigned upload", content: { "application/json": { schema: PresignedPostRef } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited", content: { "application/json": { schema: ApiErrorRef } } } } });
const AdminSupportTicketRef = registry.register("AdminSupportTicket", z.object({
id: z.string(), userId: z.string(), userEmail: z.string(), username: z.string().nullable(),
type: SupportTicketTypeEnum, title: z.string(), description: z.string(),
status: SupportTicketStatusEnum, giteaIssueUrl: z.string().nullable(), giteaError: z.string().nullable(),
createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
attachments: z.array(z.object({ id: z.string(), contentType: z.string(), storageKey: z.string(), url: z.string() })),
}));
const UpdateAdminSupportTicketRef = registry.register("UpdateAdminSupportTicket", z.object({
status: SupportTicketStatusEnum.optional(),
retryGitea: z.boolean().optional().describe("Re-attempts opening a Gitea issue for this ticket (e.g. after a prior giteaError)."),
}));
// --- Conversations: 1:1 direct messages ---
const ConversationSummaryRef = registry.register("ConversationSummary", z.object({
id: z.string(),
@@ -827,9 +839,12 @@ export function generateOpenApiSpec(): object {
registry.registerPath({ method: "delete", path: "/api/v1/admin/invites/{id}", summary: "Revoke an invite", description: "Admin only.", security: adminSecurity, request: { params: idParam }, responses: { 200: { description: "Revoked", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Invite not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/admin/reports", summary: "List pending reports (up to 100, newest first)", description: "Admin only.", security: adminSecurity, responses: { 200: { description: "Reports", content: { "application/json": { schema: z.object({ reports: z.array(AdminReportRef) }) } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/admin/support", summary: "List all support tickets, newest first", description: "Admin only.", security: adminSecurity, responses: { 200: { description: "Tickets", content: { "application/json": { schema: z.array(AdminSupportTicketRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "patch", path: "/api/v1/admin/support/{id}", summary: "Update a support ticket's status, or retry opening its Gitea issue", description: "Admin only.", security: adminSecurity, request: { params: idParam, body: { content: { "application/json": { schema: UpdateAdminSupportTicketRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "patch", path: "/api/v1/admin/reports/{id}", summary: "Resolve a report (mark reviewed or dismissed)", description: "Admin only.", security: adminSecurity, request: { params: idParam, body: { content: { "application/json": { schema: ResolveReportBodyRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: z.object({ report: ResolvedReportRef }) } } }, 400: { description: "Invalid status", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "put", path: "/api/v1/admin/settings", summary: "Update site settings (AI provider keys, VAPID keys, signups toggle)", description: "Admin only. Secret-flagged keys are encrypted at rest and never echoed back by any endpoint; this route only accepts new values, it does not return current ones.", security: adminSecurity, request: { body: { content: { "application/json": { schema: UpdateSiteSettingsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "put", path: "/api/v1/admin/settings", summary: "Update site settings (AI provider keys, VAPID keys, signups toggle)", description: "Admin only. Secret-flagged keys are encrypted at rest and never echoed back by any endpoint; this route only accepts new values, it does not return current ones.", security: adminSecurity, request: { body: { content: { "application/json": { schema: UpdateSiteSettingsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/admin/test-email", summary: "Send a test verification-style email to a given address", description: "Admin only.", security: adminSecurity, request: { body: { content: { "application/json": { schema: TestEmailBodyRef } }, required: true } }, responses: { 200: { description: "Sent", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Missing 'to'", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 500: { description: "BETTER_AUTH_URL not configured, or send failed", content: { "application/json": { schema: ApiErrorRef } } } } });
+69 -28
View File
@@ -19,9 +19,14 @@ export class TierLimitError extends Error {
}
}
/** Either the top-level db client or a transaction handle — both expose the
* same query-builder surface, so live-derivation helpers and the limit check
* can run against whichever one the caller is holding a lock in. */
type DbOrTx = typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];
/** Live count of a user's recipes — lifetime total, not a monthly counter. */
export async function getRecipeCount(userId: string): Promise<number> {
const [row] = await db
export async function getRecipeCount(userId: string, dbOrTx: DbOrTx = db): Promise<number> {
const [row] = await dbOrTx
.select({ n: sql<number>`count(*)::int` })
.from(recipes)
.where(eq(recipes.authorId, userId));
@@ -29,22 +34,42 @@ export async function getRecipeCount(userId: string): Promise<number> {
}
/** Live sum of a user's storage usage (recipe photos + review photos + avatar) — lifetime total, not a monthly counter. */
export async function getStorageUsedMb(userId: string): Promise<number> {
export async function getStorageUsedMb(userId: string, dbOrTx: DbOrTx = db): Promise<number> {
const [[photoRow], [reviewRow], [userRow]] = await Promise.all([
db
dbOrTx
.select({ total: sql<number>`coalesce(sum(${recipePhotos.sizeMb}), 0)::int` })
.from(recipePhotos)
.innerJoin(recipes, eq(recipePhotos.recipeId, recipes.id))
.where(eq(recipes.authorId, userId)),
db
dbOrTx
.select({ total: sql<number>`coalesce(sum(${ratings.photoSizeMb}), 0)::int` })
.from(ratings)
.where(eq(ratings.userId, userId)),
db.select({ avatarSizeMb: users.avatarSizeMb }).from(users).where(eq(users.id, userId)),
dbOrTx.select({ avatarSizeMb: users.avatarSizeMb }).from(users).where(eq(users.id, userId)),
]);
return (photoRow?.total ?? 0) + (reviewRow?.total ?? 0) + (userRow?.avatarSizeMb ?? 0);
}
async function checkLiveLimit(
dbOrTx: DbOrTx,
userId: string,
fallbackTier: "free" | "pro" | "family",
key: "recipe" | "storage",
amount: number
): Promise<void> {
const [dbUser] = await dbOrTx.select({ tier: users.tier }).from(users).where(eq(users.id, userId));
const userTier = (dbUser?.tier as "free" | "pro" | "family" | undefined) ?? fallbackTier;
const [tierDef] = await dbOrTx.select().from(tierDefinitions).where(eq(tierDefinitions.tier, userTier));
if (!tierDef) throw new TierLimitError(key, userTier);
const limit = key === "recipe" ? tierDef.maxRecipes : tierDef.storageMb;
if (limit === UNLIMITED) return;
const current = key === "recipe" ? await getRecipeCount(userId, dbOrTx) : await getStorageUsedMb(userId, dbOrTx);
if (current + amount > limit) throw new TierLimitError(key, userTier);
}
/**
* Checks the tier limit for the given key, throwing TierLimitError if it's
* already been reached (or would be exceeded by `amount`).
@@ -59,6 +84,11 @@ export async function getStorageUsedMb(userId: string): Promise<number> {
* "recipe" and "storage" are lifetime totals derived live from real data
* (recipes/photos/avatar rows), so they're pure checks with no counter to
* increment — deleting a recipe/photo/avatar is itself the "decrement".
*
* This plain (unlocked) check is a fast pre-flight only — two concurrent
* calls can both read the pre-write count and both pass. Anywhere the actual
* write happens in the same request, use checkTierLimitInTransaction instead
* so the check and the write are atomic together.
*/
export async function checkAndIncrementTierLimit(
userId: string,
@@ -66,17 +96,13 @@ export async function checkAndIncrementTierLimit(
key: "recipe" | "aiCall" | "storage",
amount = 1
): Promise<void> {
const [dbUser] = await db.select({ tier: users.tier }).from(users).where(eq(users.id, userId));
const userTier = (dbUser?.tier as "free" | "pro" | "family" | undefined) ?? fallbackTier;
const [tierDef] = await db
.select()
.from(tierDefinitions)
.where(eq(tierDefinitions.tier, userTier));
if (!tierDef) throw new TierLimitError(key, userTier);
if (key === "aiCall") {
const [dbUser] = await db.select({ tier: users.tier }).from(users).where(eq(users.id, userId));
const userTier = (dbUser?.tier as "free" | "pro" | "family" | undefined) ?? fallbackTier;
const [tierDef] = await db.select().from(tierDefinitions).where(eq(tierDefinitions.tier, userTier));
if (!tierDef) throw new TierLimitError(key, userTier);
const month = currentMonth();
const id = `${userId}-${month}`;
const limit = tierDef.aiCallsPerMonth;
@@ -92,19 +118,34 @@ export async function checkAndIncrementTierLimit(
if (result.length === 0) {
throw new TierLimitError("aiCall", userTier);
}
} else if (key === "recipe") {
const limit = tierDef.maxRecipes;
if (limit !== UNLIMITED) {
const current = await getRecipeCount(userId);
if (current + amount > limit) throw new TierLimitError("recipe", userTier);
}
} else {
const limit = tierDef.storageMb;
if (limit !== UNLIMITED) {
const current = await getStorageUsedMb(userId);
if (current + amount > limit) throw new TierLimitError("storage", userTier);
}
return;
}
await checkLiveLimit(db, userId, fallbackTier, key, amount);
}
/**
* Same check as checkAndIncrementTierLimit's "recipe"/"storage" branches, but
* takes a transaction and holds a per-user Postgres advisory lock for its
* duration — so a concurrent call for the same user blocks until this one
* commits (or rolls back), instead of racing to read the same pre-write
* count. The lock auto-releases at transaction end (pg_advisory_xact_lock),
* so there's no separate unlock step and no risk of a leaked lock.
*
* Call this as the first statement inside the same db.transaction that
* performs the write the check is gating — checking and inserting in
* different transactions (or different requests, like a presign-time check
* for a row written later) leaves the same TOCTOU gap this closes.
*/
export async function checkTierLimitInTransaction(
tx: DbOrTx,
userId: string,
fallbackTier: "free" | "pro" | "family",
key: "recipe" | "storage",
amount = 1
): Promise<void> {
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${userId}))`);
await checkLiveLimit(tx, userId, fallbackTier, key, amount);
}
/**