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>
126 lines
4.1 KiB
TypeScript
126 lines
4.1 KiB
TypeScript
import { NextResponse } from "next/server"
|
|
import { cookies } from "next/headers"
|
|
import { z } from "zod"
|
|
import bcrypt from "bcryptjs"
|
|
import { prisma } from "@/lib/prisma"
|
|
import { rateLimit } from "@/lib/rate-limit"
|
|
import { INVITE_COOKIE, InviteError, claimInvite } from "@/lib/invites"
|
|
|
|
const registerSchema = z.object({
|
|
name: z
|
|
.string()
|
|
.min(1, "Name is required")
|
|
.max(100, "Name must be 100 characters or less"),
|
|
email: z
|
|
.string()
|
|
.min(1, "Email is required")
|
|
.email("Invalid email address"),
|
|
password: z
|
|
.string()
|
|
.min(10, "Password must be at least 10 characters")
|
|
.max(128, "Password must be 128 characters or less")
|
|
.regex(/[a-z]/, "Password must contain at least one lowercase letter")
|
|
.regex(/[A-Z]/, "Password must contain at least one uppercase letter")
|
|
.regex(/[0-9]/, "Password must contain at least one number"),
|
|
})
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
// Rate limit: 5 registration attempts per IP per minute.
|
|
// Take the LAST hop, not the first: everything before it is client-supplied and
|
|
// can be forged to get a fresh bucket per request. The last entry is the one our
|
|
// own reverse proxy appended.
|
|
const forwarded = request.headers.get("x-forwarded-for")
|
|
const hops = forwarded?.split(",").map((h) => h.trim()).filter(Boolean) ?? []
|
|
const ip = hops.length > 0 ? hops[hops.length - 1] : "unknown"
|
|
const rl = rateLimit(`register:${ip}`, 5, 60 * 1000)
|
|
if (!rl.success) {
|
|
return NextResponse.json(
|
|
{ error: "Too many registration attempts. Please try again later." },
|
|
{ status: 429 }
|
|
)
|
|
}
|
|
|
|
const body = await request.json()
|
|
const result = registerSchema.safeParse(body)
|
|
|
|
if (!result.success) {
|
|
const errors = result.error.flatten().fieldErrors
|
|
return NextResponse.json(
|
|
{ error: "Validation failed", details: errors },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const { name, email, password } = result.data
|
|
|
|
// Signup is invite only. The token is read from the HttpOnly cookie set by
|
|
// /invite/<token>, never from the request body, so a caller cannot supply one.
|
|
const inviteToken = cookies().get(INVITE_COOKIE)?.value
|
|
if (!inviteToken) {
|
|
return NextResponse.json(
|
|
{ error: "An invitation is required to sign up." },
|
|
{ status: 403 }
|
|
)
|
|
}
|
|
|
|
const hashedPassword = await bcrypt.hash(password, 10)
|
|
|
|
// One transaction so a duplicate email rolls back the consumed invite use
|
|
// rather than burning it on a failed signup.
|
|
const user = await prisma.$transaction(async (tx) => {
|
|
const invite = await claimInvite(tx, inviteToken)
|
|
if (!invite) {
|
|
throw new InviteError("This invitation link is no longer valid.", 403)
|
|
}
|
|
|
|
const existingUser = await tx.user.findUnique({ where: { email } })
|
|
if (existingUser) {
|
|
throw new InviteError("An account with this email already exists", 409)
|
|
}
|
|
|
|
const created = await tx.user.create({
|
|
data: {
|
|
name,
|
|
email,
|
|
password: hashedPassword,
|
|
// The invite is the verification - there is no email infrastructure to
|
|
// send a confirmation, and the link was delivered out of band.
|
|
emailVerified: new Date(),
|
|
role: "MEMBER",
|
|
status: "ACTIVE",
|
|
invitedById: invite.createdById,
|
|
},
|
|
})
|
|
|
|
await tx.inviteRedemption.create({
|
|
data: {
|
|
inviteId: invite.id,
|
|
userId: created.id,
|
|
email,
|
|
provider: "credentials",
|
|
},
|
|
})
|
|
|
|
return created
|
|
})
|
|
|
|
const response = NextResponse.json(
|
|
{ id: user.id, name: user.name, email: user.email },
|
|
{ status: 201 }
|
|
)
|
|
// Spent - do not leave it lying around for a second signup attempt.
|
|
response.cookies.delete(INVITE_COOKIE)
|
|
return response
|
|
} catch (error) {
|
|
if (error instanceof InviteError) {
|
|
return NextResponse.json({ error: error.message }, { status: error.status })
|
|
}
|
|
console.error("Registration error:", error)
|
|
return NextResponse.json(
|
|
{ error: "Something went wrong. Please try again." },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|