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:
Arnaud
2026-07-09 21:50:35 +02:00
parent b4b964aafb
commit 362f65656b
128 changed files with 11271 additions and 970 deletions
@@ -93,7 +93,7 @@ export function AdaptRecipeButton({
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={() => setOpen(true)}>
<Button variant="ghost" size="icon" onClick={() => setOpen(true)} aria-label={t("adaptTooltip")}>
<Wand2 className="h-4 w-4" />
</Button>
} />
@@ -121,7 +121,7 @@ export function AddToShoppingListButton({
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={() => setOpen(true)}>
<Button variant="ghost" size="icon" onClick={() => setOpen(true)} aria-label={tShopping("addToList")}>
<ShoppingCart className="h-4 w-4" />
</Button>
} />
@@ -153,11 +153,13 @@ export function AddToShoppingListButton({
type="button" variant="ghost" size="icon" className="h-7 w-7"
onClick={() => setServings((s) => Math.max(1, s - 1))}
disabled={servings <= 1}
aria-label={tCommon("decrease")}
></Button>
<span className="w-8 text-center font-medium">{servings}</span>
<Button
type="button" variant="ghost" size="icon" className="h-7 w-7"
onClick={() => setServings((s) => s + 1)}
aria-label={tCommon("increase")}
>+</Button>
</div>
{scale !== 1 && (
@@ -1,6 +1,7 @@
"use client";
import { useState, useRef } from "react";
import Image from "next/image";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { Sparkles, Loader2, Camera, Type, Upload, X, Shuffle } from "lucide-react";
@@ -280,11 +281,12 @@ export function AiGenerateDialog({
onChange={handleFileChange}
/>
{photoPreview ? (
<div className="relative rounded-xl overflow-hidden border bg-muted">
<img
<div className="relative rounded-xl overflow-hidden border bg-muted aspect-video">
<Image
src={photoPreview}
alt="Dish preview"
className="w-full max-h-64 object-cover"
alt="Preview of uploaded dish photo for AI recipe generation"
fill
className="object-cover"
/>
<button
onClick={() => { setPhotoPreview(null); setPhotoBase64(null); }}
@@ -1,6 +1,7 @@
"use client";
import Link from "next/link";
import Image from "next/image";
import { useTranslations } from "next-intl";
import { Package, Clock } from "lucide-react";
import { Badge } from "@/components/ui/badge";
@@ -36,7 +37,9 @@ function RecipeRow({ s }: { s: ScoredItem }) {
className="flex items-center gap-4 rounded-xl border p-3 hover:bg-accent transition-colors"
>
{cover ? (
<img src={cover.url} alt="" className="h-14 w-14 rounded-lg object-cover shrink-0" />
<div className="relative h-14 w-14 rounded-lg overflow-hidden shrink-0">
<Image src={cover.url} alt={s.recipe.title} fill className="object-cover" />
</div>
) : (
<div className="h-14 w-14 rounded-lg bg-muted shrink-0" />
)}
@@ -52,6 +52,7 @@ export function DeleteRecipeButton({ recipeId }: { recipeId: string }) {
size="icon"
className={cn("text-destructive hover:text-destructive")}
onClick={() => setOpen(true)}
aria-label={tCommon("delete")}
>
<Trash2 className="h-4 w-4" />
</Button>
@@ -81,7 +81,7 @@ export function DrinkPairingButton({ recipeId }: { recipeId: string }) {
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={handleOpen}>
<Button variant="ghost" size="icon" onClick={handleOpen} aria-label={t("drinksTooltip")}>
<Wine className="h-4 w-4" />
</Button>
} />
@@ -141,7 +141,7 @@ export function MealPairingButton({ recipeId }: { recipeId: string }) {
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={() => { setOpen(true); if (pairings.length === 0) suggest(); }}>
<Button variant="ghost" size="icon" onClick={() => { setOpen(true); if (pairings.length === 0) suggest(); }} aria-label={t("pairMealTooltip")}>
<UtensilsCrossed className="h-4 w-4" />
</Button>
} />
@@ -1,6 +1,7 @@
"use client";
import { useState, useRef } from "react";
import Image from "next/image";
import { useTranslations } from "next-intl";
import { Upload, X, Star } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -32,7 +33,7 @@ export function PhotoUploader({
const res = await fetch("/api/v1/upload/presign", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ recipeId, contentType: file.type }),
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 };
@@ -61,11 +62,12 @@ export function PhotoUploader({
<div className="space-y-3">
<div className="flex flex-wrap gap-3">
{photos.map((photo) => (
<div key={photo.key} className="relative group">
<img
<div key={photo.key} className="relative group h-24 w-24">
<Image
src={photo.preview || getPublicUrl(photo.key)}
alt=""
className={`h-24 w-24 rounded-lg object-cover border-2 ${
alt="Recipe photo"
fill
className={`rounded-lg object-cover border-2 ${
photo.isCover ? "border-primary" : "border-transparent"
}`}
/>
+1 -1
View File
@@ -16,7 +16,7 @@ export function PrintButton({ recipeId }: { recipeId: string }) {
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={handlePrint}>
<Button variant="ghost" size="icon" onClick={handlePrint} aria-label={t("print")}>
<Printer className="h-4 w-4" />
</Button>
} />
+6 -3
View File
@@ -1,6 +1,7 @@
"use client";
import Link from "next/link";
import Image from "next/image";
import { useTranslations } from "next-intl";
import { Clock, Users, Lock, Globe, Link2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
@@ -42,11 +43,13 @@ export function RecipeCard({ recipe }: { recipe: Recipe }) {
<Link href={`/recipes/${recipe.id}`}>
<Card className="group overflow-hidden hover:shadow-md transition-shadow h-full flex flex-col">
{cover ? (
<div className="aspect-video overflow-hidden bg-muted">
<img
<div className="relative aspect-video overflow-hidden bg-muted">
<Image
src={getPublicUrl(cover.storageKey)}
alt={recipe.title}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
fill
sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw"
className="object-cover group-hover:scale-105 transition-transform duration-300"
/>
</div>
) : (
@@ -170,7 +170,7 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
className="flex-1"
autoComplete="off"
/>
<Button type="submit" size="icon" disabled={loading || !input.trim()}>
<Button type="submit" size="icon" disabled={loading || !input.trim()} aria-label={t("send")}>
<Send className="h-4 w-4" />
</Button>
</form>
+110 -18
View File
@@ -1,6 +1,6 @@
"use client";
import { useState, useRef, KeyboardEvent } from "react";
import { useState, useRef, useEffect, KeyboardEvent } from "react";
import { useRouter } from "next/navigation";
import { Plus, Trash2, GripVertical, X, Tag } from "lucide-react";
import { toast } from "sonner";
@@ -10,6 +10,16 @@ import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { DietaryTagPicker } from "./dietary-tag-picker";
import { PhotoUploader, type PhotoEntry } from "./photo-uploader";
@@ -90,6 +100,51 @@ export function RecipeForm({ recipeId, defaultValues }: RecipeFormProps) {
);
const [photos, setPhotos] = useState<PhotoEntry[]>(defaultValues?.photos ?? []);
const [saving, setSaving] = useState(false);
const [dirty, setDirty] = useState(false);
const [discardConfirmOpen, setDiscardConfirmOpen] = useState(false);
const hasMountedRef = useRef(false);
// Mark the form dirty on any edit after the initial mount, so we can warn the
// user before they navigate away and silently lose their changes.
useEffect(() => {
if (!hasMountedRef.current) {
hasMountedRef.current = true;
return;
}
setDirty(true);
}, [
title,
description,
baseServings,
visibility,
difficulty,
prepMins,
cookMins,
tags,
dietaryTags,
ingredients,
steps,
photos,
]);
// Browser-level guard: warn on tab close / reload / external navigation while dirty.
useEffect(() => {
if (!dirty || saving) return;
function handleBeforeUnload(e: BeforeUnloadEvent) {
e.preventDefault();
e.returnValue = "";
}
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [dirty, saving]);
function handleCancelClick() {
if (dirty) {
setDiscardConfirmOpen(true);
} else {
router.back();
}
}
function updateIngredient(i: number, patch: Partial<IngredientRow>) {
setIngredients((prev) => prev.map((row, idx) => idx === i ? { ...row, ...patch } : row));
@@ -134,6 +189,34 @@ export function RecipeForm({ recipeId, defaultValues }: RecipeFormProps) {
return;
}
const filteredIngredients = ingredients
.filter((ing) => ing.rawName.trim())
.map((ing, i) => ({
rawName: ing.rawName.trim(),
quantity: ing.quantity.trim() || undefined,
unit: ing.unit.trim() || undefined,
note: ing.note.trim() || undefined,
order: i,
}));
if (filteredIngredients.length === 0) {
toast.error(t("ingredientsRequired"));
return;
}
const filteredSteps = steps
.filter((s) => s.instruction.trim())
.map((s, i) => ({
instruction: s.instruction.trim(),
timerSeconds: s.timerSeconds ? parseInt(s.timerSeconds) : undefined,
order: i,
}));
if (filteredSteps.length === 0) {
toast.error(t("stepsRequired"));
return;
}
setSaving(true);
try {
const payload = {
@@ -146,22 +229,8 @@ export function RecipeForm({ recipeId, defaultValues }: RecipeFormProps) {
cookMins: cookMins ? parseInt(cookMins) : undefined,
tags,
dietaryTags,
ingredients: ingredients
.filter((ing) => ing.rawName.trim())
.map((ing, i) => ({
rawName: ing.rawName.trim(),
quantity: ing.quantity.trim() || undefined,
unit: ing.unit.trim() || undefined,
note: ing.note.trim() || undefined,
order: i,
})),
steps: steps
.filter((s) => s.instruction.trim())
.map((s, i) => ({
instruction: s.instruction.trim(),
timerSeconds: s.timerSeconds ? parseInt(s.timerSeconds) : undefined,
order: i,
})),
ingredients: filteredIngredients,
steps: filteredSteps,
};
const url = isEdit ? `/api/v1/recipes/${id}` : "/api/v1/recipes";
@@ -181,6 +250,7 @@ export function RecipeForm({ recipeId, defaultValues }: RecipeFormProps) {
const saved = await res.json() as { id: string };
toast.success(isEdit ? t("updateSuccess") : t("createSuccess"));
setDirty(false);
router.push(`/recipes/${saved.id}`);
router.refresh();
} finally {
@@ -443,10 +513,32 @@ export function RecipeForm({ recipeId, defaultValues }: RecipeFormProps) {
<Button type="submit" disabled={saving}>
{saving ? t("saving") : isEdit ? t("saveChanges") : t("createRecipe")}
</Button>
<Button type="button" variant="outline" onClick={() => router.back()}>
<Button type="button" variant="outline" onClick={handleCancelClick}>
{t_common("cancel")}
</Button>
</div>
<AlertDialog open={discardConfirmOpen} onOpenChange={setDiscardConfirmOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("discardChangesTitle")}</AlertDialogTitle>
<AlertDialogDescription>{t("discardChangesDescription")}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t("keepEditing")}</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
setDiscardConfirmOpen(false);
setDirty(false);
router.back();
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{t("discardChanges")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</form>
);
}
+35 -4
View File
@@ -1,6 +1,7 @@
"use client";
import { useState, useCallback, useEffect } from "react";
import Image from "next/image";
import { useTranslations } from "next-intl";
import { Trash2, Globe, Lock, Link2, X, Check, ListChecks, LayoutGrid, List, Rows3, FolderPlus } from "lucide-react";
import { AddToCollectionDialog } from "@/components/recipe/add-to-collection-dialog";
@@ -11,6 +12,16 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { toast } from "sonner";
import { getPublicUrl } from "@/lib/storage";
@@ -45,11 +56,13 @@ function RecipeThumb({ recipe, selectMode, selected, className }: { recipe: Reci
return (
<div className={cn("relative overflow-hidden bg-muted shrink-0", className)}>
{cover ? (
<img
<Image
src={getPublicUrl(cover.storageKey)}
alt={recipe.title}
fill
sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"
className={cn(
"w-full h-full object-cover transition-transform duration-300",
"object-cover transition-transform duration-300",
!selectMode && "group-hover:scale-105",
selectMode && selected && "brightness-75"
)}
@@ -264,6 +277,7 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
const [busy, setBusy] = useState(false);
const [viewMode, setViewMode] = useState<ViewMode>("grid");
const [addToCollectionOpen, setAddToCollectionOpen] = useState(false);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
useEffect(() => {
const stored = localStorage.getItem(VIEW_STORAGE_KEY) as ViewMode | null;
@@ -293,7 +307,6 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
};
async function bulkDelete() {
if (!confirm(t("bulkDeleteConfirm", { count: selected.size }))) return;
setBusy(true);
try {
const res = await fetch("/api/v1/recipes/bulk", {
@@ -415,7 +428,7 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
<FolderPlus className="h-4 w-4" />
{t("addToCollection")}
</Button>
<Button variant="destructive" size="sm" onClick={() => { void bulkDelete(); }} disabled={busy} className="gap-1.5">
<Button variant="destructive" size="sm" onClick={() => setDeleteConfirmOpen(true)} disabled={busy} className="gap-1.5">
<Trash2 className="h-4 w-4" />
{tCommon("delete")}
</Button>
@@ -429,6 +442,24 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
recipeIds={[...selected]}
onDone={exitSelect}
/>
<AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("bulkDeleteConfirmTitle", { count: selected.size })}</AlertDialogTitle>
<AlertDialogDescription>{t("bulkDeleteConfirmDescription")}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{tCommon("cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={() => { setDeleteConfirmOpen(false); void bulkDelete(); }}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{tCommon("delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
@@ -0,0 +1,77 @@
"use client";
import Link from "next/link";
import { useTranslations } from "next-intl";
import { Badge } from "@/components/ui/badge";
import { Clock, ChefHat } from "lucide-react";
import { cn } from "@/lib/utils";
const DIFFICULTY_COLORS: Record<string, string> = {
easy: "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",
medium: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200",
hard: "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200",
};
export type SearchResultRecipe = {
id: string;
title: string;
description?: string | null;
difficulty: string | null;
prepMins: number | null;
cookMins: number | null;
authorName: string | null;
};
/**
* Shared card for lightweight recipe search results (no cover photo/visibility
* data available) — used by the search and explore pages, which previously
* each had their own near-identical inline copy of this component.
*/
export function SearchResultCard({ recipe, className }: { recipe: SearchResultRecipe; className?: string }) {
const t = useTranslations("recipe");
const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
const difficultyLabel = recipe.difficulty === "easy" || recipe.difficulty === "medium" || recipe.difficulty === "hard"
? t(`difficulty.${recipe.difficulty}`)
: recipe.difficulty;
return (
<Link
href={`/recipes/${recipe.id}`}
className={cn(
"group block rounded-lg border bg-card p-4 shadow-sm transition-shadow hover:shadow-md",
className
)}
>
<div className="flex items-start justify-between gap-2">
<h3 className="font-semibold text-card-foreground group-hover:text-primary line-clamp-2 flex-1">
{recipe.title}
</h3>
{recipe.difficulty && (
<Badge
variant="secondary"
className={`shrink-0 capitalize text-xs ${DIFFICULTY_COLORS[recipe.difficulty] ?? ""}`}
>
{difficultyLabel}
</Badge>
)}
</div>
{recipe.description && (
<p className="mt-1 text-sm text-muted-foreground line-clamp-2">{recipe.description}</p>
)}
<div className="mt-3 flex items-center gap-3 text-xs text-muted-foreground">
{totalMins > 0 && (
<span className="flex items-center gap-1">
<Clock className="h-3.5 w-3.5" />
{t("total", { mins: totalMins })}
</span>
)}
{recipe.authorName && (
<span className="flex items-center gap-1">
<ChefHat className="h-3.5 w-3.5" />
{recipe.authorName}
</span>
)}
</div>
</Link>
);
}
@@ -28,7 +28,7 @@ export function ShareRecipeButton({ recipeId, visibility }: { recipeId: string;
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={() => void handleShare()}>
<Button variant="ghost" size="icon" onClick={() => void handleShare()} aria-label={t("share")}>
<Share2 className="h-4 w-4" />
</Button>
} />
@@ -69,7 +69,7 @@ export function TranslateButton({ recipeId }: { recipeId: string }) {
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={() => setOpen(true)}>
<Button variant="ghost" size="icon" onClick={() => setOpen(true)} aria-label={tRecipe("translateTooltip")}>
<Languages className="h-4 w-4" />
</Button>
} />
@@ -32,7 +32,7 @@ export function VariationsButton({
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={() => setOpen(true)}>
<Button variant="ghost" size="icon" onClick={() => setOpen(true)} aria-label={t("variationsTooltip")}>
<GitBranch className="h-4 w-4" />
</Button>
} />
@@ -133,7 +133,7 @@ export function VersionHistoryButton({
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={() => handleOpen(true)}>
<Button variant="ghost" size="icon" onClick={() => handleOpen(true)} aria-label={t("historyTooltip")}>
<History className="h-4 w-4" />
</Button>
} />
@@ -175,6 +175,7 @@ export function VersionHistoryButton({
size="icon"
className="h-7 w-7 shrink-0 sm:hidden"
title={tForm("expand")}
aria-label={tForm("expand")}
onClick={() => void handleExpand(v)}
>
<ChevronDown className={`h-4 w-4 transition-transform ${isExpanded ? "rotate-180" : ""}`} />
@@ -186,6 +187,7 @@ export function VersionHistoryButton({
size="icon"
className="h-7 w-7 shrink-0 hidden sm:inline-flex"
title={tForm("expand")}
aria-label={tForm("expand")}
onClick={() => void handleExpand(v)}
>
<ChevronDown className={`h-4 w-4 transition-transform ${isExpanded ? "rotate-180" : ""}`} />