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
+5
View File
@@ -1,8 +1,13 @@
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { SearchPageContent } from "@/components/search/search-page-content";
type Params = { searchParams: Promise<{ q?: string; difficulty?: string; dietary?: string }> };
export default async function SearchPage({ searchParams }: Params) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const { q } = await searchParams;
return <SearchPageContent initialQuery={q ?? ""} />;
}
@@ -1,39 +1,28 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
import { NextRequest, NextResponse } from "next/server";
const mockAdminSession = { user: { id: "admin-1", role: "admin" } };
vi.mock("next/headers", () => ({
headers: vi.fn().mockResolvedValue(new Headers()),
}));
vi.mock("@/lib/auth/server", () => ({
auth: { api: { getSession: vi.fn() } },
vi.mock("@/lib/api-auth", () => ({
requireAdmin: vi.fn(),
}));
vi.mock("@/lib/site-settings", () => ({
setSiteSetting: vi.fn().mockResolvedValue(undefined),
}));
const { mockSelectChain, mockInsertValues } = vi.hoisted(() => {
const mockSelectChain = {
from: vi.fn().mockReturnThis(),
where: vi.fn().mockResolvedValue([{ role: "admin" }]),
};
return { mockSelectChain, mockInsertValues: vi.fn().mockResolvedValue(undefined) };
});
const { mockInsertValues } = vi.hoisted(() => ({
mockInsertValues: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@epicure/db", () => ({
db: {
select: vi.fn(() => mockSelectChain),
insert: vi.fn(() => ({ values: mockInsertValues })),
},
users: { id: "id", role: "role" },
auditLogs: {},
eq: vi.fn((a, b) => ({ a, b, op: "eq" })),
}));
const { auth } = await import("@/lib/auth/server");
const { requireAdmin } = await import("@/lib/api-auth");
const { setSiteSetting } = await import("@/lib/site-settings");
import { PUT } from "../route";
@@ -47,21 +36,26 @@ function makeRequest(body: unknown) {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(auth.api.getSession).mockResolvedValue(mockAdminSession as never);
mockSelectChain.where.mockResolvedValue([{ role: "admin" }]);
vi.mocked(requireAdmin).mockResolvedValue({ session: mockAdminSession as never, response: null });
});
describe("PUT /api/v1/admin/settings", () => {
it("returns 403 when caller is not an admin", async () => {
mockSelectChain.where.mockResolvedValue([{ role: "user" }]);
vi.mocked(requireAdmin).mockResolvedValue({
session: null,
response: NextResponse.json({ error: "Forbidden" }, { status: 403 }),
} as never);
const res = await PUT(makeRequest({ OPENAI_API_KEY: "sk-1" }));
expect(res.status).toBe(403);
});
it("returns 403 when there is no session", async () => {
vi.mocked(auth.api.getSession).mockResolvedValue(null as never);
it("returns 401 when there is no session", async () => {
vi.mocked(requireAdmin).mockResolvedValue({
session: null,
response: NextResponse.json({ error: "Unauthorized" }, { status: 401 }),
} as never);
const res = await PUT(makeRequest({ OPENAI_API_KEY: "sk-1" }));
expect(res.status).toBe(403);
expect(res.status).toBe(401);
});
it("updates allowed keys and writes an audit log", async () => {
+6 -15
View File
@@ -1,7 +1,6 @@
import { type NextRequest, NextResponse } from "next/server";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, users, auditLogs, eq } from "@epicure/db";
import { db, auditLogs } from "@epicure/db";
import { requireAdmin } from "@/lib/api-auth";
import { setSiteSetting, type SiteSettingKey } from "@/lib/site-settings";
import { randomUUID } from "crypto";
@@ -28,31 +27,23 @@ const ALLOWED_KEYS: SiteSettingKey[] = [
"GITEA_REPO",
];
async function requireAdmin() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const [dbUser] = await db.select({ role: users.role }).from(users).where(eq(users.id, session.user.id));
if (dbUser?.role !== "admin") return null;
return session;
}
export async function PUT(req: NextRequest) {
const session = await requireAdmin();
if (!session) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const { session, response } = await requireAdmin();
if (response) return response;
const body = (await req.json()) as Record<string, string | null>;
const changed: string[] = [];
for (const [key, value] of Object.entries(body)) {
if (!ALLOWED_KEYS.includes(key as SiteSettingKey)) continue;
await setSiteSetting(key as SiteSettingKey, value, session.user.id);
await setSiteSetting(key as SiteSettingKey, value, session!.user.id);
changed.push(key);
}
if (changed.length > 0) {
await db.insert(auditLogs).values({
id: randomUUID(),
userId: session.user.id,
userId: session!.user.id,
action: "admin.settings.update",
targetType: "site_settings",
metadata: JSON.stringify({ keys: changed }),
+11 -12
View File
@@ -3,11 +3,12 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes, recipeIngredients, recipeSteps, recipeVariations } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { adaptRecipe } from "@/lib/ai/features/adapt-recipe";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
import { isRecipeUnchanged } from "@/lib/recipe-diff";
const Schema = z.object({
@@ -23,8 +24,11 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const { id } = await params;
const userId = session!.user.id;
const limited = await applyRateLimit(`rl:ai:${userId}`, 10, 60);
if (limited) return limited;
const { id } = await params;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id)),
@@ -81,20 +85,12 @@ export async function POST(req: NextRequest, { params }: Params) {
return NextResponse.json({ id: recipe.id, adaptationNotes: adapted.adaptationNotes, unchanged: true });
}
try {
await checkAndIncrementTierLimit(userId, session!.user.tier as "free" | "pro" | "family", "recipe");
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
throw err;
}
const newId = crypto.randomUUID();
const now = new Date();
try {
await db.transaction(async (tx) => {
await checkTierLimitInTransaction(tx, userId, session!.user.tier as "free" | "pro" | "family", "recipe");
await tx.insert(recipes).values({
id: newId,
authorId: userId,
@@ -147,7 +143,10 @@ export async function POST(req: NextRequest, { params }: Params) {
createdAt: now,
});
});
} catch {
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
return NextResponse.json({ error: "Failed to save the adapted recipe. Please try again." }, { status: 500 });
}
@@ -8,6 +8,7 @@ import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { generateBatchCook } from "@/lib/ai/features/generate-batch-cook";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
import { parseQuantity } from "@/lib/parse-quantity";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const Schema = z.object({
dinners: z.number().int().min(0).max(6).default(4),
@@ -62,7 +63,9 @@ export async function POST(req: NextRequest) {
const recipeId = crypto.randomUUID();
await db.transaction(async (tx) => {
try {
await db.transaction(async (tx) => {
await checkTierLimitInTransaction(tx, userId, session!.user.tier as "free" | "pro" | "family", "recipe");
await tx.insert(recipes).values({
id: recipeId,
authorId: userId,
@@ -117,7 +120,13 @@ export async function POST(req: NextRequest) {
}))
);
}
});
});
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
throw err;
}
return NextResponse.json({ id: recipeId });
}
@@ -3,6 +3,7 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestDrinks } from "@/lib/ai/features/suggest-drinks";
import { withUserKey } from "@/lib/ai/resolve-user-key";
@@ -21,6 +22,9 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
if (limited) return limited;
try {
await requireFeatureEnabled(session!.user.id, "drink_pairing");
} catch (err) {
@@ -8,6 +8,7 @@ import { getUserPrivateBio } from "@/lib/ai/user-bio";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
import { parseQuantity } from "@/lib/parse-quantity";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const Schema = z.object({
title: z.string().min(1).max(200),
@@ -51,47 +52,58 @@ export async function POST(req: NextRequest) {
const recipeId = crypto.randomUUID();
await db.insert(recipes).values({
id: recipeId,
authorId: session!.user.id,
title: recipe.title,
description: recipe.description ?? null,
baseServings: recipe.baseServings,
recipeType: recipe.recipeType,
prepMins: recipe.prepMins ?? null,
cookMins: recipe.cookMins ?? null,
difficulty: recipe.difficulty ?? null,
visibility: "private",
aiGenerated: true,
language: locale,
dietaryTags: recipe.dietaryTags ?? {},
tags: [],
});
try {
await db.transaction(async (tx) => {
await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
if (recipe.ingredients?.length) {
await db.insert(recipeIngredients).values(
recipe.ingredients.map((ing, i) => ({
id: crypto.randomUUID(),
recipeId,
rawName: ing.rawName,
quantity: parseQuantity(ing.quantity) ?? null,
unit: ing.unit ?? null,
note: ing.note ?? null,
order: i,
}))
);
}
await tx.insert(recipes).values({
id: recipeId,
authorId: session!.user.id,
title: recipe.title,
description: recipe.description ?? null,
baseServings: recipe.baseServings,
recipeType: recipe.recipeType,
prepMins: recipe.prepMins ?? null,
cookMins: recipe.cookMins ?? null,
difficulty: recipe.difficulty ?? null,
visibility: "private",
aiGenerated: true,
language: locale,
dietaryTags: recipe.dietaryTags ?? {},
tags: [],
});
if (recipe.steps?.length) {
await db.insert(recipeSteps).values(
recipe.steps.map((step, i) => ({
id: crypto.randomUUID(),
recipeId,
instruction: step.instruction,
timerSeconds: step.timerSeconds ?? null,
order: i,
}))
);
if (recipe.ingredients?.length) {
await tx.insert(recipeIngredients).values(
recipe.ingredients.map((ing, i) => ({
id: crypto.randomUUID(),
recipeId,
rawName: ing.rawName,
quantity: parseQuantity(ing.quantity) ?? null,
unit: ing.unit ?? null,
note: ing.note ?? null,
order: i,
}))
);
}
if (recipe.steps?.length) {
await tx.insert(recipeSteps).values(
recipe.steps.map((step, i) => ({
id: crypto.randomUUID(),
recipeId,
instruction: step.instruction,
timerSeconds: step.timerSeconds ?? null,
order: i,
}))
);
}
});
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
throw err;
}
return NextResponse.json({ id: recipeId });
+13 -14
View File
@@ -5,7 +5,7 @@ import { requireSessionOrApiKey } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
import { generateMeal, MEAL_COURSES } from "@/lib/ai/features/generate-meal";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
import { getMessages } from "@/lib/i18n/server";
@@ -59,20 +59,13 @@ export async function POST(req: NextRequest) {
if (!result.ok) return result.response;
const meal = result.data;
// Each recipe in the meal creates a real recipe row — check the recipe
// limit covers all of them before inserting anything.
try {
await checkAndIncrementTierLimit(userId, tier, "recipe", meal.recipes.length);
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
throw err;
}
const created: Array<{ id: string; title: string; course: string }> = [];
await db.transaction(async (tx) => {
try {
await db.transaction(async (tx) => {
// Each recipe in the meal creates a real recipe row — check the recipe
// limit covers all of them before inserting anything.
await checkTierLimitInTransaction(tx, userId, tier, "recipe", meal.recipes.length);
for (const recipe of meal.recipes) {
const recipeId = crypto.randomUUID();
await tx.insert(recipes).values({
@@ -122,7 +115,13 @@ export async function POST(req: NextRequest) {
created.push({ id: recipeId, title: recipe.title, course: recipe.course });
}
});
});
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
throw err;
}
return NextResponse.json({ collectionId, recipes: created });
}
+11 -2
View File
@@ -6,6 +6,7 @@ import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { importFromPhoto } from "@/lib/ai/features/import-photo";
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const Schema = z.object({
imageBase64: z.string().max(14_000_000),
@@ -56,7 +57,9 @@ export async function POST(req: NextRequest) {
const newRecipeId = crypto.randomUUID();
const now = new Date();
await db.transaction(async (tx) => {
try {
await db.transaction(async (tx) => {
await checkTierLimitInTransaction(tx, userId, session!.user.tier as "free" | "pro" | "family", "recipe");
await tx.insert(recipes).values({
id: newRecipeId,
authorId: userId,
@@ -105,7 +108,13 @@ export async function POST(req: NextRequest) {
}))
);
}
});
});
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
throw err;
}
return NextResponse.json({ id: newRecipeId });
}
@@ -5,7 +5,7 @@ import { requireSessionOrApiKey } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
import { generateMealPlan } from "@/lib/ai/features/generate-meal-plan";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
@@ -93,17 +93,6 @@ export async function POST(req: NextRequest) {
if (!result.ok) return result.response;
const plan = result.data;
// Each plan entry creates a draft recipe — check the recipe limit covers
// all of them before inserting anything.
try {
await checkAndIncrementTierLimit(userId, session!.user.tier as "free" | "pro" | "family", "recipe", plan.entries.length);
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
throw err;
}
// Ensure meal plan row exists for the week
let mealPlan = await db.query.mealPlans.findFirst({
where: and(eq(mealPlans.userId, userId), eq(mealPlans.weekStart, parsed.data.weekStart)),
@@ -117,7 +106,11 @@ export async function POST(req: NextRequest) {
const createdEntries: Array<{ id: string; day: string; mealType: string; recipeId: string; recipeTitle: string }> = [];
await db.transaction(async (tx) => {
try {
await db.transaction(async (tx) => {
// Each plan entry creates a draft recipe — check the recipe limit covers
// all of them before inserting anything.
await checkTierLimitInTransaction(tx, userId, session!.user.tier as "free" | "pro" | "family", "recipe", plan.entries.length);
for (const entry of plan.entries) {
// Create draft recipe
const recipeId = crypto.randomUUID();
@@ -184,7 +177,13 @@ export async function POST(req: NextRequest) {
createdEntries.push({ id: entryId, day: entry.day, mealType: entry.mealType, recipeId, recipeTitle: entry.recipe.title });
}
});
});
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
throw err;
}
return NextResponse.json({ weekStart: parsed.data.weekStart, entries: createdEntries });
}
@@ -3,6 +3,7 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestPairings } from "@/lib/ai/features/suggest-pairings";
import { withUserKey } from "@/lib/ai/resolve-user-key";
@@ -21,6 +22,9 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
if (limited) return limited;
try {
await requireFeatureEnabled(session!.user.id, "meal_pairing");
} catch (err) {
+15 -2
View File
@@ -3,9 +3,11 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { translateRecipe } from "@/lib/ai/features/translate-recipe";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const Schema = z.object({
targetLanguage: z.string().min(2).max(50),
@@ -19,6 +21,9 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
if (limited) return limited;
const { id } = await params;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
@@ -61,7 +66,9 @@ export async function POST(req: NextRequest, { params }: Params) {
const newId = crypto.randomUUID();
const now = new Date();
await db.transaction(async (tx) => {
try {
await db.transaction(async (tx) => {
await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
await tx.insert(recipes).values({
id: newId,
authorId: session!.user.id,
@@ -103,7 +110,13 @@ export async function POST(req: NextRequest, { params }: Params) {
}))
);
}
});
});
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
throw err;
}
return NextResponse.json({ id: newId });
}
@@ -3,6 +3,7 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestVariations } from "@/lib/ai/features/suggest-variations";
import { withUserKey } from "@/lib/ai/resolve-user-key";
@@ -22,6 +23,9 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
if (limited) return limited;
try {
await requireFeatureEnabled(session!.user.id, "recipe_variations");
} catch (err) {
+59 -60
View File
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import { db, recipes, recipeIngredients, recipeSteps, recipeVariations } from "@epicure/db";
import { eq, and, or, inArray } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
type Params = { params: Promise<{ id: string }> };
@@ -23,8 +23,65 @@ export async function POST(req: NextRequest, { params }: Params) {
});
if (!source) return NextResponse.json({ error: "Not found" }, { status: 404 });
const newId = crypto.randomUUID();
const now = new Date();
try {
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
await db.transaction(async (tx) => {
await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
await tx.insert(recipes).values({
id: newId,
authorId: session!.user.id,
title: source.title,
description: source.description,
baseServings: source.baseServings,
visibility: "private",
difficulty: source.difficulty,
prepMins: source.prepMins,
cookMins: source.cookMins,
tags: source.tags,
dietaryTags: source.dietaryTags ?? {},
aiGenerated: false,
language: source.language,
createdAt: now,
updatedAt: now,
});
if (source.ingredients.length > 0) {
await tx.insert(recipeIngredients).values(
source.ingredients.map((ing) => ({
id: crypto.randomUUID(),
recipeId: newId,
rawName: ing.rawName,
quantity: ing.quantity,
unit: ing.unit,
note: ing.note,
order: ing.order,
}))
);
}
if (source.steps.length > 0) {
await tx.insert(recipeSteps).values(
source.steps.map((step) => ({
id: crypto.randomUUID(),
recipeId: newId,
instruction: step.instruction,
timerSeconds: step.timerSeconds,
order: step.order,
}))
);
}
await tx.insert(recipeVariations).values({
id: crypto.randomUUID(),
parentRecipeId: source.id,
childRecipeId: newId,
description: null,
aiGenerated: false,
createdAt: now,
});
});
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
@@ -32,63 +89,5 @@ export async function POST(req: NextRequest, { params }: Params) {
throw err;
}
const newId = crypto.randomUUID();
const now = new Date();
await db.transaction(async (tx) => {
await tx.insert(recipes).values({
id: newId,
authorId: session!.user.id,
title: source.title,
description: source.description,
baseServings: source.baseServings,
visibility: "private",
difficulty: source.difficulty,
prepMins: source.prepMins,
cookMins: source.cookMins,
tags: source.tags,
dietaryTags: source.dietaryTags ?? {},
aiGenerated: false,
language: source.language,
createdAt: now,
updatedAt: now,
});
if (source.ingredients.length > 0) {
await tx.insert(recipeIngredients).values(
source.ingredients.map((ing) => ({
id: crypto.randomUUID(),
recipeId: newId,
rawName: ing.rawName,
quantity: ing.quantity,
unit: ing.unit,
note: ing.note,
order: ing.order,
}))
);
}
if (source.steps.length > 0) {
await tx.insert(recipeSteps).values(
source.steps.map((step) => ({
id: crypto.randomUUID(),
recipeId: newId,
instruction: step.instruction,
timerSeconds: step.timerSeconds,
order: step.order,
}))
);
}
await tx.insert(recipeVariations).values({
id: crypto.randomUUID(),
parentRecipeId: source.id,
childRecipeId: newId,
description: null,
aiGenerated: false,
createdAt: now,
});
});
return NextResponse.json({ id: newId }, { status: 201 });
}
+39 -17
View File
@@ -4,6 +4,7 @@ import { db, recipes, ratings, eq, and } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { createNotification } from "@/lib/notifications";
import { isOwnedReviewPhotoKey } from "@/lib/storage";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const Schema = z.object({
score: z.number().int().min(1).max(5),
@@ -39,28 +40,49 @@ export async function POST(req: NextRequest, { params }: Params) {
where: and(eq(ratings.recipeId, id), eq(ratings.userId, session!.user.id)),
});
if (existing) {
await db.update(ratings)
.set({
const newPhotoSizeMb = parsed.data.photoKey ? parsed.data.photoSizeMb : 0;
const photoSizeDeltaMb = newPhotoSizeMb - (existing?.photoSizeMb ?? 0);
try {
if (existing) {
await db.transaction(async (tx) => {
if (photoSizeDeltaMb > 0) {
await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "storage", photoSizeDeltaMb);
}
await tx.update(ratings)
.set({
score: parsed.data.score,
reviewText: parsed.data.reviewText,
photoKey: parsed.data.photoKey,
photoSizeMb: newPhotoSizeMb,
updatedAt: new Date(),
})
.where(eq(ratings.id, existing.id));
});
return NextResponse.json({ updated: true });
}
await db.transaction(async (tx) => {
if (photoSizeDeltaMb > 0) {
await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "storage", photoSizeDeltaMb);
}
await tx.insert(ratings).values({
id: crypto.randomUUID(),
recipeId: id,
userId: session!.user.id,
score: parsed.data.score,
reviewText: parsed.data.reviewText,
photoKey: parsed.data.photoKey,
photoSizeMb: parsed.data.photoKey ? parsed.data.photoSizeMb : 0,
updatedAt: new Date(),
})
.where(eq(ratings.id, existing.id));
return NextResponse.json({ updated: true });
photoSizeMb: newPhotoSizeMb,
});
});
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Storage limit reached for your tier" }, { status: 403 });
}
throw err;
}
await db.insert(ratings).values({
id: crypto.randomUUID(),
recipeId: id,
userId: session!.user.id,
score: parsed.data.score,
reviewText: parsed.data.reviewText,
photoKey: parsed.data.photoKey,
photoSizeMb: parsed.data.photoKey ? parsed.data.photoSizeMb : 0,
});
void createNotification({ userId: recipe.authorId, type: "rating", actorId: session!.user.id, recipeId: id, score: parsed.data.score });
return NextResponse.json({ created: true }, { status: 201 });
}
+17 -2
View File
@@ -3,6 +3,7 @@ import { db, recipes, recipeIngredients, recipeSteps, recipePhotos, recipeBatchD
import { eq, and, max, isNotNull } from "@epicure/db";
import { z } from "zod";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
import { deleteObject, isOwnedRecipePhotoKey } from "@/lib/storage";
import { dispatchWebhook } from "@/lib/webhooks";
import { parseQuantity } from "@/lib/parse-quantity";
@@ -124,7 +125,15 @@ export async function PUT(req: NextRequest, { params }: Params) {
return NextResponse.json({ error: "Validation error", issues: [{ path: ["photos"], message: "Photo key not issued for this recipe" }] }, { status: 400 });
}
await db.transaction(async (tx) => {
const photosSizeDeltaMb = data.photos !== undefined
? data.photos.reduce((sum, p) => sum + p.sizeMb, 0) - existing.photos.reduce((sum, p) => sum + p.sizeMb, 0)
: 0;
try {
await db.transaction(async (tx) => {
if (photosSizeDeltaMb > 0) {
await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "storage", photosSizeDeltaMb);
}
// Create a snapshot of the current state before updating
const [maxVersionRow] = await tx
.select({ v: max(recipeSnapshots.version) })
@@ -248,7 +257,13 @@ export async function PUT(req: NextRequest, { params }: Params) {
);
}
}
});
});
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Storage limit reached for your tier" }, { status: 403 });
}
throw err;
}
if (data.photos !== undefined) {
const newKeys = new Set(data.photos.map((p) => p.key));
@@ -12,8 +12,7 @@ vi.mock("@/lib/api-auth", () => ({
}));
vi.mock("@/lib/tiers", () => ({
checkAndIncrementTierLimit: vi.fn(),
incrementUsage: vi.fn(),
checkTierLimitInTransaction: vi.fn(),
TierLimitError: class TierLimitError extends Error {},
}));
@@ -134,9 +133,8 @@ describe("POST /api/v1/recipes", () => {
});
it("returns 403 when tier limit reached", async () => {
const { checkAndIncrementTierLimit } = await import("@/lib/tiers");
const { TierLimitError } = await import("@/lib/tiers");
vi.mocked(checkAndIncrementTierLimit).mockRejectedValue(new TierLimitError("recipe", "free"));
const { checkTierLimitInTransaction, TierLimitError } = await import("@/lib/tiers");
vi.mocked(checkTierLimitInTransaction).mockRejectedValue(new TierLimitError("recipe", "free"));
const res = await POST(makeRequest("POST", validRecipe));
expect(res.status).toBe(403);
+15 -11
View File
@@ -4,7 +4,7 @@ import { eq, desc, and } from "@epicure/db";
import { z } from "zod";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { isOwnedRecipePhotoKey } from "@/lib/storage";
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
import { dispatchWebhook } from "@/lib/webhooks";
import { parseQuantity } from "@/lib/parse-quantity";
import { extractIngredientQuantity } from "@/lib/extract-ingredient-quantity";
@@ -119,16 +119,14 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: "Validation error", issues: [{ path: ["photos"], message: "Photo key not issued for this recipe" }] }, { status: 400 });
}
try {
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
throw err;
}
const photosSizeMb = data.photos.reduce((sum, p) => sum + p.sizeMb, 0);
await db.transaction(async (tx) => {
try {
await db.transaction(async (tx) => {
await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
if (photosSizeMb > 0) {
await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "storage", photosSizeMb);
}
await tx.insert(recipes).values({
id,
authorId: session!.user.id,
@@ -209,7 +207,13 @@ export async function POST(req: NextRequest) {
}))
);
}
});
});
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: `${err.limit === "storage" ? "Storage" : "Recipe"} limit reached for your tier` }, { status: 403 });
}
throw err;
}
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
void dispatchWebhook(session!.user.id, "recipe.created", { id, title: data.title });
+23 -1
View File
@@ -6,6 +6,7 @@ import { z } from "zod";
import { gravatarUrl } from "@/lib/gravatar";
import { USERNAME_PATTERN, isUsernameTaken } from "@/lib/username";
import { isOwnedAvatarKey, getPublicUrl } from "@/lib/storage";
import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const PatchSchema = z.object({
name: z.string().min(1).max(100).optional(),
@@ -52,6 +53,7 @@ export async function PATCH(req: Request) {
}
}
let avatarSizeDeltaMb = 0;
if (avatarKey !== undefined) {
if (avatarKey === null) {
const gravatarOptedIn = useGravatar ?? (await getUseGravatar(session.user.id));
@@ -62,13 +64,28 @@ export async function PATCH(req: Request) {
if (!isOwnedAvatarKey(avatarKey, session.user.id)) {
return NextResponse.json({ error: "Invalid avatar key" }, { status: 400 });
}
const currentAvatarSizeMb = await getAvatarSizeMb(session.user.id);
avatarSizeDeltaMb = avatarSizeMb - currentAvatarSizeMb;
updates.avatarUrl = getPublicUrl(avatarKey);
updates.hasCustomAvatar = true;
updates.avatarSizeMb = avatarSizeMb;
}
}
await db.update(users).set(updates).where(eq(users.id, session.user.id));
try {
await db.transaction(async (tx) => {
if (avatarSizeDeltaMb > 0) {
await checkTierLimitInTransaction(tx, session.user.id, session.user.tier as "free" | "pro" | "family", "storage", avatarSizeDeltaMb);
}
await tx.update(users).set(updates).where(eq(users.id, session.user.id));
});
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Storage limit reached for your tier" }, { status: 403 });
}
throw err;
}
return NextResponse.json({ ok: true, avatarUrl: updates.avatarUrl });
}
@@ -81,3 +98,8 @@ async function getUseGravatar(userId: string): Promise<boolean> {
const row = await db.query.users.findFirst({ where: eq(users.id, userId), columns: { useGravatar: true } });
return row?.useGravatar ?? false;
}
async function getAvatarSizeMb(userId: string): Promise<number> {
const row = await db.query.users.findFirst({ where: eq(users.id, userId), columns: { avatarSizeMb: true } });
return row?.avatarSizeMb ?? 0;
}