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:
+69
-28
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user