Files
Epicure/apps/web/app/r/[id]/page.tsx
T
Arnaud 3042d289a0 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>
2026-07-14 15:05:05 +02:00

177 lines
7.5 KiB
TypeScript

import type { Metadata } from "next";
import Image from "next/image";
import Script from "next/script";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import Link from "next/link";
import { Clock, Users, ChefHat, Globe } from "lucide-react";
import { auth } from "@/lib/auth/server";
import { db, recipes, eq } from "@epicure/db";
import { Badge } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { ServingScaler } from "@/components/recipe/serving-scaler";
import { getPublicUrl } from "@/lib/storage";
import { hasQuantity } from "@/lib/fractions";
import { cn } from "@/lib/utils";
import { getMessages, formatMessage } from "@/lib/i18n/server";
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: (r, { and, eq }) => and(eq(r.id, id), eq(r.visibility, "public")),
});
if (!recipe) return {};
return {
title: recipe.title,
description: recipe.description ?? undefined,
openGraph: {
title: recipe.title,
description: recipe.description ?? undefined,
type: "article",
},
};
}
export default async function PublicRecipePage({ params }: Params) {
const { id } = await params;
const session = await auth.api.getSession({ headers: await headers() }).catch(() => null);
const m = getMessages((session?.user as { locale?: string } | undefined)?.locale);
const unitPref = (session?.user as { unitPref?: string } | undefined)?.unitPref === "imperial" ? "imperial" : "metric";
const recipe = await db.query.recipes.findFirst({
where: (r, { and, eq, ne }) => and(eq(r.id, id), ne(r.visibility, "private")),
with: {
author: true,
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
steps: { orderBy: (t, { asc }) => asc(t.order) },
photos: { orderBy: (t, { asc }) => asc(t.order) },
},
});
if (!recipe) notFound();
const cover = recipe.photos.find((p) => p.isCover) ?? recipe.photos[0];
const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
const activeTags = Object.entries(recipe.dietaryTags ?? {})
.filter(([, v]) => v)
.map(([k]) => m.recipe.dietary[k as keyof typeof m.recipe.dietary])
.filter(Boolean);
const jsonLd = {
"@context": "https://schema.org",
"@type": "Recipe",
name: recipe.title,
description: recipe.description,
author: { "@type": "Person", name: recipe.author.name },
recipeYield: String(recipe.baseServings),
prepTime: recipe.prepMins ? `PT${recipe.prepMins}M` : undefined,
cookTime: recipe.cookMins ? `PT${recipe.cookMins}M` : undefined,
recipeIngredient: recipe.ingredients.map((i) =>
[hasQuantity(i.quantity) ? i.quantity : null, i.unit, i.rawName].filter(Boolean).join(" ")
),
recipeInstructions: recipe.steps.map((s) => ({
"@type": "HowToStep",
text: s.instruction,
})),
image: cover ? [getPublicUrl(cover.storageKey)] : undefined,
};
return (
<>
<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">
<Globe className="h-3.5 w-3.5" />
<span>{m.publicRecipe.publicRecipeBy}</span>
<Link href={`/u/${recipe.author.username ?? recipe.author.id}`} className="hover:text-foreground font-medium">
{recipe.author.name}
</Link>
{session && (
<div className="ml-auto">
<Link href={`/recipes/${id}`} className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
{m.publicRecipe.viewInLibrary}
</Link>
</div>
)}
{!session && (
<div className="ml-auto flex items-center gap-2">
<Link href="/signup" className={cn(buttonVariants({ size: "sm" }))}>{m.publicRecipe.signUpFree}</Link>
<Link href="/login" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>{m.publicRecipe.logIn}</Link>
</div>
)}
</div>
<div className="space-y-4">
<h1 className="text-3xl font-bold tracking-tight">{recipe.title}</h1>
{recipe.description && (
<p className="text-muted-foreground leading-relaxed">{recipe.description}</p>
)}
<div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
{recipe.difficulty && <Badge>{recipe.difficulty}</Badge>}
<span className="flex items-center gap-1"><Users className="h-4 w-4" />{formatMessage(m.recipe.servings, { count: recipe.baseServings })}</span>
{recipe.prepMins && <span className="flex items-center gap-1"><Clock className="h-4 w-4" />{formatMessage(m.recipe.prep, { mins: recipe.prepMins })}</span>}
{recipe.cookMins && <span className="flex items-center gap-1"><ChefHat className="h-4 w-4" />{formatMessage(m.recipe.cook, { mins: recipe.cookMins })}</span>}
{totalMins > 0 && recipe.prepMins && recipe.cookMins && <span>({formatMessage(m.recipe.total, { mins: totalMins })})</span>}
</div>
{activeTags.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{activeTags.map((tag) => <Badge key={tag} variant="secondary" className="text-xs">{tag}</Badge>)}
</div>
)}
</div>
{cover && (
<div className="relative aspect-video overflow-hidden rounded-xl bg-muted">
<Image src={getPublicUrl(cover.storageKey)} alt={recipe.title} fill unoptimized className="object-cover" />
</div>
)}
<Separator />
{recipe.ingredients.length > 0 && (
<div className="space-y-4">
<h2 className="text-xl font-semibold">{m.recipe.ingredients}</h2>
<ServingScaler
baseServings={recipe.baseServings}
unitPref={unitPref}
ingredients={recipe.ingredients.map((ing) => ({
id: ing.id, rawName: ing.rawName, quantity: ing.quantity, unit: ing.unit, note: ing.note, order: ing.order,
}))}
/>
</div>
)}
{recipe.steps.length > 0 && (
<>
<Separator />
<div className="space-y-6">
<h2 className="text-xl font-semibold">{m.recipe.instructions}</h2>
<ol className="space-y-6">
{recipe.steps.map((step, i) => (
<li key={step.id} className="flex gap-4">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-bold">{i + 1}</div>
<p className="flex-1 pt-1 leading-relaxed">{step.instruction}</p>
</li>
))}
</ol>
</div>
</>
)}
{!session && (
<div className="rounded-xl border bg-muted/40 p-6 text-center space-y-3">
<p className="font-semibold">{m.publicRecipe.wantToSave}</p>
<p className="text-sm text-muted-foreground">{m.publicRecipe.wantToSaveDescription}</p>
<Link href="/signup" className={cn(buttonVariants())}>{m.publicRecipe.getStartedFree}</Link>
</div>
)}
</div>
</>
);
}