Files
drinktracker/src/app/api/bar/barcode-lookup/route.ts
JP 70db6314e3 Phase 5 hygiene: image ownership, real deletes, scan resilience
Images were readable by any signed-in user, not just their owner. Keys
are now namespaced per user in both shapes the app writes, the three
bar/ objects that predated that were migrated under the owner's prefix,
and the image route enforces the prefix - answering 404 rather than 403
so it does not confirm someone else's key exists. Barcode-mirrored
images now write under the user prefix too.

deleteImage existed but was never called, so deleting a drink, bar item
or scan removed the row and left the file in storage forever, still
fetchable. All three now clean up through one shared helper, after the
database work and best-effort, so a storage hiccup cannot block a delete
the user asked for or leave the row behind.

Menu scans are processed detached from the request, so every deploy
abandoned anything in flight and left the row PROCESSING forever with a
spinner that never resolved. They are now reaped lazily when a user
lists their scans - no scheduler needed. Concurrent extractions are
capped at two per process: each is a vision call with a four minute
timeout that costs real money, and nothing else bounded them.

MenuItem gains userId. Ownership was only ever transitive via scanId,
which held because nothing queries MenuItem directly, but left any
future direct query an IDOR with nothing to stop it.

Restore was correctly scoped but unbounded, so a crafted file could
create unlimited rows in one transaction against shared Postgres - self
harm with one user, denial of service with several. Capped, and imageUrl
from the CSV now goes through the same validation the API enforces
instead of reaching the column unchecked.

Members can delete their own account and data. Once the app holds other
people's history, including Rating.location, that is the minimum.

Registration rate limiting took the first x-forwarded-for hop, which the
client controls; it now takes the last, which our proxy appends.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 21:57:57 +00:00

184 lines
6.3 KiB
TypeScript

import { NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { getUserProvider } from "@/lib/ai/provider-factory"
import { FEATURE_ROUTING } from "@/lib/ai/routing"
import { mirrorExternalImage } from "@/lib/s3"
import { rateLimit } from "@/lib/rate-limit"
import { z } from "zod"
const barcodeLookupSchema = z.object({
barcode: z.string().min(8).max(20).regex(/^\d+$/, "Invalid barcode format"),
})
function mapOffCategoryToBarCategory(tags: string[]): string {
const joined = (tags || []).join(",").toLowerCase()
if (/spirits|whisk|bourbon|vodka|rum|gin|tequila|brandy|cognac|mezcal|scotch/.test(joined)) return "SPIRITS"
if (/liqueur|amaretto|kahlua|baileys|triple.sec|schnapps|chartreuse|campari|aperol/.test(joined)) return "LIQUEURS"
if (/juice|soda|tonic|cola|syrup|water|mixer|ginger|lemon|lime|cranberry|club/.test(joined)) return "MIXERS"
if (/bitter/.test(joined)) return "BITTERS"
return "SPIRITS"
}
function mapOffCategoryToDrinkType(tags: string[]): string | null {
const joined = (tags || []).join(",").toLowerCase()
if (/beer|ale|lager|stout|porter|pilsner|ipa|wheat.beer|craft.beer/.test(joined)) return "BEER"
if (/wine|champagne|prosecco|cava|merlot|cabernet|chardonnay|pinot|rosé|rose/.test(joined)) return "WINE"
if (/cocktail/.test(joined)) return "COCKTAIL"
if (/spirits|whisk|bourbon|vodka|rum|gin|tequila|brandy|cognac|mezcal|scotch/.test(joined)) return "SPIRIT"
return null
}
async function lookupOpenFoodFacts(barcode: string, userId: string) {
try {
const res = await fetch(
`https://world.openfoodfacts.org/api/v2/product/${barcode}.json`,
{ signal: AbortSignal.timeout(8000) }
)
if (!res.ok) return null
const data = await res.json()
if (data.status !== 1 || !data.product) return null
const product = data.product
const name = product.product_name || product.product_name_en || null
if (!name) return null
// Open Food Facts hosts these on its own domain, which the CSP blocks, so copy
// the picture into our storage and hand back a local URL. Null on failure - an
// item with no image beats one with an image that cannot render.
const remoteImage =
product.image_url || product.image_front_url || product.image_front_small_url || null
// Namespaced by user so the image route can enforce ownership by key prefix.
const imageUrl = remoteImage
? await mirrorExternalImage(remoteImage, `${userId}/bar/${barcode}`)
: null
// Extract ABV from alcohol_100g nutrient or nutriments
let abv: number | null = null
if (product.nutriments?.alcohol_100g) {
abv = parseFloat(product.nutriments.alcohol_100g)
if (isNaN(abv)) abv = null
}
// Determine drink type from categories
const drinkType = mapOffCategoryToDrinkType(product.categories_tags || [])
return {
name,
brand: product.brands || null,
category: mapOffCategoryToBarCategory(product.categories_tags || []),
imageUrl,
abv,
type: drinkType,
subType: null as string | null,
}
} catch {
return null
}
}
async function lookupViaAI(barcode: string, userId: string) {
try {
const provider = await getUserProvider(userId)
const systemPrompt = `You are a product identification expert. Given a UPC/EAN barcode number, identify the product — especially alcoholic beverages, spirits, mixers, and bar supplies.
Return ONLY a valid JSON object with these fields:
- "name" (string): The product name (e.g., "Maker's Mark Bourbon")
- "brand" (string or null): The brand name
- "category" (string): One of "SPIRITS", "LIQUEURS", "MIXERS", "BITTERS", "GARNISHES", or "TOOLS"
If you cannot confidently identify the barcode, return: { "name": null }
Do not include any text before or after the JSON.`
const response = await provider.sendTextRequest(
systemPrompt,
`Identify the product with UPC/EAN barcode: ${barcode}`,
FEATURE_ROUTING.barcodeLookup
)
const match = response.match(/\{[\s\S]*\}/)
if (!match) return null
const parsed = JSON.parse(match[0])
if (!parsed.name) return null
return {
name: parsed.name as string,
brand: (parsed.brand as string) || null,
category: parsed.category || "SPIRITS",
}
} catch (error) {
// Best-effort fallback after Open Food Facts, so a failure here is not fatal to
// the request. Logged so a gateway outage is not completely invisible.
console.warn("[switchboard] barcode AI fallback failed:", error)
return null
}
}
export async function POST(request: Request) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
const { success: withinLimit } = rateLimit(`barcode-lookup:${session.user.id}`, 10, 60000)
if (!withinLimit) {
return NextResponse.json(
{ error: "Too many requests. Please wait a moment." },
{ status: 429 }
)
}
try {
const body = await request.json()
const parsed = barcodeLookupSchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: "Invalid barcode format" }, { status: 400 })
}
const { barcode } = parsed.data
// Check if user already has this barcode in their bar
const existing = await prisma.barItem.findFirst({
where: { userId: session.user.id, barcode },
})
if (existing) {
return NextResponse.json({
barcode,
name: existing.name,
brand: null,
category: existing.category,
source: "existing",
existingId: existing.id,
})
}
// Try Open Food Facts first
const offResult = await lookupOpenFoodFacts(barcode, session.user.id)
if (offResult) {
return NextResponse.json({ ...offResult, barcode, source: "openfoodfacts" })
}
// AI fallback
const aiResult = await lookupViaAI(barcode, session.user.id)
if (aiResult) {
return NextResponse.json({ ...aiResult, barcode, source: "ai" })
}
// Not found
return NextResponse.json({
barcode,
name: null,
brand: null,
category: null,
source: "not_found",
})
} catch (error) {
console.error("Barcode lookup error:", error)
return NextResponse.json(
{ error: "Failed to look up barcode" },
{ status: 500 }
)
}
}