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
+43 -13
View File
@@ -2,9 +2,20 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Ban } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
export function BlockButton({
targetUsername,
@@ -14,13 +25,13 @@ export function BlockButton({
initialBlocked?: boolean;
}) {
const router = useRouter();
const t = useTranslations("social");
const tCommon = useTranslations("common");
const [blocked, setBlocked] = useState(initialBlocked);
const [loading, setLoading] = useState(false);
const [confirmOpen, setConfirmOpen] = useState(false);
async function toggle() {
if (!blocked && !confirm(`Block @${targetUsername}? They won't be able to follow you or comment on your recipes.`)) {
return;
}
setLoading(true);
try {
const res = await fetch(`/api/v1/users/${targetUsername}/block`, {
@@ -40,15 +51,34 @@ export function BlockButton({
}
return (
<Button
variant="outline"
size="sm"
onClick={() => { void toggle(); }}
disabled={loading}
className={blocked ? "" : "text-destructive hover:text-destructive"}
>
<Ban className="h-3.5 w-3.5" />
{loading ? "…" : blocked ? "Unblock" : "Block"}
</Button>
<>
<Button
variant="outline"
size="sm"
onClick={() => (blocked ? void toggle() : setConfirmOpen(true))}
disabled={loading}
className={blocked ? "" : "text-destructive hover:text-destructive"}
>
<Ban className="h-3.5 w-3.5" />
{loading ? "…" : blocked ? "Unblock" : "Block"}
</Button>
<AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("blockConfirmTitle", { username: targetUsername })}</AlertDialogTitle>
<AlertDialogDescription>{t("blockConfirmDescription")}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{tCommon("cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={() => { setConfirmOpen(false); void toggle(); }}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{t("blockConfirmAction")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
@@ -9,6 +9,16 @@ import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { CommentReactions } from "@/components/social/comment-reactions";
import { ReportButton } from "@/components/social/report-button";
import { cn } from "@/lib/utils";
@@ -24,6 +34,15 @@ type Comment = {
userAvatarUrl: string | null;
};
const COMMENTS_PAGE_SIZE = 20;
type CommentsResponse = {
data: Comment[];
total: number;
limit: number;
offset: number;
};
const MAX_VISUAL_INDENT = 4;
const MENTION_REGEX = /@([a-z0-9_-]{3,30})/gi;
@@ -125,6 +144,7 @@ function CommentItem({
onRefresh: () => void;
}) {
const [showReply, setShowReply] = useState(false);
const [confirmOpen, setConfirmOpen] = useState(false);
const isOwn = comment.userId === currentUserId;
const t = useTranslations("social");
const tCommon = useTranslations("common");
@@ -141,7 +161,7 @@ function CommentItem({
<div className={cn("space-y-3", indented && "ml-10 border-l pl-4")}>
<div className="flex gap-3">
<Avatar className={cn("shrink-0 mt-0.5", depth === 0 ? "h-7 w-7" : "h-6 w-6")}>
<AvatarImage src={comment.userAvatarUrl ?? ""} />
<AvatarImage src={comment.userAvatarUrl ?? ""} alt={comment.userName} />
<AvatarFallback className="text-xs">{comment.userName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0 space-y-1">
@@ -165,13 +185,30 @@ function CommentItem({
)}
{isOwn && (
<button
onClick={deleteComment}
onClick={() => setConfirmOpen(true)}
className="text-xs text-muted-foreground hover:text-destructive flex items-center gap-1"
>
<Trash2 className="h-3 w-3" /> {tCommon("delete")}
</button>
)}
</div>
<AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("deleteCommentTitle")}</AlertDialogTitle>
<AlertDialogDescription>{t("deleteCommentDescription")}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{tCommon("cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={() => { void deleteComment(); }}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{tCommon("delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{showReply && (
<CommentForm
recipeId={recipeId}
@@ -212,15 +249,40 @@ export function CommentsSection({
}) {
const [comments, setComments] = useState<Comment[]>([]);
const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [topLevelOffset, setTopLevelOffset] = useState(0);
const [topLevelTotal, setTopLevelTotal] = useState(0);
const t = useTranslations("social");
const tCommon = useTranslations("common");
// Full reload from the first page — used on mount and after any mutation (post/reply/delete)
// so the thread stays consistent rather than trying to patch pagination state in place.
const load = useCallback(async () => {
const res = await fetch(`/api/v1/recipes/${recipeId}/comments`);
if (res.ok) setComments(await res.json() as Comment[]);
const res = await fetch(`/api/v1/recipes/${recipeId}/comments?limit=${COMMENTS_PAGE_SIZE}&offset=0`);
if (res.ok) {
const json = await res.json() as CommentsResponse;
setComments(json.data);
setTopLevelTotal(json.total);
setTopLevelOffset(json.data.filter((c) => !c.parentId).length);
}
setLoading(false);
}, [recipeId]);
const loadMore = useCallback(async () => {
setLoadingMore(true);
try {
const res = await fetch(`/api/v1/recipes/${recipeId}/comments?limit=${COMMENTS_PAGE_SIZE}&offset=${topLevelOffset}`);
if (res.ok) {
const json = await res.json() as CommentsResponse;
setComments((prev) => [...prev, ...json.data]);
setTopLevelTotal(json.total);
setTopLevelOffset((prev) => prev + json.data.filter((c) => !c.parentId).length);
}
} finally {
setLoadingMore(false);
}
}, [recipeId, topLevelOffset]);
useEffect(() => { void load(); }, [load]);
const { topLevel, childrenByParent } = useMemo(() => {
@@ -269,6 +331,13 @@ export function CommentsSection({
/>
</div>
))}
{topLevelOffset < topLevelTotal && (
<div className="flex justify-center pt-2">
<Button size="sm" variant="outline" onClick={() => void loadMore()} disabled={loadingMore}>
{loadingMore ? t("loadingMoreComments") : t("loadMoreComments")}
</Button>
</div>
)}
</div>
)}
</div>
@@ -54,7 +54,7 @@ export function ConversationsList() {
)}
>
<Avatar className="h-10 w-10 shrink-0">
{c.otherUser?.avatarUrl && <AvatarImage src={c.otherUser.avatarUrl} />}
{c.otherUser?.avatarUrl && <AvatarImage src={c.otherUser.avatarUrl} alt={c.otherUser.name ?? ""} />}
<AvatarFallback>{(c.otherUser?.name ?? "?").slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
+16 -11
View File
@@ -1,6 +1,7 @@
"use client";
import { useState, useEffect, useRef } from "react";
import Image from "next/image";
import { useTranslations, useLocale } from "next-intl";
import { Star, Camera, X, ChefHat } from "lucide-react";
import { toast } from "sonner";
@@ -86,7 +87,7 @@ export function CookedItReview({
const res = await fetch("/api/v1/upload/presign", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ recipeId, contentType: file.type, purpose: "review" }),
body: JSON.stringify({ recipeId, contentType: file.type, purpose: "review", fileSize: file.size }),
});
if (!res.ok) {
toast.error(t("reviewPhotoFailed"));
@@ -143,11 +144,12 @@ export function CookedItReview({
/>
<div className="flex items-center gap-3">
{(preview || photoKey) && (
<div className="relative">
<img
<div className="relative h-16 w-16">
<Image
src={preview ?? getPublicUrl(photoKey!)}
alt=""
className="h-16 w-16 rounded-lg object-cover border"
alt="Your cooked-it photo"
fill
className="rounded-lg object-cover border"
/>
<button
type="button"
@@ -187,7 +189,7 @@ export function CookedItReview({
{reviews.map((r) => (
<div key={r.id} className="flex gap-3">
<Avatar className="h-8 w-8">
<AvatarImage src={r.user.avatarUrl ?? undefined} />
<AvatarImage src={r.user.avatarUrl ?? undefined} alt={r.user.name} />
<AvatarFallback>{r.user.name.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 space-y-1.5">
@@ -204,11 +206,14 @@ export function CookedItReview({
</div>
{r.reviewText && <p className="text-sm text-muted-foreground">{r.reviewText}</p>}
{r.photoKey && (
<img
src={getPublicUrl(r.photoKey)}
alt=""
className="h-32 w-32 rounded-lg object-cover border"
/>
<div className="relative h-32 w-32">
<Image
src={getPublicUrl(r.photoKey)}
alt={`${r.user.name}'s cooked-it photo`}
fill
className="rounded-lg object-cover border"
/>
</div>
)}
</div>
</div>
+18 -4
View File
@@ -1,7 +1,9 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { Heart } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
@@ -13,17 +15,23 @@ export function FavoriteButton({
recipeId: string;
initialFavorited?: boolean;
}) {
const tCommon = useTranslations("common");
const tSocial = useTranslations("social");
const [favorited, setFavorited] = useState(initialFavorited);
const [loading, setLoading] = useState(false);
async function toggle() {
const next = !favorited;
setFavorited(next);
setLoading(true);
try {
const res = await fetch(`/api/v1/recipes/${recipeId}/favorite`, {
method: favorited ? "DELETE" : "POST",
method: next ? "POST" : "DELETE",
});
if (!res.ok) return;
setFavorited(!favorited);
if (!res.ok) throw new Error();
} catch {
setFavorited(!next);
toast.error(tCommon("updateFailed"));
} finally {
setLoading(false);
}
@@ -33,7 +41,13 @@ export function FavoriteButton({
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={toggle} disabled={loading}>
<Button
variant="ghost"
size="icon"
onClick={toggle}
disabled={loading}
aria-label={favorited ? tSocial("favoriteRemove") : tSocial("favoriteAdd")}
>
<Heart className={cn("h-4 w-4", favorited && "fill-red-500 text-red-500")} />
</Button>
} />
+9 -6
View File
@@ -17,18 +17,21 @@ export function FollowButton({
const [loading, setLoading] = useState(false);
async function toggle() {
const next = !following;
setFollowing(next);
setLoading(true);
try {
const res = await fetch(`/api/v1/users/${targetUsername}/follow`, {
method: following ? "DELETE" : "POST",
method: next ? "POST" : "DELETE",
});
if (!res.ok) {
const err = await res.json() as { error?: string };
toast.error(err.error ?? "Failed");
return;
throw new Error(err.error);
}
setFollowing(!following);
toast.success(following ? "Unfollowed" : "Following");
toast.success(next ? "Following" : "Unfollowed");
} catch (err) {
setFollowing(!next);
toast.error(err instanceof Error && err.message ? err.message : "Failed");
} finally {
setLoading(false);
}
@@ -36,7 +39,7 @@ export function FollowButton({
return (
<Button variant={following ? "outline" : "default"} size="sm" onClick={toggle} disabled={loading}>
{loading ? "…" : following ? "Following" : "Follow"}
{following ? "Following" : "Follow"}
</Button>
);
}
+66 -16
View File
@@ -25,19 +25,50 @@ export function MessageThread({
const t = useTranslations("messages");
const [messages, setMessages] = useState<Message[]>([]);
const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [nextCursor, setNextCursor] = useState<string | null>(null);
const [content, setContent] = useState("");
const [sending, setSending] = useState(false);
const bottomRef = useRef<HTMLDivElement>(null);
// Loads the latest page of messages. On the very first load this replaces
// the (empty) list outright; on subsequent polls it merges in only the
// messages we don't already have, so it doesn't clobber older history the
// user paged back through via loadMore().
const load = useCallback(async () => {
const res = await fetch(`/api/v1/conversations/${conversationId}/messages`);
if (res.ok) {
const data = (await res.json()) as { messages: Message[] };
setMessages(data.messages);
const data = (await res.json()) as { messages: Message[]; nextCursor: string | null };
setMessages((prev) => {
if (prev.length === 0) return data.messages;
const existingIds = new Set(prev.map((m) => m.id));
const fresh = data.messages.filter((m) => !existingIds.has(m.id));
return fresh.length > 0 ? [...prev, ...fresh] : prev;
});
setNextCursor((prev) => prev ?? data.nextCursor);
}
setLoading(false);
}, [conversationId]);
// Loads an older page (before the oldest message currently loaded) and
// prepends it, using the server-provided cursor.
const loadMore = useCallback(async () => {
if (!nextCursor || loadingMore) return;
setLoadingMore(true);
try {
const res = await fetch(
`/api/v1/conversations/${conversationId}/messages?before=${encodeURIComponent(nextCursor)}`
);
if (res.ok) {
const data = (await res.json()) as { messages: Message[]; nextCursor: string | null };
setMessages((prev) => [...data.messages, ...prev]);
setNextCursor(data.nextCursor);
}
} finally {
setLoadingMore(false);
}
}, [conversationId, nextCursor, loadingMore]);
useEffect(() => {
void load();
const interval = setInterval(() => { void load(); }, 5000);
@@ -77,21 +108,35 @@ export function MessageThread({
) : messages.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-8">{t("noMessagesYet")}</p>
) : (
messages.map((m) => {
const isOwn = m.senderId === currentUserId;
return (
<div key={m.id} className={cn("flex", isOwn ? "justify-end" : "justify-start")}>
<div
className={cn(
"max-w-[70%] rounded-2xl px-4 py-2 text-sm whitespace-pre-wrap",
isOwn ? "bg-primary text-primary-foreground" : "bg-muted"
)}
<>
{nextCursor && (
<div className="flex justify-center pb-2">
<Button
variant="ghost"
size="sm"
onClick={() => { void loadMore(); }}
disabled={loadingMore}
>
{m.content}
</div>
{loadingMore ? t("loadingOlder") : t("loadOlder")}
</Button>
</div>
);
})
)}
{messages.map((m) => {
const isOwn = m.senderId === currentUserId;
return (
<div key={m.id} className={cn("flex", isOwn ? "justify-end" : "justify-start")}>
<div
className={cn(
"max-w-[70%] rounded-2xl px-4 py-2 text-sm whitespace-pre-wrap",
isOwn ? "bg-primary text-primary-foreground" : "bg-muted"
)}
>
{m.content}
</div>
</div>
);
})}
</>
)}
<div ref={bottomRef} />
</div>
@@ -109,7 +154,12 @@ export function MessageThread({
rows={1}
className="resize-none"
/>
<Button size="icon" onClick={() => { void send(); }} disabled={!content.trim() || sending}>
<Button
size="icon"
aria-label={t("send")}
onClick={() => { void send(); }}
disabled={!content.trim() || sending}
>
<Send className="h-4 w-4" />
</Button>
</div>
@@ -27,7 +27,7 @@ export function MessagesNavLink() {
}, []);
return (
<Button variant="ghost" size="icon" className="relative" nativeButton={false} render={<Link href="/messages" />}>
<Button variant="ghost" size="icon" className="relative" nativeButton={false} aria-label="Messages" render={<Link href="/messages" />}>
<MessageCircle className="h-4 w-4" />
{unreadTotal > 0 && (
<Badge
@@ -64,7 +64,7 @@ export function NotificationBell() {
return (
<DropdownMenu open={open} onOpenChange={(next) => { setOpen(next); if (next) void load(); }}>
<DropdownMenuTrigger render={<Button variant="ghost" size="icon" className="relative" />}>
<DropdownMenuTrigger render={<Button variant="ghost" size="icon" className="relative" aria-label={t("title")} />}>
<Bell className="h-4 w-4" />
{unreadCount > 0 && (
<Badge
+2 -2
View File
@@ -54,7 +54,7 @@ export function ReportButton({
<Flag className="h-3 w-3" /> Report
</button>
) : (
<Button variant="ghost" size="icon" onClick={() => setOpen(true)}>
<Button variant="ghost" size="icon" onClick={() => setOpen(true)} aria-label="Report">
<Flag className="h-4 w-4" />
</Button>
)}
@@ -66,7 +66,7 @@ export function ReportButton({
) : (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="report-reason">What's wrong with this?</Label>
<Label htmlFor="report-reason">What&apos;s wrong with this?</Label>
<Textarea
id="report-reason"
value={reason}