// AK-P14a ยท P14 Email โ€” per-tenant Mailjet sending-domain provisioning seam. // // The SMTP-provider abstraction for sending domains (AD-6, EU provider = Mailjet, // no US-core dependency). A tenant adds a domain โ†’ we register a Mailjet sender // for it and read back the DKIM/SPF records the tenant must publish (Mailjet // generates + holds the DKIM key, so no private key is stored on our side). The // 5-minute worker probe (email-domain-probe-cron) verifies the published records // against live DNS; `check()` here additionally asks Mailjet to re-validate. // // Behind a typed interface so the host app depends on the capability, not the // HTTP shape, and the unit tests inject a fake fetch. Basic auth mirrors // MailjetProvider (apiKey:secretKey, base64). import { MailProviderError } from "./types.js"; export const mailjetApiBaseUrl = "https://api.mailjet.com"; const DEFAULT_TIMEOUT_MS = 10_000; type Fetch = typeof fetch; /** Mailjet per-record status, normalized to our verification vocabulary. */ export type MailjetRecordStatus = "ok" | "pending" | "error"; /** The DNS records a tenant must publish, as returned by Mailjet. */ export type MailjetDnsRecords = { dnsId: string | null; dkimSelector: string | null; dkimRecord: string | null; spfRecord: string | null; dkimStatus: MailjetRecordStatus; spfStatus: MailjetRecordStatus; }; export type MailjetDnsProvisioner = { /** Register a sending domain (idempotent on Mailjet's side). */ registerDomain(domain: string): Promise<{ ok: true }>; /** Read the DKIM/SPF records + current Mailjet status for a domain. */ getRecords(domain: string): Promise; /** Ask Mailjet to re-validate the domain's DNS now. */ check(domain: string): Promise<{ dkimStatus: MailjetRecordStatus; spfStatus: MailjetRecordStatus }>; }; export type MailjetDnsProvisionerOptions = { apiKey: string; secretKey: string; baseUrl?: string; fetch?: Fetch; timeoutMs?: number; }; function normalizeStatus(raw: unknown): MailjetRecordStatus { const value = typeof raw === "string" ? raw.trim().toLowerCase() : ""; if (value === "ok") return "ok"; if (value === "error") return "error"; return "pending"; } function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null; } function readString(value: unknown): string | null { return typeof value === "string" && value.trim() ? value.trim() : null; } export function createMailjetDnsProvisioner(options: MailjetDnsProvisionerOptions): MailjetDnsProvisioner { const authorization = `Basic ${Buffer.from(`${options.apiKey}:${options.secretKey}`, "utf8").toString("base64")}`; const baseUrl = (options.baseUrl ?? mailjetApiBaseUrl).replace(/\/+$/, ""); const fetchImpl = options.fetch ?? fetch; const timeoutMs = options.timeoutMs && options.timeoutMs > 0 ? options.timeoutMs : DEFAULT_TIMEOUT_MS; async function request(method: string, path: string, body?: unknown): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); let response: Response; try { response = await fetchImpl(`${baseUrl}${path}`, { method, headers: { Authorization: authorization, "Content-Type": "application/json", Accept: "application/json" }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), signal: controller.signal, }); } catch (error) { if (error instanceof Error && error.name === "AbortError") { throw new MailProviderError("Mailjet DNS request timed out.", { provider: "mailjet" }); } throw error; } finally { clearTimeout(timer); } // 400 on register often means "already exists" โ€” treat as success upstream. if (!response.ok && response.status !== 400) { throw new MailProviderError(`Mailjet DNS request failed with ${response.status}.`, { provider: "mailjet", statusCode: response.status }); } try { return (await response.json()) as unknown; } catch { return null; } } function parseRecords(payload: unknown): MailjetDnsRecords { const data = isRecord(payload) && Array.isArray(payload["Data"]) ? payload["Data"][0] : undefined; if (!isRecord(data)) { return { dnsId: null, dkimSelector: null, dkimRecord: null, spfRecord: null, dkimStatus: "pending", spfStatus: "pending" }; } return { dnsId: readString(data["ID"]) ?? (typeof data["ID"] === "number" ? String(data["ID"]) : null), dkimSelector: readString(data["DKIMRecordName"]), dkimRecord: readString(data["DKIMRecordValue"]), spfRecord: readString(data["SPFRecordValue"]), dkimStatus: normalizeStatus(data["DKIMStatus"]), spfStatus: normalizeStatus(data["SPFStatus"]), }; } return { async registerDomain(domain) { // A Mailjet "sender" for the wildcard domain registers it for DNS setup. await request("POST", "/v3/REST/sender", { Email: `*@${domain}`, IsDefaultSender: false }); return { ok: true }; }, async getRecords(domain) { return parseRecords(await request("GET", `/v3/REST/dns/${encodeURIComponent(domain)}`)); }, async check(domain) { const payload = await request("POST", `/v3/REST/dns/${encodeURIComponent(domain)}/check`); const records = parseRecords(payload); return { dkimStatus: records.dkimStatus, spfStatus: records.spfStatus }; }, }; }