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
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, conversations, conversationReads, messages, eq, asc } from "@epicure/db";
import { db, conversations, conversationReads, messages, eq, and, desc, lt } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { isParticipant, otherParticipantId } from "@/lib/messaging";
@@ -13,7 +13,9 @@ interface RouteContext {
const Schema = z.object({ content: z.string().min(1).max(4000) });
export async function GET(_req: NextRequest, { params }: RouteContext) {
const PAGE_SIZE = 50;
export async function GET(req: NextRequest, { params }: RouteContext) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
@@ -23,22 +25,42 @@ export async function GET(_req: NextRequest, { params }: RouteContext) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
// Cursor-based pagination: fetch the page ending just before `before`
// (an ISO createdAt timestamp), newest-first, then reverse so the client
// still receives oldest-first order for the page. This avoids the old
// `asc + limit(200)` bug, which permanently hid every message past the
// 200th once a conversation grew beyond that.
const before = req.nextUrl.searchParams.get("before");
const beforeDate = before ? new Date(before) : null;
const validBefore = beforeDate && !isNaN(beforeDate.getTime()) ? beforeDate : null;
const rows = await db
.select()
.from(messages)
.where(eq(messages.conversationId, id))
.orderBy(asc(messages.createdAt))
.limit(200);
.where(
validBefore
? and(eq(messages.conversationId, id), lt(messages.createdAt, validBefore))
: eq(messages.conversationId, id)
)
.orderBy(desc(messages.createdAt))
.limit(PAGE_SIZE);
await db
.insert(conversationReads)
.values({ conversationId: id, userId: session!.user.id, lastReadAt: new Date() })
.onConflictDoUpdate({
target: [conversationReads.conversationId, conversationReads.userId],
set: { lastReadAt: new Date() },
});
const ordered = rows.slice().reverse();
const nextCursor = rows.length === PAGE_SIZE ? rows[rows.length - 1]!.createdAt.toISOString() : null;
return NextResponse.json({ messages: rows });
// Only mark the conversation read when loading the latest page, not when
// paging through history.
if (!validBefore) {
await db
.insert(conversationReads)
.values({ conversationId: id, userId: session!.user.id, lastReadAt: new Date() })
.onConflictDoUpdate({
target: [conversationReads.conversationId, conversationReads.userId],
set: { lastReadAt: new Date() },
});
}
return NextResponse.json({ messages: ordered, nextCursor });
}
export async function POST(req: NextRequest, { params }: RouteContext) {