/** * Finding: A-03 (and S-04 for the per-recipient cap) * * Transactional outbox. The request handler writes the business row and an OutboxMessage in * the same database transaction, then returns. A separate dispatcher sends the email. * * - Resend slow or down? The applicant still gets an instant 201; delivery retries later. * - Database insert fails? No email is sent for an application that doesn't exist. * - Dispatcher crashes mid-send? The Idempotency-Key makes the retry a no-op at Resend. * * Payloads carry IDs, not personal data or user free text. The recipient address is decrypted * at send time, so the outbox table never holds plaintext PII. */ import { db } from "@/lib/db"; import { decrypt, ctx } from "../08-pii-encryption/field-encryption"; import { limiters } from "../05-abuse-protection/rate-limit"; export type OutboxKind = "email.application_received" | "email.team_new_application"; /** Structural type: any Prisma interactive-transaction client satisfies it. */ type Tx = { outboxMessage: { create(args: { data: { kind: OutboxKind; payload: { applicationId: string } } }): Promise }; }; /** Call inside the same $transaction that creates the Application. */ export function enqueue(tx: Tx, kind: OutboxKind, payload: { applicationId: string }) { return tx.outboxMessage.create({ data: { kind, payload } }); } type Leased = { id: string; kind: OutboxKind; payload: { applicationId: string }; attempts: number }; const MAX_ATTEMPTS = 8; const LEASE = "5 minutes"; const backoffMs = (attempt: number) => Math.min(60 * 60_000, 2 ** attempt * 30_000); // 1m, 2m, 4m ... capped at 1h /** * Lease a batch atomically. FOR UPDATE SKIP LOCKED lets several dispatcher invocations run * concurrently without picking the same rows; pushing nextAttemptAt forward acts as a * visibility timeout if this invocation dies before marking the row. */ async function leaseBatch(limit = 20): Promise { return db.$queryRaw` UPDATE "OutboxMessage" SET "nextAttemptAt" = now() + ${LEASE}::interval, "attempts" = "attempts" + 1 WHERE "id" IN ( SELECT "id" FROM "OutboxMessage" WHERE "status" = 'PENDING' AND "nextAttemptAt" <= now() ORDER BY "nextAttemptAt" LIMIT ${limit} FOR UPDATE SKIP LOCKED) RETURNING "id", "kind", "payload", "attempts"`; } async function render(msg: Leased): Promise<{ to: string; subject: string; text: string } | null> { const app = await db.application.findUnique({ where: { id: msg.payload.applicationId }, select: { emailEnc: true, fullNameEnc: true, jobPosting: { select: { title: true, slug: true } } }, }); if (!app) return null; // purged or withdrawn: nothing to send if (msg.kind === "email.application_received") { const to = decrypt(app.emailEnc, ctx.applicantEmail); const firstName = decrypt(app.fullNameEnc, ctx.applicantName).split(" ")[0]; // Fixed template. No user-supplied free text is echoed to an unverified address. return { to, subject: `We received your application for ${app.jobPosting.title}`, text: `Hi ${firstName},\n\nThanks for applying to ${app.jobPosting.title} at Cynbit. Our team reviews applications within 48 hours.\n\nCynbit Technologies`, }; } return { to: process.env.HIRING_INBOX ?? "opportunities@cynbit.in", subject: `New application: ${app.jobPosting.title}`, text: `Review it in the admin panel: https://admin.cynbit.in/applications/${msg.payload.applicationId}`, }; } async function sendViaResend(msg: Leased, mail: { to: string; subject: string; text: string }) { const res = await fetch("https://api.resend.com/emails", { method: "POST", headers: { Authorization: `Bearer ${process.env.RESEND_API_KEY}`, "Content-Type": "application/json", "Idempotency-Key": `outbox-${msg.id}`, // same message id => Resend sends at most once }, body: JSON.stringify({ from: "Cynbit Careers ", ...mail }), signal: AbortSignal.timeout(10_000), }); if (!res.ok) throw new Error(`Resend ${res.status}: ${(await res.text()).slice(0, 300)}`); } export async function dispatchOutbox(): Promise<{ sent: number; failed: number; skipped: number }> { const batch = await leaseBatch(); let sent = 0, failed = 0, skipped = 0; for (const msg of batch) { try { const mail = await render(msg); if (!mail) { await db.outboxMessage.update({ where: { id: msg.id }, data: { status: "SENT", sentAt: new Date(), lastError: "skipped: source row gone" } }); skipped++; continue; } if (msg.kind === "email.application_received") { const cap = await limiters.outboundToRecipient.limit(mail.to); if (!cap.success) { await db.outboxMessage.update({ where: { id: msg.id }, data: { status: "SENT", sentAt: new Date(), lastError: "skipped: recipient cap" } }); skipped++; continue; } } await sendViaResend(msg, mail); await db.outboxMessage.update({ where: { id: msg.id }, data: { status: "SENT", sentAt: new Date() } }); sent++; } catch (err) { const terminal = msg.attempts >= MAX_ATTEMPTS; await db.outboxMessage.update({ where: { id: msg.id }, data: { status: terminal ? "FAILED" : "PENDING", lastError: String(err instanceof Error ? err.message : err).slice(0, 500), nextAttemptAt: new Date(Date.now() + backoffMs(msg.attempts)), }, }); failed++; } } return { sent, failed, skipped }; }