/** * Findings: S-01, S-02, S-03, S-04, A-01, A-02, A-03 * * app/api/v1/careers/[slug]/applications/route.ts * * The order of checks is deliberate: cheapest and most selective first, so abusive traffic is * turned away before it costs a Turnstile round-trip or a database transaction. * * 1. size + content-type (free) * 2. per-IP rate limit (one Redis call) * 3. schema validation (CPU only, same schema as the client form) * 4. honeypot + fill time (free) * 5. Turnstile (one HTTPS call) * 6. per-email rate limit (one Redis call) * 7. idempotency key (one indexed read/insert) * 8. transaction: application + qualifications + consent + outbox * 9. after(): kick the email dispatcher without delaying the response * * The same pipeline works as a Server Action; a versioned Route Handler is shown because it * gives a stable contract for a future mobile app or ATS integration. */ import { after } from "next/server"; import { createHash, randomUUID } from "node:crypto"; import { db } from "@/lib/db"; import { ApplicationSchema } from "../02-validation/application.schema"; import { Problems, problemResponse } from "../04-errors/problem"; import { clientIp, limiters } from "../05-abuse-protection/rate-limit"; import { looksAutomated, verifyTurnstile } from "../05-abuse-protection/turnstile"; import { blindIndex, ctx, encrypt } from "../08-pii-encryption/field-encryption"; import { dispatchOutbox, enqueue } from "../06-outbox/outbox"; export const runtime = "nodejs"; const MAX_BODY_BYTES = 32 * 1024; // a real application is ~3 KB const RETENTION_DAYS = 180; // publish this number in the privacy notice (S-02) const IDEMPOTENCY_TTL_MS = 24 * 60 * 60 * 1000; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; async function readCappedBody(req: Request): Promise { const declared = Number(req.headers.get("content-length") ?? "0"); if (declared > MAX_BODY_BYTES) throw Problems.payloadTooLarge(); const reader = req.body?.getReader(); if (!reader) return ""; const chunks: Uint8Array[] = []; let total = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; total += value.byteLength; if (total > MAX_BODY_BYTES) throw Problems.payloadTooLarge(); // chunked bodies lie about length chunks.push(value); } return Buffer.concat(chunks).toString("utf8"); } export async function POST(req: Request, { params }: { params: Promise<{ slug: string }> }) { const requestId = req.headers.get("x-vercel-id") ?? randomUUID(); let claimedKey: string | null = null; try { // 1. Transport checks if (!req.headers.get("content-type")?.startsWith("application/json")) throw Problems.unsupportedMedia(); const raw = await readCappedBody(req); // 2. Per-IP limit const ip = clientIp(req); const byIp = await limiters.applicationByIp.limit(ip); if (!byIp.success) throw Problems.rateLimited(byIp.retryAfterSeconds); // 3. Validation (throws ZodError -> 422 with per-field errors) let json: unknown; try { json = JSON.parse(raw); } catch { throw Problems.validation([{ path: "", message: "Body is not valid JSON" }]); } const input = ApplicationSchema.parse(json); // 4. Cheap bot heuristics. Respond as if accepted so bots learn nothing. if (looksAutomated(input)) { return Response.json({ id: randomUUID(), status: "RECEIVED" }, { status: 201 }); } // 5. Turnstile, bound to this form's action name if (!(await verifyTurnstile(input.turnstileToken, ip, "careers_apply"))) throw Problems.botCheckFailed(); // 6. Per-email limit (keyed on the blind index, never the raw address) const emailHash = blindIndex(input.email); const byEmail = await limiters.applicationByEmail.limit(emailHash); if (!byEmail.success) throw Problems.rateLimited(byEmail.retryAfterSeconds); // 7. Idempotency: a double-tapped submit replays the first response instead of re-running const idemKey = req.headers.get("idempotency-key"); if (!idemKey || !UUID.test(idemKey)) { throw Problems.validation([{ path: "Idempotency-Key", message: "Send a UUID Idempotency-Key header" }]); } const requestHash = createHash("sha256").update(raw).digest("hex"); const existing = await db.idempotencyKey.findUnique({ where: { key: idemKey } }); if (existing) { if (existing.requestHash !== requestHash) { throw Problems.validation([{ path: "Idempotency-Key", message: "Key was already used with a different body" }]); } if (existing.responseCode == null) throw Problems.idempotencyConflict(); return Response.json(existing.responseBody, { status: existing.responseCode, headers: { "Idempotent-Replayed": "true" } }); } // Primary-key insert: if two identical requests race, exactly one wins; the other gets 409. try { await db.idempotencyKey.create({ data: { key: idemKey, scope: "applications:create", requestHash, expiresAt: new Date(Date.now() + IDEMPOTENCY_TTL_MS) }, }); claimedKey = idemKey; } catch { throw Problems.idempotencyConflict(); } // 8. Persist everything atomically const { slug } = await params; const job = await db.jobPosting.findFirst({ where: { slug, isOpen: true }, select: { id: true, slug: true } }); if (!job) throw Problems.notFound("Open role"); const now = new Date(); const encrypted = { fullNameEnc: encrypt(input.fullName, ctx.applicantName), emailEnc: encrypt(input.email, ctx.applicantEmail), phoneEnc: encrypt(input.phone, ctx.applicantPhone), }; const fields = { ...encrypted, phoneIsWhatsApp: input.phoneIsWhatsApp, currentCity: input.currentCity, noticePeriodDays: input.noticePeriodDays, skills: input.skills, portfolioUrl: input.portfolioUrl, linkedinUrl: input.linkedinUrl, githubUrl: input.githubUrl ?? null, statement: input.statement, purgeAfter: new Date(now.getTime() + RETENTION_DAYS * 86_400_000), }; const qualifications = input.qualifications.map((q, position) => ({ ...q, position })); const consent = { purpose: `recruitment:${job.slug}`, privacyPolicyVersion: input.privacyPolicyVersion, ipHash: blindIndex(ip), grantedAt: now, withdrawnAt: null, }; const application = await db.$transaction(async (tx: any) => { // Re-applying to the same role updates the existing record (unique jobPostingId+emailHash). const app = await tx.application.upsert({ where: { jobPostingId_emailHash: { jobPostingId: job.id, emailHash } }, create: { jobPostingId: job.id, emailHash, ...fields, qualifications: { create: qualifications }, consent: { create: consent } }, update: { ...fields, status: "RECEIVED", statusChangedAt: now, qualifications: { deleteMany: {}, create: qualifications }, consent: { upsert: { create: consent, update: consent } }, }, select: { id: true, status: true }, }); await enqueue(tx, "email.application_received", { applicationId: app.id }); await enqueue(tx, "email.team_new_application", { applicationId: app.id }); return app; }); const body = { id: application.id, status: application.status }; await db.idempotencyKey.update({ where: { key: idemKey }, data: { responseCode: 201, responseBody: body } }); claimedKey = null; // 9. Send emails after the response is flushed; the cron dispatcher is the safety net. after(() => dispatchOutbox().catch(() => undefined)); return Response.json(body, { status: 201, headers: { "Cache-Control": "no-store", "X-Request-Id": requestId } }); } catch (err) { // Release a claimed key if we failed before recording a response, so the client can retry. if (claimedKey) await db.idempotencyKey.delete({ where: { key: claimedKey } }).catch(() => undefined); return problemResponse(err, requestId); } }