security: fix full audit findings (v0.32.0)

Full list of the audit's confirmed findings and their fixes:

- Stored XSS via unescaped JSON-LD on the public recipe page
  (app/r/[id]/page.tsx) — escape < before injecting.
- CSP allowed unsafe-eval in production — now dev-only (Next prod
  never eval()s; only its HMR does).
- avatarUrl accepted any URL with no ownership check — now takes an
  avatarKey issued by avatar-presign, validated server-side, same
  pattern as recipe/review photos.
- No session revocation on password change/reset — both now revoke
  other sessions (revokeOtherSessions: true, revokeSessionsOnPasswordReset).
- Rate-limit bypass via spoofable X-Forwarded-For — take the last
  (proxy-appended) hop instead of the first (client-supplied) one,
  matching the single-Traefik-hop topology.
- Webhook signing secrets stored plaintext — now AES-256-GCM
  encrypted like every other secret in this app, with a legacy-
  plaintext fallback for pre-existing rows (bare hex has no ":", our
  ciphertext format always does).
- Better Auth's own rate limiter defaulted to in-memory storage,
  ineffective across replicas — now backed by the same Redis as
  lib/rate-limit.ts (secondaryStorage), with storeSessionInDatabase
  explicit so session storage itself doesn't move as a side effect.
- Presigned upload URLs didn't bind the declared file size to the
  actual upload, letting a client under-declare size (and quota
  charge) then PUT an arbitrarily large object — switched to S3
  presigned POST with a signed content-length-range condition,
  enforced by the storage server itself.
- generateMetadata() on the recipe page skipped the visibility
  filter the page body uses, leaking a private recipe's title via
  <title> to any signed-in user with the id.
- Block/unblock had no rate limit, unlike follow/unfollow.
- AI quota was charged even when a user's own BYOK key was used
  (their own credentials/billing) — added an isByok flag through
  the config-resolution chain and skip the charge when set. Also
  wired BYOK into generate/generate-from-idea/translate/import-url,
  which never looked it up at all before.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-14 15:05:05 +02:00
parent 6f11dc07fd
commit 3042d289a0
42 changed files with 508 additions and 417 deletions
+8 -1
View File
@@ -45,7 +45,14 @@ type Params = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: Params): Promise<Metadata> {
const { id } = await params;
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return { title: "Recipe" };
const recipe = await db.query.recipes.findFirst({
where: and(
eq(recipes.id, id),
or(eq(recipes.authorId, session.user.id), inArray(recipes.visibility, ["public", "unlisted"]))
),
});
return { title: recipe?.title ?? "Recipe" };
}
+1 -1
View File
@@ -65,7 +65,7 @@ export async function POST(req: NextRequest, { params }: Params) {
},
{ ...aiConfig, userContext: privateBio ?? undefined },
(session!.user as { locale?: string }).locale ?? "en"
)
), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
const adapted = result.data;
@@ -55,7 +55,7 @@ export async function POST(req: NextRequest) {
},
{ ...config, userContext: privateBio ?? undefined },
locale
)
), { skipQuota: config.isByok }
);
if (!result.ok) return result.response;
const plan = result.data;
+3 -2
View File
@@ -33,7 +33,8 @@ export async function POST(req: NextRequest) {
getUserPrivateBio(session!.user.id),
]);
if (!configResult.ok) return configResult.response;
const model = resolveModel(configResult.data);
const aiConfig = configResult.data;
const model = resolveModel(aiConfig);
const bioContext = buildUserBioContext(privateBio);
const locale = (session!.user as { locale?: string }).locale ?? "en";
const lang = LANG[locale] ?? "English";
@@ -43,7 +44,7 @@ export async function POST(req: NextRequest) {
model,
system: `You are Epicure, a helpful culinary assistant answering general cooking questions — not tied to any specific recipe (techniques, substitutions, timing, equipment, food safety, etc). If asked who you are or what model/AI you're built on, say you're Epicure — never name the underlying model or provider. If a question has nothing to do with cooking or food, politely redirect. Keep answers under 200 words. Respond in ${lang}.${bioContext}`,
prompt: parsed.data.question,
})
}), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
+1 -1
View File
@@ -55,7 +55,7 @@ export async function POST(req: NextRequest, { params }: Params) {
parsed.data.count,
{ ...aiConfig, userContext: privateBio ?? undefined },
(session!.user as { locale?: string }).locale ?? "en"
)
), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
@@ -2,9 +2,10 @@ import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSessionOrApiKey } 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 { generateRecipe } from "@/lib/ai/features/generate-recipe";
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";
@@ -32,13 +33,18 @@ export async function POST(req: NextRequest) {
const privateBio = await getUserPrivateBio(session!.user.id);
const locale = (session!.user as { locale?: string }).locale ?? "en";
const configResult = await resolveAiConfigOrError(() =>
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model })
);
if (!configResult.ok) return configResult.response;
const aiConfig = configResult.data;
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
generateRecipe(parsed.data.title, {
provider: parsed.data.provider,
model: parsed.data.model,
...aiConfig,
userContext: privateBio ?? undefined,
language: LANG[locale] ?? "English",
})
}), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
const recipe = result.data;
+10 -4
View File
@@ -2,9 +2,10 @@ import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSessionOrApiKey } 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 { generateRecipe } from "@/lib/ai/features/generate-recipe";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
import { withUserKey } from "@/lib/ai/resolve-user-key";
const Schema = z.object({
prompt: z.string().min(3).max(500),
@@ -29,14 +30,19 @@ export async function POST(req: NextRequest) {
const privateBio = await getUserPrivateBio(session!.user.id);
const configResult = await resolveAiConfigOrError(() =>
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model })
);
if (!configResult.ok) return configResult.response;
const aiConfig = configResult.data;
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
generateRecipe(parsed.data.prompt, {
provider: parsed.data.provider,
model: parsed.data.model,
...aiConfig,
language: parsed.data.language,
difficulty: parsed.data.difficulty,
userContext: privateBio ?? undefined,
})
}), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
+2 -1
View File
@@ -39,7 +39,8 @@ export async function POST(req: NextRequest) {
}
const result = await withAiQuota(userId, session!.user.tier as "free" | "pro", () =>
importFromPhoto(parsed.data.imageBase64, parsed.data.mimeType, aiConfig, locale)
importFromPhoto(parsed.data.imageBase64, parsed.data.mimeType, aiConfig, locale),
{ skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
const recipe = result.data;
+9 -5
View File
@@ -2,9 +2,10 @@ import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSessionOrApiKey } 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 { importFromUrl } from "@/lib/ai/features/import-url";
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
import { withUserKey } from "@/lib/ai/resolve-user-key";
const Schema = z.object({
url: z.string().url(),
@@ -30,11 +31,14 @@ export async function POST(req: NextRequest) {
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
if (limited) return limited;
const configResult = await resolveAiConfigOrError(() =>
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model })
);
if (!configResult.ok) return configResult.response;
const aiConfig = configResult.data;
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
importFromUrl(parsed.data.url, {
provider: parsed.data.provider,
model: parsed.data.model,
})
importFromUrl(parsed.data.url, aiConfig), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
@@ -88,7 +88,7 @@ export async function POST(req: NextRequest) {
},
{ ...config, userContext: privateBio ?? undefined },
locale
)
), { skipQuota: config.isByok }
);
if (!result.ok) return result.response;
const plan = result.data;
@@ -56,7 +56,7 @@ export async function POST(req: NextRequest, { params }: Params) {
parsed.data.count,
{ ...aiConfig, userContext: privateBio ?? undefined },
(session!.user as { locale?: string }).locale ?? "en"
)
), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
+3 -2
View File
@@ -68,7 +68,8 @@ ${stepList || "None listed"}
getUserPrivateBio(session!.user.id),
]);
if (!configResult.ok) return configResult.response;
const model = resolveModel(configResult.data);
const aiConfig = configResult.data;
const model = resolveModel(aiConfig);
const bioContext = buildUserBioContext(privateBio);
const locale = (session!.user as { locale?: string }).locale ?? "en";
const lang = LANG[locale] ?? "English";
@@ -80,7 +81,7 @@ ${stepList || "None listed"}
${recipeContext}${bioContext}`,
prompt: parsed.data.question,
})
}), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
+3 -2
View File
@@ -42,7 +42,8 @@ export async function POST(req: NextRequest) {
getUserPrivateBio(session!.user.id),
]);
if (!configResult.ok) return configResult.response;
const model = resolveModel(configResult.data);
const aiConfig = configResult.data;
const model = resolveModel(aiConfig);
const bioContext = buildUserBioContext(privateBio);
const userContext = bioContext
@@ -62,7 +63,7 @@ export async function POST(req: NextRequest) {
schema: IdeasSchema,
system: `Respond in ${lang}.`,
prompt,
})
}), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
+1 -1
View File
@@ -55,7 +55,7 @@ export async function POST(req: NextRequest) {
recipe.baseServings,
aiConfig,
(session!.user as { locale?: string }).locale ?? "en"
)
), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
+4 -2
View File
@@ -5,6 +5,7 @@ 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";
import type { AiConfig } from "@/lib/ai/factory";
const Schema = z.object({
ingredient: z.string().min(1).max(200),
@@ -28,7 +29,7 @@ export async function POST(req: NextRequest) {
? `recipe "${parsed.data.recipeTitle}"`
: "a general recipe";
let aiConfig;
let aiConfig: AiConfig;
if (parsed.data.provider) {
aiConfig = { provider: parsed.data.provider, model: parsed.data.model };
} else {
@@ -40,7 +41,8 @@ export async function POST(req: NextRequest) {
const locale = (session!.user as { locale?: string }).locale ?? "en";
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
substituteIngredient(parsed.data.ingredient, context, aiConfig, locale)
substituteIngredient(parsed.data.ingredient, context, aiConfig, locale),
{ skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
+10 -3
View File
@@ -3,8 +3,9 @@ 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 { withAiQuota } from "@/lib/ai/ai-error";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { translateRecipe } from "@/lib/ai/features/translate-recipe";
import { withUserKey } from "@/lib/ai/resolve-user-key";
const Schema = z.object({
targetLanguage: z.string().min(2).max(50),
@@ -35,6 +36,12 @@ export async function POST(req: NextRequest, { params }: Params) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
const configResult = await resolveAiConfigOrError(() =>
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model })
);
if (!configResult.ok) return configResult.response;
const aiConfig = configResult.data;
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
translateRecipe(
{
@@ -44,8 +51,8 @@ export async function POST(req: NextRequest, { params }: Params) {
steps: recipe.steps,
},
parsed.data.targetLanguage,
{ provider: parsed.data.provider, model: parsed.data.model }
)
aiConfig
), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
const translation = result.data;
@@ -59,7 +59,7 @@ export async function POST(req: NextRequest, { params }: Params) {
{ ...aiConfig, userContext: privateBio ?? undefined },
parsed.data.directions,
(session!.user as { locale?: string }).locale ?? "en"
)
), { skipQuota: aiConfig.isByok }
);
if (!result.ok) return result.response;
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/api-auth";
import { createPresignedUploadUrl } from "@/lib/storage";
import { createPresignedUploadPost } from "@/lib/storage";
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/avif"] as const;
@@ -39,7 +39,7 @@ export async function POST(req: NextRequest) {
const ext = contentType.split("/")[1] ?? "jpg";
const key = `user-avatars/${session!.user.id}/${crypto.randomUUID()}.${ext}`;
const url = await createPresignedUploadUrl(key, contentType);
const { url, fields } = await createPresignedUploadPost(key, contentType, MAX_FILE_SIZE);
return NextResponse.json({ url, key });
return NextResponse.json({ url, fields, key });
}
+3 -3
View File
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/api-auth";
import { createPresignedUploadUrl } from "@/lib/storage";
import { createPresignedUploadPost } from "@/lib/storage";
import { db, recipes, eq, and } from "@epicure/db";
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
@@ -53,7 +53,7 @@ export async function POST(req: NextRequest) {
const ext = contentType.split("/")[1] ?? "jpg";
const folder = purpose === "review" ? "reviews" : "photos";
const key = `recipes/${recipeId}/${folder}/${session!.user.id}-${crypto.randomUUID()}.${ext}`;
const url = await createPresignedUploadUrl(key, contentType);
const { url, fields } = await createPresignedUploadPost(key, contentType, MAX_FILE_SIZE);
return NextResponse.json({ url, key });
return NextResponse.json({ url, fields, key });
}
@@ -1,12 +1,17 @@
import { NextRequest, NextResponse } from "next/server";
import { db, users, userBlocks, userFollows, eq, and, or } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
type Params = { params: Promise<{ username: string }> };
export async function POST(_req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const limited = await applyRateLimit(`rl:block:${session!.user.id}`, 30, 60);
if (limited) return limited;
const { username } = await params;
const target = await db.query.users.findFirst({ where: eq(users.username, username) });
@@ -31,6 +36,10 @@ export async function POST(_req: NextRequest, { params }: Params) {
export async function DELETE(_req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const limited = await applyRateLimit(`rl:block:${session!.user.id}`, 30, 60);
if (limited) return limited;
const { username } = await params;
const target = await db.query.users.findFirst({ where: eq(users.username, username) });
+14 -7
View File
@@ -5,6 +5,7 @@ import { db, users, eq } from "@epicure/db";
import { z } from "zod";
import { gravatarUrl } from "@/lib/gravatar";
import { USERNAME_PATTERN, isUsernameTaken } from "@/lib/username";
import { isOwnedAvatarKey, getPublicUrl } from "@/lib/storage";
const PatchSchema = z.object({
name: z.string().min(1).max(100).optional(),
@@ -13,9 +14,12 @@ const PatchSchema = z.object({
privateBio: z.string().max(2000).optional().nullable(),
isPrivate: z.boolean().optional(),
username: z.string().trim().toLowerCase().regex(USERNAME_PATTERN, "3-20 characters, lowercase letters, numbers, and underscores only").optional(),
// A custom-uploaded avatar URL, or null to revert to the initials fallback
// (or Gravatar, if useGravatar is on — see below).
avatarUrl: z.string().url().max(2048).optional().nullable(),
// The storage key returned by /api/v1/upload/avatar-presign (not a URL) —
// the server validates it was actually issued to this user and builds the
// public URL itself, so a client can't point avatarUrl at an arbitrary or
// another user's object. `null` reverts to the initials fallback (or
// Gravatar, if useGravatar is on — see below).
avatarKey: z.string().max(500).optional().nullable(),
// Off by default (Settings → Profile) — Gravatar is looked up by an MD5
// hash of the user's email, sent to a third party.
useGravatar: z.boolean().optional(),
@@ -32,7 +36,7 @@ export async function PATCH(req: Request) {
return NextResponse.json({ error: "Username already taken" }, { status: 409 });
}
const { avatarUrl, useGravatar, ...rest } = body.data;
const { avatarKey, useGravatar, ...rest } = body.data;
const updates: Partial<typeof users.$inferInsert> = { ...rest };
// useGravatar is only ever toggled from the settings form, never alongside
@@ -45,13 +49,16 @@ export async function PATCH(req: Request) {
}
}
if (avatarUrl !== undefined) {
if (avatarUrl === null) {
if (avatarKey !== undefined) {
if (avatarKey === null) {
const gravatarOptedIn = useGravatar ?? (await getUseGravatar(session.user.id));
updates.avatarUrl = gravatarOptedIn ? gravatarUrl(session.user.email) : null;
updates.hasCustomAvatar = false;
} else {
updates.avatarUrl = avatarUrl;
if (!isOwnedAvatarKey(avatarKey, session.user.id)) {
return NextResponse.json({ error: "Invalid avatar key" }, { status: 400 });
}
updates.avatarUrl = getPublicUrl(avatarKey);
updates.hasCustomAvatar = true;
}
}
+2 -1
View File
@@ -5,6 +5,7 @@ import { db, webhooks, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
import { WEBHOOK_EVENTS } from "@/lib/webhooks";
import { encrypt } from "@/lib/encrypt";
const CreateWebhookBody = z.object({
url: z.string().min(1).max(2048),
@@ -64,7 +65,7 @@ export async function POST(req: NextRequest) {
userId: session!.user.id,
url: parsed.data.url,
events: parsed.data.events,
secret,
secret: encrypt(secret),
active: true,
createdAt: now,
});
+1 -1
View File
@@ -82,7 +82,7 @@ export default async function PublicRecipePage({ params }: Params) {
return (
<>
<Script id="recipe-jsonld" type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
<Script id="recipe-jsonld" type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }} />
<div className="container mx-auto max-w-3xl px-4 py-8 space-y-8">
{/* Breadcrumb-style nav */}
<div className="flex items-center gap-2 text-sm text-muted-foreground">
@@ -6,6 +6,7 @@ import { useTranslations } from "next-intl";
import { Upload, X, Star } from "lucide-react";
import { Button } from "@/components/ui/button";
import { getPublicUrl } from "@/lib/storage";
import { uploadToPresignedPost } from "@/lib/upload-client";
export type PhotoEntry = {
key: string;
@@ -41,8 +42,9 @@ export function PhotoUploader({
body: JSON.stringify({ recipeId, contentType: file.type, fileSize: file.size }),
});
if (!res.ok) continue;
const { url, key } = await res.json() as { url: string; key: string };
await fetch(url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });
const { url, fields, key } = await res.json() as { url: string; fields: Record<string, string>; key: string };
const uploaded = await uploadToPresignedPost(url, fields, file);
if (!uploaded) continue;
const isFirst = next.length === 0;
next = [...next, { key, isCover: isFirst, preview: URL.createObjectURL(file) }];
onChange(next);
@@ -6,6 +6,7 @@ import { toast } from "sonner";
import { Camera, Loader2, X } from "lucide-react";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { uploadToPresignedPost } from "@/lib/upload-client";
export function AvatarUploader({
name,
@@ -37,22 +38,27 @@ export function AvatarUploader({
toast.error(err.error ?? t("avatarUploadFailed"));
return;
}
const { url } = await presignRes.json() as { url: string; key: string };
await fetch(url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });
const { url, fields, key } = await presignRes.json() as { url: string; fields: Record<string, string>; key: string };
const uploaded = await uploadToPresignedPost(url, fields, file);
if (!uploaded) {
toast.error(t("avatarUploadFailed"));
return;
}
// The presigned PUT URL is already publicUrl/bucket/key with query-string
// signing params appended — strip those to get the plain public GET URL.
// Send back the storage key we were issued, not a client-derived URL —
// the server validates the key belongs to us and builds the public URL
// itself, so a client can't set avatarUrl to an arbitrary/unowned target.
const saveRes = await fetch("/api/v1/users/me", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ avatarUrl: url.split("?")[0] }),
body: JSON.stringify({ avatarKey: key }),
});
if (!saveRes.ok) {
toast.error(t("avatarUploadFailed"));
return;
}
const saved = await saveRes.json() as { avatarUrl?: string };
onChange(saved.avatarUrl ?? url.split("?")[0]!, true);
onChange(saved.avatarUrl ?? null, true);
toast.success(t("avatarUploadSuccess"));
} finally {
setUploading(false);
@@ -59,7 +59,7 @@ export function SecurityForm({
const { error } = await authClient.changePassword({
currentPassword,
newPassword,
revokeOtherSessions: false,
revokeOtherSessions: true,
});
if (error) {
toast.error(error.message ?? t("passwordChangeFailed"));
@@ -9,6 +9,7 @@ import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { getPublicUrl } from "@/lib/storage";
import { uploadToPresignedPost } from "@/lib/upload-client";
import { cn } from "@/lib/utils";
type Review = {
@@ -93,8 +94,12 @@ export function CookedItReview({
toast.error(t("reviewPhotoFailed"));
return;
}
const { url, key } = (await res.json()) as { url: string; key: string };
await fetch(url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });
const { url, fields, key } = (await res.json()) as { url: string; fields: Record<string, string>; key: string };
const uploaded = await uploadToPresignedPost(url, fields, file);
if (!uploaded) {
toast.error(t("reviewPhotoFailed"));
return;
}
setPhotoKey(key);
setPreview(URL.createObjectURL(file));
} finally {
+15 -8
View File
@@ -47,26 +47,33 @@ type QuotaResult<T> = { ok: true; data: T } | { ok: false; response: NextRespons
* throws — so a provider outage never silently burns a user's quota.
* Centralizes the TierLimitError → 403 and AI-failure → clean-JSON mapping
* that every AI route needs instead of repeating try/catch per route.
*
* Pass `skipQuota: true` when the resolved AiConfig used the caller's own
* BYOK key (config.isByok) — it's their own credentials/billing, so it
* shouldn't count against the platform's monthly AI-call limit.
*/
export async function withAiQuota<T>(
userId: string,
tier: "free" | "pro",
fn: () => Promise<T>
fn: () => Promise<T>,
opts?: { skipQuota?: boolean }
): Promise<QuotaResult<T>> {
try {
await checkAndIncrementTierLimit(userId, tier, "aiCall");
} catch (err) {
if (err instanceof TierLimitError) {
return { ok: false, response: NextResponse.json({ error: "AI call limit reached for your tier" }, { status: 403 }) };
if (!opts?.skipQuota) {
try {
await checkAndIncrementTierLimit(userId, tier, "aiCall");
} catch (err) {
if (err instanceof TierLimitError) {
return { ok: false, response: NextResponse.json({ error: "AI call limit reached for your tier" }, { status: 403 }) };
}
throw err;
}
throw err;
}
try {
const data = await fn();
return { ok: true, data };
} catch (err) {
await refundAiCall(userId);
if (!opts?.skipQuota) await refundAiCall(userId);
return { ok: false, response: aiErrorResponse(err) };
}
}
+3
View File
@@ -8,6 +8,9 @@ export type AiConfig = {
provider?: AiProvider;
model?: string;
apiKey?: string;
/** True when apiKey is the caller's own BYOK key — their own credentials
* and billing, so platform AI-call quota shouldn't be charged for it. */
isByok?: boolean;
};
export function resolveModel(config: AiConfig = {}): LanguageModel {
+2 -2
View File
@@ -44,7 +44,7 @@ export async function withUserKey(userId: string, config: AiConfig): Promise<AiC
try {
const apiKey = decrypt(row.encryptedKey);
return { ...config, apiKey };
return { ...config, apiKey, isByok: true };
} catch {
throw new ByokDecryptError(provider);
}
@@ -81,7 +81,7 @@ export async function getDefaultProviderWithKey(userId: string, useCase?: ModelU
const row = keys.find((k) => k.provider === p);
if (row) {
try {
return { provider: p, apiKey: decrypt(row.encryptedKey) };
return { provider: p, apiKey: decrypt(row.encryptedKey), isByok: true };
} catch {
throw new ByokDecryptError(p);
}
+31
View File
@@ -6,10 +6,32 @@ import { sendEmail, verifyEmailHtml, resetPasswordHtml, welcomeHtml } from "@/li
import { isSignupsDisabled } from "@/lib/site-settings";
import { findValidInvite, consumeInvite, INVITE_COOKIE } from "@/lib/invites";
import { generateUniqueUsername } from "@/lib/username";
import { getRedis } from "@/lib/redis";
// Without this, better-auth's own rate limiter (sign-in/sign-up/2FA/password
// reset throttles below) defaults to an in-process Map — fine for a single
// instance, but each replica gets its own independent counter the moment
// this app is ever scaled horizontally, multiplying the effective limit by
// the instance count. Backing it with the same Redis used elsewhere
// (lib/rate-limit.ts) makes the limit actually shared and enforceable.
const redisSecondaryStorage = {
async get(key: string) {
return getRedis().get(key);
},
async set(key: string, value: string, ttl?: number) {
if (ttl) await getRedis().set(key, value, "EX", ttl);
else await getRedis().set(key, value);
},
async delete(key: string) {
await getRedis().del(key);
},
};
export const auth = betterAuth({
trustedOrigins: [process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000"],
secondaryStorage: redisSecondaryStorage,
// Explicit rather than relying on the isProduction default so dev/staging
// are protected too. Sign-in/sign-up/change-password/change-email get a
// strict built-in 3-req/10s-per-IP rule (better-auth's default special
@@ -34,6 +56,9 @@ export const auth = betterAuth({
emailAndPassword: {
enabled: true,
requireEmailVerification: true,
// A stolen session should not survive the account owner noticing and
// resetting their password.
revokeSessionsOnPasswordReset: true,
sendResetPassword: async ({ user, url }) => {
await sendEmail({
to: user.email,
@@ -100,6 +125,12 @@ export const auth = betterAuth({
enabled: true,
maxAge: 60 * 5,
},
// secondaryStorage above is only meant to back the rate limiter — without
// this, better-auth would also move session storage itself into Redis
// (see internal-adapter.mjs's `storeInDb` checks), which is an unrelated,
// much bigger behavior change (session data no longer queryable from the
// `sessions` table at all) that nothing else in this app expects.
storeSessionInDatabase: true,
},
databaseHooks: {
+17 -1
View File
@@ -1,5 +1,5 @@
// Mirrors CHANGELOG.md at the repo root — update both together.
export const APP_VERSION = "0.31.0";
export const APP_VERSION = "0.32.0";
export type ChangelogEntry = {
version: string;
@@ -11,6 +11,22 @@ export type ChangelogEntry = {
};
export const CHANGELOG: ChangelogEntry[] = [
{
version: "0.32.0",
date: "2026-07-14 17:10",
security: [
"Fixed a stored-XSS hole in public recipe pages' embedded structured data, and tightened the production Content-Security-Policy so script injection like it can't execute even if a similar bug slips in again.",
"Avatar photos now require proof you actually own the upload — previously any URL was accepted, including another user's uploaded photo key.",
"Changing your password now signs out every other active session, and so does resetting a forgotten password.",
"Fixed a rate-limit bypass on public share-link throttling caused by trusting a spoofable header.",
"Webhook signing secrets are now encrypted at rest, matching how API keys and other secrets are already stored.",
"Login/2FA/password-reset rate limiting now shares Redis instead of quietly resetting per server instance.",
"Photo/avatar uploads are now size-capped by the storage server itself, not just a number the client could lie about.",
"A private recipe's title could leak via its page's browser-tab title to any signed-in user who had the link — fixed to respect the same visibility rules as the page itself.",
"Blocking/unblocking a user is now rate-limited, matching follow/unfollow.",
"AI calls made with your own API key (Settings → AI Keys) no longer count against your monthly AI-call limit.",
],
},
{
version: "0.31.0",
date: "2026-07-14 16:35",
+9 -5
View File
@@ -395,7 +395,7 @@ export function generateOpenApiSpec(): object {
name: z.string().min(1).max(100).optional(), locale: z.string().max(10).optional(),
bio: z.string().max(500).nullable().optional(), privateBio: z.string().max(2000).nullable().optional(),
isPrivate: z.boolean().optional(), username: z.string().regex(USERNAME_PATTERN, "3-20 characters, lowercase letters, numbers, and underscores only").optional(),
avatarUrl: z.string().url().max(2048).nullable().optional(), useGravatar: z.boolean().optional(),
avatarKey: z.string().max(500).nullable().optional().describe("Storage key returned by POST /upload/avatar-presign, not a URL — validated server-side against the caller's own uploads."), useGravatar: z.boolean().optional(),
}));
const ModelPrefsRef = registry.register("ModelPrefs", z.object({
id: z.string(), userId: z.string(),
@@ -450,7 +450,7 @@ export function generateOpenApiSpec(): object {
recipeCount: z.number().int(), isFollowing: z.boolean(),
}));
registry.registerPath({ method: "patch", path: "/api/v1/users/me", summary: "Update your profile", description: "Toggling useGravatar or clearing avatarUrl re-derives the effective avatar (Gravatar or initials fallback).", security, request: { body: { content: { "application/json": { schema: UpdateMeRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: z.object({ ok: z.boolean(), avatarUrl: z.string().nullable() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 409: { description: "Username already taken", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "patch", path: "/api/v1/users/me", summary: "Update your profile", description: "Toggling useGravatar or clearing avatarKey re-derives the effective avatar (Gravatar or initials fallback).", security, request: { body: { content: { "application/json": { schema: UpdateMeRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: z.object({ ok: z.boolean(), avatarUrl: z.string().nullable() }) } } }, 400: { description: "Validation error, or avatarKey wasn't issued to you by avatar-presign", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 409: { description: "Username already taken", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/users/me/export", summary: "Export all of your account data as a JSON file", description: "Rate-limited: 3 req/hour. Includes profile, recipes, social graph, collections, meal plans, pantry, shopping lists, webhooks, API keys, messages, and more.", security, responses: { 200: { description: "Downloadable JSON export", content: { "application/json": { schema: z.record(z.string(), z.unknown()) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/users/me/model-prefs", summary: "Get your AI model provider/model preferences", security, responses: { 200: { description: "Preferences or null", content: { "application/json": { schema: ModelPrefsRef.nullable() } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "put", path: "/api/v1/users/me/model-prefs", summary: "Set your AI model provider/model preferences", security, request: { body: { content: { "application/json": { schema: UpdateModelPrefsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Invalid request", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
@@ -620,10 +620,14 @@ export function generateOpenApiSpec(): object {
contentType: z.enum(["image/jpeg", "image/png", "image/webp", "image/avif"]),
fileSize: z.number().int().positive().max(5 * 1024 * 1024, "File exceeds 5MB limit"),
}));
const PresignResponseRef = registry.register("PresignResponse", z.object({ url: z.string(), key: z.string() }));
const PresignResponseRef = registry.register("PresignResponse", z.object({
url: z.string().describe("POST this URL as multipart/form-data — include every field below, then the file itself last."),
fields: z.record(z.string(), z.string()).describe("Form fields to include in the upload POST, including a signed content-length-range condition that the storage server enforces (the declared fileSize can't be lied about)."),
key: z.string(),
}));
registry.registerPath({ method: "post", path: "/api/v1/upload/presign", summary: "Get a presigned S3 URL to upload a recipe or review photo", description: "Recipe photos: recipeId must be your own recipe. Review photos: recipe must be visible to you. Charges your tier's storage quota.", security, request: { body: { content: { "application/json": { schema: PresignUploadRef } }, required: true } }, responses: { 200: { description: "Presigned URL and object key", content: { "application/json": { schema: PresignResponseRef } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Storage limit reached for your tier", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/upload/avatar-presign", summary: "Get a presigned S3 URL to upload your avatar photo", description: "Charges your tier's storage quota.", security, request: { body: { content: { "application/json": { schema: PresignAvatarUploadRef } }, required: true } }, responses: { 200: { description: "Presigned URL and object key", content: { "application/json": { schema: PresignResponseRef } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Storage limit reached for your tier", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/upload/presign", summary: "Get a presigned S3 upload POST (URL + form fields) for a recipe or review photo", description: "Recipe photos: recipeId must be your own recipe. Review photos: recipe must be visible to you. Charges your tier's storage quota.", security, request: { body: { content: { "application/json": { schema: PresignUploadRef } }, required: true } }, responses: { 200: { description: "Presigned POST", content: { "application/json": { schema: PresignResponseRef } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Storage limit reached for your tier", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/upload/avatar-presign", summary: "Get a presigned S3 upload POST (URL + form fields) for your avatar photo", description: "Charges your tier's storage quota.", security, request: { body: { content: { "application/json": { schema: PresignAvatarUploadRef } }, required: true } }, responses: { 200: { description: "Presigned POST", content: { "application/json": { schema: PresignResponseRef } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Storage limit reached for your tier", content: { "application/json": { schema: ApiErrorRef } } } } });
// --- Push notifications ---
const PushSubscribeRef = registry.register("PushSubscribe", z.object({
+32 -5
View File
@@ -1,5 +1,5 @@
import { S3Client, PutObjectCommand, DeleteObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { S3Client, DeleteObjectCommand } from "@aws-sdk/client-s3";
import { createPresignedPost } from "@aws-sdk/s3-presigned-post";
const bucket = process.env["STORAGE_BUCKET"] || "epicure-uploads";
const endpoint = process.env["STORAGE_ENDPOINT"] || "http://localhost:9000";
@@ -32,9 +32,31 @@ const presignS3 = new S3Client({
credentials,
});
export async function createPresignedUploadUrl(key: string, contentType: string): Promise<string> {
const command = new PutObjectCommand({ Bucket: bucket, Key: key, ContentType: contentType });
return getSignedUrl(presignS3, command, { expiresIn: 300 });
/**
* A presigned PUT URL only signs Bucket/Key/ContentType nothing binds the
* actual request body size to what the caller declared when it asked for the
* URL (and was charged storage-tier quota for), so a client could declare
* 1 byte and then PUT an arbitrarily large object. S3/MinIO's POST-policy
* upload flow is the fix: `content-length-range` is a *signed* condition,
* enforced by the storage server itself when it receives the upload a
* mismatched Content-Length is rejected before the bytes are ever accepted,
* not just checked against something the client also controls.
*/
export async function createPresignedUploadPost(
key: string,
contentType: string,
maxBytes: number
): Promise<{ url: string; fields: Record<string, string> }> {
return createPresignedPost(presignS3, {
Bucket: bucket,
Key: key,
Conditions: [
["content-length-range", 0, maxBytes],
{ "Content-Type": contentType },
],
Fields: { "Content-Type": contentType },
Expires: 300,
});
}
export async function deleteObject(key: string): Promise<void> {
@@ -60,3 +82,8 @@ export function isOwnedRecipePhotoKey(key: string, recipeId: string, userId: str
export function isOwnedReviewPhotoKey(key: string, recipeId: string, userId: string): boolean {
return key.startsWith(`recipes/${recipeId}/reviews/${userId}-`);
}
/** Same rationale as isOwnedRecipePhotoKey, for the avatar-presign key prefix. */
export function isOwnedAvatarKey(key: string, userId: string): boolean {
return key.startsWith(`user-avatars/${userId}/`);
}
+15
View File
@@ -0,0 +1,15 @@
/** Uploads a file to an S3/MinIO presigned POST URL (see lib/storage.ts's
* createPresignedUploadPost) unlike a presigned PUT, the storage server
* itself rejects a mismatched size via the signed content-length-range
* condition, so this can't be used to upload past the declared limit. */
export async function uploadToPresignedPost(
url: string,
fields: Record<string, string>,
file: File
): Promise<boolean> {
const formData = new FormData();
for (const [key, value] of Object.entries(fields)) formData.append(key, value);
formData.append("file", file);
const res = await fetch(url, { method: "POST", body: formData });
return res.ok;
}
+11 -1
View File
@@ -3,6 +3,16 @@ import { db } from "@epicure/db";
import { webhooks, webhookDeliveries } from "@epicure/db";
import { eq, and } from "@epicure/db";
import { safeFetch } from "@/lib/validate-webhook-url";
import { decrypt } from "@/lib/encrypt";
// Secrets created before encryption-at-rest was added are a bare 64-char hex
// string (crypto.randomBytes(32).toString("hex")) with no ":" separators —
// encrypt()'s output is always "iv:authTag:ciphertext". Fall back to treating
// the value as already-plaintext rather than a hard migration, since this is
// only reached with a value this app itself generated (never user input).
function decryptWebhookSecret(stored: string): string {
return stored.split(":").length === 3 ? decrypt(stored) : stored;
}
export const WEBHOOK_EVENTS = [
"recipe.created",
@@ -27,7 +37,7 @@ export async function dispatchWebhook(userId: string, event: WebhookEvent, paylo
await Promise.allSettled(
filtered.map(async (hook) => {
const body = JSON.stringify({ event, payload, timestamp: new Date().toISOString() });
const sig = crypto.createHmac("sha256", hook.secret).update(body).digest("hex");
const sig = crypto.createHmac("sha256", decryptWebhookSecret(hook.secret)).update(body).digest("hex");
let statusCode = 0;
let success = false;
try {
+8 -1
View File
@@ -4,6 +4,13 @@ const storagePublicUrl = process.env["STORAGE_PUBLIC_URL"] || "http://localhost:
const storageUrl = new URL(storagePublicUrl);
const storageOrigin = storageUrl.origin;
// unsafe-eval is only needed by Next.js dev's HMR/Fast Refresh — production
// builds never eval(), so drop it there instead of leaving XSS payloads a
// wide-open eval sink in the deployed app.
const scriptSrc = process.env.NODE_ENV === "production"
? "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net"
: "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net";
const securityHeaders = [
{
key: "X-Content-Type-Options",
@@ -33,7 +40,7 @@ const securityHeaders = [
key: "Content-Security-Policy",
value: [
"default-src 'self'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net", // unsafe-eval needed by Next.js dev; tighten in prod. jsdelivr serves the Scalar API-reference bundle on /docs.
scriptSrc, // jsdelivr serves the Scalar API-reference bundle on /docs.
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net",
`img-src 'self' data: blob: ${storageOrigin} https://www.gravatar.com`,
"font-src 'self' https://cdn.jsdelivr.net data:",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@epicure/web",
"version": "0.31.0",
"version": "0.32.0",
"private": true,
"scripts": {
"dev": "next dev",
@@ -16,8 +16,8 @@
"@ai-sdk/anthropic": "^3.0.86",
"@ai-sdk/openai": "^3.0.74",
"@asteasolutions/zod-to-openapi": "^7.3.4",
"@aws-sdk/client-s3": "^3.1075.0",
"@aws-sdk/s3-request-presigner": "^3.1075.0",
"@aws-sdk/client-s3": "^3.1085.0",
"@aws-sdk/s3-presigned-post": "^3.1085.0",
"@base-ui/react": "^1.6.0",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
+13 -1
View File
@@ -18,9 +18,21 @@ const IP_RATE_LIMITED_PATHS = ["/r/", "/s/"];
const IP_RATE_LIMIT = 60;
const IP_RATE_LIMIT_WINDOW_SECONDS = 60;
// Epicure sits behind exactly one reverse proxy (Traefik — see traefik/epicure.yml).
// Each hop *appends* the address it saw to X-Forwarded-For, so with a single
// trusted hop in front of us, the rightmost entry is the address Traefik itself
// observed — i.e. the real client — while anything to its left (including the
// entire header, on a direct request with no proxy at all) is attacker-supplied
// and must not be trusted. Taking the leftmost entry, as before, let a client
// set an arbitrary X-Forwarded-For and get a fresh rate-limit bucket on every
// request. If another reverse proxy is ever added in front of Traefik, this
// needs to pop one more entry per added hop.
function getClientIp(request: NextRequest): string {
const forwardedFor = request.headers.get("x-forwarded-for");
if (forwardedFor) return forwardedFor.split(",")[0]!.trim();
if (forwardedFor) {
const parts = forwardedFor.split(",");
return parts[parts.length - 1]!.trim();
}
return request.headers.get("x-real-ip") ?? "unknown";
}