// AK-P14a · P14 Email — sending-domain DNS auto-probe cron. // // Every 5 minutes the worker walks each tenant's not-yet-settled sending domains // (status pending|verifying), resolves the published DKIM/SPF/DMARC records and // advances `verificationStatus`: // // pending → verifying (at least one record now resolves) // * → verified (all three resolve) // * → failed (still incomplete 7 days after the first probe) // // Mirrors the hr-upload-reminder-cron / task-reminder-sweep shape: this file // carries the config + scheduler registration + the PURE decision helper // (unit-tested without DNS or a DB). The execution logic (Prisma + notify()) // lives in the maintenance handler which holds the DB client. The DNS lookup is // behind an injectable `DomainDnsResolver` seam so the handler binds the real // node:dns resolver while tests inject a deterministic fake. import { resolveTxt } from "node:dns/promises"; export const EMAIL_DOMAIN_PROBE_JOB_ID = "email-domain-probe" as const; /** Five-minute cadence per the AK-P14a DoD (5-Min-Auto-Probe). */ export const EMAIL_DOMAIN_PROBE_EVERY_MS = 5 * 60 * 1000; /** After this long without full verification a domain flips to `failed` (Klartext). */ export const EMAIL_DOMAIN_PROBE_FAILURE_AFTER_MS = 7 * 24 * 60 * 60 * 1000; /** i18n (M002) key surfaced on `lastError` once the 7-day window elapses. */ export const EMAIL_DOMAIN_PROBE_FAILURE_KEY = "email.domain.error.notVerifiedAfter7Days" as const; export type SendingDomainProbeStatus = "pending" | "verifying" | "verified" | "failed"; /** Which of the three required records currently resolve in DNS. */ export type DnsProbeResult = { readonly dkim: boolean; readonly spf: boolean; readonly dmarc: boolean; }; export type ProbeDecision = { readonly status: SendingDomainProbeStatus; /** i18n key for the Klartext failure detail, or null. */ readonly lastError: string | null; }; /** * Pure: given which records resolve, when probing started and the current time, * decide the next verification status and Klartext error. No DNS, no DB — fully * unit-testable. `failureAfterMs` is injectable for tests; production uses the * 7-day default. */ export function decideDomainProbeStatus(input: { dns: DnsProbeResult; firstProbeAt: Date | null; now: Date; failureAfterMs?: number; }): ProbeDecision { if (input.dns.dkim && input.dns.spf && input.dns.dmarc) { return { status: "verified", lastError: null }; } const failureAfterMs = input.failureAfterMs ?? EMAIL_DOMAIN_PROBE_FAILURE_AFTER_MS; const elapsed = input.firstProbeAt ? input.now.getTime() - input.firstProbeAt.getTime() : 0; if (input.firstProbeAt && elapsed >= failureAfterMs) { return { status: "failed", lastError: EMAIL_DOMAIN_PROBE_FAILURE_KEY }; } const anyPresent = input.dns.dkim || input.dns.spf || input.dns.dmarc; return { status: anyPresent ? "verifying" : "pending", lastError: null }; } /** Lookup seam: resolves the three records for a domain. Injected for testing. */ export type DomainDnsResolver = (input: { domain: string; dkimSelector: string | null }) => Promise; /** Join a multi-string TXT answer (DNS chunks records at 255 chars) into one. */ function joinTxt(records: string[][]): string[] { return records.map((chunks) => chunks.join("")); } /** * Production DNS resolver (node:dns). A record counts as present when its TXT * marker resolves: DKIM at `._domainkey.`, SPF (`v=spf1`) at * the apex, DMARC (`v=DMARC1`) at `_dmarc.`. Lookups are best-effort — * a NXDOMAIN / SERVFAIL resolves to "not present", never throws. */ export function createDnsDomainResolver(deps: { resolveTxt: (hostname: string) => Promise } = { resolveTxt }): DomainDnsResolver { const lookup = async (hostname: string): Promise => { try { return joinTxt(await deps.resolveTxt(hostname)); } catch { return []; } }; return async ({ domain, dkimSelector }) => { const [dkimTxt, apexTxt, dmarcTxt] = await Promise.all([ dkimSelector ? lookup(`${dkimSelector}._domainkey.${domain}`) : Promise.resolve([]), lookup(domain), lookup(`_dmarc.${domain}`), ]); return { dkim: dkimTxt.some((value) => value.includes("v=DKIM1") || value.includes("k=rsa")), spf: apexTxt.some((value) => value.toLowerCase().includes("v=spf1")), dmarc: dmarcTxt.some((value) => value.toUpperCase().includes("V=DMARC1")), }; }; } export async function registerEmailDomainProbeCron(queue: { upsertJobScheduler: (schedulerId: string, options: { every: number }, template: { name: string; data?: Record }) => Promise; }): Promise { await queue.upsertJobScheduler( EMAIL_DOMAIN_PROBE_JOB_ID, { every: EMAIL_DOMAIN_PROBE_EVERY_MS }, { name: EMAIL_DOMAIN_PROBE_JOB_ID, data: { kind: "cleanup.run", task: EMAIL_DOMAIN_PROBE_JOB_ID } }, ); }