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
+84 -49
View File
@@ -1,12 +1,15 @@
"use client";
import { useState, useEffect } from "react";
import { useState, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl";
import Link from "next/link";
import { Clock, Users, ChefHat, Flame, Heart, Sparkles } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useLocale } from "@/lib/i18n/provider";
const PAGE_SIZE = 20;
type FeedRecipe = {
id: string;
title: string;
@@ -25,9 +28,15 @@ type FeedRecipe = {
favoriteCount?: number;
};
type FeedResponse = {
data: FeedRecipe[];
total: number;
limit: number;
offset: number;
};
type Props = {
followedCount: number;
feedRecipes: FeedRecipe[];
};
function RecipeCard({ recipe, locale }: { recipe: FeedRecipe; locale: string }) {
@@ -35,7 +44,7 @@ function RecipeCard({ recipe, locale }: { recipe: FeedRecipe; locale: string })
<article className="rounded-xl border p-4 hover:shadow-sm transition-shadow">
<div className="flex items-center gap-3 mb-3">
<Avatar className="h-7 w-7">
<AvatarImage src={recipe.authorAvatarUrl ?? ""} />
<AvatarImage src={recipe.authorAvatarUrl ?? ""} alt={recipe.authorName} />
<AvatarFallback className="text-xs">{recipe.authorName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex items-baseline gap-2 text-sm">
@@ -57,7 +66,7 @@ function RecipeCard({ recipe, locale }: { recipe: FeedRecipe; locale: string })
</div>
</div>
<Link href={`/r/${recipe.id}`} className="group block space-y-2">
<Link href={`/recipes/${recipe.id}`} className="group block space-y-2">
<h2 className="font-semibold text-lg group-hover:text-primary transition-colors">{recipe.title}</h2>
{recipe.description && (
<p className="text-sm text-muted-foreground line-clamp-2">{recipe.description}</p>
@@ -73,61 +82,93 @@ function RecipeCard({ recipe, locale }: { recipe: FeedRecipe; locale: string })
);
}
function TrendingTab() {
/** Shared paginated tab: fetches `endpoint`, supports "load more", and surfaces network
* failures as a real error state (with retry) instead of silently rendering an empty list. */
function PaginatedFeedTab({
endpoint,
emptyMessage,
}: {
endpoint: string;
emptyMessage: string;
}) {
const { locale } = useLocale();
const t = useTranslations("feed");
const [recipes, setRecipes] = useState<FeedRecipe[]>([]);
const [total, setTotal] = useState(0);
const [offset, setOffset] = useState(0);
const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState(false);
const fetchPage = useCallback(
async (off: number, append: boolean) => {
if (append) setLoadingMore(true);
else setLoading(true);
setError(false);
try {
const res = await fetch(`${endpoint}?limit=${PAGE_SIZE}&offset=${off}`);
if (!res.ok) throw new Error("Request failed");
const json = (await res.json()) as FeedResponse;
setRecipes((prev) => (append ? [...prev, ...json.data] : json.data));
setTotal(json.total);
setOffset(off + json.data.length);
} catch {
setError(true);
} finally {
setLoading(false);
setLoadingMore(false);
}
},
[endpoint]
);
useEffect(() => {
fetch("/api/v1/feed/trending")
.then((r) => r.json() as Promise<{ data: FeedRecipe[] }>)
.then(({ data }) => setRecipes(data))
.catch(() => {})
.finally(() => setLoading(false));
}, []);
void fetchPage(0, false);
}, [fetchPage]);
if (loading) return <p className="text-sm text-muted-foreground">{t("loading")}</p>;
if (recipes.length === 0) return <p className="text-sm text-muted-foreground">{t("trendingEmpty")}</p>;
if (error && recipes.length === 0) {
return (
<div className="flex flex-col items-start gap-2">
<p className="text-sm text-destructive">{t("loadFailed")}</p>
<Button variant="outline" size="sm" onClick={() => void fetchPage(0, false)}>
{t("retry")}
</Button>
</div>
);
}
if (recipes.length === 0) return <p className="text-sm text-muted-foreground">{emptyMessage}</p>;
const hasMore = recipes.length < total;
return (
<div className="space-y-4">
{recipes.map((recipe) => (
<RecipeCard key={recipe.id} recipe={recipe} locale={locale} />
))}
{error && (
<p className="text-sm text-destructive">{t("loadFailed")}</p>
)}
{hasMore || error ? (
<div className="flex justify-center pt-2">
<Button
variant="outline"
size="sm"
onClick={() => void fetchPage(offset, true)}
disabled={loadingMore}
>
{loadingMore ? t("loading") : error ? t("retry") : t("loadMore")}
</Button>
</div>
) : null}
</div>
);
}
function ForYouTab() {
const { locale } = useLocale();
export function FeedPageContent({ followedCount }: Props) {
const t = useTranslations("feed");
const [recipes, setRecipes] = useState<FeedRecipe[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("/api/v1/feed/for-you")
.then((r) => r.json() as Promise<{ data: FeedRecipe[] }>)
.then(({ data }) => setRecipes(data))
.catch(() => {})
.finally(() => setLoading(false));
}, []);
if (loading) return <p className="text-sm text-muted-foreground">{t("loading")}</p>;
if (recipes.length === 0) return <p className="text-sm text-muted-foreground">{t("forYouEmpty")}</p>;
return (
<div className="space-y-4">
{recipes.map((recipe) => (
<RecipeCard key={recipe.id} recipe={recipe} locale={locale} />
))}
</div>
);
}
export function FeedPageContent({ followedCount, feedRecipes }: Props) {
const t = useTranslations("feed");
const { locale } = useLocale();
const [tab, setTab] = useState<"following" | "trending" | "forYou">("following");
return (
@@ -175,19 +216,13 @@ export function FeedPageContent({ followedCount, feedRecipes }: Props) {
<div className="flex flex-col items-center justify-center h-64 border-2 border-dashed rounded-xl gap-4">
<p className="text-muted-foreground text-sm">{t("followEmpty")}</p>
</div>
) : feedRecipes.length === 0 ? (
<p className="text-muted-foreground text-sm">{t("noNew")}</p>
) : (
<div className="space-y-4">
{feedRecipes.map((recipe) => (
<RecipeCard key={recipe.id} recipe={recipe} locale={locale} />
))}
</div>
<PaginatedFeedTab endpoint="/api/v1/feed" emptyMessage={t("noNew")} />
)
) : tab === "trending" ? (
<TrendingTab />
<PaginatedFeedTab endpoint="/api/v1/feed/trending" emptyMessage={t("trendingEmpty")} />
) : (
<ForYouTab />
<PaginatedFeedTab endpoint="/api/v1/feed/for-you" emptyMessage={t("forYouEmpty")} />
)}
</div>
);