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>
This commit is contained in:
JP
2026-08-08 21:57:57 +00:00
parent 0ead1385f7
commit 70db6314e3
15 changed files with 364 additions and 27 deletions

View File

@@ -0,0 +1,62 @@
import { NextResponse } from "next/server"
import { requireUser } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import { deleteImagesByUrl } from "@/lib/images"
import { revokeGatewayKey } from "@/lib/ai/switchboard-keys"
/**
* Self-service account deletion.
*
* Once the app holds other people's drink history - including Rating.location, which
* is a record of where they were - being able to delete it themselves is the minimum,
* rather than having to ask the owner.
*
* The owner cannot delete themselves this way: it would strand the deployment with
* no one able to issue invites or manage members.
*/
export async function DELETE() {
const session = await requireUser()
if (session instanceof NextResponse) return session
const userId = session.user.id
const user = await prisma.user.findUnique({
where: { id: userId },
select: { role: true },
})
if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 })
if (user.role === "OWNER") {
return NextResponse.json(
{
error:
"The owner account cannot be deleted here. Transfer ownership first.",
},
{ status: 400 }
)
}
// Collected before the cascade makes them unreachable.
const [drinks, barItems, scans, keys] = await Promise.all([
prisma.drink.findMany({ where: { userId }, select: { imageUrl: true } }),
prisma.barItem.findMany({ where: { userId }, select: { imageUrl: true } }),
prisma.menuScan.findMany({ where: { userId }, select: { imageUrl: true } }),
prisma.userApiKey.findMany({ where: { userId }, select: { gatewayKeyId: true } }),
])
await prisma.user.delete({ where: { id: userId } })
// Best effort: storage or the gateway being unavailable must not leave the
// account half-deleted.
const gatewayKeyIds = keys
.map((k) => k.gatewayKeyId)
.filter((id): id is string => !!id)
await Promise.all([
deleteImagesByUrl([...drinks, ...barItems, ...scans].map((r) => r.imageUrl)),
Promise.allSettled(gatewayKeyIds.map((id) => revokeGatewayKey(id))),
])
// The jwt callback returns null once the user is gone, so the session ends on the
// next request without any extra step here.
return NextResponse.json({ success: true })
}