fix: audit fixes — tier-quota bypass, webhook SSRF, auth hardening, pagination, a11y
Full audit (bugs/UI-UX/backend/feature-gap) turned up a money-leak AI quota bypass, webhook SSRF, and a long tail of missing pagination/auth/a11y work. Fixes land together since HANDOFF.md tracked them as one backlog. - AI routes charge tier quota before generating; nutrition POST is author-only - Webhook dispatch re-validates URL per delivery (SSRF/DNS-rebinding), treats redirects as failures; recipe.published now actually dispatches - New indexes/unique constraints on recipes, meal-planning, comments FK cascade - Recipe PUT/restore snapshot only inside the transaction, after validation - Recipe DELETE cleans up S3 objects (recipe + review photos) - Optimistic UI (favorite/star/follow/shopping-list) rolls back on failure - Upload presign enforces file size cap + per-tier storage quota - Route-level loading/error/not-found states across (app), admin, and root - middleware.ts guards (app)/admin; requireAdmin checks DB role, not cached session; rate limiting applied to both session and API-key branches, bucketed per key; Stripe webhook dedupes by event id - Pagination added to recipes, feed, profile, comments, pantry, admin tables - Nav shows real avatar + profile link + dark-mode toggle; destructive actions standardized on AlertDialog - Unsaved-changes guard + real ingredient/step validation on recipe form; canonical /recipes/[id] used in-app; next/image migration; aria-labels and alt text across icon buttons, avatars, recipe photos - packages/api-types removed (zero callers, too drifted to safely rewire); openapi.ts and ai-keys error shape drift fixed; BYOK decrypt failures now surface instead of silently falling back to the platform key Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -32,7 +32,7 @@ export async function POST(req: Request) {
|
||||
if (limited) return limited;
|
||||
|
||||
const body = PostSchema.safeParse(await req.json());
|
||||
if (!body.success) return NextResponse.json({ error: body.error.flatten() }, { status: 400 });
|
||||
if (!body.success) return NextResponse.json({ error: "Validation error", issues: body.error.issues }, { status: 400 });
|
||||
|
||||
const { provider, apiKey } = body.data;
|
||||
const userId = session!.user.id;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { and, eq } from "@epicure/db";
|
||||
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
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";
|
||||
@@ -43,10 +43,12 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
return NextResponse.json({ error: "Provide at least one constraint" }, { status: 400 });
|
||||
}
|
||||
|
||||
const [aiConfig, privateBio] = await Promise.all([
|
||||
withUserKey(userId, { provider: parsed.data.provider, model: parsed.data.model }),
|
||||
const [configResult, privateBio] = await Promise.all([
|
||||
resolveAiConfigOrError(() => withUserKey(userId, { provider: parsed.data.provider, model: parsed.data.model })),
|
||||
getUserPrivateBio(userId),
|
||||
]);
|
||||
if (!configResult.ok) return configResult.response;
|
||||
const aiConfig = configResult.data;
|
||||
|
||||
const result = await withAiQuota(userId, session!.user.tier as "free" | "pro", () =>
|
||||
adaptRecipe(
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { and, eq } from "@epicure/db";
|
||||
import { db, recipes } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||
import { suggestDrinks } from "@/lib/ai/features/suggest-drinks";
|
||||
import { withUserKey } from "@/lib/ai/resolve-user-key";
|
||||
import { getUserPrivateBio } from "@/lib/ai/user-bio";
|
||||
@@ -34,10 +34,14 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
const parsed = Schema.safeParse(body ?? {});
|
||||
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
||||
|
||||
const [aiConfig, privateBio] = await Promise.all([
|
||||
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model }),
|
||||
const [configResult, privateBio] = await Promise.all([
|
||||
resolveAiConfigOrError(() =>
|
||||
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model })
|
||||
),
|
||||
getUserPrivateBio(session!.user.id),
|
||||
]);
|
||||
if (!configResult.ok) return configResult.response;
|
||||
const aiConfig = configResult.data;
|
||||
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
suggestDrinks(
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||
import { importFromPhoto } from "@/lib/ai/features/import-photo";
|
||||
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
|
||||
|
||||
@@ -28,7 +28,9 @@ export async function POST(req: NextRequest) {
|
||||
const userId = session!.user.id;
|
||||
const locale = (session!.user as { locale?: string }).locale ?? "en";
|
||||
|
||||
const aiConfig = await getModelConfigForUseCase(userId, "vision");
|
||||
const configResult = await resolveAiConfigOrError(() => getModelConfigForUseCase(userId, "vision"));
|
||||
if (!configResult.ok) return configResult.response;
|
||||
const aiConfig = configResult.data;
|
||||
|
||||
// Fall back to vision-capable defaults if no explicit model configured
|
||||
if (!aiConfig.model) {
|
||||
|
||||
@@ -4,7 +4,8 @@ import { db, recipes, recipeIngredients, recipeSteps, mealPlans, mealPlanEntries
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
|
||||
import { aiErrorResponse } from "@/lib/ai/ai-error";
|
||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||
import { checkAndIncrementTierLimit, incrementUsage, TierLimitError } from "@/lib/tiers";
|
||||
import { generateMealPlan } from "@/lib/ai/features/generate-meal-plan";
|
||||
import { getUserPrivateBio } from "@/lib/ai/user-bio";
|
||||
|
||||
@@ -35,10 +36,12 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
const userId = session!.user.id;
|
||||
const locale = (session!.user as { locale?: string }).locale ?? "en";
|
||||
const [config, privateBio] = await Promise.all([
|
||||
getDefaultProviderWithKey(userId),
|
||||
const [configResult, privateBio] = await Promise.all([
|
||||
resolveAiConfigOrError(() => getDefaultProviderWithKey(userId)),
|
||||
getUserPrivateBio(userId),
|
||||
]);
|
||||
if (!configResult.ok) return configResult.response;
|
||||
const config = configResult.data;
|
||||
|
||||
// pantryMode forces usePantry on so pantry items are always fetched when maximizing pantry use
|
||||
const effectiveUsePantry = parsed.data.usePantry || parsed.data.pantryMode;
|
||||
@@ -53,9 +56,8 @@ export async function POST(req: NextRequest) {
|
||||
pantryItemNames = pantry.map((p) => p.rawName);
|
||||
}
|
||||
|
||||
let plan;
|
||||
try {
|
||||
plan = await generateMealPlan(
|
||||
const result = await withAiQuota(userId, session!.user.tier as "free" | "pro", () =>
|
||||
generateMealPlan(
|
||||
{
|
||||
dietaryPrefs: parsed.data.dietaryPrefs,
|
||||
servings: parsed.data.servings,
|
||||
@@ -66,9 +68,26 @@ export async function POST(req: NextRequest) {
|
||||
},
|
||||
{ ...config, userContext: privateBio ?? undefined },
|
||||
locale
|
||||
);
|
||||
)
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
const plan = result.data;
|
||||
|
||||
// Each plan entry creates a draft recipe — charge the recipe limit for all
|
||||
// of them before inserting anything, refunding on breach so a rejected plan
|
||||
// doesn't consume quota.
|
||||
let chargedRecipes = 0;
|
||||
try {
|
||||
for (let i = 0; i < plan.entries.length; i++) {
|
||||
await checkAndIncrementTierLimit(userId, session!.user.tier as "free" | "pro", "recipe");
|
||||
chargedRecipes++;
|
||||
}
|
||||
} catch (err) {
|
||||
return aiErrorResponse(err);
|
||||
if (err instanceof TierLimitError) {
|
||||
if (chargedRecipes > 0) await incrementUsage(userId, "recipe", -chargedRecipes);
|
||||
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Ensure meal plan row exists for the week
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { and, eq } from "@epicure/db";
|
||||
import { db, recipes } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||
import { suggestPairings } from "@/lib/ai/features/suggest-pairings";
|
||||
import { withUserKey } from "@/lib/ai/resolve-user-key";
|
||||
import { getUserPrivateBio } from "@/lib/ai/user-bio";
|
||||
@@ -35,10 +35,14 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
const parsed = Schema.safeParse(body ?? {});
|
||||
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
||||
|
||||
const [aiConfig, privateBio] = await Promise.all([
|
||||
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model }),
|
||||
const [configResult, privateBio] = await Promise.all([
|
||||
resolveAiConfigOrError(() =>
|
||||
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model })
|
||||
),
|
||||
getUserPrivateBio(session!.user.id),
|
||||
]);
|
||||
if (!configResult.ok) return configResult.response;
|
||||
const aiConfig = configResult.data;
|
||||
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
suggestPairings(
|
||||
|
||||
@@ -3,6 +3,7 @@ import { z } from "zod";
|
||||
import { generateText } from "ai";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
|
||||
import { resolveModel } from "@/lib/ai/factory";
|
||||
import { db, recipes, eq, and } from "@epicure/db";
|
||||
@@ -62,22 +63,26 @@ STEPS:
|
||||
${stepList || "None listed"}
|
||||
`.trim();
|
||||
|
||||
const [config, privateBio] = await Promise.all([
|
||||
getModelConfigForUseCase(session!.user.id, "text"),
|
||||
const [configResult, privateBio] = await Promise.all([
|
||||
resolveAiConfigOrError(() => getModelConfigForUseCase(session!.user.id, "text")),
|
||||
getUserPrivateBio(session!.user.id),
|
||||
]);
|
||||
const model = resolveModel(config);
|
||||
if (!configResult.ok) return configResult.response;
|
||||
const model = resolveModel(configResult.data);
|
||||
const bioContext = buildUserBioContext(privateBio);
|
||||
const locale = (session!.user as { locale?: string }).locale ?? "en";
|
||||
const lang = LANG[locale] ?? "English";
|
||||
|
||||
const { text } = await generateText({
|
||||
model,
|
||||
system: `You are a helpful culinary assistant. Answer questions about the following recipe concisely and accurately. If a question is not related to the recipe or cooking, politely redirect. Keep answers under 200 words. Respond in ${lang}.
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
generateText({
|
||||
model,
|
||||
system: `You are a helpful culinary assistant. Answer questions about the following recipe concisely and accurately. If a question is not related to the recipe or cooking, politely redirect. Keep answers under 200 words. Respond in ${lang}.
|
||||
|
||||
${recipeContext}${bioContext}`,
|
||||
prompt: parsed.data.question,
|
||||
});
|
||||
prompt: parsed.data.question,
|
||||
})
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
|
||||
return NextResponse.json({ answer: text });
|
||||
return NextResponse.json({ answer: result.data.text });
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { z } from "zod";
|
||||
import { generateObject } from "ai";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
|
||||
import { resolveModel } from "@/lib/ai/factory";
|
||||
import { getUserPrivateBio, buildUserBioContext } from "@/lib/ai/user-bio";
|
||||
@@ -36,11 +37,12 @@ export async function POST(req: NextRequest) {
|
||||
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
const [config, privateBio] = await Promise.all([
|
||||
getModelConfigForUseCase(session!.user.id, "text"),
|
||||
const [configResult, privateBio] = await Promise.all([
|
||||
resolveAiConfigOrError(() => getModelConfigForUseCase(session!.user.id, "text")),
|
||||
getUserPrivateBio(session!.user.id),
|
||||
]);
|
||||
const model = resolveModel(config);
|
||||
if (!configResult.ok) return configResult.response;
|
||||
const model = resolveModel(configResult.data);
|
||||
const bioContext = buildUserBioContext(privateBio);
|
||||
|
||||
const userContext = bioContext
|
||||
@@ -54,12 +56,15 @@ export async function POST(req: NextRequest) {
|
||||
? `${userContext}Generate 6 diverse recipe ideas based on: "${parsed.data.prompt}". Include a mix of difficulty levels.`
|
||||
: `${userContext}Generate 6 diverse, creative recipe ideas. Include different cuisines, difficulty levels, and meal types.`;
|
||||
|
||||
const { object } = await generateObject({
|
||||
model,
|
||||
schema: IdeasSchema,
|
||||
system: `Respond in ${lang}.`,
|
||||
prompt,
|
||||
});
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
generateObject({
|
||||
model,
|
||||
schema: IdeasSchema,
|
||||
system: `Respond in ${lang}.`,
|
||||
prompt,
|
||||
})
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
|
||||
return NextResponse.json(object.ideas);
|
||||
return NextResponse.json(result.data.object.ideas);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { db, recipes, eq, and, or } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||
import { scaleRecipe } from "@/lib/ai/features/scale-recipe";
|
||||
|
||||
const Schema = z.object({
|
||||
@@ -40,7 +40,9 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const aiConfig = await getDefaultProviderWithKey(session!.user.id);
|
||||
const configResult = await resolveAiConfigOrError(() => getDefaultProviderWithKey(session!.user.id));
|
||||
if (!configResult.ok) return configResult.response;
|
||||
const aiConfig = configResult.data;
|
||||
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
scaleRecipe(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
|
||||
import { substituteIngredient } from "@/lib/ai/features/substitute-ingredient";
|
||||
@@ -28,9 +28,14 @@ export async function POST(req: NextRequest) {
|
||||
? `recipe "${parsed.data.recipeTitle}"`
|
||||
: "a general recipe";
|
||||
|
||||
const aiConfig = parsed.data.provider
|
||||
? { provider: parsed.data.provider, model: parsed.data.model }
|
||||
: await getDefaultProviderWithKey(session!.user.id);
|
||||
let aiConfig;
|
||||
if (parsed.data.provider) {
|
||||
aiConfig = { provider: parsed.data.provider, model: parsed.data.model };
|
||||
} else {
|
||||
const configResult = await resolveAiConfigOrError(() => getDefaultProviderWithKey(session!.user.id));
|
||||
if (!configResult.ok) return configResult.response;
|
||||
aiConfig = configResult.data;
|
||||
}
|
||||
|
||||
const locale = (session!.user as { locale?: string }).locale ?? "en";
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { and, eq } from "@epicure/db";
|
||||
import { db, recipes } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||
import { suggestVariations } from "@/lib/ai/features/suggest-variations";
|
||||
import { withUserKey } from "@/lib/ai/resolve-user-key";
|
||||
import { getUserPrivateBio } from "@/lib/ai/user-bio";
|
||||
@@ -38,10 +38,14 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
const [aiConfig, privateBio] = await Promise.all([
|
||||
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model }),
|
||||
const [configResult, privateBio] = await Promise.all([
|
||||
resolveAiConfigOrError(() =>
|
||||
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model })
|
||||
),
|
||||
getUserPrivateBio(session!.user.id),
|
||||
]);
|
||||
if (!configResult.ok) return configResult.response;
|
||||
const aiConfig = configResult.data;
|
||||
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
suggestVariations(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, conversations, conversationReads, messages, eq, asc } from "@epicure/db";
|
||||
import { db, conversations, conversationReads, messages, eq, and, desc, lt } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { isParticipant, otherParticipantId } from "@/lib/messaging";
|
||||
@@ -13,7 +13,9 @@ interface RouteContext {
|
||||
|
||||
const Schema = z.object({ content: z.string().min(1).max(4000) });
|
||||
|
||||
export async function GET(_req: NextRequest, { params }: RouteContext) {
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
export async function GET(req: NextRequest, { params }: RouteContext) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
const { id } = await params;
|
||||
@@ -23,22 +25,42 @@ export async function GET(_req: NextRequest, { params }: RouteContext) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Cursor-based pagination: fetch the page ending just before `before`
|
||||
// (an ISO createdAt timestamp), newest-first, then reverse so the client
|
||||
// still receives oldest-first order for the page. This avoids the old
|
||||
// `asc + limit(200)` bug, which permanently hid every message past the
|
||||
// 200th once a conversation grew beyond that.
|
||||
const before = req.nextUrl.searchParams.get("before");
|
||||
const beforeDate = before ? new Date(before) : null;
|
||||
const validBefore = beforeDate && !isNaN(beforeDate.getTime()) ? beforeDate : null;
|
||||
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(messages)
|
||||
.where(eq(messages.conversationId, id))
|
||||
.orderBy(asc(messages.createdAt))
|
||||
.limit(200);
|
||||
.where(
|
||||
validBefore
|
||||
? and(eq(messages.conversationId, id), lt(messages.createdAt, validBefore))
|
||||
: eq(messages.conversationId, id)
|
||||
)
|
||||
.orderBy(desc(messages.createdAt))
|
||||
.limit(PAGE_SIZE);
|
||||
|
||||
await db
|
||||
.insert(conversationReads)
|
||||
.values({ conversationId: id, userId: session!.user.id, lastReadAt: new Date() })
|
||||
.onConflictDoUpdate({
|
||||
target: [conversationReads.conversationId, conversationReads.userId],
|
||||
set: { lastReadAt: new Date() },
|
||||
});
|
||||
const ordered = rows.slice().reverse();
|
||||
const nextCursor = rows.length === PAGE_SIZE ? rows[rows.length - 1]!.createdAt.toISOString() : null;
|
||||
|
||||
return NextResponse.json({ messages: rows });
|
||||
// Only mark the conversation read when loading the latest page, not when
|
||||
// paging through history.
|
||||
if (!validBefore) {
|
||||
await db
|
||||
.insert(conversationReads)
|
||||
.values({ conversationId: id, userId: session!.user.id, lastReadAt: new Date() })
|
||||
.onConflictDoUpdate({
|
||||
target: [conversationReads.conversationId, conversationReads.userId],
|
||||
set: { lastReadAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ messages: ordered, nextCursor });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest, { params }: RouteContext) {
|
||||
|
||||
@@ -10,6 +10,8 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
const { searchParams } = new URL(req.url);
|
||||
const limit = Math.min(parseInt(searchParams.get("limit") ?? "20"), 50);
|
||||
const offsetRaw = parseInt(searchParams.get("offset") ?? "0");
|
||||
const offset = Number.isNaN(offsetRaw) ? 0 : Math.max(0, offsetRaw);
|
||||
|
||||
// Recipes the user has favorited, or rated 4+, define their taste profile.
|
||||
const [favoritedRows, highRatedRows] = await Promise.all([
|
||||
@@ -60,10 +62,12 @@ export async function GET(req: NextRequest) {
|
||||
? rankForYou(candidates, preferences)
|
||||
: [...candidates].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
|
||||
|
||||
const data = ranked.slice(0, limit).map(({ tags: _tags, dietaryTags: _dietaryTags, ...r }) => ({
|
||||
const data = ranked.slice(offset, offset + limit).map(({ tags: _tags, dietaryTags: _dietaryTags, ...r }) => ({
|
||||
...r,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
}));
|
||||
|
||||
return NextResponse.json({ data });
|
||||
// `ranked` is capped to a bounded recent window (see `candidates` query above), so this
|
||||
// total reflects the size of that ranked window rather than every eligible recipe.
|
||||
return NextResponse.json({ data, total: ranked.length, limit, offset });
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db, recipes, users, userFollows, eq, and, ne } from "@epicure/db";
|
||||
import { db, recipes, users, userFollows, eq, and, ne, sql } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { desc, inArray } from "@epicure/db";
|
||||
|
||||
@@ -20,32 +20,43 @@ export async function GET(req: NextRequest) {
|
||||
const followedIds = followedRows.map((r) => r.followingId);
|
||||
|
||||
if (followedIds.length === 0) {
|
||||
return NextResponse.json({ data: [], limit, offset, message: "Follow some users to see their recipes here." });
|
||||
return NextResponse.json({ data: [], total: 0, limit, offset, message: "Follow some users to see their recipes here." });
|
||||
}
|
||||
|
||||
const feedRecipes = await db
|
||||
.select({
|
||||
id: recipes.id,
|
||||
title: recipes.title,
|
||||
description: recipes.description,
|
||||
baseServings: recipes.baseServings,
|
||||
prepMins: recipes.prepMins,
|
||||
cookMins: recipes.cookMins,
|
||||
difficulty: recipes.difficulty,
|
||||
visibility: recipes.visibility,
|
||||
createdAt: recipes.createdAt,
|
||||
updatedAt: recipes.updatedAt,
|
||||
authorId: recipes.authorId,
|
||||
authorName: users.name,
|
||||
authorUsername: users.username,
|
||||
authorAvatarUrl: users.avatarUrl,
|
||||
})
|
||||
.from(recipes)
|
||||
.innerJoin(users, eq(recipes.authorId, users.id))
|
||||
.where((t) => and(inArray(t.authorId, followedIds), ne(recipes.visibility, "private")))
|
||||
.orderBy(desc(recipes.createdAt))
|
||||
.limit(limit)
|
||||
.offset(offset);
|
||||
const where = and(inArray(recipes.authorId, followedIds), ne(recipes.visibility, "private"));
|
||||
|
||||
return NextResponse.json({ data: feedRecipes, limit, offset });
|
||||
const [feedRecipes, totalRow] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: recipes.id,
|
||||
title: recipes.title,
|
||||
description: recipes.description,
|
||||
baseServings: recipes.baseServings,
|
||||
prepMins: recipes.prepMins,
|
||||
cookMins: recipes.cookMins,
|
||||
difficulty: recipes.difficulty,
|
||||
visibility: recipes.visibility,
|
||||
createdAt: recipes.createdAt,
|
||||
updatedAt: recipes.updatedAt,
|
||||
authorId: recipes.authorId,
|
||||
authorName: users.name,
|
||||
authorUsername: users.username,
|
||||
authorAvatarUrl: users.avatarUrl,
|
||||
})
|
||||
.from(recipes)
|
||||
.innerJoin(users, eq(recipes.authorId, users.id))
|
||||
.where(where)
|
||||
.orderBy(desc(recipes.createdAt))
|
||||
.limit(limit)
|
||||
.offset(offset),
|
||||
db
|
||||
.select({ total: sql<number>`count(*)::int` })
|
||||
.from(recipes)
|
||||
.innerJoin(users, eq(recipes.authorId, users.id))
|
||||
.where(where),
|
||||
]);
|
||||
|
||||
const total = totalRow[0]?.total ?? 0;
|
||||
|
||||
return NextResponse.json({ data: feedRecipes, total, limit, offset });
|
||||
}
|
||||
|
||||
@@ -3,40 +3,55 @@ import { db, recipes, users, favorites, eq, desc, sql, and, gte } from "@epicure
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const limit = Math.min(parseInt(searchParams.get("limit") ?? "20"), 50);
|
||||
const limitRaw = parseInt(searchParams.get("limit") ?? "20");
|
||||
const limit = Math.min(Number.isNaN(limitRaw) ? 20 : Math.max(1, limitRaw), 50);
|
||||
const offsetRaw = parseInt(searchParams.get("offset") ?? "0");
|
||||
const offset = Number.isNaN(offsetRaw) ? 0 : Math.max(0, offsetRaw);
|
||||
|
||||
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
const trending = await db
|
||||
.select({
|
||||
id: recipes.id,
|
||||
title: recipes.title,
|
||||
description: recipes.description,
|
||||
baseServings: recipes.baseServings,
|
||||
prepMins: recipes.prepMins,
|
||||
cookMins: recipes.cookMins,
|
||||
difficulty: recipes.difficulty,
|
||||
visibility: recipes.visibility,
|
||||
aiGenerated: recipes.aiGenerated,
|
||||
createdAt: recipes.createdAt,
|
||||
authorId: recipes.authorId,
|
||||
authorName: users.name,
|
||||
authorUsername: users.username,
|
||||
authorAvatarUrl: users.avatarUrl,
|
||||
favoriteCount: sql<number>`cast(count(${favorites.recipeId}) as int)`,
|
||||
})
|
||||
.from(recipes)
|
||||
.innerJoin(users, eq(recipes.authorId, users.id))
|
||||
.leftJoin(
|
||||
favorites,
|
||||
and(eq(favorites.recipeId, recipes.id), gte(favorites.createdAt, sevenDaysAgo))
|
||||
)
|
||||
.where(eq(recipes.visibility, "public"))
|
||||
.groupBy(recipes.id, users.id)
|
||||
.orderBy(desc(sql`count(${favorites.recipeId})`), desc(recipes.createdAt))
|
||||
.limit(limit);
|
||||
const [trending, totalRow] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: recipes.id,
|
||||
title: recipes.title,
|
||||
description: recipes.description,
|
||||
baseServings: recipes.baseServings,
|
||||
prepMins: recipes.prepMins,
|
||||
cookMins: recipes.cookMins,
|
||||
difficulty: recipes.difficulty,
|
||||
visibility: recipes.visibility,
|
||||
aiGenerated: recipes.aiGenerated,
|
||||
createdAt: recipes.createdAt,
|
||||
authorId: recipes.authorId,
|
||||
authorName: users.name,
|
||||
authorUsername: users.username,
|
||||
authorAvatarUrl: users.avatarUrl,
|
||||
favoriteCount: sql<number>`cast(count(${favorites.recipeId}) as int)`,
|
||||
})
|
||||
.from(recipes)
|
||||
.innerJoin(users, eq(recipes.authorId, users.id))
|
||||
.leftJoin(
|
||||
favorites,
|
||||
and(eq(favorites.recipeId, recipes.id), gte(favorites.createdAt, sevenDaysAgo))
|
||||
)
|
||||
.where(eq(recipes.visibility, "public"))
|
||||
.groupBy(recipes.id, users.id)
|
||||
.orderBy(desc(sql`count(${favorites.recipeId})`), desc(recipes.createdAt))
|
||||
.limit(limit)
|
||||
.offset(offset),
|
||||
db
|
||||
.select({ total: sql<number>`count(*)::int` })
|
||||
.from(recipes)
|
||||
.where(eq(recipes.visibility, "public")),
|
||||
]);
|
||||
|
||||
const total = totalRow[0]?.total ?? 0;
|
||||
|
||||
return NextResponse.json({
|
||||
data: trending.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() })),
|
||||
total,
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, mealPlans, mealPlanEntries, eq, and } from "@epicure/db";
|
||||
import { db, mealPlans, mealPlanEntries, recipes, eq, and, or, ne } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { dispatchWebhook } from "@/lib/webhooks";
|
||||
|
||||
@@ -34,6 +34,16 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
const parsed = Schema.safeParse(body);
|
||||
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
||||
|
||||
if (parsed.data.recipeId) {
|
||||
const recipe = await db.query.recipes.findFirst({
|
||||
where: and(
|
||||
eq(recipes.id, parsed.data.recipeId),
|
||||
or(eq(recipes.authorId, session!.user.id), ne(recipes.visibility, "private"))
|
||||
),
|
||||
});
|
||||
if (!recipe) return NextResponse.json({ error: "Recipe not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const plan = await getOrCreatePlan(session!.user.id, weekStart);
|
||||
|
||||
// Remove existing entry for same day+mealType before inserting
|
||||
|
||||
@@ -103,16 +103,20 @@ export async function DELETE(req: NextRequest, { params }: Params) {
|
||||
const memberId = req.nextUrl.searchParams.get("memberId");
|
||||
if (!memberId) return NextResponse.json({ error: "memberId required" }, { status: 400 });
|
||||
|
||||
const plan = await db.query.mealPlans.findFirst({
|
||||
where: and(eq(mealPlans.userId, session!.user.id), eq(mealPlans.weekStart, weekStart)),
|
||||
});
|
||||
if (!plan) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
// Look up the member row first (not scoped to plans owned by the caller) —
|
||||
// a member removing themselves isn't the plan owner, so scoping the plan
|
||||
// lookup to `ownerId = session.user.id` would 404 before we ever reach the
|
||||
// self-leave check below.
|
||||
const member = await db.query.mealPlanMembers.findFirst({
|
||||
where: and(eq(mealPlanMembers.id, memberId), eq(mealPlanMembers.mealPlanId, plan.id)),
|
||||
where: eq(mealPlanMembers.id, memberId),
|
||||
});
|
||||
if (!member) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
const plan = await db.query.mealPlans.findFirst({
|
||||
where: and(eq(mealPlans.id, member.mealPlanId), eq(mealPlans.weekStart, weekStart)),
|
||||
});
|
||||
if (!plan) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
const isOwner = plan.userId === session!.user.id;
|
||||
const isSelf = member.userId === session!.user.id;
|
||||
if (!isOwner && !isSelf) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, pantryItems, eq, desc } from "@epicure/db";
|
||||
import { db, pantryItems, eq, desc, sql } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
|
||||
const Schema = z.object({
|
||||
@@ -10,16 +10,32 @@ const Schema = z.object({
|
||||
expiresAt: z.string().datetime().optional(),
|
||||
});
|
||||
|
||||
export async function GET(_req: NextRequest) {
|
||||
export async function GET(req: NextRequest) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const items = await db.query.pantryItems.findMany({
|
||||
where: eq(pantryItems.userId, session!.user.id),
|
||||
orderBy: desc(pantryItems.createdAt),
|
||||
});
|
||||
const { searchParams } = req.nextUrl;
|
||||
const limitRaw = parseInt(searchParams.get("limit") ?? "50");
|
||||
const limit = Math.min(Number.isNaN(limitRaw) ? 50 : Math.max(1, limitRaw), 100);
|
||||
const offsetRaw = parseInt(searchParams.get("offset") ?? "0");
|
||||
const offset = Number.isNaN(offsetRaw) ? 0 : Math.max(0, offsetRaw);
|
||||
|
||||
return NextResponse.json(items);
|
||||
const [items, totalRow] = await Promise.all([
|
||||
db.query.pantryItems.findMany({
|
||||
where: eq(pantryItems.userId, session!.user.id),
|
||||
orderBy: desc(pantryItems.createdAt),
|
||||
limit,
|
||||
offset,
|
||||
}),
|
||||
db
|
||||
.select({ total: sql<number>`count(*)::int` })
|
||||
.from(pantryItems)
|
||||
.where(eq(pantryItems.userId, session!.user.id)),
|
||||
]);
|
||||
|
||||
const total = totalRow[0]?.total ?? 0;
|
||||
|
||||
return NextResponse.json({ data: items, total, limit, offset });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, recipes, comments, users, userBlocks, eq, and, inArray } from "@epicure/db";
|
||||
import { db, recipes, comments, users, userBlocks, eq, and, inArray, isNull, sql } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { dispatchWebhook } from "@/lib/webhooks";
|
||||
@@ -16,7 +16,19 @@ const Schema = z.object({
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function GET(_req: NextRequest, { params }: Params) {
|
||||
const COMMENT_COLUMNS = {
|
||||
id: comments.id,
|
||||
content: comments.content,
|
||||
parentId: comments.parentId,
|
||||
createdAt: comments.createdAt,
|
||||
updatedAt: comments.updatedAt,
|
||||
userId: comments.userId,
|
||||
userName: users.name,
|
||||
userUsername: users.username,
|
||||
userAvatarUrl: users.avatarUrl,
|
||||
} as const;
|
||||
|
||||
export async function GET(req: NextRequest, { params }: Params) {
|
||||
const { id } = await params;
|
||||
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
|
||||
if (!recipe || recipe.visibility === "private") {
|
||||
@@ -25,32 +37,55 @@ export async function GET(_req: NextRequest, { params }: Params) {
|
||||
|
||||
const { session } = await requireSession();
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
id: comments.id,
|
||||
content: comments.content,
|
||||
parentId: comments.parentId,
|
||||
createdAt: comments.createdAt,
|
||||
updatedAt: comments.updatedAt,
|
||||
userId: comments.userId,
|
||||
userName: users.name,
|
||||
userUsername: users.username,
|
||||
userAvatarUrl: users.avatarUrl,
|
||||
})
|
||||
.from(comments)
|
||||
.innerJoin(users, eq(comments.userId, users.id))
|
||||
.where(eq(comments.recipeId, id))
|
||||
.orderBy(comments.createdAt);
|
||||
const { searchParams } = req.nextUrl;
|
||||
const limitRaw = parseInt(searchParams.get("limit") ?? "20");
|
||||
const limit = Math.min(Number.isNaN(limitRaw) ? 20 : Math.max(1, limitRaw), 50);
|
||||
const offsetRaw = parseInt(searchParams.get("offset") ?? "0");
|
||||
const offset = Number.isNaN(offsetRaw) ? 0 : Math.max(0, offsetRaw);
|
||||
|
||||
if (!session) return NextResponse.json(rows);
|
||||
// Paginate top-level comments; replies to a loaded top-level comment are always
|
||||
// fetched alongside it so threads render complete (threads are typically small).
|
||||
const [topLevel, totalRow] = await Promise.all([
|
||||
db
|
||||
.select(COMMENT_COLUMNS)
|
||||
.from(comments)
|
||||
.innerJoin(users, eq(comments.userId, users.id))
|
||||
.where(and(eq(comments.recipeId, id), isNull(comments.parentId)))
|
||||
.orderBy(comments.createdAt)
|
||||
.limit(limit)
|
||||
.offset(offset),
|
||||
db
|
||||
.select({ total: sql<number>`count(*)::int` })
|
||||
.from(comments)
|
||||
.where(and(eq(comments.recipeId, id), isNull(comments.parentId))),
|
||||
]);
|
||||
|
||||
const blocked = await db
|
||||
.select({ blockedId: userBlocks.blockedId })
|
||||
.from(userBlocks)
|
||||
.where(eq(userBlocks.blockerId, session.user.id));
|
||||
const blockedIds = new Set(blocked.map((b) => b.blockedId));
|
||||
const total = totalRow[0]?.total ?? 0;
|
||||
const topLevelIds = topLevel.map((c) => c.id);
|
||||
|
||||
return NextResponse.json(rows.filter((r) => !blockedIds.has(r.userId)));
|
||||
const replies = topLevelIds.length > 0
|
||||
? await db
|
||||
.select(COMMENT_COLUMNS)
|
||||
.from(comments)
|
||||
.innerJoin(users, eq(comments.userId, users.id))
|
||||
.where(inArray(comments.parentId, topLevelIds))
|
||||
.orderBy(comments.createdAt)
|
||||
: [];
|
||||
|
||||
const rows = [...topLevel, ...replies];
|
||||
|
||||
const data = session
|
||||
? await (async () => {
|
||||
const blocked = await db
|
||||
.select({ blockedId: userBlocks.blockedId })
|
||||
.from(userBlocks)
|
||||
.where(eq(userBlocks.blockerId, session.user.id));
|
||||
const blockedIds = new Set(blocked.map((b) => b.blockedId));
|
||||
return rows.filter((r) => !blockedIds.has(r.userId));
|
||||
})()
|
||||
: rows;
|
||||
|
||||
return NextResponse.json({ data, total, limit, offset });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest, { params }: Params) {
|
||||
|
||||
@@ -2,6 +2,8 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { db, recipes, recipeIngredients } from "@epicure/db";
|
||||
import { eq, and, or, ne } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { withAiQuota } from "@/lib/ai/ai-error";
|
||||
import { estimateNutrition } from "@/lib/ai/features/estimate-nutrition";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
@@ -31,14 +33,12 @@ export async function POST(_req: NextRequest, { params }: Params) {
|
||||
if (response) return response;
|
||||
const { id } = await params;
|
||||
|
||||
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
// Only the recipe author may trigger a (paid) nutrition estimate
|
||||
const recipe = await db.query.recipes.findFirst({
|
||||
where: and(
|
||||
eq(recipes.id, id),
|
||||
or(
|
||||
eq(recipes.authorId, session!.user.id),
|
||||
ne(recipes.visibility, "private")
|
||||
)
|
||||
),
|
||||
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
|
||||
with: {
|
||||
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
},
|
||||
@@ -46,17 +46,20 @@ export async function POST(_req: NextRequest, { params }: Params) {
|
||||
|
||||
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
const result = await estimateNutrition({
|
||||
title: recipe.title,
|
||||
baseServings: recipe.baseServings,
|
||||
ingredients: recipe.ingredients.map((i) => ({
|
||||
rawName: i.rawName,
|
||||
quantity: i.quantity,
|
||||
unit: i.unit,
|
||||
})),
|
||||
});
|
||||
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
|
||||
estimateNutrition({
|
||||
title: recipe.title,
|
||||
baseServings: recipe.baseServings,
|
||||
ingredients: recipe.ingredients.map((i) => ({
|
||||
rawName: i.rawName,
|
||||
quantity: i.quantity,
|
||||
unit: i.unit,
|
||||
})),
|
||||
})
|
||||
);
|
||||
if (!result.ok) return result.response;
|
||||
|
||||
await db.update(recipes).set({ nutritionData: result }).where(and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)));
|
||||
await db.update(recipes).set({ nutritionData: result.data }).where(and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)));
|
||||
|
||||
return NextResponse.json({ nutrition: result });
|
||||
return NextResponse.json({ nutrition: result.data });
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db, recipes, recipeIngredients, recipeSteps, recipeSnapshots } from "@epicure/db";
|
||||
import { eq, and, max } from "@epicure/db";
|
||||
import { db, recipes, recipeIngredients, recipeSteps, recipeSnapshots, ratings } from "@epicure/db";
|
||||
import { eq, and, max, isNotNull } from "@epicure/db";
|
||||
import { z } from "zod";
|
||||
import { requireSessionOrApiKey } from "@/lib/api-auth";
|
||||
import { deleteObject } from "@/lib/storage";
|
||||
import { dispatchWebhook } from "@/lib/webhooks";
|
||||
import { parseQuantity } from "@/lib/parse-quantity";
|
||||
|
||||
@@ -69,41 +70,6 @@ export async function PUT(req: NextRequest, { params }: Params) {
|
||||
});
|
||||
if (!existing) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
// Create a snapshot of the current state before updating
|
||||
const [maxVersionRow] = await db
|
||||
.select({ v: max(recipeSnapshots.version) })
|
||||
.from(recipeSnapshots)
|
||||
.where(eq(recipeSnapshots.recipeId, id));
|
||||
const nextVersion = (maxVersionRow?.v ?? 0) + 1;
|
||||
await db.insert(recipeSnapshots).values({
|
||||
id: crypto.randomUUID(),
|
||||
recipeId: id,
|
||||
authorId: session!.user.id,
|
||||
version: nextVersion,
|
||||
title: existing.title,
|
||||
snapshotData: {
|
||||
title: existing.title,
|
||||
description: existing.description,
|
||||
baseServings: existing.baseServings,
|
||||
difficulty: existing.difficulty,
|
||||
prepMins: existing.prepMins,
|
||||
cookMins: existing.cookMins,
|
||||
dietaryTags: existing.dietaryTags ?? {},
|
||||
ingredients: existing.ingredients.map((i) => ({
|
||||
rawName: i.rawName,
|
||||
quantity: i.quantity,
|
||||
unit: i.unit,
|
||||
note: i.note,
|
||||
order: i.order,
|
||||
})),
|
||||
steps: existing.steps.map((s) => ({
|
||||
instruction: s.instruction,
|
||||
timerSeconds: s.timerSeconds,
|
||||
order: s.order,
|
||||
})),
|
||||
},
|
||||
});
|
||||
|
||||
const body = await req.json() as unknown;
|
||||
const parsed = UpdateRecipeSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
@@ -113,6 +79,41 @@ export async function PUT(req: NextRequest, { params }: Params) {
|
||||
const data = parsed.data;
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
// Create a snapshot of the current state before updating
|
||||
const [maxVersionRow] = await tx
|
||||
.select({ v: max(recipeSnapshots.version) })
|
||||
.from(recipeSnapshots)
|
||||
.where(eq(recipeSnapshots.recipeId, id));
|
||||
const nextVersion = (maxVersionRow?.v ?? 0) + 1;
|
||||
await tx.insert(recipeSnapshots).values({
|
||||
id: crypto.randomUUID(),
|
||||
recipeId: id,
|
||||
authorId: session!.user.id,
|
||||
version: nextVersion,
|
||||
title: existing.title,
|
||||
snapshotData: {
|
||||
title: existing.title,
|
||||
description: existing.description,
|
||||
baseServings: existing.baseServings,
|
||||
difficulty: existing.difficulty,
|
||||
prepMins: existing.prepMins,
|
||||
cookMins: existing.cookMins,
|
||||
dietaryTags: existing.dietaryTags ?? {},
|
||||
ingredients: existing.ingredients.map((i) => ({
|
||||
rawName: i.rawName,
|
||||
quantity: i.quantity,
|
||||
unit: i.unit,
|
||||
note: i.note,
|
||||
order: i.order,
|
||||
})),
|
||||
steps: existing.steps.map((s) => ({
|
||||
instruction: s.instruction,
|
||||
timerSeconds: s.timerSeconds,
|
||||
order: s.order,
|
||||
})),
|
||||
},
|
||||
});
|
||||
|
||||
const updates: Partial<typeof recipes.$inferInsert> = { updatedAt: new Date() };
|
||||
if (data.title !== undefined) updates.title = data.title;
|
||||
if (data.description !== undefined) updates.description = data.description;
|
||||
@@ -161,6 +162,9 @@ export async function PUT(req: NextRequest, { params }: Params) {
|
||||
|
||||
const updated = await getOwnedRecipe(id, session!.user.id);
|
||||
void dispatchWebhook(session!.user.id, "recipe.updated", { id, title: updated?.title });
|
||||
if (existing.visibility === "private" && data.visibility === "public") {
|
||||
void dispatchWebhook(session!.user.id, "recipe.published", { id, title: updated?.title });
|
||||
}
|
||||
return NextResponse.json(updated);
|
||||
}
|
||||
|
||||
@@ -171,10 +175,33 @@ export async function DELETE(req: NextRequest, { params }: Params) {
|
||||
|
||||
const existing = await db.query.recipes.findFirst({
|
||||
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
|
||||
with: { photos: true },
|
||||
});
|
||||
if (!existing) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
// Collect storage keys before the cascade delete removes the rows.
|
||||
// recipeSteps.photoUrl stores a full URL rather than a storage key, so it
|
||||
// is intentionally not deleted here — only objects this app stored by key.
|
||||
const reviewPhotos = await db
|
||||
.select({ photoKey: ratings.photoKey })
|
||||
.from(ratings)
|
||||
.where(and(eq(ratings.recipeId, id), isNotNull(ratings.photoKey)));
|
||||
const storageKeys = [
|
||||
...existing.photos.map((p) => p.storageKey),
|
||||
...reviewPhotos.map((r) => r.photoKey).filter((k): k is string => k !== null),
|
||||
];
|
||||
|
||||
await db.delete(recipes).where(eq(recipes.id, id));
|
||||
|
||||
// Best-effort object cleanup: a storage failure must not fail the response.
|
||||
for (const key of storageKeys) {
|
||||
try {
|
||||
await deleteObject(key);
|
||||
} catch (err) {
|
||||
console.error(`Failed to delete storage object ${key} for recipe ${id}`, err);
|
||||
}
|
||||
}
|
||||
|
||||
void dispatchWebhook(session!.user.id, "recipe.deleted", { id });
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
@@ -55,41 +55,6 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
});
|
||||
if (!snapshot) return NextResponse.json({ error: "Snapshot not found" }, { status: 404 });
|
||||
|
||||
// Create a snapshot of the current state before restoring
|
||||
const [maxVersionRow] = await db
|
||||
.select({ v: max(recipeSnapshots.version) })
|
||||
.from(recipeSnapshots)
|
||||
.where(eq(recipeSnapshots.recipeId, id));
|
||||
const nextVersion = (maxVersionRow?.v ?? 0) + 1;
|
||||
await db.insert(recipeSnapshots).values({
|
||||
id: crypto.randomUUID(),
|
||||
recipeId: id,
|
||||
authorId: session!.user.id,
|
||||
version: nextVersion,
|
||||
title: currentRecipe.title,
|
||||
snapshotData: {
|
||||
title: currentRecipe.title,
|
||||
description: currentRecipe.description,
|
||||
baseServings: currentRecipe.baseServings,
|
||||
difficulty: currentRecipe.difficulty,
|
||||
prepMins: currentRecipe.prepMins,
|
||||
cookMins: currentRecipe.cookMins,
|
||||
dietaryTags: currentRecipe.dietaryTags ?? {},
|
||||
ingredients: currentRecipe.ingredients.map((i) => ({
|
||||
rawName: i.rawName,
|
||||
quantity: i.quantity,
|
||||
unit: i.unit,
|
||||
note: i.note,
|
||||
order: i.order,
|
||||
})),
|
||||
steps: currentRecipe.steps.map((s) => ({
|
||||
instruction: s.instruction,
|
||||
timerSeconds: s.timerSeconds,
|
||||
order: s.order,
|
||||
})),
|
||||
},
|
||||
});
|
||||
|
||||
// Restore the recipe from the snapshot
|
||||
const data = snapshot.snapshotData as {
|
||||
title: string;
|
||||
|
||||
@@ -66,11 +66,14 @@ export async function GET(req: NextRequest) {
|
||||
: [];
|
||||
|
||||
// --- Build WHERE conditions ---
|
||||
// Escape ilike wildcard chars (% and _) so user input like "100%" is matched literally.
|
||||
const escapedQ = q.replace(/[\\%_]/g, (c) => `\\${c}`);
|
||||
|
||||
const conditions = [
|
||||
eq(recipes.visibility, "public"),
|
||||
or(
|
||||
ilike(recipes.title, `%${q}%`),
|
||||
ilike(recipes.description, `%${q}%`)
|
||||
ilike(recipes.title, `%${escapedQ}%`),
|
||||
ilike(recipes.description, `%${escapedQ}%`)
|
||||
)!,
|
||||
];
|
||||
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, shoppingListItems, eq, and } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { getShoppingListAccess, canWriteShoppingList } from "@/lib/shopping-list-access";
|
||||
|
||||
type Params = { params: Promise<{ id: string; itemId: string }> };
|
||||
|
||||
const UpdateItemSchema = z.object({
|
||||
checked: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export async function PUT(req: NextRequest, { params }: Params) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
@@ -14,9 +19,13 @@ export async function PUT(req: NextRequest, { params }: Params) {
|
||||
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
if (!canWriteShoppingList(access.role)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
|
||||
const body = await req.json() as { checked?: boolean };
|
||||
const parsed = UpdateItemSchema.safeParse(await req.json());
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
await db.update(shoppingListItems)
|
||||
.set({ checked: body.checked ?? false })
|
||||
.set({ checked: parsed.data.checked ?? false })
|
||||
.where(and(eq(shoppingListItems.id, itemId), eq(shoppingListItems.listId, id)));
|
||||
|
||||
return NextResponse.json({ updated: true });
|
||||
|
||||
@@ -3,9 +3,11 @@ import { z } from "zod";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { createPresignedUploadUrl } from "@/lib/storage";
|
||||
import { db, recipes, eq, and } from "@epicure/db";
|
||||
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
|
||||
|
||||
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/avif"] as const;
|
||||
type AllowedType = (typeof ALLOWED_TYPES)[number];
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024;
|
||||
|
||||
const Schema = z.object({
|
||||
contentType: z.string().refine((t): t is AllowedType => (ALLOWED_TYPES as readonly string[]).includes(t), {
|
||||
@@ -13,6 +15,7 @@ const Schema = z.object({
|
||||
}),
|
||||
recipeId: z.string().uuid(),
|
||||
purpose: z.enum(["recipe", "review"]).default("recipe"),
|
||||
fileSize: z.number().int().positive().max(MAX_FILE_SIZE, "File exceeds 10MB limit"),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
@@ -25,7 +28,7 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
const { recipeId, contentType, purpose } = parsed.data;
|
||||
const { recipeId, contentType, purpose, fileSize } = parsed.data;
|
||||
const recipe = await db.query.recipes.findFirst({
|
||||
where: purpose === "recipe"
|
||||
? and(eq(recipes.id, recipeId), eq(recipes.authorId, session!.user.id))
|
||||
@@ -37,6 +40,16 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
try {
|
||||
const sizeMb = Math.ceil(fileSize / (1024 * 1024));
|
||||
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "storage", sizeMb);
|
||||
} catch (err) {
|
||||
if (err instanceof TierLimitError) {
|
||||
return NextResponse.json({ error: "Storage limit reached for your tier" }, { status: 403 });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const ext = contentType.split("/")[1] ?? "jpg";
|
||||
const folder = purpose === "review" ? "reviews" : "photos";
|
||||
const key = `recipes/${recipeId}/${folder}/${session!.user.id}-${crypto.randomUUID()}.${ext}`;
|
||||
|
||||
@@ -3,12 +3,11 @@ import { z } from "zod";
|
||||
import { db, webhooks, eq, and } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
|
||||
|
||||
const VALID_EVENTS = ["recipe.created", "recipe.updated", "recipe.published", "recipe.deleted"] as const;
|
||||
import { WEBHOOK_EVENTS } from "@/lib/webhooks";
|
||||
|
||||
const UpdateWebhookBody = z.object({
|
||||
url: z.string().min(1).max(2048).optional(),
|
||||
events: z.array(z.enum(VALID_EVENTS)).optional(),
|
||||
events: z.array(z.enum(WEBHOOK_EVENTS)).optional(),
|
||||
active: z.boolean().optional(),
|
||||
});
|
||||
|
||||
|
||||
@@ -4,17 +4,16 @@ import { z } from "zod";
|
||||
import { db, webhooks, eq } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
|
||||
|
||||
const VALID_EVENTS = ["recipe.created", "recipe.updated", "recipe.published", "recipe.deleted"] as const;
|
||||
import { WEBHOOK_EVENTS } from "@/lib/webhooks";
|
||||
|
||||
const CreateWebhookBody = z.object({
|
||||
url: z.string().min(1).max(2048),
|
||||
events: z.array(z.enum(VALID_EVENTS)).default([]),
|
||||
events: z.array(z.enum(WEBHOOK_EVENTS)).default([]),
|
||||
});
|
||||
|
||||
const UpdateWebhookBody = z.object({
|
||||
url: z.string().min(1).max(2048).optional(),
|
||||
events: z.array(z.enum(VALID_EVENTS)).optional(),
|
||||
events: z.array(z.enum(WEBHOOK_EVENTS)).optional(),
|
||||
active: z.boolean().optional(),
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user