Files
Arnaud 3e71bd29a2 security: widen API-key auth to content/AI routes (v0.27.0)
Convert requireSession -> requireSessionOrApiKey across recipes,
collections, meal-plans, shopping-lists, pantry, feed, and ai/*
(52 routes) so API keys work end-to-end, not just for the handful of
endpoints that supported them before. Scope was explicitly confirmed
per-resource-family with the user before any file was touched.

Left session-cookie-only, deliberately: users/me*, ai-keys/*,
webhooks/*, conversations/*, notifications/*, push/subscribe, admin/*
— account/credential-adjacent surface that shouldn't widen without a
separate, explicit decision.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 11:20:26 +02:00

56 lines
1.9 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, pantryItems, eq } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
const Schema = z.object({
items: z.array(z.object({
rawName: z.string().min(1).max(200),
quantity: z.string().optional(),
unit: z.string().max(50).optional(),
})).min(1).max(100),
});
export async function POST(req: NextRequest) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
const userId = session!.user.id;
const existing = await db.query.pantryItems.findMany({
where: eq(pantryItems.userId, userId),
});
for (const incoming of parsed.data.items) {
const key = incoming.rawName.toLowerCase();
const match = existing.find(
(e) => e.rawName.toLowerCase() === key && (e.unit ?? "") === (incoming.unit ?? "")
);
if (match) {
const existingQty = match.quantity ? parseFloat(match.quantity) : null;
const incomingQty = incoming.quantity ? parseFloat(incoming.quantity) : null;
if (existingQty !== null && incomingQty !== null && !isNaN(existingQty) && !isNaN(incomingQty)) {
const merged = existingQty + incomingQty;
await db.update(pantryItems)
.set({ quantity: String(merged) })
.where(eq(pantryItems.id, match.id));
}
// if quantities aren't numeric, leave as-is (item already exists)
} else {
await db.insert(pantryItems).values({
id: crypto.randomUUID(),
userId,
rawName: incoming.rawName,
quantity: incoming.quantity,
unit: incoming.unit,
});
}
}
return NextResponse.json({ ok: true });
}