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:
@@ -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 () => {
|
||||
|
||||
@@ -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 }),
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@epicure/web",
|
||||
"version": "0.57.2",
|
||||
"version": "0.60.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
@@ -31,7 +31,7 @@
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"diff": "^9.0.0",
|
||||
"drizzle-orm": "^0.44.7",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"ioredis": "^5.11.1",
|
||||
"lucide-react": "^1.21.0",
|
||||
"next": "16.2.9",
|
||||
|
||||
Reference in New Issue
Block a user