Files
Epicure/apps/web/app/r/[id]/page.tsx
T
Arnaud 362f65656b 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>
2026-07-09 21:50:35 +02:00

175 lines
7.4 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 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) }} />
<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 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}
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>
</>
);
}