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
@@ -0,0 +1,14 @@
import { PageHeaderSkeleton, InfoCardSkeleton } from "@/components/shared/skeletons";
export default function CollectionsLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={1} />
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
{Array.from({ length: 6 }).map((_, i) => (
<InfoCardSkeleton key={i} />
))}
</div>
</div>
);
}
+27
View File
@@ -0,0 +1,27 @@
"use client";
import { useEffect } from "react";
import { Button } from "@/components/ui/button";
export default function AppError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div className="flex flex-col items-center justify-center gap-4 py-24 text-center">
<h2 className="text-xl font-semibold">Something went wrong</h2>
<p className="text-muted-foreground max-w-md">
An unexpected error occurred while loading this page. You can try again, or head back
later.
</p>
<Button onClick={() => reset()}>Try again</Button>
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
import { Skeleton } from "@/components/ui/skeleton";
import { InfoCardSkeleton } from "@/components/shared/skeletons";
function ExploreSection() {
return (
<div className="space-y-4">
<Skeleton className="h-6 w-32" />
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{Array.from({ length: 4 }).map((_, i) => (
<InfoCardSkeleton key={i} />
))}
</div>
</div>
);
}
export default function ExploreLoading() {
return (
<div className="space-y-8">
<Skeleton className="h-12 w-full max-w-xl rounded-md" />
<ExploreSection />
<ExploreSection />
</div>
);
}
+11
View File
@@ -0,0 +1,11 @@
import { FeedItemSkeleton } from "@/components/shared/skeletons";
export default function FeedLoading() {
return (
<div className="max-w-2xl mx-auto space-y-8">
{Array.from({ length: 4 }).map((_, i) => (
<FeedItemSkeleton key={i} />
))}
</div>
);
}
+2 -37
View File
@@ -1,8 +1,7 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, recipes, users, userFollows, eq, desc, inArray } from "@epicure/db";
import { getPublicUrl } from "@/lib/storage";
import { db, userFollows, eq } from "@epicure/db";
import { FeedPageContent } from "@/components/feed/feed-page-content";
export const metadata: Metadata = {};
@@ -16,39 +15,5 @@ export default async function FeedPage() {
.from(userFollows)
.where(eq(userFollows.followerId, session.user.id));
const followedIds = followedRows.map((r) => r.followingId);
if (followedIds.length === 0) {
return <FeedPageContent followedCount={0} feedRecipes={[]} />;
}
const feedRecipes = await db
.select({
id: recipes.id,
title: recipes.title,
description: recipes.description,
baseServings: recipes.baseServings,
prepMins: recipes.prepMins,
cookMins: recipes.cookMins,
difficulty: recipes.difficulty,
visibility: recipes.visibility,
aiGenerated: recipes.aiGenerated,
createdAt: recipes.createdAt,
authorId: recipes.authorId,
authorName: users.name,
authorUsername: users.username,
authorAvatarUrl: users.avatarUrl,
})
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.where(inArray(recipes.authorId, followedIds))
.orderBy(desc(recipes.createdAt))
.limit(40);
return (
<FeedPageContent
followedCount={followedIds.length}
feedRecipes={feedRecipes.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() }))}
/>
);
return <FeedPageContent followedCount={followedRows.length} />;
}
+10
View File
@@ -0,0 +1,10 @@
import { PageHeaderSkeleton, RecipeCardGridSkeleton } from "@/components/shared/skeletons";
export default function AppLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={1} />
<RecipeCardGridSkeleton />
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { Skeleton } from "@/components/ui/skeleton";
import { PageHeaderSkeleton } from "@/components/shared/skeletons";
export default function MealPlanLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={4} subtitle />
<Skeleton className="h-16 w-full rounded-xl" />
<div className="grid grid-cols-1 md:grid-cols-7 gap-3">
{Array.from({ length: 7 }).map((_, i) => (
<Skeleton key={i} className="h-64 w-full rounded-xl" />
))}
</div>
</div>
);
}
+1 -1
View File
@@ -31,7 +31,7 @@ export default async function ConversationPage({ params }: Params) {
<div className="border-b p-3 flex items-center gap-3">
<Link href={`/u/${other.username}`} className="flex items-center gap-3">
<Avatar className="h-8 w-8">
{other.avatarUrl && <AvatarImage src={other.avatarUrl} />}
{other.avatarUrl && <AvatarImage src={other.avatarUrl} alt={other.name} />}
<AvatarFallback className="text-xs">{other.name.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<span className="font-medium text-sm hover:underline">{other.name}</span>
+16
View File
@@ -0,0 +1,16 @@
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
export default function AppNotFound() {
return (
<div className="flex flex-col items-center justify-center gap-4 py-24 text-center">
<h1 className="text-2xl font-bold tracking-tight">Page not found</h1>
<p className="text-muted-foreground max-w-md">
The page you&apos;re looking for doesn&apos;t exist or may have been moved.
</p>
<Link href="/recipes" className={buttonVariants({ variant: "default" })}>
Back home
</Link>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { Skeleton } from "@/components/ui/skeleton";
import { PageHeaderSkeleton, ListRowSkeleton } from "@/components/shared/skeletons";
export default function PantryLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={1} />
<Skeleton className="h-20 w-full rounded-xl" />
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
{Array.from({ length: 6 }).map((_, i) => (
<ListRowSkeleton key={i} />
))}
</div>
</div>
);
}
@@ -0,0 +1,29 @@
import { Skeleton } from "@/components/ui/skeleton";
import { ListRowSkeleton } from "@/components/shared/skeletons";
export default function RecipeDetailLoading() {
return (
<div className="max-w-4xl mx-auto space-y-8">
<div className="space-y-4">
<Skeleton className="h-9 w-2/3" />
<div className="flex items-center gap-2">
{Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="h-8 w-8 rounded-lg" />
))}
</div>
<Skeleton className="h-4 w-full max-w-lg" />
<div className="flex flex-wrap items-center gap-3">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-20" />
<Skeleton className="h-5 w-20" />
</div>
</div>
<Skeleton className="aspect-video w-full rounded-xl" />
<div className="space-y-4">
<Skeleton className="h-6 w-32" />
<ListRowSkeleton />
<ListRowSkeleton />
</div>
</div>
);
}
+13 -6
View File
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
import Image from "next/image";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import Link from "next/link";
@@ -287,11 +288,12 @@ export default async function RecipePage({ params }: Params) {
{/* Cover photo */}
{cover && (
<div className="aspect-video overflow-hidden rounded-xl bg-muted">
<img
<div className="relative aspect-video overflow-hidden rounded-xl bg-muted">
<Image
src={getPublicUrl(cover.storageKey)}
alt={recipe.title}
className="w-full h-full object-cover"
fill
className="object-cover"
/>
</div>
)}
@@ -373,9 +375,14 @@ export default async function RecipePage({ params }: Params) {
<div className="space-y-3">
<h2 className="text-xl font-semibold">Photos</h2>
<div className="grid grid-cols-3 gap-3">
{recipe.photos.map((photo) => (
<div key={photo.id} className="aspect-square rounded-lg overflow-hidden bg-muted">
<img src={getPublicUrl(photo.storageKey)} alt="" className="w-full h-full object-cover" />
{recipe.photos.map((photo, i) => (
<div key={photo.id} className="relative aspect-square rounded-lg overflow-hidden bg-muted">
<Image
src={getPublicUrl(photo.storageKey)}
alt={`${recipe.title} photo ${i + 1}`}
fill
className="object-cover"
/>
</div>
))}
</div>
+10
View File
@@ -0,0 +1,10 @@
import { PageHeaderSkeleton, RecipeCardGridSkeleton } from "@/components/shared/skeletons";
export default function RecipesLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={2} subtitle />
<RecipeCardGridSkeleton />
</div>
);
}
+64 -18
View File
@@ -1,7 +1,8 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import Link from "next/link";
import { auth } from "@/lib/auth/server";
import { db, recipes, sql } from "@epicure/db";
import { db, recipes, sql, count } from "@epicure/db";
import { eq, desc, asc, and, ilike, or } from "@epicure/db";
import { RecipesHeader } from "@/components/recipe/recipes-header";
import { RecipesEmptyState } from "@/components/recipe/recipes-empty-state";
@@ -9,12 +10,15 @@ import { RecipesGrid } from "@/components/recipe/recipes-grid";
export const metadata: Metadata = {};
const PAGE_SIZE = 24;
type SearchParams = Promise<{
q?: string;
sort?: string;
visibility?: string;
difficulty?: string;
tag?: string;
page?: string;
}>;
const SORT_MAP = {
@@ -32,10 +36,12 @@ export default async function RecipesPage({ searchParams }: { searchParams: Sear
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const { q, sort, visibility, difficulty, tag } = await searchParams;
const { q, sort, visibility, difficulty, tag, page: pageParam } = await searchParams;
const query = (q ?? "").trim().slice(0, 200);
const sortKey: SortKey = (sort && sort in SORT_MAP ? sort : "updated_desc") as SortKey;
const tagFilter = tag?.trim().slice(0, 50) || undefined;
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
const offset = (page - 1) * PAGE_SIZE;
const visibilityFilter = visibility && ["private", "unlisted", "public"].includes(visibility)
? (visibility as "private" | "unlisted" | "public")
@@ -44,32 +50,72 @@ export default async function RecipesPage({ searchParams }: { searchParams: Sear
? (difficulty as "easy" | "medium" | "hard")
: undefined;
const userRecipes = await db.query.recipes.findMany({
where: and(
eq(recipes.authorId, session.user.id),
query
? or(ilike(recipes.title, `%${query}%`), ilike(recipes.description, `%${query}%`))
: undefined,
visibilityFilter ? eq(recipes.visibility, visibilityFilter) : undefined,
difficultyFilter ? eq(recipes.difficulty, difficultyFilter) : undefined,
tagFilter ? sql`${recipes.tags} @> ARRAY[${tagFilter}]::text[]` : undefined,
),
orderBy: SORT_MAP[sortKey],
with: { photos: true },
});
const where = and(
eq(recipes.authorId, session.user.id),
query
? or(ilike(recipes.title, `%${query}%`), ilike(recipes.description, `%${query}%`))
: undefined,
visibilityFilter ? eq(recipes.visibility, visibilityFilter) : undefined,
difficultyFilter ? eq(recipes.difficulty, difficultyFilter) : undefined,
tagFilter ? sql`${recipes.tags} @> ARRAY[${tagFilter}]::text[]` : undefined,
);
const [userRecipes, totalRow] = await Promise.all([
db.query.recipes.findMany({
where,
orderBy: SORT_MAP[sortKey],
with: { photos: true },
limit: PAGE_SIZE,
offset,
}),
db.select({ count: count() }).from(recipes).where(where),
]);
const total = totalRow[0]?.count ?? 0;
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
const pageHref = (p: number) => {
const params = new URLSearchParams();
if (query) params.set("q", query);
if (sortKey !== "updated_desc") params.set("sort", sortKey);
if (visibilityFilter) params.set("visibility", visibilityFilter);
if (difficultyFilter) params.set("difficulty", difficultyFilter);
if (tagFilter) params.set("tag", tagFilter);
if (p > 1) params.set("page", String(p));
const qs = params.toString();
return qs ? `/recipes?${qs}` : "/recipes";
};
return (
<div className="space-y-6">
<RecipesHeader
count={userRecipes.length}
count={total}
initialQuery={query}
initialSort={sortKey}
initialVisibility={visibilityFilter ?? ""}
initialDifficulty={difficultyFilter ?? ""}
initialTag={tagFilter ?? ""}
/>
<RecipesEmptyState query={query} count={userRecipes.length} />
<RecipesGrid key={`${query}-${sortKey}-${visibilityFilter}-${difficultyFilter}-${tagFilter}`} recipes={userRecipes} />
<RecipesEmptyState query={query} count={total} />
<RecipesGrid key={`${query}-${sortKey}-${visibilityFilter}-${difficultyFilter}-${tagFilter}-${page}`} recipes={userRecipes} />
{totalPages > 1 && (
<div className="flex items-center justify-center gap-2 pt-2">
{page > 1 && (
<Link href={pageHref(page - 1)} className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent">
Previous
</Link>
)}
<span className="text-sm text-muted-foreground px-2">
Page {page} of {totalPages}
</span>
{page < totalPages && (
<Link href={pageHref(page + 1)} className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent">
Next
</Link>
)}
</div>
)}
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
import { Skeleton } from "@/components/ui/skeleton";
import { InfoCardSkeleton } from "@/components/shared/skeletons";
export default function SearchLoading() {
return (
<div className="max-w-5xl mx-auto space-y-6">
<div>
<Skeleton className="h-9 w-56 mb-6" />
<Skeleton className="h-12 w-full rounded-md" />
<div className="mt-3 flex flex-wrap items-center gap-3">
<Skeleton className="h-9 w-40" />
<Skeleton className="h-9 w-36" />
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{Array.from({ length: 8 }).map((_, i) => (
<InfoCardSkeleton key={i} />
))}
</div>
</div>
);
}
@@ -0,0 +1,14 @@
import { PageHeaderSkeleton, ListRowSkeleton } from "@/components/shared/skeletons";
export default function ShoppingListsLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={1} />
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
{Array.from({ length: 6 }).map((_, i) => (
<ListRowSkeleton key={i} />
))}
</div>
</div>
);
}
@@ -0,0 +1,32 @@
import { Skeleton } from "@/components/ui/skeleton";
import { SquareTileSkeleton } from "@/components/shared/skeletons";
export default function UserProfileLoading() {
return (
<div className="max-w-4xl mx-auto space-y-10">
<div className="flex flex-col sm:flex-row gap-6 items-start sm:items-center">
<Skeleton className="h-24 w-24 shrink-0 rounded-full" />
<div className="flex-1 space-y-3">
<div className="space-y-2">
<Skeleton className="h-7 w-40" />
<Skeleton className="h-4 w-24" />
</div>
<Skeleton className="h-4 w-64" />
<div className="flex flex-wrap gap-2">
<Skeleton className="h-6 w-20 rounded-full" />
<Skeleton className="h-6 w-24 rounded-full" />
<Skeleton className="h-6 w-24 rounded-full" />
</div>
</div>
</div>
<div className="space-y-4">
<Skeleton className="h-6 w-24" />
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
{Array.from({ length: 8 }).map((_, i) => (
<SquareTileSkeleton key={i} />
))}
</div>
</div>
</div>
);
}
+44 -7
View File
@@ -1,6 +1,7 @@
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import Link from "next/link";
import Image from "next/image";
import { auth } from "@/lib/auth/server";
import {
db,
@@ -20,7 +21,12 @@ import { BlockButton } from "@/components/social/block-button";
import { MessageButton } from "@/components/social/message-button";
import { getPublicUrl } from "@/lib/storage";
type Params = { params: Promise<{ username: string }> };
const PAGE_SIZE = 24;
type Params = {
params: Promise<{ username: string }>;
searchParams: Promise<{ page?: string }>;
};
export async function generateMetadata({ params }: Params) {
const { username } = await params;
@@ -28,8 +34,11 @@ export async function generateMetadata({ params }: Params) {
return { title: user ? `${user.name} (@${user.username})` : "Profile" };
}
export default async function UserProfilePage({ params }: Params) {
export default async function UserProfilePage({ params, searchParams }: Params) {
const { username } = await params;
const { page: pageParam } = await searchParams;
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
const offset = (page - 1) * PAGE_SIZE;
const session = await auth.api.getSession({ headers: await headers() });
@@ -52,7 +61,8 @@ export default async function UserProfilePage({ params }: Params) {
db.query.recipes.findMany({
where: and(eq(recipes.authorId, user.id), eq(recipes.visibility, "public")),
orderBy: desc(recipes.createdAt),
limit: 24,
limit: PAGE_SIZE,
offset,
with: {
photos: { orderBy: (t, { asc }) => asc(t.order), limit: 1 },
},
@@ -62,6 +72,7 @@ export default async function UserProfilePage({ params }: Params) {
const followerCount = followerCountRow[0]?.count ?? 0;
const followingCount = followingCountRow[0]?.count ?? 0;
const recipeCount = recipeCountRow[0]?.count ?? 0;
const totalPages = Math.max(1, Math.ceil(recipeCount / PAGE_SIZE));
let isFollowing = false;
let isBlocked = false;
@@ -148,15 +159,17 @@ export default async function UserProfilePage({ params }: Params) {
return (
<Link
key={recipe.id}
href={`/r/${recipe.id}`}
href={`/recipes/${recipe.id}`}
className="group block rounded-xl overflow-hidden border bg-card hover:shadow-md transition-shadow"
>
<div className="aspect-square bg-muted overflow-hidden">
<div className="relative aspect-square bg-muted overflow-hidden">
{cover ? (
<img
<Image
src={getPublicUrl(cover.storageKey)}
alt={recipe.title}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
fill
sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, 25vw"
className="object-cover group-hover:scale-105 transition-transform duration-200"
/>
) : (
<div className="w-full h-full flex items-center justify-center text-muted-foreground text-3xl">
@@ -171,6 +184,30 @@ export default async function UserProfilePage({ params }: Params) {
);
})}
</div>
{totalPages > 1 && (
<div className="flex items-center justify-center gap-2 pt-2">
{page > 1 && (
<Link
href={`/u/${username}${page - 1 > 1 ? `?page=${page - 1}` : ""}`}
className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent"
>
Previous
</Link>
)}
<span className="text-sm text-muted-foreground px-2">
Page {page} of {totalPages}
</span>
{page < totalPages && (
<Link
href={`/u/${username}?page=${page + 1}`}
className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent"
>
Next
</Link>
)}
</div>
)}
</div>
) : (
<div className="text-center py-16 text-muted-foreground">