/** * Finding: S-02 (no retention period) * * app/api/internal/retention/purge/route.ts, scheduled daily by Vercel Cron. * * Applications past `purgeAfter` are deleted (qualifications and consent cascade). Applicants * still in an active stage get a grace extension instead of disappearing mid-process. * Expired idempotency keys and old sent outbox rows are cleaned up in the same pass. * The job logs counts only, never personal data. */ import { timingSafeEqual } from "node:crypto"; import { db } from "@/lib/db"; export const dynamic = "force-dynamic"; const ACTIVE = ["SCREENING", "INTERVIEW", "OFFER"] as const; function authorised(req: Request) { const secret = process.env.CRON_SECRET; const got = Buffer.from(req.headers.get("authorization") ?? ""); const want = Buffer.from(`Bearer ${secret ?? ""}`); return Boolean(secret) && got.length === want.length && timingSafeEqual(got, want); } export async function GET(req: Request) { if (!authorised(req)) return new Response(null, { status: 404 }); const now = new Date(); const extended = await db.application.updateMany({ where: { purgeAfter: { lte: now }, status: { in: [...ACTIVE] } }, data: { purgeAfter: new Date(now.getTime() + 30 * 86_400_000) }, }); const purged = await db.application.deleteMany({ where: { purgeAfter: { lte: now }, status: { notIn: [...ACTIVE] } }, }); const keys = await db.idempotencyKey.deleteMany({ where: { expiresAt: { lte: now } } }); const outbox = await db.outboxMessage.deleteMany({ where: { status: "SENT", sentAt: { lte: new Date(now.getTime() - 30 * 86_400_000) } }, }); const result = { purged: purged.count, extended: extended.count, idempotencyKeys: keys.count, outbox: outbox.count }; console.info(JSON.stringify({ level: "info", event: "retention.purge", ...result })); return Response.json(result, { headers: { "Cache-Control": "no-store" } }); }