@tgoliveira/outpost 1.2.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +172 -18
- package/README.md +17 -12
- package/dist/adapters/drizzle/index.cjs +194 -15
- package/dist/adapters/drizzle/index.cjs.map +1 -1
- package/dist/adapters/drizzle/index.d.cts +124 -7
- package/dist/adapters/drizzle/index.d.ts +124 -7
- package/dist/adapters/drizzle/index.js +194 -15
- package/dist/adapters/drizzle/index.js.map +1 -1
- package/dist/adapters/index.cjs +148 -38
- package/dist/adapters/index.cjs.map +1 -1
- package/dist/adapters/index.d.cts +21 -13
- package/dist/adapters/index.d.ts +21 -13
- package/dist/adapters/index.js +149 -39
- package/dist/adapters/index.js.map +1 -1
- package/dist/admin/index.cjs +10 -3
- package/dist/admin/index.cjs.map +1 -1
- package/dist/admin/index.d.cts +7 -7
- package/dist/admin/index.d.ts +7 -7
- package/dist/admin/index.js +10 -3
- package/dist/admin/index.js.map +1 -1
- package/dist/{fake-BY6t7UXb.d.cts → fake-B6OIEdod.d.ts} +6 -4
- package/dist/{fake-en-oOdg0.d.ts → fake-CpQc9p0N.d.cts} +6 -4
- package/dist/http/index.cjs.map +1 -1
- package/dist/http/index.d.cts +6 -6
- package/dist/http/index.d.ts +6 -6
- package/dist/http/index.js.map +1 -1
- package/dist/{index-c6caPsUG.d.ts → index-B4F7euCt.d.cts} +53 -21
- package/dist/{index-BO0GiZmP.d.cts → index-Cn1YsmGe.d.ts} +53 -21
- package/dist/index.cjs +509 -146
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -15
- package/dist/index.d.ts +17 -15
- package/dist/index.js +509 -148
- package/dist/index.js.map +1 -1
- package/dist/modules/ui/index.cjs +3 -3
- package/dist/modules/ui/index.cjs.map +1 -1
- package/dist/modules/ui/index.js +3 -3
- package/dist/modules/ui/index.js.map +1 -1
- package/dist/modules/ui/pages/admin/admin-config-page.cjs +2 -2
- package/dist/modules/ui/pages/admin/admin-config-page.cjs.map +1 -1
- package/dist/modules/ui/pages/admin/admin-config-page.js +2 -2
- package/dist/modules/ui/pages/admin/admin-config-page.js.map +1 -1
- package/dist/modules/ui/pages/admin/admin-panel-page.cjs +1 -1
- package/dist/modules/ui/pages/admin/admin-panel-page.js +1 -1
- package/dist/modules/ui/pages/index.cjs +3 -3
- package/dist/modules/ui/pages/index.cjs.map +1 -1
- package/dist/modules/ui/pages/index.js +3 -3
- package/dist/modules/ui/pages/index.js.map +1 -1
- package/dist/{outpost-client-BItbgqIo.d.ts → outpost-client-BX3SsOFb.d.ts} +50 -21
- package/dist/{outpost-client-BlVf4gjo.d.cts → outpost-client-DhQgZY16.d.cts} +50 -21
- package/dist/react/index.cjs +3 -3
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.js +3 -3
- package/dist/react/index.js.map +1 -1
- package/dist/repositories-DJYu4nGV.d.ts +322 -0
- package/dist/repositories-sMN6RHZJ.d.cts +322 -0
- package/dist/{services-CfTEsetF.d.ts → services-DZwZjDn_.d.cts} +9 -3
- package/dist/{services-CQINhAGo.d.cts → services-PoM2bxjP.d.ts} +9 -3
- package/dist/{template-DxI_p2Ny.d.cts → template-Dl1_ciRo.d.ts} +24 -4
- package/dist/{template-CREUq7bB.d.ts → template-Dny_7Ymi.d.cts} +24 -4
- package/dist/testing/index.cjs +200 -15
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +26 -7
- package/dist/testing/index.d.ts +26 -7
- package/dist/testing/index.js +200 -15
- package/dist/testing/index.js.map +1 -1
- package/dist/{webhook-kp6CiXk-.d.cts → webhook-B158Vi6p.d.cts} +20 -4
- package/dist/{webhook-kp6CiXk-.d.ts → webhook-B158Vi6p.d.ts} +20 -4
- package/dist/workers/index.cjs +471 -85
- package/dist/workers/index.cjs.map +1 -1
- package/dist/workers/index.d.cts +5 -5
- package/dist/workers/index.d.ts +5 -5
- package/dist/workers/index.js +471 -85
- package/dist/workers/index.js.map +1 -1
- package/package.json +6 -3
- package/dist/repositories-CHIOFGn3.d.cts +0 -182
- package/dist/repositories-WyhvxzyY.d.ts +0 -182
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/application/pipeline/retry-policy.ts","../src/domain/errors.ts","../src/application/pipeline/sanitize.ts","../src/application/pipeline/domain-validation.ts","../src/domain/retention.ts","../src/application/config.ts","../src/application/enqueue-message.ts","../src/domain/webhook.ts","../src/domain/lifecycle.ts","../src/application/ingest-webhook.ts","../src/application/manage-suppression.ts","../src/application/manage-api-key.ts","../src/domain/api-key.ts","../src/application/authenticate.ts","../src/application/message-queries.ts","../src/application/dispatch-message.ts","../src/workers/send-worker.ts","../src/application/purge-retention.ts","../src/workers/retention-worker.ts","../src/client/outpost-client.ts","../src/adapters/crypto/recipient-hasher.ts","../src/adapters/crypto/encryptors.ts","../src/adapters/rate-limit/in-memory.ts","../src/adapters/services/system.ts","../src/adapters/observability/logger.ts","../src/adapters/observability/telemetry.ts","../src/create-outpost.ts","../src/domain/suppression.ts"],"names":["nextAttemptAt","randomBytes","cryptoConstants","dnsResolveMx"],"mappings":";;;;AAiBO,IAAM,aAAA,GAA6B;AAAA,EACxC,WAAA,EAAa,CAAA;AAAA,EACb,WAAA,EAAa,GAAA;AAAA;AAAA,EACb,UAAA,EAAY,KAAK,EAAA,GAAK;AAAA;AACxB;AAGO,SAAS,WAAA,CAAY,UAAkB,MAAA,EAA8B;AAC1E,EAAA,OAAO,YAAY,MAAA,CAAO,WAAA;AAC5B;AAOO,SAAS,SAAA,CAAU,QAAA,EAAkB,MAAA,EAAqB,MAAA,EAAwB;AACvF,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,UAAA,EAAY,MAAA,CAAO,WAAA,GAAc,CAAA,IAAK,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,QAAA,GAAW,CAAC,CAAC,CAAA;AAC3F,EAAA,OAAO,IAA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AA,EAAK;AAC1B,IAAA,OAAO,EAAE,aAAA,EAAe,GAAA,CAAI,aAAA,EAAe,aAAA,EAAe,IAAI,aAAA,EAAc;AAAA,EAC9E;AACA,EAAA,QAAQ,IAAI,IAAA;AAAM,IAChB,KAAK,MAAA,EAAQ;AACX,MAAA,MAAM,IAAA,GAAO,IAAI,aAAA,EAAc;AAC/B,MAAA,OAAO,EAAE,aAAA,EAAe,IAAA,EAAM,aAAA,EAAe,IAAA,EAAK;AAAA,IACpD;AAAA,IACA,KAAK,WAAA,EAAa;AAChB,MAAA,MAAM,GAAA,GAAM,OAAO,GAAA,CAAI,GAAA,KAAQ,QAAA,GAAW,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,GAAA,EAAK,QAAQ,CAAA,GAAI,GAAA,CAAI,GAAA;AAC/E,MAAA,MAAM,CAAA,GAAI,IAAI,eAAA,CAAgB,GAAA,EAAK,IAAI,KAAK,CAAA;AAC5C,MAAA,OAAO,EAAE,aAAA,EAAe,CAAA,EAAG,aAAA,EAAe,CAAA,EAAE;AAAA,IAC9C;AAAA,IACA,KAAK,YAAA,EAAc;AACjB,MAAA,MAAM,OAAO,IAAI,mBAAA,CAAoB,GAAA,CAAI,SAAA,EAAW,IAAI,KAAK,CAAA;AAG7D,MAAA,MAAM,OAAO,GAAA,CAAI,UAAA,GAAa,IAAI,mBAAA,CAAoB,GAAA,CAAI,UAAU,CAAA,GAAI,IAAA;AACxE,MAAA,OAAO,EAAE,aAAA,EAAe,IAAA,EAAM,aAAA,EAAe,IAAA,EAAK;AAAA,IACpD;AAAA;AAEJ;;;AC9KO,IAAM,mBAAA,GAAsB;AAAA,EACjC,aAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF","file":"index.js","sourcesContent":["/**\n * Retry policy: exponential backoff with full jitter (TDR §3.4).\n *\n * Pure function of (attempt number, config) → delay. Jitter is injected as a\n * 0..1 random sample so the policy stays deterministic and testable (the\n * worker passes a real random; tests pass a fixed value).\n */\n\nexport interface RetryConfig {\n /** Max dispatch attempts before a message is dead-lettered. */\n readonly maxAttempts: number;\n /** Base backoff in ms (first retry waits ~this, before jitter). */\n readonly baseDelayMs: number;\n /** Cap on the backoff in ms. */\n readonly maxDelayMs: number;\n}\n\nexport const DEFAULT_RETRY: RetryConfig = {\n maxAttempts: 5,\n baseDelayMs: 30_000, // 30s\n maxDelayMs: 60 * 60 * 1000, // 1h\n};\n\n/** True once attempts have reached the budget — message goes to the DLQ. */\nexport function isExhausted(attempts: number, config: RetryConfig): boolean {\n return attempts >= config.maxAttempts;\n}\n\n/**\n * Backoff for the NEXT attempt after `attempts` failed tries.\n * delay = min(maxDelay, base * 2^(attempts-1)) then full-jitter: random in\n * [0, delay]. `jitter` is a sample in [0,1).\n */\nexport function backoffMs(attempts: number, config: RetryConfig, jitter: number): number {\n const exp = Math.min(config.maxDelayMs, config.baseDelayMs * 2 ** Math.max(0, attempts - 1));\n return Math.floor(exp * jitter);\n}\n\n/** Convenience: the Date of the next attempt from `now`. */\nexport function nextAttemptAt(\n attempts: number,\n config: RetryConfig,\n jitter: number,\n now: Date,\n): Date {\n return new Date(now.getTime() + backoffMs(attempts, config, jitter));\n}\n","/**\n * Domain error taxonomy.\n *\n * Errors are classified so the dispatch pipeline can decide retry vs. fail\n * without inspecting provider-specific error shapes (TDR §3.4). Adapters map\n * their native errors onto these classes; the core never sees raw SDK errors.\n */\n\nexport type ErrorClass = \"transient\" | \"permanent\";\n\n/** Base class for all errors Outpost raises. Carries a stable machine `code`. */\nexport class OutpostError extends Error {\n readonly code: string;\n constructor(code: string, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = new.target.name;\n this.code = code;\n }\n}\n\n/** A request failed authentication (missing/expired/revoked key). → HTTP 401. */\nexport class UnauthorizedError extends OutpostError {\n constructor(message = \"Missing, expired, or revoked API key\") {\n super(\"unauthorized\", message);\n }\n}\n\n/** A valid key lacked the required scope. → HTTP 403. */\nexport class ForbiddenError extends OutpostError {\n constructor(message = \"API key lacks the required scope\") {\n super(\"forbidden\", message);\n }\n}\n\n/** Caller input failed validation/sanitization. Never retried. → HTTP 400. */\nexport class ValidationError extends OutpostError {\n readonly details?: unknown;\n constructor(message: string, details?: unknown) {\n super(\"validation_failed\", message);\n this.details = details;\n }\n}\n\n/** A referenced resource does not exist. → HTTP 404. */\nexport class NotFoundError extends OutpostError {\n constructor(message = \"Resource not found\") {\n super(\"not_found\", message);\n }\n}\n\n/** A lifecycle transition violated the state machine. Programming/state bug. */\nexport class InvalidStateTransitionError extends OutpostError {\n constructor(from: string, to: string) {\n super(\"invalid_transition\", `Cannot transition message from \"${from}\" to \"${to}\"`);\n }\n}\n\n/** Webhook signature verification failed. → HTTP 401, logged. */\nexport class WebhookVerificationError extends OutpostError {\n constructor(message = \"Webhook signature verification failed\") {\n super(\"webhook_unverified\", message);\n }\n}\n\n/**\n * Raised by `EmailProvider` implementations. The `errorClass` drives retry:\n * `transient` errors go back to the queue with backoff; `permanent` errors go\n * straight to `failed` and the Dead Letter Queue.\n */\nexport class ProviderError extends OutpostError {\n readonly errorClass: ErrorClass;\n readonly providerCode?: string;\n constructor(\n errorClass: ErrorClass,\n message: string,\n options?: { providerCode?: string; cause?: unknown },\n ) {\n super(`provider_${errorClass}`, message, options);\n this.errorClass = errorClass;\n this.providerCode = options?.providerCode;\n }\n\n static transient(message: string, options?: { providerCode?: string; cause?: unknown }) {\n return new ProviderError(\"transient\", message, options);\n }\n\n static permanent(message: string, options?: { providerCode?: string; cause?: unknown }) {\n return new ProviderError(\"permanent\", message, options);\n }\n}\n\n/** Returns true when an unknown thrown value should be treated as retryable. */\nexport function isTransient(err: unknown): boolean {\n return err instanceof ProviderError && err.errorClass === \"transient\";\n}\n","import { ValidationError } from \"../../domain/errors.js\";\n\n/**\n * Outbound sanitization (TDR §3.2 step 2, §5.3).\n *\n * These are conservative, dependency-free guards focused on the email-specific\n * attack surface: header injection (CRLF) and oversize payloads. For rich HTML\n * sanitization against XSS you SHOULD plug a hardened sanitizer (e.g.\n * `sanitize-html` / DOMPurify) via `createOutpost({ sanitizeHtml })`; the\n * built-in `stripDangerousHtml` below is a last-resort fallback, not a\n * substitute for a real sanitizer.\n */\n\n/** Default ceilings; override via config. */\nexport interface SanitizeLimits {\n readonly maxSubjectBytes: number;\n readonly maxBodyBytes: number;\n readonly maxRecipientBytes: number;\n readonly maxHeaderValueBytes: number;\n}\n\nexport const DEFAULT_SANITIZE_LIMITS: SanitizeLimits = {\n maxSubjectBytes: 2_000,\n maxBodyBytes: 5_000_000, // 5 MB\n maxRecipientBytes: 320, // RFC 5321 max\n maxHeaderValueBytes: 4_000,\n};\n\nconst byteLen = (s: string) => Buffer.byteLength(s, \"utf8\");\n\n/**\n * Reject control characters in any value used as an email header (To, Subject,\n * custom headers). This is THE header-injection defense — without it an attacker\n * can inject a CR/LF + \"Bcc:\" and turn one message into many, or use a NUL to\n * truncate. Implemented as a char-code scan (not a regex) so the intent is\n * unambiguous: reject every C0 control char (0x00–0x1F, which includes CR, LF,\n * NUL and TAB) and DEL (0x7F), while ALLOWING ordinary printable characters\n * including the space (0x20). An earlier regex form also matched the space,\n * which wrongly rejected normal multi-word subjects.\n */\nexport function assertNoHeaderInjection(field: string, value: string): void {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < 0x20 || code === 0x7f) {\n throw new ValidationError(`Illegal control character in \"${field}\" (header injection attempt)`);\n }\n }\n}\n\nexport function sanitizeSubject(subject: string, limits = DEFAULT_SANITIZE_LIMITS): string {\n assertNoHeaderInjection(\"subject\", subject);\n const trimmed = subject.trim();\n if (byteLen(trimmed) > limits.maxSubjectBytes) {\n throw new ValidationError(`Subject exceeds ${limits.maxSubjectBytes} bytes`);\n }\n return trimmed;\n}\n\nexport function sanitizeRecipient(to: string, limits = DEFAULT_SANITIZE_LIMITS): string {\n assertNoHeaderInjection(\"to\", to);\n const trimmed = to.trim();\n if (byteLen(trimmed) > limits.maxRecipientBytes) {\n throw new ValidationError(`Recipient exceeds ${limits.maxRecipientBytes} bytes`);\n }\n return trimmed;\n}\n\nexport function sanitizeHeaders(\n headers: Record<string, string>,\n limits = DEFAULT_SANITIZE_LIMITS,\n): Record<string, string> {\n for (const [k, v] of Object.entries(headers)) {\n assertNoHeaderInjection(`header:${k}`, k);\n assertNoHeaderInjection(`header:${k}`, v);\n if (byteLen(v) > limits.maxHeaderValueBytes) {\n throw new ValidationError(`Header \"${k}\" exceeds ${limits.maxHeaderValueBytes} bytes`);\n }\n }\n return headers;\n}\n\nexport function assertBodyWithinLimits(\n body: { html?: string; text?: string },\n limits = DEFAULT_SANITIZE_LIMITS,\n): void {\n const total = byteLen(body.html ?? \"\") + byteLen(body.text ?? \"\");\n if (total === 0) {\n throw new ValidationError(\"Message body is empty (provide html and/or text)\");\n }\n if (total > limits.maxBodyBytes) {\n throw new ValidationError(`Body exceeds ${limits.maxBodyBytes} bytes`);\n }\n}\n\n/**\n * Last-resort HTML hardening: strip <script>/<style>/<iframe>/<object> blocks,\n * `on*=` event handlers, and `javascript:` URLs. NOT a full sanitizer — prefer\n * a real one via config. Returns cleaned HTML.\n */\nexport function stripDangerousHtml(html: string): string {\n return html\n .replace(/<\\s*(script|style|iframe|object|embed)[\\s\\S]*?<\\s*\\/\\s*\\1\\s*>/gi, \"\")\n .replace(/<\\s*(script|style|iframe|object|embed)\\b[^>]*\\/?\\s*>/gi, \"\")\n .replace(/\\son\\w+\\s*=\\s*\"[^\"]*\"/gi, \"\")\n .replace(/\\son\\w+\\s*=\\s*'[^']*'/gi, \"\")\n .replace(/\\son\\w+\\s*=\\s*[^\\s>]+/gi, \"\")\n .replace(/(href|src)\\s*=\\s*(\"|')\\s*javascript:[^\"']*\\2/gi, '$1=$2#$2');\n}\n\n/** Validate an attachment's MIME type and size (TDR §3.2). */\nexport interface AttachmentSpec {\n readonly filename: string;\n readonly contentType: string;\n readonly sizeBytes: number;\n}\n\nexport interface AttachmentPolicy {\n readonly allowedMimeTypes: readonly string[];\n readonly maxSizeBytes: number;\n}\n\nexport const DEFAULT_ATTACHMENT_POLICY: AttachmentPolicy = {\n allowedMimeTypes: [\n \"application/pdf\",\n \"image/png\",\n \"image/jpeg\",\n \"image/gif\",\n \"text/plain\",\n \"text/csv\",\n ],\n maxSizeBytes: 10_000_000, // 10 MB\n};\n\nexport function validateAttachment(att: AttachmentSpec, policy = DEFAULT_ATTACHMENT_POLICY): void {\n assertNoHeaderInjection(\"attachment.filename\", att.filename);\n if (!policy.allowedMimeTypes.includes(att.contentType)) {\n throw new ValidationError(`Attachment MIME type \"${att.contentType}\" is not allowed`);\n }\n if (att.sizeBytes > policy.maxSizeBytes) {\n throw new ValidationError(`Attachment \"${att.filename}\" exceeds ${policy.maxSizeBytes} bytes`);\n }\n}\n","import { ValidationError } from \"../../domain/errors.js\";\n\n/**\n * Recipient domain validation (TDR §3.2 step 3, §3.10, decision #4).\n *\n * Two checks, in order of cost:\n * 1. Syntax — always on. RFC-5322-ish address shape.\n * 2. MX records — optional, cached. Confirms the domain can receive mail.\n *\n * Outpost deliberately does NOT probe whether an individual mailbox exists:\n * it is unreliable and damages sender reputation (decision #4).\n */\n\nexport interface DomainValidationConfig {\n readonly syntax: boolean;\n readonly mx: boolean;\n readonly mailboxProbe: false; // typed as a constant: never supported\n /** TTL for the MX-result cache, ms. */\n readonly mxCacheTtlMs?: number;\n}\n\nexport const DEFAULT_DOMAIN_VALIDATION: DomainValidationConfig = {\n syntax: true,\n mx: false,\n mailboxProbe: false,\n mxCacheTtlMs: 60 * 60 * 1000,\n};\n\n/**\n * Pluggable MX resolver so the core stays free of `node:dns`. The default\n * resolver (provided in adapters) uses `dns/promises`. Returns the MX hosts.\n */\nexport interface MxResolver {\n resolveMx(domain: string): Promise<string[]>;\n}\n\n// Pragmatic, conservative address syntax check. Not a full RFC 5322 grammar\n// (that grammar admits forms no provider accepts); this matches what real\n// transactional senders use.\n//\n// SECURITY: the local part is a single negated character class with NO nested\n// quantifier. An earlier form, `[^\\s@\"]+(?:\\.[^\\s@\"]+)*`, was ambiguous (`.`\n// is inside `[^\\s@\"]`), causing catastrophic backtracking (ReDoS) on inputs\n// like \"a.a.a...!\" — ~8s for 62 chars. The recipient is attacker-controlled at\n// enqueue, so that was a remote DoS. This form matches/rejects in linear time.\nconst ADDR_RE = /^[^\\s@\"]+@([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+)$/;\n\nexport function extractDomain(address: string): string {\n const at = address.lastIndexOf(\"@\");\n if (at < 0) throw new ValidationError(\"Address has no domain part\");\n return address.slice(at + 1).toLowerCase();\n}\n\nexport function validateSyntax(address: string): string {\n const m = ADDR_RE.exec(address);\n if (!m) throw new ValidationError(`Recipient \"${address}\" is not a valid email address`);\n return m[1]!.toLowerCase(); // the domain\n}\n\n/** Small in-process TTL cache for MX results to avoid hammering DNS. */\nexport class MxCache {\n private readonly entries = new Map<string, { hosts: string[]; expiresAt: number }>();\n constructor(private readonly ttlMs: number) {}\n\n get(domain: string, nowMs: number): string[] | undefined {\n const e = this.entries.get(domain);\n if (!e) return undefined;\n if (e.expiresAt <= nowMs) {\n this.entries.delete(domain);\n return undefined;\n }\n return e.hosts;\n }\n\n set(domain: string, hosts: string[], nowMs: number): void {\n this.entries.set(domain, { hosts, expiresAt: nowMs + this.ttlMs });\n }\n}\n\n/**\n * Full recipient validation. `syntax` is enforced synchronously; `mx`, when\n * enabled, resolves (cached) and throws if the domain has no usable MX (and no\n * fallback A record — many small domains accept mail on the A record).\n */\nexport async function validateRecipient(\n address: string,\n config: DomainValidationConfig,\n deps: { mxResolver?: MxResolver; mxCache?: MxCache; nowMs: number },\n): Promise<void> {\n if (config.syntax) {\n const domain = validateSyntax(address);\n if (config.mx && deps.mxResolver) {\n const cached = deps.mxCache?.get(domain, deps.nowMs);\n let hosts = cached;\n if (hosts === undefined) {\n try {\n hosts = await deps.mxResolver.resolveMx(domain);\n } catch {\n hosts = [];\n }\n deps.mxCache?.set(domain, hosts, deps.nowMs);\n }\n if (hosts.length === 0) {\n throw new ValidationError(`Recipient domain \"${domain}\" has no MX records`);\n }\n }\n }\n}\n","/**\n * Retention policy domain types (TDR §3.9, §5.5).\n *\n * Operational data (the outbox payload) and audit data have independent TTLs.\n * The default action on purge is REDACTION, not deletion: the PII payload is\n * wiped while the audit row (metadata + HMAC) survives. This satisfies data\n * minimization without destroying the audit trail.\n */\n\nexport interface RetentionPolicy {\n /** Age (days) after which a terminal outbox row's PII may be purged. */\n readonly operationalTtlDays: number;\n /** Age (days) after which audit events may be deleted. */\n readonly auditTtlDays: number;\n /** When true (default) purge redacts PII; when false it deletes the row. */\n readonly redactOnPurge: boolean;\n /**\n * Grace window (hours) after a message reaches a terminal state during which\n * it is NOT purged, so late webhooks (delivery/bounce) can still arrive.\n * Purging earlier would break bounce/complaint handling.\n */\n readonly webhookWindowHours: number;\n /** Rows deleted/redacted per batch, to avoid long table locks. */\n readonly batchSize: number;\n}\n\nexport const DEFAULT_RETENTION: RetentionPolicy = {\n operationalTtlDays: 30,\n auditTtlDays: 365,\n redactOnPurge: true,\n webhookWindowHours: 72,\n batchSize: 1000,\n};\n\n/**\n * The cutoff before which a terminal message becomes eligible for purge:\n * it must be older than the operational TTL AND past the webhook window.\n * Returns the latest (most conservative) of the two cutoffs.\n */\nexport function purgeCutoff(policy: RetentionPolicy, now: Date): Date {\n const ttlCutoff = now.getTime() - policy.operationalTtlDays * 24 * 60 * 60 * 1000;\n const windowCutoff = now.getTime() - policy.webhookWindowHours * 60 * 60 * 1000;\n return new Date(Math.min(ttlCutoff, windowCutoff));\n}\n","import { DEFAULT_RETRY, type RetryConfig } from \"./pipeline/retry-policy.js\";\nimport {\n DEFAULT_SANITIZE_LIMITS,\n DEFAULT_ATTACHMENT_POLICY,\n type SanitizeLimits,\n type AttachmentPolicy,\n} from \"./pipeline/sanitize.js\";\nimport {\n DEFAULT_DOMAIN_VALIDATION,\n type DomainValidationConfig,\n} from \"./pipeline/domain-validation.js\";\nimport { DEFAULT_RETENTION, type RetentionPolicy } from \"../domain/retention.js\";\n\n/**\n * Layered rate-limit budgets (TDR §3.2 step 4). Each is a token-bucket-style\n * \"max events per window\". The in-memory limiter and any external limiter share\n * this shape via the `RateLimiter` port.\n */\nexport interface RateLimitConfig {\n /** Global ceiling across all providers/recipients. */\n readonly global?: RateBudget;\n /** Per-provider ceiling, keyed by provider name. */\n readonly perProvider?: RateBudget;\n /** Per recipient-domain ceiling. */\n readonly perRecipientDomain?: RateBudget;\n}\n\nexport interface RateBudget {\n readonly max: number;\n readonly windowMs: number;\n}\n\n/** Fully-resolved internal config — every field defaulted, no optionals. */\nexport interface ResolvedConfig {\n readonly retry: RetryConfig;\n readonly retention: RetentionPolicy;\n readonly sanitize: SanitizeLimits;\n readonly attachments: AttachmentPolicy;\n readonly domainValidation: DomainValidationConfig;\n readonly rateLimits: RateLimitConfig;\n /** Max rows the send worker claims per poll. */\n readonly sendBatchSize: number;\n /**\n * Lease window for `sending` rows, ms. A row left in `sending` longer than\n * this is treated as abandoned (its worker crashed mid-dispatch) and is\n * reclaimed by the next poll. Keep comfortably larger than a real dispatch.\n */\n readonly staleSendingLeaseMs: number;\n}\n\nexport interface ConfigOverrides {\n retry?: Partial<RetryConfig>;\n retention?: Partial<RetentionPolicy>;\n sanitize?: Partial<SanitizeLimits>;\n attachments?: Partial<AttachmentPolicy>;\n domainValidation?: Partial<Omit<DomainValidationConfig, \"mailboxProbe\">>;\n rateLimits?: RateLimitConfig;\n sendBatchSize?: number;\n staleSendingLeaseMs?: number;\n}\n\nexport function resolveConfig(overrides: ConfigOverrides = {}): ResolvedConfig {\n return {\n retry: { ...DEFAULT_RETRY, ...overrides.retry },\n retention: { ...DEFAULT_RETENTION, ...overrides.retention },\n sanitize: { ...DEFAULT_SANITIZE_LIMITS, ...overrides.sanitize },\n attachments: { ...DEFAULT_ATTACHMENT_POLICY, ...overrides.attachments },\n domainValidation: {\n ...DEFAULT_DOMAIN_VALIDATION,\n ...overrides.domainValidation,\n mailboxProbe: false,\n },\n rateLimits: overrides.rateLimits ?? {},\n sendBatchSize: overrides.sendBatchSize ?? 50,\n staleSendingLeaseMs: overrides.staleSendingLeaseMs ?? 5 * 60 * 1000,\n };\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { Message, MessageBody } from \"../domain/message.js\";\nimport { ValidationError } from \"../domain/errors.js\";\nimport {\n sanitizeSubject,\n sanitizeRecipient,\n assertBodyWithinLimits,\n stripDangerousHtml,\n} from \"./pipeline/sanitize.js\";\nimport { validateSyntax } from \"./pipeline/domain-validation.js\";\n\n/**\n * Input accepted by `outpost.send(...)` and `POST /messages` (TDR §4.3).\n * Either `template` OR (`subject` + `html`/`text`) must be supplied.\n */\nexport interface EnqueueInput {\n /** Required. Dedupes re-enqueues (TDR §3.1, decision #3). */\n readonly idempotencyKey: string;\n readonly to: string;\n readonly template?: { id: string; version?: number; vars: Record<string, unknown> };\n readonly subject?: string;\n readonly html?: string;\n readonly text?: string;\n /** Override the default provider for this message. */\n readonly provider?: string;\n /** Clear, queryable metadata. Never put PII here. */\n readonly metadata?: Record<string, unknown>;\n /** Phase 2 scheduling; if set, the worker won't claim it until then. */\n readonly scheduledFor?: Date;\n}\n\nexport interface EnqueueResult {\n readonly id: string;\n readonly state: Message[\"state\"];\n readonly idempotencyKey: string;\n /** True when an existing message was returned (idempotent replay). */\n readonly deduplicated: boolean;\n}\n\n/**\n * EnqueueMessage — persist-before-dispatch ingestion (TDR §3.1, decision #1).\n *\n * Order of operations is load-bearing:\n * 1. Validate + sanitize (reject bad input synchronously, before any write).\n * 2. Idempotency guard — return the existing message if the key is known.\n * 3. Suppression check — suppressed recipients are recorded, never dispatched.\n * 4. Seal PII (recipient + body) with the WRITE-side encryptor.\n * 5. Insert as `queued`. The row exists before anything tries to send it.\n * 6. Append an `enqueued` audit event.\n *\n * The send worker (a separate process) picks it up later by polling — the\n * ingestion path NEVER publishes to a queue, avoiding the dual-write hazard\n * (decision #2).\n */\nexport class EnqueueMessage {\n constructor(private readonly deps: CoreDeps) {}\n\n async execute(input: EnqueueInput, actor: string): Promise<EnqueueResult> {\n const { deps } = this;\n return deps.telemetry.span(\"outpost.enqueue\", { idempotencyKey: input.idempotencyKey }, async () => {\n if (!input.idempotencyKey || input.idempotencyKey.trim() === \"\") {\n throw new ValidationError(\"idempotencyKey is required\");\n }\n\n // 1. Validate + sanitize ----------------------------------------------\n const to = sanitizeRecipient(input.to, deps.config.sanitize);\n validateSyntax(to); // syntax always; MX check happens in the send worker\n const { subject, body } = await this.resolveContent(input);\n const cleanSubject = sanitizeSubject(subject, deps.config.sanitize);\n const cleanBody = this.sanitizeBody(body);\n assertBodyWithinLimits(cleanBody, deps.config.sanitize);\n\n const recipientHmac = deps.recipientHasher.hash(to);\n const provider = input.provider ?? deps.defaultProvider;\n\n // 2. Idempotency guard ------------------------------------------------\n const existing = await deps.outbox.findByIdempotencyKey(input.idempotencyKey);\n if (existing) {\n deps.telemetry.counter(\"outpost.enqueue.deduplicated\", 1);\n return {\n id: existing.id,\n state: existing.state,\n idempotencyKey: existing.idempotencyKey,\n deduplicated: true,\n };\n }\n\n // 3. Suppression check ------------------------------------------------\n const suppressed = await deps.suppressions.isSuppressed(recipientHmac);\n\n // 4. Seal PII (write-side encryptor) ----------------------------------\n const [recipientSealed, bodySealed] = await Promise.all([\n deps.sealEncryptor.seal(to),\n deps.sealEncryptor.seal(JSON.stringify(cleanBody)),\n ]);\n\n const now = deps.clock.now();\n\n // 5. Insert -----------------------------------------------------------\n const message = await deps.outbox.insert({\n idempotencyKey: input.idempotencyKey,\n recipientHmac,\n recipientSealed,\n bodySealed,\n subject: cleanSubject,\n templateId: input.template?.id ?? null,\n templateVersion: input.template?.version ?? null,\n provider,\n metadata: input.metadata ?? {},\n state: suppressed ? \"suppressed\" : \"queued\",\n scheduledFor: input.scheduledFor ?? null,\n nextAttemptAt: input.scheduledFor ?? now,\n });\n\n // 6. Audit ------------------------------------------------------------\n await deps.audit.append({\n messageId: message.id,\n eventType: suppressed ? \"suppressed\" : \"enqueued\",\n actor,\n detail: suppressed ? { reason: \"recipient_on_suppression_list\" } : { provider },\n });\n deps.telemetry.counter(suppressed ? \"outpost.enqueue.suppressed\" : \"outpost.enqueue.queued\", 1);\n\n return {\n id: message.id,\n state: message.state,\n idempotencyKey: message.idempotencyKey,\n deduplicated: false,\n };\n });\n }\n\n /** Resolve template or raw content into subject + body. */\n private async resolveContent(input: EnqueueInput): Promise<{ subject: string; body: MessageBody }> {\n if (input.template) {\n if (!this.deps.templates) {\n throw new ValidationError(\"A template was supplied but no TemplateRenderer is configured\");\n }\n const rendered = await this.deps.templates.render(input.template);\n // A caller-supplied subject overrides the template's, if present.\n return { subject: input.subject ?? rendered.subject, body: rendered.body };\n }\n if (input.subject === undefined) {\n throw new ValidationError(\"Either `template` or `subject` must be provided\");\n }\n return { subject: input.subject, body: { html: input.html, text: input.text } };\n }\n\n /** Apply the configured strong sanitizer (or built-in fallback) to HTML. */\n private sanitizeBody(body: MessageBody): MessageBody {\n if (body.html === undefined) return body;\n const clean = this.deps.sanitizeHtml ? this.deps.sanitizeHtml(body.html) : stripDangerousHtml(body.html);\n return { ...body, html: clean };\n }\n}\n","import type { LifecycleState } from \"./lifecycle.js\";\n\n/**\n * Normalized webhook event (TDR §3.5).\n *\n * Each provider has its own webhook payload shape and signature scheme. The\n * provider adapter's `verifyWebhook` verifies the signature and maps the native\n * payload onto this uniform type, so the `IngestWebhook` use case never has to\n * know about provider specifics.\n */\n\nexport type WebhookEventType =\n | \"delivered\"\n | \"bounced\"\n | \"complained\"\n | \"opened\"\n | \"failed\";\n\nexport interface WebhookEvent {\n readonly provider: string;\n readonly type: WebhookEventType;\n /** Provider's message id — used to correlate back to the outbox row. */\n readonly providerMessageId: string;\n /** Recipient address as the provider reports it (used to derive the HMAC). */\n readonly recipient?: string;\n /** True for hard bounces; soft bounces should not suppress. */\n readonly isHardBounce?: boolean;\n /** Provider's own timestamp for the event, if supplied. */\n readonly occurredAt?: Date;\n /** Raw provider payload, retained for traceability/replay. */\n readonly raw: unknown;\n}\n\n/** Maps a webhook event type to the lifecycle state it drives the message to. */\nexport function webhookToState(type: WebhookEventType): LifecycleState | null {\n switch (type) {\n case \"delivered\":\n return \"delivered\";\n case \"bounced\":\n return \"bounced\";\n case \"complained\":\n return \"complained\";\n case \"failed\":\n return \"failed\";\n case \"opened\":\n return null; // tracking-only; does not change lifecycle state\n }\n}\n","/**\n * Message lifecycle states and the transition rules between them.\n *\n * This module is PURE: no I/O, no framework, no provider. It encodes the\n * state machine described in the TDR §3.3. Everything outward (use cases,\n * repositories, workers) leans on these rules rather than re-deriving them.\n *\n * ┌─────────────┐\n * enqueue ─────▶│ queued │\n * └──────┬──────┘\n * │ claimed by send worker\n * ▼\n * ┌─────────────┐ suppressed recipient\n * │ sending │────────────────────────▶ suppressed\n * └──────┬──────┘\n * │ provider accepted\n * ▼\n * ┌─────────────┐\n * │ sent │ (accepted, not yet confirmed)\n * └──────┬──────┘\n * │ webhook\n * ┌──────────────┼───────────────┬────────────┐\n * ▼ ▼ ▼ ▼\n * delivered bounced complained failed\n *\n * Transient dispatch error → back to `queued` with backoff (retry).\n * Permanent error / retries exhausted → `failed` (terminal, DLQ).\n */\n\nexport const LIFECYCLE_STATES = [\n \"queued\",\n \"sending\",\n \"sent\",\n \"delivered\",\n \"bounced\",\n \"complained\",\n \"failed\",\n \"suppressed\",\n] as const;\n\nexport type LifecycleState = (typeof LIFECYCLE_STATES)[number];\n\n/**\n * Terminal states never transition again. The retention worker only ever acts\n * on rows in a terminal state (and only after the webhook window has closed),\n * which is what makes it safe to run concurrently with the send worker.\n */\nexport const TERMINAL_STATES = [\n \"delivered\",\n \"bounced\",\n \"complained\",\n \"failed\",\n \"suppressed\",\n] as const satisfies readonly LifecycleState[];\n\nconst TERMINAL_SET = new Set<LifecycleState>(TERMINAL_STATES);\n\nexport function isTerminal(state: LifecycleState): boolean {\n return TERMINAL_SET.has(state);\n}\n\n/**\n * Allowed transitions. A transition not present here is a domain invariant\n * violation and must be rejected by the use case (never silently applied).\n */\nconst ALLOWED_TRANSITIONS: Record<LifecycleState, readonly LifecycleState[]> = {\n queued: [\"sending\", \"suppressed\", \"failed\"],\n // `sending` can fall back to `queued` on a transient error (retry).\n sending: [\"sent\", \"queued\", \"failed\", \"suppressed\"],\n sent: [\"delivered\", \"bounced\", \"complained\", \"failed\"],\n delivered: [],\n bounced: [],\n complained: [],\n failed: [\"queued\"], // DLQ replay re-enqueues a failed message\n suppressed: [],\n};\n\nexport function canTransition(from: LifecycleState, to: LifecycleState): boolean {\n return ALLOWED_TRANSITIONS[from].includes(to);\n}\n\n/**\n * Which lifecycle states must feed the suppression list when reached.\n * Hard bounces and complaints damage sender reputation if re-sent, so the\n * recipient is suppressed automatically (TDR §3.6).\n */\nexport function shouldSuppressOn(state: LifecycleState): boolean {\n return state === \"bounced\" || state === \"complained\";\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { RawWebhook } from \"../ports/email-provider.js\";\nimport type { WebhookEvent } from \"../domain/webhook.js\";\nimport type { AuditEventType } from \"../domain/audit.js\";\nimport { webhookToState } from \"../domain/webhook.js\";\nimport { canTransition, shouldSuppressOn } from \"../domain/lifecycle.js\";\nimport { WebhookVerificationError } from \"../domain/errors.js\";\n\nexport interface IngestWebhookResult {\n readonly accepted: boolean;\n readonly eventType: WebhookEvent[\"type\"];\n readonly messageId: string | null;\n /** Why a verified event did not change state (e.g. unknown message). */\n readonly note?: string;\n}\n\n/**\n * IngestWebhook — the webhook worker's single responsibility (TDR §3.5).\n *\n * 1. Verify the signature via the named provider (NEVER trust unverified).\n * 2. Record the raw event for traceability/replay.\n * 3. Correlate to the outbox row by providerMessageId.\n * 4. Transition the message lifecycle (validated against the state machine).\n * 5. Feed the suppression list on hard bounce / complaint.\n * 6. Append an audit event.\n *\n * Webhook endpoints are NOT API-key authenticated — the provider calls them.\n * Trust is established purely by signature verification (TDR §5.2).\n */\nexport class IngestWebhook {\n constructor(private readonly deps: CoreDeps) {}\n\n async execute(providerName: string, raw: RawWebhook): Promise<IngestWebhookResult> {\n const { deps } = this;\n const provider = deps.providers.get(providerName);\n if (!provider) {\n throw new WebhookVerificationError(`Unknown provider \"${providerName}\"`);\n }\n\n return deps.telemetry.span(\"outpost.webhook.ingest\", { provider: providerName }, async () => {\n // 1. Verify — throws WebhookVerificationError on bad signature.\n const event = await provider.verifyWebhook(raw);\n\n // 2. Record raw verified event.\n await deps.webhookEvents.record(event);\n deps.telemetry.counter(\"outpost.webhook.received\", 1, {\n provider: providerName,\n type: event.type,\n });\n\n // 3. Correlate.\n const message = await deps.outbox.findByProviderMessageId(event.providerMessageId);\n if (!message) {\n return {\n accepted: true,\n eventType: event.type,\n messageId: null,\n note: \"no matching message for providerMessageId\",\n };\n }\n\n // 4. Transition (if the event maps to a state change).\n const target = webhookToState(event.type);\n if (target && canTransition(message.state, target)) {\n await deps.outbox.updateState(message.id, { state: target });\n }\n\n // 5. Suppress on hard bounce / complaint.\n if (target && shouldSuppressOn(target) && this.isSuppressable(event)) {\n await deps.suppressions.add({\n recipientHmac: message.recipientHmac,\n reason: target === \"bounced\" ? \"hard_bounce\" : \"complaint\",\n createdBy: `provider:${providerName}`,\n note: `webhook ${event.type}`,\n });\n }\n\n // 6. Audit.\n await deps.audit.append({\n messageId: message.id,\n eventType: this.auditType(event.type),\n actor: `provider:${providerName}`,\n detail: { type: event.type, occurredAt: event.occurredAt?.toISOString() ?? null },\n });\n\n return { accepted: true, eventType: event.type, messageId: message.id };\n });\n }\n\n /** A soft bounce must not suppress; only hard bounces and complaints do. */\n private isSuppressable(event: WebhookEvent): boolean {\n if (event.type === \"complained\") return true;\n if (event.type === \"bounced\") return event.isHardBounce !== false;\n return false;\n }\n\n private auditType(type: WebhookEvent[\"type\"]): AuditEventType {\n switch (type) {\n case \"delivered\":\n return \"webhook_delivered\";\n case \"bounced\":\n return \"webhook_bounced\";\n case \"complained\":\n return \"webhook_complained\";\n case \"opened\":\n return \"webhook_opened\";\n case \"failed\":\n return \"dispatch_failed\";\n }\n }\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { SuppressionEntry, SuppressionReason } from \"../domain/suppression.js\";\n\n/**\n * ManageSuppression — view/add/remove suppression entries (TDR §3.6).\n *\n * All matching is by recipient HMAC, so the plaintext address is hashed with\n * the same keyed HMAC used at ingestion. Adds/removes are audited.\n */\nexport class ManageSuppression {\n constructor(private readonly deps: CoreDeps) {}\n\n async isSuppressed(address: string): Promise<boolean> {\n return this.deps.suppressions.isSuppressed(this.deps.recipientHasher.hash(address));\n }\n\n /** Lookup by precomputed HMAC (the form the HTTP API exposes). */\n async getByHmac(recipientHmac: string): Promise<SuppressionEntry | null> {\n return this.deps.suppressions.get(recipientHmac);\n }\n\n async suppress(\n address: string,\n reason: SuppressionReason,\n actor: string,\n note?: string,\n ): Promise<SuppressionEntry> {\n const recipientHmac = this.deps.recipientHasher.hash(address);\n const entry = await this.deps.suppressions.add({ recipientHmac, reason, createdBy: actor, note });\n await this.deps.audit.append({\n messageId: null,\n eventType: \"suppressed\",\n actor,\n detail: { recipientHmac, reason },\n });\n this.deps.telemetry.counter(\"outpost.suppression.added\", 1, { reason });\n return entry;\n }\n\n /** Remove by HMAC (what the DELETE endpoint receives). Audited. */\n async unsuppressByHmac(recipientHmac: string, actor: string): Promise<boolean> {\n const removed = await this.deps.suppressions.remove(recipientHmac);\n if (removed) {\n await this.deps.audit.append({\n messageId: null,\n eventType: \"unsuppressed\",\n actor,\n detail: { recipientHmac },\n });\n }\n return removed;\n }\n\n async list(limit = 100, offset = 0): Promise<SuppressionEntry[]> {\n return this.deps.suppressions.list(limit, offset);\n }\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport type { CoreDeps } from \"./context.js\";\nimport type { ApiKey, ApiScope } from \"../domain/api-key.js\";\n\n/**\n * Hash an API key secret for storage. Keys are high-entropy random tokens\n * (not user passwords), so a fast one-way SHA-256 is appropriate and lets us\n * look the hash up directly. A slow password hash (bcrypt/argon2) buys nothing\n * against a 256-bit random secret and would break O(1) lookup.\n */\nexport function hashApiKey(secret: string): string {\n return createHash(\"sha256\").update(secret, \"utf8\").digest(\"hex\");\n}\n\n/** Generate an opaque, high-entropy key with a recognizable prefix. */\nexport function generateApiKeySecret(): string {\n return `opk_${randomBytes(32).toString(\"base64url\")}`;\n}\n\nexport interface CreatedApiKey {\n readonly id: string;\n readonly label: string;\n readonly scopes: readonly ApiScope[];\n readonly expiresAt: Date | null;\n /** The plaintext secret — shown ONCE, never stored, never recoverable. */\n readonly secret: string;\n}\n\n/**\n * ManageApiKey — admin-side key lifecycle (TDR §5.1, §3.12).\n *\n * Only the hash is stored. The plaintext is returned exactly once at creation.\n * Revocation takes effect immediately (no caching of key state beyond the\n * documented short window in the Authenticate use case).\n */\nexport class ManageApiKey {\n constructor(private readonly deps: CoreDeps) {}\n\n async create(input: {\n label: string;\n scopes: readonly ApiScope[];\n expiresAt?: Date | null;\n }): Promise<CreatedApiKey> {\n const secret = generateApiKeySecret();\n const key = await this.deps.apiKeys.insert({\n label: input.label,\n keyHash: hashApiKey(secret),\n scopes: input.scopes,\n expiresAt: input.expiresAt ?? null,\n });\n await this.deps.audit.append({\n messageId: null,\n eventType: \"key_created\",\n actor: \"admin\",\n detail: { keyId: key.id, label: key.label, scopes: key.scopes },\n });\n return {\n id: key.id,\n label: key.label,\n scopes: key.scopes,\n expiresAt: key.expiresAt,\n secret,\n };\n }\n\n async revoke(id: string): Promise<boolean> {\n const ok = await this.deps.apiKeys.revoke(id, this.deps.clock.now());\n if (ok) {\n await this.deps.audit.append({\n messageId: null,\n eventType: \"key_revoked\",\n actor: \"admin\",\n detail: { keyId: id },\n });\n }\n return ok;\n }\n\n /** Lists keys WITHOUT secrets (only hashes are stored anyway). */\n async list(): Promise<ApiKey[]> {\n return this.deps.apiKeys.list();\n }\n}\n","/**\n * API key domain types and scope model (TDR §5.1).\n *\n * Keys are opaque high-entropy secrets. Only a hash is ever stored; the\n * plaintext is shown once at creation. A key carries a label, optional expiry,\n * and a revoked flag — both enforced on every request. Scopes implement\n * least-privilege (a send-only key cannot manage suppressions).\n */\n\nexport const API_SCOPES = [\n \"messages:send\",\n \"messages:read\",\n \"messages:replay\",\n \"suppressions:read\",\n \"suppressions:write\",\n \"keys:manage\",\n \"admin\", // implies all of the above\n] as const;\n\nexport type ApiScope = (typeof API_SCOPES)[number];\n\nexport interface ApiKey {\n readonly id: string;\n /** Human label shown in the admin panel. */\n readonly label: string;\n /** Hash of the secret (never the secret itself). */\n readonly keyHash: string;\n readonly scopes: readonly ApiScope[];\n readonly expiresAt: Date | null;\n revokedAt: Date | null;\n readonly createdAt: Date;\n lastUsedAt: Date | null;\n}\n\n/** A key is usable iff it is not revoked and not past its expiry. */\nexport function isKeyActive(key: Pick<ApiKey, \"revokedAt\" | \"expiresAt\">, now: Date): boolean {\n if (key.revokedAt !== null) return false;\n if (key.expiresAt !== null && key.expiresAt.getTime() <= now.getTime()) return false;\n return true;\n}\n\n/** True when the key's scopes satisfy the required scope (admin implies all). */\nexport function hasScope(scopes: readonly ApiScope[], required: ApiScope): boolean {\n return scopes.includes(\"admin\") || scopes.includes(required);\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { ApiKey, ApiScope } from \"../domain/api-key.js\";\nimport { isKeyActive, hasScope } from \"../domain/api-key.js\";\nimport { UnauthorizedError, ForbiddenError } from \"../domain/errors.js\";\nimport { hashApiKey } from \"./manage-api-key.js\";\n\nexport interface AuthContext {\n readonly keyId: string;\n readonly scopes: readonly ApiScope[];\n}\n\n/**\n * Authenticate — validates an API key on every request (TDR §5.1).\n *\n * - Hashes the presented secret and looks up the stored hash.\n * - Rejects missing / unknown / expired / revoked keys with 401.\n * - Enforces the required scope (least privilege) with 403.\n * - Touches `last_used_at` for observability.\n *\n * Revocation/expiry are enforced on every call (no long-lived caching), so\n * they take effect immediately as the TDR requires.\n */\nexport class Authenticate {\n constructor(private readonly deps: CoreDeps) {}\n\n /** Resolve a bearer secret to an AuthContext or throw UnauthorizedError. */\n async resolve(presentedSecret: string | null | undefined): Promise<AuthContext> {\n if (!presentedSecret) throw new UnauthorizedError();\n const keyHash = hashApiKey(presentedSecret);\n const key = await this.deps.apiKeys.findByHash(keyHash);\n if (!key) throw new UnauthorizedError();\n if (!isKeyActive(key, this.deps.clock.now())) throw new UnauthorizedError();\n\n // Fire-and-forget last-used update; never block the request on it.\n void this.deps.apiKeys.touchLastUsed(key.id, this.deps.clock.now());\n\n return { keyId: key.id, scopes: key.scopes };\n }\n\n /** Resolve then assert the context carries the required scope. */\n async authorize(presentedSecret: string | null | undefined, required: ApiScope): Promise<AuthContext> {\n const ctx = await this.resolve(presentedSecret);\n if (!hasScope(ctx.scopes, required)) throw new ForbiddenError();\n return ctx;\n }\n\n /** Assert a scope on an already-resolved context. */\n static requireScope(ctx: AuthContext, required: ApiScope): void {\n if (!hasScope(ctx.scopes, required)) throw new ForbiddenError();\n }\n\n /** Helper to extract a bearer/x-outpost-key value from headers. */\n static extractKey(headers: Record<string, string | string[] | undefined>): string | null {\n const auth = headerValue(headers, \"authorization\");\n if (auth && /^bearer\\s+/i.test(auth)) return auth.replace(/^bearer\\s+/i, \"\").trim();\n return headerValue(headers, \"x-outpost-key\");\n }\n\n // Exposed for tests / admin tooling.\n async findKey(presentedSecret: string): Promise<ApiKey | null> {\n return this.deps.apiKeys.findByHash(hashApiKey(presentedSecret));\n }\n}\n\nfunction headerValue(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | null {\n const raw = headers[name] ?? headers[name.toLowerCase()];\n if (Array.isArray(raw)) return raw[0] ?? null;\n return raw ?? null;\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { Message } from \"../domain/message.js\";\nimport type { ListMessagesQuery } from \"../ports/repositories.js\";\nimport { NotFoundError, InvalidStateTransitionError } from \"../domain/errors.js\";\nimport { canTransition } from \"../domain/lifecycle.js\";\n\n/**\n * A safe, PII-free projection of a message for read APIs and the admin panel.\n * Operators see metadata and lifecycle, NOT the encrypted body/recipient.\n * Body access is a separate, gated, audited operation (not exposed here).\n */\nexport interface MessageView {\n readonly id: string;\n readonly idempotencyKey: string;\n readonly state: Message[\"state\"];\n readonly recipientHmac: string;\n readonly subject: string;\n readonly provider: string;\n readonly templateId: string | null;\n readonly templateVersion: number | null;\n readonly metadata: Record<string, unknown>;\n readonly attempts: number;\n readonly nextAttemptAt: string;\n readonly providerMessageId: string | null;\n readonly lastError: string | null;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\nexport function toView(m: Message): MessageView {\n return {\n id: m.id,\n idempotencyKey: m.idempotencyKey,\n state: m.state,\n recipientHmac: m.recipientHmac,\n subject: m.subject,\n provider: m.provider,\n templateId: m.templateId,\n templateVersion: m.templateVersion,\n metadata: m.metadata,\n attempts: m.attempts,\n nextAttemptAt: m.nextAttemptAt.toISOString(),\n providerMessageId: m.providerMessageId,\n lastError: m.lastError,\n createdAt: m.createdAt.toISOString(),\n updatedAt: m.updatedAt.toISOString(),\n };\n}\n\nexport class GetMessage {\n constructor(private readonly deps: CoreDeps) {}\n async execute(id: string): Promise<MessageView> {\n const m = await this.deps.outbox.findById(id);\n if (!m) throw new NotFoundError(`Message \"${id}\" not found`);\n return toView(m);\n }\n}\n\nexport class ListMessages {\n constructor(private readonly deps: CoreDeps) {}\n async execute(query: ListMessagesQuery): Promise<MessageView[]> {\n const messages = await this.deps.outbox.list({ limit: 50, offset: 0, ...query });\n return messages.map(toView);\n }\n}\n\n/**\n * ReplayMessage — re-enqueue a dead-lettered (`failed`) message from the DLQ\n * (TDR §3.4, §3.12). Resets the retry budget and schedules an immediate retry.\n */\nexport class ReplayMessage {\n constructor(private readonly deps: CoreDeps) {}\n async execute(id: string, actor: string): Promise<MessageView> {\n const m = await this.deps.outbox.findById(id);\n if (!m) throw new NotFoundError(`Message \"${id}\" not found`);\n if (!canTransition(m.state, \"queued\")) {\n throw new InvalidStateTransitionError(m.state, \"queued\");\n }\n await this.deps.outbox.updateState(id, {\n state: \"queued\",\n attempts: 0,\n nextAttemptAt: this.deps.clock.now(),\n lastError: null,\n });\n await this.deps.audit.append({\n messageId: id,\n eventType: \"replayed\",\n actor,\n detail: { fromState: m.state },\n });\n const updated = await this.deps.outbox.findById(id);\n return toView(updated!);\n }\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { Message, MessageBody, DispatchableMessage } from \"../domain/message.js\";\nimport { ProviderError } from \"../domain/errors.js\";\nimport { isExhausted, backoffMs } from \"./pipeline/retry-policy.js\";\nimport { validateRecipient, MxCache, extractDomain } from \"./pipeline/domain-validation.js\";\nimport { sanitizeRecipient, sanitizeSubject, assertBodyWithinLimits } from \"./pipeline/sanitize.js\";\n\nexport type DispatchOutcome =\n | { kind: \"sent\"; providerMessageId: string }\n | { kind: \"retry\"; nextAttemptAt: Date }\n | { kind: \"rate_limited\"; nextAttemptAt: Date }\n | { kind: \"failed\"; reason: string }\n | { kind: \"skipped\"; reason: string };\n\n/**\n * DispatchMessage — processes ONE message already claimed (state `sending`) by\n * the send worker. Implements the outbound pipeline (TDR §3.2):\n *\n * 1. Idempotency / state guard (no double-send under concurrency)\n * 2. Decrypt PII (READ-side encryptor, only here)\n * 3. Re-sanitize decrypted data (defense in depth)\n * 4. Domain validation (syntax + cached MX)\n * 5. Rate limiting (global / provider / domain)\n * 6. Dispatch (provider.send)\n * 7. State transition + audit\n *\n * Decryption happens as late as possible — immediately before dispatch — so\n * plaintext never lives in the queue (TDR §5.4).\n */\nexport class DispatchMessage {\n private readonly mxCache: MxCache;\n\n constructor(private readonly deps: CoreDeps) {\n this.mxCache = new MxCache(deps.config.domainValidation.mxCacheTtlMs ?? 3_600_000);\n }\n\n async execute(message: Message): Promise<DispatchOutcome> {\n const { deps } = this;\n return deps.telemetry.span(\n \"outpost.dispatch\",\n { messageId: message.id, provider: message.provider },\n async () => {\n // 1. State guard — only act on a message we still own in `sending`.\n const fresh = await deps.outbox.findById(message.id);\n if (!fresh || fresh.state !== \"sending\") {\n return { kind: \"skipped\", reason: \"no longer in sending state\" };\n }\n\n const provider = deps.providers.get(fresh.provider);\n if (!provider) {\n return this.fail(fresh, `No provider registered for \"${fresh.provider}\"`);\n }\n\n try {\n // 2. Decrypt (read-side) -----------------------------------------\n const to = await deps.openEncryptor.open(fresh.recipientSealed);\n const bodyJson = await deps.openEncryptor.open(fresh.bodySealed);\n const body = JSON.parse(bodyJson) as MessageBody;\n\n // 3. Re-sanitize decrypted values --------------------------------\n const cleanTo = sanitizeRecipient(to, deps.config.sanitize);\n const cleanSubject = sanitizeSubject(fresh.subject, deps.config.sanitize);\n assertBodyWithinLimits(body, deps.config.sanitize);\n\n // 4. Domain validation -------------------------------------------\n await validateRecipient(cleanTo, deps.config.domainValidation, {\n mxResolver: deps.mxResolver,\n mxCache: this.mxCache,\n nowMs: deps.clock.now().getTime(),\n });\n\n // 5. Rate limiting ------------------------------------------------\n const limited = await this.checkRateLimits(fresh.provider, cleanTo);\n if (limited) {\n return this.requeueRateLimited(fresh);\n }\n\n // 6. Dispatch -----------------------------------------------------\n const dispatchable: DispatchableMessage = {\n id: fresh.id,\n to: cleanTo,\n subject: cleanSubject,\n body,\n headers: this.buildHeaders(),\n metadata: fresh.metadata,\n };\n const receipt = await provider.send(dispatchable);\n\n // 7. Transition to `sent` ----------------------------------------\n await deps.outbox.updateState(fresh.id, {\n state: \"sent\",\n providerMessageId: receipt.providerMessageId,\n lastError: null,\n });\n await deps.audit.append({\n messageId: fresh.id,\n eventType: \"dispatch_accepted\",\n actor: `provider:${fresh.provider}`,\n detail: { providerMessageId: receipt.providerMessageId },\n });\n deps.telemetry.counter(\"outpost.dispatch.sent\", 1, { provider: fresh.provider });\n return { kind: \"sent\", providerMessageId: receipt.providerMessageId };\n } catch (err) {\n return this.handleError(fresh, err);\n }\n },\n );\n }\n\n /** Classify the error and either retry-with-backoff or dead-letter. */\n private async handleError(message: Message, err: unknown): Promise<DispatchOutcome> {\n const permanent = err instanceof ProviderError && err.errorClass === \"permanent\";\n const reason = err instanceof Error ? err.message : String(err);\n\n if (permanent) {\n return this.fail(message, reason);\n }\n\n // Transient (or unknown → treated as transient). Increment attempts.\n const attempts = message.attempts + 1;\n if (isExhausted(attempts, this.deps.config.retry)) {\n return this.fail(message, `Retries exhausted (${attempts}): ${reason}`, attempts);\n }\n\n const delay = backoffMs(attempts, this.deps.config.retry, this.deps.random());\n const nextAttemptAt = new Date(this.deps.clock.now().getTime() + delay);\n await this.deps.outbox.updateState(message.id, {\n state: \"queued\",\n attempts,\n nextAttemptAt,\n lastError: reason,\n });\n await this.deps.audit.append({\n messageId: message.id,\n eventType: \"retry_scheduled\",\n actor: `provider:${message.provider}`,\n detail: { attempts, nextAttemptAt: nextAttemptAt.toISOString(), reason },\n });\n this.deps.telemetry.counter(\"outpost.dispatch.retry\", 1, { provider: message.provider });\n return { kind: \"retry\", nextAttemptAt };\n }\n\n /** Move to `failed` (terminal) and record in the Dead Letter Queue. */\n private async fail(message: Message, reason: string, attempts?: number): Promise<DispatchOutcome> {\n await this.deps.outbox.updateState(message.id, {\n state: \"failed\",\n attempts: attempts ?? message.attempts,\n lastError: reason,\n });\n await this.deps.audit.append({\n messageId: message.id,\n eventType: \"dead_lettered\",\n actor: `provider:${message.provider}`,\n detail: { reason },\n });\n this.deps.telemetry.counter(\"outpost.dispatch.failed\", 1, { provider: message.provider });\n return { kind: \"failed\", reason };\n }\n\n /** Re-queue without counting a failed attempt; short, jittered backoff. */\n private async requeueRateLimited(message: Message): Promise<DispatchOutcome> {\n const delay = 1_000 + Math.floor(this.deps.random() * 4_000); // 1–5s\n const nextAttemptAt = new Date(this.deps.clock.now().getTime() + delay);\n await this.deps.outbox.updateState(message.id, {\n state: \"queued\",\n nextAttemptAt,\n });\n this.deps.telemetry.counter(\"outpost.dispatch.rate_limited\", 1, { provider: message.provider });\n return { kind: \"rate_limited\", nextAttemptAt };\n }\n\n private async checkRateLimits(provider: string, to: string): Promise<boolean> {\n const checks = [\n this.deps.rateLimiter.acquire({ kind: \"global\" }),\n this.deps.rateLimiter.acquire({ kind: \"provider\", key: provider }),\n this.deps.rateLimiter.acquire({ kind: \"recipientDomain\", key: extractDomain(to) }),\n ];\n const results = await Promise.all(checks);\n return results.some((ok) => ok === false);\n }\n\n /** List-Unsubscribe and other always-on headers (TDR §3.11). */\n private buildHeaders(): Record<string, string> {\n // Transactional messages still benefit from List-Unsubscribe hygiene.\n // Consumers can extend via provider config; kept minimal here.\n return {};\n }\n}\n","import type { CoreDeps } from \"../application/context.js\";\nimport { DispatchMessage, type DispatchOutcome } from \"../application/dispatch-message.js\";\n\nexport interface SendTickReport {\n readonly claimed: number;\n readonly outcomes: DispatchOutcome[];\n}\n\nexport interface SendWorkerOptions {\n /** Poll interval for the long-running loop, ms. Default 1000. */\n readonly intervalMs?: number;\n /** Max messages claimed per tick. Defaults to config.sendBatchSize. */\n readonly batchSize?: number;\n /** Max concurrent dispatches within a tick. Default 10. */\n readonly concurrency?: number;\n}\n\n/**\n * SendWorker — the polling outbound processor (TDR §3.2, decision #2).\n *\n * Polls the outbox (NEVER a dual-written queue), atomically claims a batch with\n * `FOR UPDATE SKIP LOCKED`, and runs each message through `DispatchMessage`.\n * Safe to run as multiple concurrent instances — the claim guarantees no two\n * workers process the same row.\n *\n * Two ways to run it:\n * - `start()` / `stop()` — long-running process (setInterval-style loop).\n * - `tick()` — one cycle; call it from a cron job or Next.js route handler\n * (e.g. a Vercel Cron hitting `/api/cron/outpost-send`).\n */\nexport class SendWorker {\n private readonly dispatch: DispatchMessage;\n private running = false;\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n private readonly deps: CoreDeps,\n private readonly options: SendWorkerOptions = {},\n ) {\n this.dispatch = new DispatchMessage(deps);\n }\n\n /** Process one batch. Returns what happened (for logging/metrics/tests). */\n async tick(): Promise<SendTickReport> {\n const now = this.deps.clock.now();\n const batchSize = this.options.batchSize ?? this.deps.config.sendBatchSize;\n const reclaimBefore = new Date(now.getTime() - this.deps.config.staleSendingLeaseMs);\n const claimed = await this.deps.outbox.claimBatchForSending(batchSize, now, reclaimBefore);\n\n this.deps.telemetry.gauge(\"outpost.send.claimed\", claimed.length);\n if (claimed.length === 0) return { claimed: 0, outcomes: [] };\n\n const concurrency = this.options.concurrency ?? 10;\n const outcomes = await runWithConcurrency(claimed, concurrency, (m) =>\n this.dispatch.execute(m).catch((err) => {\n // DispatchMessage handles its own errors; this guards against an\n // unexpected throw so one bad message can't kill the whole tick.\n this.deps.logger.log(\"error\", \"dispatch threw unexpectedly\", {\n messageId: m.id,\n error: err instanceof Error ? err.message : String(err),\n });\n return { kind: \"failed\", reason: \"unexpected error\" } as DispatchOutcome;\n }),\n );\n\n return { claimed: claimed.length, outcomes };\n }\n\n /** Start the long-running poll loop. Idempotent. */\n start(): void {\n if (this.running) return;\n this.running = true;\n const interval = this.options.intervalMs ?? 1000;\n const loop = async () => {\n if (!this.running) return;\n try {\n await this.tick();\n } catch (err) {\n this.deps.logger.log(\"error\", \"send worker tick failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n } finally {\n if (this.running) this.timer = setTimeout(loop, interval);\n }\n };\n void loop();\n }\n\n /** Stop the loop. In-flight dispatches complete; no new tick starts. */\n stop(): void {\n this.running = false;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n }\n}\n\n/** Run `fn` over items with a bounded concurrency, preserving input order. */\nasync function runWithConcurrency<T, R>(\n items: T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let cursor = 0;\n const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {\n for (;;) {\n const i = cursor++;\n if (i >= items.length) return;\n results[i] = await fn(items[i]!);\n }\n });\n await Promise.all(workers);\n return results;\n}\n","import type { CoreDeps } from \"./context.js\";\nimport { purgeCutoff } from \"../domain/retention.js\";\n\nexport interface PurgeReport {\n /** Outbox rows whose PII was redacted (or deleted if redactOnPurge=false). */\n readonly operationalProcessed: number;\n /** Audit rows deleted. */\n readonly auditDeleted: number;\n readonly redacted: boolean;\n}\n\n/**\n * PurgeRetention — the executor of the data-minimization policy (TDR §3.9, §5.5).\n *\n * Safety properties baked in here:\n * - Acts ONLY on terminal rows older than the operational TTL AND past the\n * webhook window (`purgeCutoff`). Never touches `sent`/non-terminal rows,\n * so it can run concurrently with the send worker.\n * - Default action is REDACTION (wipe PII, keep audit metadata), not deletion.\n * - Works in batches with pauses to avoid long-held table locks.\n * - Logs counts per cycle so operators can detect \"stopped cleaning\" and\n * \"cleaning too much\".\n */\nexport class PurgeRetention {\n constructor(private readonly deps: CoreDeps) {}\n\n async execute(): Promise<PurgeReport> {\n const { deps } = this;\n return deps.telemetry.span(\"outpost.retention.purge\", {}, async () => {\n const now = deps.clock.now();\n const policy = deps.config.retention;\n const cutoff = purgeCutoff(policy, now);\n\n // 1. Operational data: redact or delete terminal+aged rows, batched.\n let operationalProcessed = 0;\n for (;;) {\n const batch = await deps.outbox.claimTerminalForPurge(cutoff, policy.batchSize);\n if (batch.length === 0) break;\n const ids = batch.map((m) => m.id);\n const count = policy.redactOnPurge\n ? await deps.outbox.redactBatch(ids)\n : await deps.outbox.deleteBatch(ids);\n operationalProcessed += count;\n\n await deps.audit.append({\n messageId: null,\n eventType: policy.redactOnPurge ? \"redacted\" : \"purged\",\n actor: \"system:retention\",\n detail: { count, cutoff: cutoff.toISOString() },\n });\n // Stop if the repo returned a short batch (no more eligible rows).\n if (batch.length < policy.batchSize) break;\n }\n\n // 2. Audit data: independent, longer TTL.\n const auditCutoff = new Date(now.getTime() - policy.auditTtlDays * 24 * 60 * 60 * 1000);\n const auditDeleted = await deps.audit.purgeOlderThan(auditCutoff, policy.batchSize);\n\n deps.telemetry.gauge(\"outpost.retention.operational_processed\", operationalProcessed);\n deps.telemetry.gauge(\"outpost.retention.audit_deleted\", auditDeleted);\n deps.logger.log(\"info\", \"retention cycle complete\", {\n operationalProcessed,\n auditDeleted,\n redacted: policy.redactOnPurge,\n });\n\n return { operationalProcessed, auditDeleted, redacted: policy.redactOnPurge };\n });\n }\n}\n","import type { CoreDeps } from \"../application/context.js\";\nimport { PurgeRetention, type PurgeReport } from \"../application/purge-retention.js\";\n\nexport interface RetentionWorkerOptions {\n /** Loop interval, ms. Default 1 hour. Retention is not latency-sensitive. */\n readonly intervalMs?: number;\n}\n\n/**\n * RetentionWorker — periodically enforces the retention/purge policy\n * (TDR §3.9). Like the send worker it offers both a long-running `start()`\n * loop and a single `tick()` for cron/route-handler deployments. It only ever\n * touches terminal, aged rows, so it is safe to run alongside the send worker.\n */\nexport class RetentionWorker {\n private readonly purge: PurgeRetention;\n private running = false;\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n private readonly deps: CoreDeps,\n private readonly options: RetentionWorkerOptions = {},\n ) {\n this.purge = new PurgeRetention(deps);\n }\n\n async tick(): Promise<PurgeReport> {\n return this.purge.execute();\n }\n\n start(): void {\n if (this.running) return;\n this.running = true;\n const interval = this.options.intervalMs ?? 60 * 60 * 1000;\n const loop = async () => {\n if (!this.running) return;\n try {\n await this.tick();\n } catch (err) {\n this.deps.logger.log(\"error\", \"retention worker tick failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n } finally {\n if (this.running) this.timer = setTimeout(loop, interval);\n }\n };\n void loop();\n }\n\n stop(): void {\n this.running = false;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n }\n}\n","import type { CoreDeps } from \"../application/context.js\";\nimport { EnqueueMessage, type EnqueueInput, type EnqueueResult } from \"../application/enqueue-message.js\";\nimport { IngestWebhook, type IngestWebhookResult } from \"../application/ingest-webhook.js\";\nimport { ManageSuppression } from \"../application/manage-suppression.js\";\nimport { ManageApiKey } from \"../application/manage-api-key.js\";\nimport { Authenticate } from \"../application/authenticate.js\";\nimport {\n GetMessage,\n ListMessages,\n ReplayMessage,\n type MessageView,\n} from \"../application/message-queries.js\";\nimport type { ListMessagesQuery } from \"../ports/repositories.js\";\nimport type { SuppressionReason, SuppressionEntry } from \"../domain/suppression.js\";\nimport type { RawWebhook } from \"../ports/email-provider.js\";\nimport { SendWorker } from \"../workers/send-worker.js\";\nimport { RetentionWorker } from \"../workers/retention-worker.js\";\n\n/**\n * The high-level, typed programmatic client returned by `createOutpost`\n * (TDR §4.2). Server-side use within the same app calls these methods directly;\n * cross-service callers go through the HTTP handlers (which call the same use\n * cases under the hood).\n *\n * `actor` labels who performed an action in the audit trail. The programmatic\n * client defaults to `\"programmatic\"`; the HTTP layer passes the API key id.\n */\nexport class Outpost {\n readonly enqueueMessage: EnqueueMessage;\n readonly ingestWebhook: IngestWebhook;\n readonly suppression: ManageSuppression;\n readonly keys: ManageApiKey;\n readonly auth: Authenticate;\n readonly send_worker: SendWorker;\n readonly retention_worker: RetentionWorker;\n\n private readonly getMessage: GetMessage;\n private readonly listMessages: ListMessages;\n private readonly replayMessage: ReplayMessage;\n\n constructor(\n readonly deps: CoreDeps,\n private readonly defaultActor = \"programmatic\",\n ) {\n this.enqueueMessage = new EnqueueMessage(deps);\n this.ingestWebhook = new IngestWebhook(deps);\n this.suppression = new ManageSuppression(deps);\n this.keys = new ManageApiKey(deps);\n this.auth = new Authenticate(deps);\n this.getMessage = new GetMessage(deps);\n this.listMessages = new ListMessages(deps);\n this.replayMessage = new ReplayMessage(deps);\n this.send_worker = new SendWorker(deps);\n this.retention_worker = new RetentionWorker(deps);\n }\n\n /** Enqueue a message (persist-then-queue). Idempotent on `idempotencyKey`. */\n send(input: EnqueueInput, opts?: { actor?: string }): Promise<EnqueueResult> {\n return this.enqueueMessage.execute(input, opts?.actor ?? this.defaultActor);\n }\n\n /** Fetch a message's lifecycle + metadata (PII-free view). */\n get(id: string): Promise<MessageView> {\n return this.getMessage.execute(id);\n }\n\n /** List messages by state / recipient hash / date. */\n list(query: ListMessagesQuery = {}): Promise<MessageView[]> {\n return this.listMessages.execute(query);\n }\n\n /** Re-enqueue a dead-lettered (failed) message from the DLQ. */\n replay(id: string, opts?: { actor?: string }): Promise<MessageView> {\n return this.replayMessage.execute(id, opts?.actor ?? this.defaultActor);\n }\n\n /** Check whether an address is on the suppression list. */\n isSuppressed(address: string): Promise<boolean> {\n return this.suppression.isSuppressed(address);\n }\n\n /** Add an address to the suppression list (audited). */\n suppress(\n address: string,\n reason: SuppressionReason = \"manual\",\n opts?: { note?: string; actor?: string },\n ): Promise<SuppressionEntry> {\n return this.suppression.suppress(address, reason, opts?.actor ?? this.defaultActor, opts?.note);\n }\n\n /** Remove an address from the suppression list (audited). */\n async unsuppress(address: string, opts?: { actor?: string }): Promise<boolean> {\n const hmac = this.deps.recipientHasher.hash(address);\n return this.suppression.unsuppressByHmac(hmac, opts?.actor ?? this.defaultActor);\n }\n\n /** Ingest a verified provider webhook (used by the HTTP webhook sink). */\n webhook(provider: string, raw: RawWebhook): Promise<IngestWebhookResult> {\n return this.ingestWebhook.execute(provider, raw);\n }\n\n /** Convenience: run one send-worker cycle (cron/route-handler deployments). */\n tickSend(): ReturnType<SendWorker[\"tick\"]> {\n return this.send_worker.tick();\n }\n\n /** Convenience: run one retention cycle. */\n tickRetention(): ReturnType<RetentionWorker[\"tick\"]> {\n return this.retention_worker.tick();\n }\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\nimport type { RecipientHasher } from \"../../ports/crypto.js\";\n\n/**\n * Keyed HMAC-SHA256 recipient hasher (TDR §5.4 condition 3).\n *\n * Deterministic (same address → same digest, so suppression/idempotency work)\n * and keyed (a leaked DB dump cannot be brute-forced into addresses without the\n * key). The key MUST live outside the database — pass it from KMS/Vault/secrets,\n * never store it in a column.\n *\n * Addresses are normalized (trim + lowercase) before hashing so casing/whitespace\n * variants of the same address collapse to one digest.\n */\nexport class HmacRecipientHasher implements RecipientHasher {\n private readonly key: Buffer;\n\n constructor(key: string | Buffer) {\n this.key = typeof key === \"string\" ? Buffer.from(key, \"utf8\") : key;\n if (this.key.length < 16) {\n throw new Error(\"Recipient HMAC key must be at least 16 bytes of entropy\");\n }\n }\n\n hash(address: string): string {\n const normalized = address.trim().toLowerCase();\n return createHmac(\"sha256\", this.key).update(normalized, \"utf8\").digest(\"hex\");\n }\n\n /** Constant-time comparison helper for callers that compare digests. */\n static equals(a: string, b: string): boolean {\n const ab = Buffer.from(a);\n const bb = Buffer.from(b);\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n }\n}\n","import {\n randomBytes,\n createCipheriv,\n createDecipheriv,\n publicEncrypt,\n privateDecrypt,\n constants as cryptoConstants,\n} from \"node:crypto\";\nimport type { Encryptor } from \"../../ports/crypto.js\";\nimport type { Sealed } from \"../../domain/message.js\";\n\n/**\n * Encryptor implementations (TDR §5.4). All use vetted primitives — no\n * hand-rolled crypto. Three flavors:\n *\n * - NoopEncryptor — encryption disabled; `alg: \"plain\"`. Same column\n * shape so encryption can be turned on later with no\n * row-format migration.\n * - AesGcmEncryptor — symmetric AEAD (AES-256-GCM). One key seals+opens.\n * - Hybrid{Seal,Open} — asymmetric least-privilege split: the ingestion API\n * gets seal-only (public key), the send worker gets\n * open (private key). The web tier physically cannot\n * read plaintext back.\n *\n * For production, hold key material in KMS/Vault and implement `Encryptor`\n * against it (envelope encryption) — these local-key classes are the reference\n * and the dev/test default. See docs/security.md.\n */\n\nconst PLAIN_ALG = \"plain\";\n\n/** No-op: stores base64(plaintext). Used when encryption is disabled. */\nexport class NoopEncryptor implements Encryptor {\n readonly alg = PLAIN_ALG;\n async seal(plaintext: string): Promise<Sealed> {\n return { alg: PLAIN_ALG, ciphertext: Buffer.from(plaintext, \"utf8\").toString(\"base64\") };\n }\n async open(sealed: Sealed): Promise<string> {\n return Buffer.from(sealed.ciphertext, \"base64\").toString(\"utf8\");\n }\n}\n\nconst AES_ALG = \"aes-256-gcm\";\n\n/** Symmetric AEAD. The 32-byte key MUST come from KMS/secrets, not the DB. */\nexport class AesGcmEncryptor implements Encryptor {\n readonly alg = AES_ALG;\n private readonly key: Buffer;\n\n constructor(key: Buffer, private readonly keyId = \"default\") {\n if (key.length !== 32) throw new Error(\"AES-256-GCM requires a 32-byte key\");\n this.key = key;\n }\n\n async seal(plaintext: string): Promise<Sealed> {\n const iv = randomBytes(12);\n const cipher = createCipheriv(AES_ALG, this.key, iv);\n const ct = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n const tag = cipher.getAuthTag();\n return {\n alg: AES_ALG,\n ciphertext: ct.toString(\"base64\"),\n iv: iv.toString(\"base64\"),\n tag: tag.toString(\"base64\"),\n keyId: this.keyId,\n };\n }\n\n async open(sealed: Sealed): Promise<string> {\n if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);\n if (!sealed.iv || !sealed.tag) throw new Error(\"Sealed value missing iv/tag\");\n const decipher = createDecipheriv(AES_ALG, this.key, Buffer.from(sealed.iv, \"base64\"));\n decipher.setAuthTag(Buffer.from(sealed.tag, \"base64\"));\n const pt = Buffer.concat([\n decipher.update(Buffer.from(sealed.ciphertext, \"base64\")),\n decipher.final(),\n ]);\n return pt.toString(\"utf8\");\n }\n}\n\nconst HYBRID_ALG = \"hybrid-rsa-aes-256-gcm\";\n\nfunction rsaOaep(key: string) {\n return { key, padding: cryptoConstants.RSA_PKCS1_OAEP_PADDING, oaepHash: \"sha256\" } as const;\n}\n\n/**\n * Seal-only encryptor for the ingestion tier. Holds ONLY the public key:\n * generates a fresh AES data key per message, seals the payload with it, and\n * wraps the data key under RSA-OAEP. `open` throws — by construction the web\n * tier cannot decrypt (TDR §5.4 condition 2).\n */\nexport class HybridSealEncryptor implements Encryptor {\n readonly alg = HYBRID_ALG;\n constructor(private readonly publicKeyPem: string, private readonly keyId = \"default\") {}\n\n async seal(plaintext: string): Promise<Sealed> {\n const dataKey = randomBytes(32);\n const iv = randomBytes(12);\n const cipher = createCipheriv(AES_ALG, dataKey, iv);\n const ct = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n const tag = cipher.getAuthTag();\n const wrappedKey = publicEncrypt(rsaOaep(this.publicKeyPem), dataKey);\n return {\n alg: HYBRID_ALG,\n ciphertext: ct.toString(\"base64\"),\n iv: iv.toString(\"base64\"),\n tag: tag.toString(\"base64\"),\n wrappedKey: wrappedKey.toString(\"base64\"),\n keyId: this.keyId,\n };\n }\n\n async open(): Promise<string> {\n throw new Error(\n \"HybridSealEncryptor cannot decrypt: the ingestion tier holds only the public key (by design)\",\n );\n }\n}\n\n/**\n * Open-capable encryptor for the send worker. Holds the private key; unwraps the\n * data key and decrypts. `seal` throws — the worker is not the writer.\n */\nexport class HybridOpenEncryptor implements Encryptor {\n readonly alg = HYBRID_ALG;\n constructor(private readonly privateKeyPem: string) {}\n\n async seal(): Promise<Sealed> {\n throw new Error(\"HybridOpenEncryptor is read-only; use HybridSealEncryptor to seal\");\n }\n\n async open(sealed: Sealed): Promise<string> {\n if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);\n if (!sealed.wrappedKey || !sealed.iv || !sealed.tag) {\n throw new Error(\"Sealed value missing wrappedKey/iv/tag for hybrid open\");\n }\n const dataKey = privateDecrypt(\n rsaOaep(this.privateKeyPem),\n Buffer.from(sealed.wrappedKey, \"base64\"),\n );\n const decipher = createDecipheriv(AES_ALG, dataKey, Buffer.from(sealed.iv, \"base64\"));\n decipher.setAuthTag(Buffer.from(sealed.tag, \"base64\"));\n const pt = Buffer.concat([\n decipher.update(Buffer.from(sealed.ciphertext, \"base64\")),\n decipher.final(),\n ]);\n return pt.toString(\"utf8\");\n }\n}\n","import type { RateLimiter, RateLimitScope, Clock } from \"../../ports/services.js\";\nimport type { RateLimitConfig, RateBudget } from \"../../application/config.js\";\n\n/**\n * In-memory token-bucket rate limiter (TDR §3.2 step 4).\n *\n * Layered: a distinct bucket per (scope.kind + scope.key). A budget of\n * `{ max, windowMs }` refills `max` tokens over `windowMs`. `acquire` consumes\n * one token; returns false when the bucket is empty (caller re-queues).\n *\n * This is correct for a SINGLE process. For multiple send-worker instances,\n * implement the `RateLimiter` port against Redis (shared counters) — the port\n * is the seam, the core does not change.\n */\nexport class InMemoryRateLimiter implements RateLimiter {\n private readonly buckets = new Map<string, { tokens: number; lastRefill: number }>();\n\n constructor(\n private readonly config: RateLimitConfig,\n private readonly clock: Clock,\n ) {}\n\n async acquire(scope: RateLimitScope): Promise<boolean> {\n const budget = this.budgetFor(scope);\n if (!budget) return true; // unlimited when no budget configured\n\n const key = `${scope.kind}:${scope.key ?? \"\"}`;\n const now = this.clock.now().getTime();\n const refillRate = budget.max / budget.windowMs; // tokens per ms\n\n let bucket = this.buckets.get(key);\n if (!bucket) {\n bucket = { tokens: budget.max, lastRefill: now };\n this.buckets.set(key, bucket);\n } else {\n const elapsed = now - bucket.lastRefill;\n bucket.tokens = Math.min(budget.max, bucket.tokens + elapsed * refillRate);\n bucket.lastRefill = now;\n }\n\n if (bucket.tokens >= 1) {\n bucket.tokens -= 1;\n return true;\n }\n return false;\n }\n\n private budgetFor(scope: RateLimitScope): RateBudget | undefined {\n switch (scope.kind) {\n case \"global\":\n return this.config.global;\n case \"provider\":\n return this.config.perProvider;\n case \"recipientDomain\":\n return this.config.perRecipientDomain;\n }\n }\n}\n\n/** Always allows. Used when no rate limits are configured. */\nexport class UnlimitedRateLimiter implements RateLimiter {\n async acquire(): Promise<boolean> {\n return true;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { resolveMx as dnsResolveMx } from \"node:dns/promises\";\nimport type { Clock, IdGenerator } from \"../../ports/services.js\";\nimport type { MxResolver } from \"../../application/pipeline/domain-validation.js\";\n\n/** Real wall-clock. Inject a fake `Clock` in tests for determinism. */\nexport class SystemClock implements Clock {\n now(): Date {\n return new Date();\n }\n}\n\n/** UUID v4 ids via node:crypto. */\nexport class UuidGenerator implements IdGenerator {\n generate(): string {\n return randomUUID();\n }\n}\n\n/** MX resolver backed by node:dns. Used only when domainValidation.mx is on. */\nexport class DnsMxResolver implements MxResolver {\n async resolveMx(domain: string): Promise<string[]> {\n const records = await dnsResolveMx(domain);\n return records\n .sort((a, b) => a.priority - b.priority)\n .map((r) => r.exchange);\n }\n}\n","import type { Logger, LogLevel } from \"../../ports/services.js\";\n\n/** Structured console logger (JSON lines). The default when none is provided. */\nexport class ConsoleLogger implements Logger {\n constructor(private readonly minLevel: LogLevel = \"info\") {}\n\n private static readonly RANK: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n };\n\n log(level: LogLevel, message: string, fields?: Record<string, unknown>): void {\n if (ConsoleLogger.RANK[level] < ConsoleLogger.RANK[this.minLevel]) return;\n const line = JSON.stringify({ level, message, ...fields });\n if (level === \"error\") console.error(line);\n else if (level === \"warn\") console.warn(line);\n else console.log(line);\n }\n}\n\n/** Drops everything. Useful in tests. */\nexport class NoopLogger implements Logger {\n log(): void {}\n}\n","import type { Telemetry } from \"../../ports/services.js\";\n\n/**\n * No-op telemetry. Used when observability is disabled. Still runs the wrapped\n * function so behavior is identical to the instrumented path.\n */\nexport class NoopTelemetry implements Telemetry {\n async span<T>(_name: string, _attrs: Record<string, unknown>, fn: () => Promise<T>): Promise<T> {\n return fn();\n }\n counter(): void {}\n gauge(): void {}\n}\n\n/**\n * OpenTelemetry-backed telemetry (TDR §8). `@opentelemetry/api` is an OPTIONAL\n * peer dependency: this adapter imports it lazily so the package works without\n * it installed. Wire the OTel SDK (exporters, providers) in your application;\n * this adapter only emits to whatever global meter/tracer is registered.\n *\n * Usage:\n * import { OtelTelemetry } from \"@tgoliveira/outpost/adapters\";\n * const telemetry = await OtelTelemetry.create();\n */\nexport class OtelTelemetry implements Telemetry {\n private constructor(\n // Loosely typed to avoid a hard dependency on @opentelemetry/api types.\n private readonly tracer: any,\n private readonly counters: Map<string, any>,\n private readonly gauges: Map<string, any>,\n private readonly meter: any,\n private readonly api: any,\n ) {}\n\n static async create(serviceName = \"outpost\"): Promise<Telemetry> {\n try {\n const api = await import(\"@opentelemetry/api\");\n const tracer = api.trace.getTracer(serviceName);\n const meter = api.metrics.getMeter(serviceName);\n return new OtelTelemetry(tracer, new Map(), new Map(), meter, api);\n } catch {\n // @opentelemetry/api not installed → degrade gracefully to no-op.\n return new NoopTelemetry();\n }\n }\n\n async span<T>(name: string, attrs: Record<string, unknown>, fn: () => Promise<T>): Promise<T> {\n return this.tracer.startActiveSpan(name, async (span: any) => {\n try {\n for (const [k, v] of Object.entries(attrs)) span.setAttribute(k, v as any);\n const result = await fn();\n span.setStatus({ code: this.api.SpanStatusCode.OK });\n return result;\n } catch (err) {\n span.recordException(err as Error);\n span.setStatus({\n code: this.api.SpanStatusCode.ERROR,\n message: err instanceof Error ? err.message : String(err),\n });\n throw err;\n } finally {\n span.end();\n }\n });\n }\n\n counter(name: string, value: number, attrs?: Record<string, unknown>): void {\n let c = this.counters.get(name);\n if (!c) {\n c = this.meter.createCounter(name);\n this.counters.set(name, c);\n }\n c.add(value, attrs);\n }\n\n gauge(name: string, value: number, attrs?: Record<string, unknown>): void {\n // Use a counter-style observation; for true gauges wire an observable\n // gauge in your SDK. Recorded as a histogram-friendly value here.\n let g = this.gauges.get(name);\n if (!g) {\n g = this.meter.createHistogram(name);\n this.gauges.set(name, g);\n }\n g.record(value, attrs);\n }\n}\n","import type { CoreDeps } from \"./application/context.js\";\nimport { resolveConfig, type ConfigOverrides, type RateLimitConfig } from \"./application/config.js\";\nimport { Outpost } from \"./client/outpost-client.js\";\nimport type {\n OutboxRepository,\n SuppressionRepository,\n AuditRepository,\n ApiKeyRepository,\n WebhookEventRepository,\n} from \"./ports/repositories.js\";\nimport type { EmailProvider } from \"./ports/email-provider.js\";\nimport type { Encryptor } from \"./ports/crypto.js\";\nimport type { Clock, IdGenerator, Logger, Telemetry, RateLimiter } from \"./ports/services.js\";\nimport type { TemplateRenderer } from \"./ports/template.js\";\nimport type { MxResolver } from \"./application/pipeline/domain-validation.js\";\n\nimport { HmacRecipientHasher } from \"./adapters/crypto/recipient-hasher.js\";\nimport {\n NoopEncryptor,\n AesGcmEncryptor,\n HybridSealEncryptor,\n HybridOpenEncryptor,\n} from \"./adapters/crypto/encryptors.js\";\nimport { InMemoryRateLimiter, UnlimitedRateLimiter } from \"./adapters/rate-limit/in-memory.js\";\nimport { SystemClock, UuidGenerator, DnsMxResolver } from \"./adapters/services/system.js\";\nimport { ConsoleLogger } from \"./adapters/observability/logger.js\";\nimport { NoopTelemetry } from \"./adapters/observability/telemetry.js\";\n\n/**\n * Encryption posture (TDR §5.4). Pick one:\n *\n * - `none` — encryption disabled (`alg: \"plain\"`). Dev default.\n * - `symmetric` — AES-256-GCM; one 32-byte key seals and opens. Simple,\n * single-process. Key MUST come from KMS/secrets.\n * - `asymmetric` — least-privilege split: the web tier seals with the\n * PUBLIC key and can never read back; the send worker opens\n * with the PRIVATE key. Omit `privateKey` on the web tier.\n * - bring-your-own `Encryptor` pair — back it with AWS KMS / GCP KMS / Vault.\n */\nexport type EncryptionOptions =\n | { mode: \"none\" }\n | { mode: \"symmetric\"; key: Buffer | string; keyId?: string }\n | { mode: \"asymmetric\"; publicKey: string; privateKey?: string; keyId?: string }\n | { sealEncryptor: Encryptor; openEncryptor: Encryptor };\n\nexport interface OutpostOptions extends ConfigOverrides {\n /**\n * Persistence. Build these from your Drizzle db via the helpers in\n * `@tgoliveira/outpost/drizzle`, or use the in-memory ones from\n * `@tgoliveira/outpost/testing`.\n */\n repositories: {\n outbox: OutboxRepository;\n suppressions: SuppressionRepository;\n audit: AuditRepository;\n apiKeys: ApiKeyRepository;\n webhookEvents: WebhookEventRepository;\n };\n\n /** One or more transport adapters. The first is the default unless overridden. */\n providers: EmailProvider[];\n defaultProvider?: string;\n\n /**\n * Key for the deterministic recipient HMAC (TDR §5.4). REQUIRED — it backs\n * suppression matching and recipient-keyed lookups even when encryption is\n * off. Must be ≥16 bytes of entropy and live OUTSIDE the database.\n */\n recipientHmacKey: string | Buffer;\n\n /** Encryption-at-rest posture. Defaults to `{ mode: \"none\" }`. */\n encryption?: EncryptionOptions;\n\n rateLimits?: RateLimitConfig;\n\n /** Template renderer (e.g. InMemoryTemplateRenderer). Optional. */\n templates?: TemplateRenderer;\n\n /** Pre-built telemetry. For OTel: `telemetry: await OtelTelemetry.create()`. */\n telemetry?: Telemetry;\n logger?: Logger;\n clock?: Clock;\n ids?: IdGenerator;\n rateLimiter?: RateLimiter;\n mxResolver?: MxResolver;\n /** Strong HTML sanitizer (e.g. sanitize-html). Falls back to a built-in. */\n sanitizeHtml?: (html: string) => string;\n /** Random source for retry jitter. Defaults to Math.random. */\n random?: () => number;\n /** Default audit actor for programmatic calls. Default \"programmatic\". */\n defaultActor?: string;\n}\n\n/**\n * Composition root (TDR §6, Dependency Inversion). Resolves config, wires the\n * adapters into a `CoreDeps`, and returns the high-level `Outpost` client.\n *\n * This is the ONLY place concrete adapters are assembled — everything inward\n * depends on ports. Swapping a provider, storage backend, or KMS is a change\n * here, never in the core.\n */\nexport function createOutpost(options: OutpostOptions): Outpost {\n const config = resolveConfig({\n retry: options.retry,\n retention: options.retention,\n sanitize: options.sanitize,\n attachments: options.attachments,\n domainValidation: options.domainValidation,\n rateLimits: options.rateLimits,\n sendBatchSize: options.sendBatchSize,\n });\n\n if (options.providers.length === 0) {\n throw new Error(\"createOutpost requires at least one provider\");\n }\n const providers = new Map<string, EmailProvider>();\n for (const p of options.providers) providers.set(p.name, p);\n const defaultProvider = options.defaultProvider ?? options.providers[0]!.name;\n if (!providers.has(defaultProvider)) {\n throw new Error(`defaultProvider \"${defaultProvider}\" is not in the providers list`);\n }\n\n const { sealEncryptor, openEncryptor } = resolveEncryption(options.encryption ?? { mode: \"none\" });\n const recipientHasher = new HmacRecipientHasher(options.recipientHmacKey);\n\n const clock: Clock = options.clock ?? new SystemClock();\n const rateLimiter: RateLimiter =\n options.rateLimiter ??\n (options.rateLimits ? new InMemoryRateLimiter(options.rateLimits, clock) : new UnlimitedRateLimiter());\n\n const deps: CoreDeps = {\n config,\n outbox: options.repositories.outbox,\n suppressions: options.repositories.suppressions,\n audit: options.repositories.audit,\n apiKeys: options.repositories.apiKeys,\n webhookEvents: options.repositories.webhookEvents,\n providers,\n defaultProvider,\n sealEncryptor,\n openEncryptor,\n recipientHasher,\n rateLimiter,\n clock,\n ids: options.ids ?? new UuidGenerator(),\n logger: options.logger ?? new ConsoleLogger(),\n telemetry: options.telemetry ?? new NoopTelemetry(),\n templates: options.templates,\n mxResolver:\n options.mxResolver ?? (config.domainValidation.mx ? new DnsMxResolver() : undefined),\n sanitizeHtml: options.sanitizeHtml,\n random: options.random ?? Math.random,\n };\n\n return new Outpost(deps, options.defaultActor);\n}\n\nfunction resolveEncryption(enc: EncryptionOptions): {\n sealEncryptor: Encryptor;\n openEncryptor: Encryptor;\n} {\n if (\"sealEncryptor\" in enc) {\n return { sealEncryptor: enc.sealEncryptor, openEncryptor: enc.openEncryptor };\n }\n switch (enc.mode) {\n case \"none\": {\n const noop = new NoopEncryptor();\n return { sealEncryptor: noop, openEncryptor: noop };\n }\n case \"symmetric\": {\n const key = typeof enc.key === \"string\" ? Buffer.from(enc.key, \"base64\") : enc.key;\n const e = new AesGcmEncryptor(key, enc.keyId);\n return { sealEncryptor: e, openEncryptor: e };\n }\n case \"asymmetric\": {\n const seal = new HybridSealEncryptor(enc.publicKey, enc.keyId);\n // No private key (web tier) → an opener that refuses, preserving the\n // \"web tier cannot read\" invariant.\n const open = enc.privateKey ? new HybridOpenEncryptor(enc.privateKey) : seal;\n return { sealEncryptor: seal, openEncryptor: open };\n }\n }\n}\n","/**\n * Suppression list domain types.\n *\n * The suppression list is the reputation guardrail: any address on it is never\n * dispatched to. Entries are keyed by the recipient HMAC (not plaintext) so the\n * list keeps working when recipients are encrypted at rest (TDR §3.6, §5.4).\n */\n\nexport const SUPPRESSION_REASONS = [\n \"hard_bounce\",\n \"complaint\",\n \"unsubscribe\",\n \"invalid\",\n \"manual\",\n] as const;\n\nexport type SuppressionReason = (typeof SUPPRESSION_REASONS)[number];\n\nexport interface SuppressionEntry {\n /** Keyed HMAC of the suppressed address. Unique. */\n readonly recipientHmac: string;\n readonly reason: SuppressionReason;\n /** api key id, provider name, or \"system\". For the audit trail. */\n readonly createdBy: string;\n readonly createdAt: Date;\n /** Optional free-text note (e.g. the provider bounce message). */\n readonly note?: string;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/application/pipeline/retry-policy.ts","../src/domain/provider-failure.ts","../src/domain/errors.ts","../src/application/pipeline/sanitize.ts","../src/application/pipeline/domain-validation.ts","../src/domain/retention.ts","../src/application/config.ts","../src/application/enqueue-message.ts","../src/domain/webhook.ts","../src/domain/lifecycle.ts","../src/application/ingest-webhook.ts","../src/application/manage-suppression.ts","../src/application/manage-api-key.ts","../src/domain/api-key.ts","../src/application/authenticate.ts","../src/application/message-queries.ts","../src/application/dispatch-message.ts","../src/workers/send-worker.ts","../src/application/purge-retention.ts","../src/workers/retention-worker.ts","../src/client/outpost-client.ts","../src/adapters/crypto/recipient-hasher.ts","../src/adapters/crypto/encryptors.ts","../src/adapters/rate-limit/in-memory.ts","../src/adapters/services/system.ts","../src/adapters/observability/logger.ts","../src/adapters/observability/telemetry.ts","../src/create-outpost.ts","../src/domain/suppression.ts"],"names":["nextAttemptAt","randomBytes","cryptoConstants","dnsResolveMx"],"mappings":";;;;AAiBO,IAAM,aAAA,GAA6B;AAAA,EACxC,WAAA,EAAa,CAAA;AAAA,EACb,WAAA,EAAa,GAAA;AAAA;AAAA,EACb,UAAA,EAAY,KAAK,EAAA,GAAK;AAAA;AACxB;AAGO,SAAS,WAAA,CAAY,UAAkB,MAAA,EAA8B;AAC1E,EAAA,OAAO,YAAY,MAAA,CAAO,WAAA;AAC5B;AAOO,SAAS,SAAA,CAAU,QAAA,EAAkB,MAAA,EAAqB,MAAA,EAAwB;AACvF,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,UAAA,EAAY,MAAA,CAAO,WAAA,GAAc,CAAA,IAAK,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,QAAA,GAAW,CAAC,CAAC,CAAA;AAC3F,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,GAAM,MAAM,CAAA;AAChC;AAGO,SAAS,aAAA,CACd,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,IAAA,EAAK;AAAA,IACpD;AAAA,IACA,KAAK,WAAA,EAAa;AAChB,MAAA,MAAM,GAAA,GAAM,OAAO,GAAA,CAAI,GAAA,KAAQ,QAAA,GAAW,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,GAAA,EAAK,QAAQ,CAAA,GAAI,GAAA,CAAI,GAAA;AAC/E,MAAA,MAAM,CAAA,GAAI,IAAI,eAAA,CAAgB,GAAA,EAAK,IAAI,KAAK,CAAA;AAC5C,MAAA,OAAO,EAAE,aAAA,EAAe,CAAA,EAAG,aAAA,EAAe,CAAA,EAAE;AAAA,IAC9C;AAAA,IACA,KAAK,YAAA,EAAc;AACjB,MAAA,MAAM,OAAO,IAAI,mBAAA,CAAoB,GAAA,CAAI,SAAA,EAAW,IAAI,KAAK,CAAA;AAG7D,MAAA,MAAM,IAAA,GAAO,IAAI,UAAA,GAAa,IAAI,oBAAoB,GAAA,CAAI,UAAA,EAAY,GAAA,CAAI,KAAK,CAAA,GAAI,IAAA;AACnF,MAAA,OAAO,EAAE,aAAA,EAAe,IAAA,EAAM,aAAA,EAAe,IAAA,EAAK;AAAA,IACpD;AAAA;AAEJ;;;AChLO,IAAM,mBAAA,GAAsB;AAAA,EACjC,aAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF","file":"index.js","sourcesContent":["/**\n * Retry policy: exponential backoff with full jitter (TDR §3.4).\n *\n * Pure function of (attempt number, config) → delay. Jitter is injected as a\n * 0..1 random sample so the policy stays deterministic and testable (the\n * worker passes a real random; tests pass a fixed value).\n */\n\nexport interface RetryConfig {\n /** Max dispatch attempts before a message is dead-lettered. */\n readonly maxAttempts: number;\n /** Base backoff in ms (first retry waits ~this, before jitter). */\n readonly baseDelayMs: number;\n /** Cap on the backoff in ms. */\n readonly maxDelayMs: number;\n}\n\nexport const DEFAULT_RETRY: RetryConfig = {\n maxAttempts: 5,\n baseDelayMs: 30_000, // 30s\n maxDelayMs: 60 * 60 * 1000, // 1h\n};\n\n/** True once attempts have reached the budget — message goes to the DLQ. */\nexport function isExhausted(attempts: number, config: RetryConfig): boolean {\n return attempts >= config.maxAttempts;\n}\n\n/**\n * Backoff for the NEXT attempt after `attempts` failed tries.\n * delay = min(maxDelay, base * 2^(attempts-1)) then full-jitter: random in\n * [0, delay]. `jitter` is a sample in [0,1).\n */\nexport function backoffMs(attempts: number, config: RetryConfig, jitter: number): number {\n const exp = Math.min(config.maxDelayMs, config.baseDelayMs * 2 ** Math.max(0, attempts - 1));\n return Math.floor(exp * jitter);\n}\n\n/** Convenience: the Date of the next attempt from `now`. */\nexport function nextAttemptAt(\n attempts: number,\n config: RetryConfig,\n jitter: number,\n now: Date,\n): Date {\n return new Date(now.getTime() + backoffMs(attempts, config, jitter));\n}\n","/**\n * Classifies a thrown value by the public provider-failure pair.\n * This module is not on the package barrel.\n *\n * Permanent only when errorClass === \"permanent\" and code === \"provider_permanent\".\n * Transient only when errorClass === \"transient\" and code === \"provider_transient\".\n * One field, a mismatched pair, a plain Error, null, or a non-object is neither.\n */\n\n/** \"permanent\", \"transient\", or unrecognized. */\nexport function classifyProviderFailure(err: unknown): \"permanent\" | \"transient\" | undefined {\n if (typeof err !== \"object\" || err === null) return undefined;\n const errorClass = (err as { errorClass?: unknown }).errorClass;\n const code = (err as { code?: unknown }).code;\n if (errorClass === \"permanent\" && code === \"provider_permanent\") return \"permanent\";\n if (errorClass === \"transient\" && code === \"provider_transient\") return \"transient\";\n return undefined;\n}\n","/**\n * Domain error taxonomy.\n *\n * Errors are classified so the dispatch pipeline can decide retry vs. fail\n * without inspecting provider-specific error shapes (TDR §3.4). Adapters map\n * their native errors onto these classes; the core never sees raw SDK errors.\n */\n\nimport { classifyProviderFailure } from \"./provider-failure.js\";\n\nexport type ErrorClass = \"transient\" | \"permanent\";\n\n/** Base class for all errors Outpost raises. Carries a stable machine `code`. */\nexport class OutpostError extends Error {\n readonly code: string;\n constructor(code: string, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = new.target.name;\n this.code = code;\n }\n}\n\n/** A request failed authentication (missing/expired/revoked key). → HTTP 401. */\nexport class UnauthorizedError extends OutpostError {\n constructor(message = \"Missing, expired, or revoked API key\") {\n super(\"unauthorized\", message);\n }\n}\n\n/** A valid key lacked the required scope. → HTTP 403. */\nexport class ForbiddenError extends OutpostError {\n constructor(message = \"API key lacks the required scope\") {\n super(\"forbidden\", message);\n }\n}\n\n/** Caller input failed validation/sanitization. Never retried. → HTTP 400. */\nexport class ValidationError extends OutpostError {\n readonly details?: unknown;\n constructor(message: string, details?: unknown) {\n super(\"validation_failed\", message);\n this.details = details;\n }\n}\n\n/** A referenced resource does not exist. → HTTP 404. */\nexport class NotFoundError extends OutpostError {\n constructor(message = \"Resource not found\") {\n super(\"not_found\", message);\n }\n}\n\n/** A lifecycle transition violated the state machine. Programming/state bug. */\nexport class InvalidStateTransitionError extends OutpostError {\n constructor(from: string, to: string) {\n super(\"invalid_transition\", `Cannot transition message from \"${from}\" to \"${to}\"`);\n }\n}\n\n/** Webhook signature verification failed. → HTTP 401, logged. */\nexport class WebhookVerificationError extends OutpostError {\n constructor(message = \"Webhook signature verification failed\") {\n super(\"webhook_unverified\", message);\n }\n}\n\n/**\n * Raised by `EmailProvider` implementations. Classification uses the stored\n * pair, not one field alone: `errorClass === \"transient\"` with\n * `code === \"provider_transient\"`, or `errorClass === \"permanent\"` with\n * `code === \"provider_permanent\"`.\n */\nexport class ProviderError extends OutpostError {\n readonly errorClass: ErrorClass;\n readonly providerCode?: string;\n constructor(\n errorClass: ErrorClass,\n message: string,\n options?: { providerCode?: string; cause?: unknown },\n ) {\n super(`provider_${errorClass}`, message, options);\n this.errorClass = errorClass;\n this.providerCode = options?.providerCode;\n }\n\n static transient(message: string, options?: { providerCode?: string; cause?: unknown }) {\n return new ProviderError(\"transient\", message, options);\n }\n\n static permanent(message: string, options?: { providerCode?: string; cause?: unknown }) {\n return new ProviderError(\"permanent\", message, options);\n }\n}\n\n/** True only when `errorClass === \"transient\"` and `code === \"provider_transient\"`. */\nexport function isTransient(err: unknown): boolean {\n return classifyProviderFailure(err) === \"transient\";\n}\n","import { ValidationError } from \"../../domain/errors.js\";\n\n/**\n * Outbound sanitization (TDR §3.2 step 2, §5.3).\n *\n * These are conservative, dependency-free guards focused on the email-specific\n * attack surface: header injection (CRLF) and oversize payloads. For rich HTML\n * sanitization against XSS you SHOULD plug a hardened sanitizer (e.g.\n * `sanitize-html` / DOMPurify) via `createOutpost({ sanitizeHtml })`; the\n * built-in `stripDangerousHtml` below is a last-resort fallback, not a\n * substitute for a real sanitizer.\n */\n\n/** Default ceilings; override via config. */\nexport interface SanitizeLimits {\n readonly maxSubjectBytes: number;\n readonly maxBodyBytes: number;\n readonly maxRecipientBytes: number;\n readonly maxHeaderValueBytes: number;\n}\n\nexport const DEFAULT_SANITIZE_LIMITS: SanitizeLimits = {\n maxSubjectBytes: 2_000,\n maxBodyBytes: 5_000_000, // 5 MB\n maxRecipientBytes: 320, // RFC 5321 max\n maxHeaderValueBytes: 4_000,\n};\n\nconst byteLen = (s: string) => Buffer.byteLength(s, \"utf8\");\n\n/**\n * Reject control characters in any value used as an email header (To, Subject,\n * custom headers). This is THE header-injection defense — without it an attacker\n * can inject a CR/LF + \"Bcc:\" and turn one message into many, or use a NUL to\n * truncate. Implemented as a char-code scan (not a regex) so the intent is\n * unambiguous: reject every C0 control char (0x00–0x1F, which includes CR, LF,\n * NUL and TAB) and DEL (0x7F), while ALLOWING ordinary printable characters\n * including the space (0x20). An earlier regex form also matched the space,\n * which wrongly rejected normal multi-word subjects.\n */\nexport function assertNoHeaderInjection(field: string, value: string): void {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < 0x20 || code === 0x7f) {\n throw new ValidationError(`Illegal control character in \"${field}\" (header injection attempt)`);\n }\n }\n}\n\nexport function sanitizeSubject(subject: string, limits = DEFAULT_SANITIZE_LIMITS): string {\n assertNoHeaderInjection(\"subject\", subject);\n const trimmed = subject.trim();\n if (byteLen(trimmed) > limits.maxSubjectBytes) {\n throw new ValidationError(`Subject exceeds ${limits.maxSubjectBytes} bytes`);\n }\n return trimmed;\n}\n\nexport function sanitizeRecipient(to: string, limits = DEFAULT_SANITIZE_LIMITS): string {\n assertNoHeaderInjection(\"to\", to);\n const trimmed = to.trim();\n if (byteLen(trimmed) > limits.maxRecipientBytes) {\n throw new ValidationError(`Recipient exceeds ${limits.maxRecipientBytes} bytes`);\n }\n return trimmed;\n}\n\nexport function sanitizeHeaders(\n headers: Record<string, string>,\n limits = DEFAULT_SANITIZE_LIMITS,\n): Record<string, string> {\n for (const [k, v] of Object.entries(headers)) {\n assertNoHeaderInjection(`header:${k}`, k);\n assertNoHeaderInjection(`header:${k}`, v);\n if (byteLen(v) > limits.maxHeaderValueBytes) {\n throw new ValidationError(`Header \"${k}\" exceeds ${limits.maxHeaderValueBytes} bytes`);\n }\n }\n return headers;\n}\n\nexport function assertBodyWithinLimits(\n body: { html?: string; text?: string },\n limits = DEFAULT_SANITIZE_LIMITS,\n): void {\n const total = byteLen(body.html ?? \"\") + byteLen(body.text ?? \"\");\n if (total === 0) {\n throw new ValidationError(\"Message body is empty (provide html and/or text)\");\n }\n if (total > limits.maxBodyBytes) {\n throw new ValidationError(`Body exceeds ${limits.maxBodyBytes} bytes`);\n }\n}\n\n/**\n * Last-resort HTML hardening: strip <script>/<style>/<iframe>/<object> blocks,\n * `on*=` event handlers, and `javascript:` URLs. NOT a full sanitizer — prefer\n * a real one via config. Returns cleaned HTML.\n */\nexport function stripDangerousHtml(html: string): string {\n return html\n .replace(/<\\s*(script|style|iframe|object|embed)[\\s\\S]*?<\\s*\\/\\s*\\1\\s*>/gi, \"\")\n .replace(/<\\s*(script|style|iframe|object|embed)\\b[^>]*\\/?\\s*>/gi, \"\")\n .replace(/\\son\\w+\\s*=\\s*\"[^\"]*\"/gi, \"\")\n .replace(/\\son\\w+\\s*=\\s*'[^']*'/gi, \"\")\n .replace(/\\son\\w+\\s*=\\s*[^\\s>]+/gi, \"\")\n .replace(/(href|src)\\s*=\\s*(\"|')\\s*javascript:[^\"']*\\2/gi, '$1=$2#$2');\n}\n\n/** Validate an attachment's MIME type and size (TDR §3.2). */\nexport interface AttachmentSpec {\n readonly filename: string;\n readonly contentType: string;\n readonly sizeBytes: number;\n}\n\nexport interface AttachmentPolicy {\n readonly allowedMimeTypes: readonly string[];\n readonly maxSizeBytes: number;\n}\n\nexport const DEFAULT_ATTACHMENT_POLICY: AttachmentPolicy = {\n allowedMimeTypes: [\n \"application/pdf\",\n \"image/png\",\n \"image/jpeg\",\n \"image/gif\",\n \"text/plain\",\n \"text/csv\",\n ],\n maxSizeBytes: 10_000_000, // 10 MB\n};\n\nexport function validateAttachment(att: AttachmentSpec, policy = DEFAULT_ATTACHMENT_POLICY): void {\n assertNoHeaderInjection(\"attachment.filename\", att.filename);\n if (!policy.allowedMimeTypes.includes(att.contentType)) {\n throw new ValidationError(`Attachment MIME type \"${att.contentType}\" is not allowed`);\n }\n if (att.sizeBytes > policy.maxSizeBytes) {\n throw new ValidationError(`Attachment \"${att.filename}\" exceeds ${policy.maxSizeBytes} bytes`);\n }\n}\n","import { ValidationError } from \"../../domain/errors.js\";\n\n/**\n * Recipient domain validation (TDR §3.2 step 3, §3.10, decision #4).\n *\n * Two checks, in order of cost:\n * 1. Syntax — always on. RFC-5322-ish address shape.\n * 2. MX records — optional, cached. Confirms the domain can receive mail.\n *\n * Outpost deliberately does NOT probe whether an individual mailbox exists:\n * it is unreliable and damages sender reputation (decision #4).\n */\n\nexport interface DomainValidationConfig {\n readonly syntax: boolean;\n readonly mx: boolean;\n readonly mailboxProbe: false; // typed as a constant: never supported\n /** TTL for the MX-result cache, ms. */\n readonly mxCacheTtlMs?: number;\n}\n\nexport const DEFAULT_DOMAIN_VALIDATION: DomainValidationConfig = {\n syntax: true,\n mx: false,\n mailboxProbe: false,\n mxCacheTtlMs: 60 * 60 * 1000,\n};\n\n/**\n * Pluggable MX resolver so the core stays free of `node:dns`. The default\n * resolver (provided in adapters) uses `dns/promises`. Returns the MX hosts.\n */\nexport interface MxResolver {\n resolveMx(domain: string): Promise<string[]>;\n}\n\n// Pragmatic, conservative address syntax check. Not a full RFC 5322 grammar\n// (that grammar admits forms no provider accepts); this matches what real\n// transactional senders use.\n//\n// SECURITY: the local part is a single negated character class with NO nested\n// quantifier. An earlier form, `[^\\s@\"]+(?:\\.[^\\s@\"]+)*`, was ambiguous (`.`\n// is inside `[^\\s@\"]`), causing catastrophic backtracking (ReDoS) on inputs\n// like \"a.a.a...!\" — ~8s for 62 chars. The recipient is attacker-controlled at\n// enqueue, so that was a remote DoS. This form matches/rejects in linear time.\nconst ADDR_RE = /^[^\\s@\"]+@([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+)$/;\n\nexport function extractDomain(address: string): string {\n const at = address.lastIndexOf(\"@\");\n if (at < 0) throw new ValidationError(\"Address has no domain part\");\n return address.slice(at + 1).toLowerCase();\n}\n\nexport function validateSyntax(address: string): string {\n const m = ADDR_RE.exec(address);\n if (!m) throw new ValidationError(`Recipient \"${address}\" is not a valid email address`);\n return m[1]!.toLowerCase(); // the domain\n}\n\n/** Small in-process TTL cache for MX results to avoid hammering DNS. */\nexport class MxCache {\n private readonly entries = new Map<string, { hosts: string[]; expiresAt: number }>();\n constructor(private readonly ttlMs: number) {}\n\n get(domain: string, nowMs: number): string[] | undefined {\n const e = this.entries.get(domain);\n if (!e) return undefined;\n if (e.expiresAt <= nowMs) {\n this.entries.delete(domain);\n return undefined;\n }\n return e.hosts;\n }\n\n set(domain: string, hosts: string[], nowMs: number): void {\n this.entries.set(domain, { hosts, expiresAt: nowMs + this.ttlMs });\n }\n}\n\n/**\n * Full recipient validation. `syntax` is enforced synchronously; `mx`, when\n * enabled, resolves (cached) and throws if the domain has no usable MX (and no\n * fallback A record — many small domains accept mail on the A record).\n */\nexport async function validateRecipient(\n address: string,\n config: DomainValidationConfig,\n deps: { mxResolver?: MxResolver; mxCache?: MxCache; nowMs: number },\n): Promise<void> {\n if (config.syntax) {\n const domain = validateSyntax(address);\n if (config.mx && deps.mxResolver) {\n const cached = deps.mxCache?.get(domain, deps.nowMs);\n let hosts = cached;\n if (hosts === undefined) {\n hosts = await deps.mxResolver.resolveMx(domain);\n deps.mxCache?.set(domain, hosts, deps.nowMs);\n }\n if (hosts.length === 0) {\n throw new ValidationError(`Recipient domain \"${domain}\" has no MX records`);\n }\n }\n }\n}\n","/**\n * Retention policy domain types (TDR §3.9, §5.5).\n *\n * Operational data (the outbox payload) and audit data have independent TTLs.\n * The default action on purge is REDACTION, not deletion: the PII payload is\n * wiped while the audit row (metadata + HMAC) survives. This satisfies data\n * minimization without destroying the audit trail.\n */\n\nexport interface RetentionPolicy {\n /** Age (days) after which a terminal outbox row's PII may be purged. */\n readonly operationalTtlDays: number;\n /** Age (days) after which audit events may be deleted. */\n readonly auditTtlDays: number;\n /** When true (default) purge redacts PII; when false it deletes the row. */\n readonly redactOnPurge: boolean;\n /**\n * Grace window (hours) after a message reaches a terminal state during which\n * it is NOT purged, so late webhooks (delivery/bounce) can still arrive.\n * Purging earlier would break bounce/complaint handling.\n */\n readonly webhookWindowHours: number;\n /** Rows deleted/redacted per batch, to avoid long table locks. */\n readonly batchSize: number;\n /**\n * Milliseconds to wait after a full batch before the next one.\n * A short batch does not wait. A non-finite or non-positive value does not wait.\n */\n readonly batchPauseMs: number;\n}\n\nexport const DEFAULT_RETENTION: RetentionPolicy = {\n operationalTtlDays: 30,\n auditTtlDays: 365,\n redactOnPurge: true,\n webhookWindowHours: 72,\n batchSize: 1000,\n batchPauseMs: 50,\n};\n\n/** Pause used between full retention batches. Non-finite and non-positive values wait 0ms. */\nexport function normalizeBatchPauseMs(ms: number): number {\n if (!Number.isFinite(ms) || ms <= 0) return 0;\n return ms;\n}\n\n/** Resolves immediately when `ms` is not a positive finite duration. */\nexport function waitForBatchPause(ms: number): Promise<void> {\n const pause = normalizeBatchPauseMs(ms);\n if (pause === 0) return Promise.resolve();\n return new Promise((resolve) => {\n setTimeout(resolve, pause);\n });\n}\n\n/**\n * The cutoff before which a terminal message becomes eligible for purge:\n * it must be older than the operational TTL AND past the webhook window.\n * Returns the latest (most conservative) of the two cutoffs.\n */\nexport function purgeCutoff(policy: RetentionPolicy, now: Date): Date {\n const ttlCutoff = now.getTime() - policy.operationalTtlDays * 24 * 60 * 60 * 1000;\n const windowCutoff = now.getTime() - policy.webhookWindowHours * 60 * 60 * 1000;\n return new Date(Math.min(ttlCutoff, windowCutoff));\n}\n","import { DEFAULT_RETRY, type RetryConfig } from \"./pipeline/retry-policy.js\";\nimport {\n DEFAULT_SANITIZE_LIMITS,\n DEFAULT_ATTACHMENT_POLICY,\n type SanitizeLimits,\n type AttachmentPolicy,\n} from \"./pipeline/sanitize.js\";\nimport {\n DEFAULT_DOMAIN_VALIDATION,\n type DomainValidationConfig,\n} from \"./pipeline/domain-validation.js\";\nimport { DEFAULT_RETENTION, type RetentionPolicy } from \"../domain/retention.js\";\n\n/**\n * Layered rate-limit budgets (TDR §3.2 step 4). Each is a token-bucket-style\n * \"max events per window\". The in-memory limiter and any external limiter share\n * this shape via the `RateLimiter` port.\n */\nexport interface RateLimitConfig {\n /** Global ceiling across all providers/recipients. */\n readonly global?: RateBudget;\n /** Per-provider ceiling, keyed by provider name. */\n readonly perProvider?: RateBudget;\n /** Per recipient-domain ceiling. */\n readonly perRecipientDomain?: RateBudget;\n}\n\nexport interface RateBudget {\n readonly max: number;\n readonly windowMs: number;\n}\n\n/** Fully-resolved internal config — every field defaulted, no optionals. */\nexport interface ResolvedConfig {\n readonly retry: RetryConfig;\n readonly retention: RetentionPolicy;\n readonly sanitize: SanitizeLimits;\n readonly attachments: AttachmentPolicy;\n readonly domainValidation: DomainValidationConfig;\n readonly rateLimits: RateLimitConfig;\n /** Max rows the send worker claims per poll. */\n readonly sendBatchSize: number;\n /**\n * Lease window for `sending` rows, ms. A row left in `sending` longer than\n * this is treated as abandoned (its worker crashed mid-dispatch) and is\n * reclaimed by the next poll. Keep comfortably larger than a real dispatch.\n */\n readonly staleSendingLeaseMs: number;\n}\n\nexport interface ConfigOverrides {\n retry?: Partial<RetryConfig>;\n retention?: Partial<RetentionPolicy>;\n sanitize?: Partial<SanitizeLimits>;\n attachments?: Partial<AttachmentPolicy>;\n domainValidation?: Partial<Omit<DomainValidationConfig, \"mailboxProbe\">>;\n rateLimits?: RateLimitConfig;\n sendBatchSize?: number;\n staleSendingLeaseMs?: number;\n}\n\nexport function resolveConfig(overrides: ConfigOverrides = {}): ResolvedConfig {\n return {\n retry: { ...DEFAULT_RETRY, ...overrides.retry },\n retention: { ...DEFAULT_RETENTION, ...overrides.retention },\n sanitize: { ...DEFAULT_SANITIZE_LIMITS, ...overrides.sanitize },\n attachments: { ...DEFAULT_ATTACHMENT_POLICY, ...overrides.attachments },\n domainValidation: {\n ...DEFAULT_DOMAIN_VALIDATION,\n ...overrides.domainValidation,\n mailboxProbe: false,\n },\n rateLimits: overrides.rateLimits ?? {},\n sendBatchSize: overrides.sendBatchSize ?? 50,\n staleSendingLeaseMs: overrides.staleSendingLeaseMs ?? 5 * 60 * 1000,\n };\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { Message, MessageBody } from \"../domain/message.js\";\nimport { ValidationError } from \"../domain/errors.js\";\nimport {\n sanitizeSubject,\n sanitizeRecipient,\n assertBodyWithinLimits,\n stripDangerousHtml,\n} from \"./pipeline/sanitize.js\";\nimport { validateSyntax } from \"./pipeline/domain-validation.js\";\n\n/**\n * Input accepted by `outpost.send(...)` and `POST /messages` (TDR §4.3).\n * Either `template` OR (`subject` + `html`/`text`) must be supplied.\n */\nexport interface EnqueueInput {\n /** Required. Dedupes re-enqueues (TDR §3.1, decision #3). */\n readonly idempotencyKey: string;\n readonly to: string;\n readonly template?: { id: string; version?: number; vars: Record<string, unknown> };\n readonly subject?: string;\n readonly html?: string;\n readonly text?: string;\n /** Override the default provider for this message. */\n readonly provider?: string;\n /** Clear, queryable metadata. Never put PII here. */\n readonly metadata?: Record<string, unknown>;\n /** Phase 2 scheduling; if set, the worker won't claim it until then. */\n readonly scheduledFor?: Date;\n}\n\nexport interface EnqueueResult {\n readonly id: string;\n readonly state: Message[\"state\"];\n readonly idempotencyKey: string;\n /** True when an existing message was returned (idempotent replay). */\n readonly deduplicated: boolean;\n}\n\n/**\n * EnqueueMessage — persist-before-dispatch ingestion (TDR §3.1, decision #1).\n *\n * Order of operations is load-bearing:\n * 1. Validate + sanitize (reject bad input synchronously, before any write).\n * 2. Idempotency guard — return the existing message if the key is known.\n * 3. Suppression check — suppressed recipients are recorded, never dispatched.\n * 4. Seal PII (recipient + body) with the WRITE-side encryptor.\n * 5. Insert as `queued` or `suppressed`. The row exists before anything tries\n * to send it.\n * 6. Append an `enqueued` or `suppressed` audit event. When the outbox\n * implements `insertWithEnqueueAudit`, steps 5 and 6 are one write.\n * When it does not, they stay two steps, and a failed audit append can\n * leave the row.\n *\n * The send worker (a separate process) picks it up later by polling — the\n * ingestion path NEVER publishes to a queue, avoiding the dual-write hazard\n * (decision #2).\n */\nexport class EnqueueMessage {\n constructor(private readonly deps: CoreDeps) {}\n\n async execute(input: EnqueueInput, actor: string): Promise<EnqueueResult> {\n const { deps } = this;\n return deps.telemetry.span(\"outpost.enqueue\", { idempotencyKey: input.idempotencyKey }, async () => {\n if (!input.idempotencyKey || input.idempotencyKey.trim() === \"\") {\n throw new ValidationError(\"idempotencyKey is required\");\n }\n\n // 1. Validate + sanitize ----------------------------------------------\n const to = sanitizeRecipient(input.to, deps.config.sanitize);\n validateSyntax(to); // syntax always; MX check happens in the send worker\n const { subject, body } = await this.resolveContent(input);\n const cleanSubject = sanitizeSubject(subject, deps.config.sanitize);\n const cleanBody = this.sanitizeBody(body);\n assertBodyWithinLimits(cleanBody, deps.config.sanitize);\n\n const recipientHmac = deps.recipientHasher.hash(to);\n const provider = input.provider ?? deps.defaultProvider;\n\n // 2. Idempotency guard ------------------------------------------------\n const existing = await deps.outbox.findByIdempotencyKey(input.idempotencyKey);\n if (existing) {\n deps.telemetry.counter(\"outpost.enqueue.deduplicated\", 1);\n return {\n id: existing.id,\n state: existing.state,\n idempotencyKey: existing.idempotencyKey,\n deduplicated: true,\n };\n }\n\n // 3. Suppression check ------------------------------------------------\n const suppressed = await deps.suppressions.isSuppressed(recipientHmac);\n\n // 4. Seal PII (write-side encryptor) ----------------------------------\n const id = deps.ids.generate();\n const [recipientSealed, bodySealed] = await Promise.all([\n deps.sealEncryptor.seal(to, { messageId: id, column: \"recipient\" }),\n deps.sealEncryptor.seal(JSON.stringify(cleanBody), { messageId: id, column: \"body\" }),\n ]);\n\n const now = deps.clock.now();\n const draft = {\n id,\n idempotencyKey: input.idempotencyKey,\n recipientHmac,\n recipientSealed,\n bodySealed,\n subject: cleanSubject,\n templateId: input.template?.id ?? null,\n templateVersion: input.template?.version ?? null,\n provider,\n metadata: input.metadata ?? {},\n state: suppressed ? (\"suppressed\" as const) : (\"queued\" as const),\n scheduledFor: input.scheduledFor ?? null,\n nextAttemptAt: input.scheduledFor ?? now,\n };\n const audit = {\n eventType: suppressed ? (\"suppressed\" as const) : (\"enqueued\" as const),\n actor,\n detail: suppressed ? { reason: \"recipient_on_suppression_list\" } : { provider },\n };\n\n // 5–6. One write when the repository supports it; otherwise insert, then audit.\n if (deps.outbox.insertWithEnqueueAudit) {\n const written = await deps.outbox.insertWithEnqueueAudit(draft, audit);\n if (written.deduplicated) {\n deps.telemetry.counter(\"outpost.enqueue.deduplicated\", 1);\n return {\n id: written.message.id,\n state: written.message.state,\n idempotencyKey: written.message.idempotencyKey,\n deduplicated: true,\n };\n }\n deps.telemetry.counter(suppressed ? \"outpost.enqueue.suppressed\" : \"outpost.enqueue.queued\", 1);\n return {\n id: written.message.id,\n state: written.message.state,\n idempotencyKey: written.message.idempotencyKey,\n deduplicated: false,\n };\n }\n\n const message = await deps.outbox.insert(draft);\n await deps.audit.append({\n messageId: message.id,\n eventType: audit.eventType,\n actor: audit.actor,\n detail: audit.detail,\n });\n deps.telemetry.counter(suppressed ? \"outpost.enqueue.suppressed\" : \"outpost.enqueue.queued\", 1);\n\n return {\n id: message.id,\n state: message.state,\n idempotencyKey: message.idempotencyKey,\n deduplicated: false,\n };\n });\n }\n\n /** Resolve template or raw content into subject + body. */\n private async resolveContent(input: EnqueueInput): Promise<{ subject: string; body: MessageBody }> {\n if (input.template) {\n if (!this.deps.templates) {\n throw new ValidationError(\"A template was supplied but no TemplateRenderer is configured\");\n }\n const rendered = await this.deps.templates.render(input.template);\n // A caller-supplied subject overrides the template's, if present.\n return { subject: input.subject ?? rendered.subject, body: rendered.body };\n }\n if (input.subject === undefined) {\n throw new ValidationError(\"Either `template` or `subject` must be provided\");\n }\n return { subject: input.subject, body: { html: input.html, text: input.text } };\n }\n\n /** Apply the configured strong sanitizer (or built-in fallback) to HTML. */\n private sanitizeBody(body: MessageBody): MessageBody {\n if (body.html === undefined) return body;\n const clean = this.deps.sanitizeHtml ? this.deps.sanitizeHtml(body.html) : stripDangerousHtml(body.html);\n return { ...body, html: clean };\n }\n}\n","import type { LifecycleState } from \"./lifecycle.js\";\n\n/**\n * Normalized webhook event (TDR §3.5).\n *\n * Each provider has its own webhook payload shape and signature scheme. The\n * provider adapter's `verifyWebhook` verifies the signature and maps the native\n * payload onto this uniform type, so the `IngestWebhook` use case never has to\n * know about provider specifics.\n */\n\nexport type WebhookEventType =\n | \"delivered\"\n | \"bounced\"\n | \"complained\"\n | \"opened\"\n | \"failed\";\n\nexport interface WebhookEvent {\n readonly provider: string;\n readonly type: WebhookEventType;\n /** Provider's message id — used to correlate back to the outbox row. */\n readonly providerMessageId: string;\n /** Address the provider reported. Stored rows omit it. Suppression uses the outbox HMAC. */\n readonly recipient?: string;\n /** True for hard bounces; soft bounces should not suppress. */\n readonly isHardBounce?: boolean;\n /** Provider's own timestamp for the event, if supplied. */\n readonly occurredAt?: Date;\n /**\n * Provider's id for this event, when the payload includes one.\n * When set, webhook identity is (provider, providerEventId).\n */\n readonly providerEventId?: string;\n /**\n * Time the adapter associates with verification, such as the signature\n * timestamp. Freshness prefers this over `occurredAt`.\n */\n readonly verifiedAt?: Date;\n /** Raw provider payload, retained for traceability/replay. */\n readonly raw: unknown;\n}\n\n/** Maps a webhook event type to the lifecycle state it drives the message to. */\nexport function webhookToState(type: WebhookEventType): LifecycleState | null {\n switch (type) {\n case \"delivered\":\n return \"delivered\";\n case \"bounced\":\n return \"bounced\";\n case \"complained\":\n return \"complained\";\n case \"failed\":\n return \"failed\";\n case \"opened\":\n return null; // tracking-only; does not change lifecycle state\n }\n}\n","/**\n * Message lifecycle states and the transition rules between them.\n *\n * This module is PURE: no I/O, no framework, no provider. It encodes the\n * state machine described in the TDR §3.3. Everything outward (use cases,\n * repositories, workers) leans on these rules rather than re-deriving them.\n *\n * ┌─────────────┐\n * enqueue ─────▶│ queued │\n * └──────┬──────┘\n * │ claimed by send worker\n * ▼\n * ┌─────────────┐ suppressed recipient\n * │ sending │────────────────────────▶ suppressed\n * └──────┬──────┘\n * │ provider accepted\n * ▼\n * ┌─────────────┐\n * │ sent │ (accepted, not yet confirmed)\n * └──────┬──────┘\n * │ webhook\n * ┌──────────────┼───────────────┬────────────┐\n * ▼ ▼ ▼ ▼\n * delivered bounced complained failed\n *\n * Transient dispatch error → back to `queued` with backoff (retry).\n * Permanent error / retries exhausted → `failed` (terminal, DLQ).\n */\n\nexport const LIFECYCLE_STATES = [\n \"queued\",\n \"sending\",\n \"sent\",\n \"delivered\",\n \"bounced\",\n \"complained\",\n \"failed\",\n \"suppressed\",\n] as const;\n\nexport type LifecycleState = (typeof LIFECYCLE_STATES)[number];\n\n/**\n * Terminal states never transition again. Outbox retention acts on a row only\n * while it is terminal and past the webhook window. Aged webhook rows are\n * deleted as well. A non-terminal outbox row stays for the send worker.\n */\nexport const TERMINAL_STATES = [\n \"delivered\",\n \"bounced\",\n \"complained\",\n \"failed\",\n \"suppressed\",\n] as const satisfies readonly LifecycleState[];\n\nconst TERMINAL_SET = new Set<LifecycleState>(TERMINAL_STATES);\n\nexport function isTerminal(state: LifecycleState): boolean {\n return TERMINAL_SET.has(state);\n}\n\n/**\n * Allowed transitions. A transition not present here is a domain invariant\n * violation and must be rejected by the use case (never silently applied).\n */\nconst ALLOWED_TRANSITIONS: Record<LifecycleState, readonly LifecycleState[]> = {\n // Dead-letter is `sending` → `failed`, or a `failed` webhook from `sent`.\n queued: [\"sending\", \"suppressed\"],\n // `sending` can fall back to `queued` on a transient error (retry).\n sending: [\"sent\", \"queued\", \"failed\", \"suppressed\"],\n sent: [\"delivered\", \"bounced\", \"complained\", \"failed\"],\n delivered: [],\n bounced: [],\n complained: [],\n failed: [\"queued\"], // DLQ replay re-enqueues a failed message\n suppressed: [],\n};\n\nexport function canTransition(from: LifecycleState, to: LifecycleState): boolean {\n return ALLOWED_TRANSITIONS[from].includes(to);\n}\n\n/**\n * Which lifecycle states must feed the suppression list when reached.\n * Hard bounces and complaints damage sender reputation if re-sent, so the\n * recipient is suppressed automatically (TDR §3.6).\n */\nexport function shouldSuppressOn(state: LifecycleState): boolean {\n return state === \"bounced\" || state === \"complained\";\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { RawWebhook } from \"../ports/email-provider.js\";\nimport type { Message } from \"../domain/message.js\";\nimport type { WebhookEvent } from \"../domain/webhook.js\";\nimport type { AuditEventType } from \"../domain/audit.js\";\nimport type { WebhookDisposition, WebhookIdentityQuery } from \"../ports/repositories.js\";\nimport { webhookToState } from \"../domain/webhook.js\";\nimport { canTransition, shouldSuppressOn } from \"../domain/lifecycle.js\";\nimport { WebhookVerificationError } from \"../domain/errors.js\";\n\n/** Absolute skew against the clock. Exactly this many milliseconds is fresh. */\nconst WEBHOOK_FRESHNESS_WINDOW_MS = 300_000;\n\nexport interface IngestWebhookResult {\n readonly accepted: boolean;\n /** Absent when a signed event has no lifecycle effect. */\n readonly eventType?: WebhookEvent[\"type\"];\n readonly messageId: string | null;\n /** Why a verified event did not change state (e.g. unknown message). */\n readonly note?: string;\n}\n\ninterface AppliedEffect {\n readonly disposition: WebhookDisposition;\n readonly result: IngestWebhookResult;\n}\n\n/**\n * IngestWebhook — verify a provider webhook and apply its effect (TDR §3.5).\n *\n * 1. Verify the signature. A bad signature throws `WebhookVerificationError`.\n * `null` is a signed event with no lifecycle effect: return immediately.\n * 2. Reject a lifecycle timestamp outside five minutes. Nothing is stored\n * or audited.\n * 3. Identity dedupe, when the repository implements `findByIdentity`.\n * 4. Correlate by `providerMessageId`.\n * 5. Apply the effect, then store the row with its disposition.\n *\n * No matching outbox row is stored as `pending` and applied later by\n * `applyPending`, without a second freshness check. `opened` audits once and\n * does not change state. Suppression runs only with a committed hard bounce\n * or complaint. Missing optional repository methods skip dedupe and pending\n * apply; transition, suppression, and audit gates still run.\n *\n * Webhook endpoints are not API-key authenticated. Trust is the signature.\n */\nexport class IngestWebhook {\n constructor(private readonly deps: CoreDeps) {}\n\n async execute(providerName: string, raw: RawWebhook): Promise<IngestWebhookResult> {\n const { deps } = this;\n const provider = deps.providers.get(providerName);\n if (!provider) {\n throw new WebhookVerificationError(`Unknown provider \"${providerName}\"`);\n }\n\n return deps.telemetry.span(\"outpost.webhook.ingest\", { provider: providerName }, async () => {\n const event = await provider.verifyWebhook(raw);\n if (!event) {\n return { accepted: true, messageId: null, note: \"ignored\" };\n }\n this.assertFresh(event);\n\n const duplicate = await deps.webhookEvents.findByIdentity?.(identityQuery(event));\n if (duplicate) return this.duplicateResult(event);\n\n const message = await deps.outbox.findByProviderMessageId(event.providerMessageId);\n if (!message) {\n // A new provider event id is its own delivery. The legacy match is only\n // for a redelivery that still has no id.\n const settled = event.providerEventId\n ? null\n : await deps.webhookEvents.findByIdentity?.({\n match: \"settledWithoutEventId\",\n provider: event.provider,\n providerMessageId: event.providerMessageId,\n type: event.type,\n });\n if (settled) {\n return {\n accepted: true,\n eventType: event.type,\n messageId: null,\n note: \"duplicate provider event\",\n };\n }\n await this.store(event, \"pending\", providerName);\n return {\n accepted: true,\n eventType: event.type,\n messageId: null,\n note: \"no matching message for providerMessageId\",\n };\n }\n\n const effect = await this.applyEffects(event, message);\n await this.store(event, effect.disposition, providerName);\n return effect.result;\n });\n }\n\n /**\n * Apply pending rows for a provider message id, oldest `receivedAt` first.\n * No freshness check. Skips the call when the repository has no list method.\n * Does not store another row or increment `outpost.webhook.received`.\n */\n async applyPending(providerMessageId: string): Promise<void> {\n const list = this.deps.webhookEvents.listPendingByProviderMessageId;\n if (!list) return;\n\n const rows = await list.call(this.deps.webhookEvents, providerMessageId);\n const ordered = [...rows].sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime());\n for (const row of ordered) {\n if (row.disposition !== \"pending\") continue;\n const message = await this.deps.outbox.findByProviderMessageId(providerMessageId);\n if (!message) continue;\n const effect = await this.applyEffects(row.event, message);\n await this.deps.webhookEvents.setDisposition?.(row.id, effect.disposition);\n }\n }\n\n /** `verifiedAt` wins. Otherwise `occurredAt`. Neither present: do not reject. */\n private assertFresh(event: WebhookEvent): void {\n const timestamp = event.verifiedAt !== undefined ? event.verifiedAt : event.occurredAt;\n if (timestamp === undefined) return;\n const skew = Math.abs(this.deps.clock.now().getTime() - timestamp.getTime());\n if (skew > WEBHOOK_FRESHNESS_WINDOW_MS) {\n throw new WebhookVerificationError(\"Webhook timestamp is stale\");\n }\n }\n\n private async duplicateResult(event: WebhookEvent): Promise<IngestWebhookResult> {\n const message = await this.deps.outbox.findByProviderMessageId(event.providerMessageId);\n return {\n accepted: true,\n eventType: event.type,\n messageId: message?.id ?? null,\n note: \"duplicate provider event\",\n };\n }\n\n /**\n * State change, suppression, and one audit. Disposition is the caller's\n * to persist: `applied` after a committed effect, `rejected` when the\n * transition is not allowed.\n */\n private async applyEffects(event: WebhookEvent, message: Message): Promise<AppliedEffect> {\n const target = webhookToState(event.type);\n if (target === null) {\n await this.appendAudit(event, message.id);\n return {\n disposition: \"applied\",\n result: { accepted: true, eventType: event.type, messageId: message.id },\n };\n }\n\n if (!canTransition(message.state, target)) {\n return {\n disposition: \"rejected\",\n result: {\n accepted: true,\n eventType: event.type,\n messageId: message.id,\n note: \"transition rejected\",\n },\n };\n }\n\n await this.deps.outbox.updateState(message.id, { state: target });\n if (shouldSuppressOn(target) && this.isSuppressable(event)) {\n const reason = target === \"bounced\" ? \"hard_bounce\" : \"complaint\";\n const already = await this.deps.suppressions.get(message.recipientHmac);\n await this.deps.suppressions.add({\n recipientHmac: message.recipientHmac,\n reason,\n createdBy: `provider:${event.provider}`,\n note: `webhook ${event.type}`,\n });\n if (!already) {\n this.deps.telemetry.counter(\"outpost.suppression.added\", 1, { reason });\n }\n }\n await this.appendAudit(event, message.id);\n return {\n disposition: \"applied\",\n result: { accepted: true, eventType: event.type, messageId: message.id },\n };\n }\n\n private async store(\n event: WebhookEvent,\n disposition: WebhookDisposition,\n providerName: string,\n ): Promise<void> {\n await this.deps.webhookEvents.record(event, { disposition });\n this.deps.telemetry.counter(\"outpost.webhook.received\", 1, {\n provider: providerName,\n type: event.type,\n });\n }\n\n private async appendAudit(event: WebhookEvent, messageId: string): Promise<void> {\n const detail: Record<string, unknown> = {\n type: event.type,\n occurredAt: event.occurredAt?.toISOString() ?? null,\n };\n if (event.providerEventId) detail.providerEventId = event.providerEventId;\n await this.deps.audit.append({\n messageId,\n eventType: this.auditType(event.type),\n actor: `provider:${event.provider}`,\n detail,\n });\n }\n\n /** A soft bounce must not suppress; only hard bounces and complaints do. */\n private isSuppressable(event: WebhookEvent): boolean {\n if (event.type === \"complained\") return true;\n if (event.type === \"bounced\") return event.isHardBounce !== false;\n return false;\n }\n\n private auditType(type: WebhookEvent[\"type\"]): AuditEventType {\n switch (type) {\n case \"delivered\":\n return \"webhook_delivered\";\n case \"bounced\":\n return \"webhook_bounced\";\n case \"complained\":\n return \"webhook_complained\";\n case \"opened\":\n return \"webhook_opened\";\n case \"failed\":\n return \"dispatch_failed\";\n }\n }\n}\n\nfunction identityQuery(event: WebhookEvent): WebhookIdentityQuery {\n if (event.providerEventId) {\n return {\n match: \"providerEvent\",\n provider: event.provider,\n providerEventId: event.providerEventId,\n };\n }\n return {\n match: \"providerMessage\",\n provider: event.provider,\n providerMessageId: event.providerMessageId,\n type: event.type,\n occurredAt: event.occurredAt ?? null,\n };\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { SuppressionEntry, SuppressionReason } from \"../domain/suppression.js\";\n\n/**\n * ManageSuppression — view/add/remove suppression entries (TDR §3.6).\n *\n * All matching is by recipient HMAC, so the plaintext address is hashed with\n * the same keyed HMAC used at ingestion. Adds/removes are audited.\n */\nexport class ManageSuppression {\n constructor(private readonly deps: CoreDeps) {}\n\n async isSuppressed(address: string): Promise<boolean> {\n return this.deps.suppressions.isSuppressed(this.deps.recipientHasher.hash(address));\n }\n\n /** Lookup by precomputed HMAC (the form the HTTP API exposes). */\n async getByHmac(recipientHmac: string): Promise<SuppressionEntry | null> {\n return this.deps.suppressions.get(recipientHmac);\n }\n\n async suppress(\n address: string,\n reason: SuppressionReason,\n actor: string,\n note?: string,\n ): Promise<SuppressionEntry> {\n const recipientHmac = this.deps.recipientHasher.hash(address);\n const entry = await this.deps.suppressions.add({ recipientHmac, reason, createdBy: actor, note });\n await this.deps.audit.append({\n messageId: null,\n eventType: \"suppressed\",\n actor,\n detail: { recipientHmac, reason },\n });\n this.deps.telemetry.counter(\"outpost.suppression.added\", 1, { reason });\n return entry;\n }\n\n /** Remove by HMAC (what the DELETE endpoint receives). Audited. */\n async unsuppressByHmac(recipientHmac: string, actor: string): Promise<boolean> {\n const removed = await this.deps.suppressions.remove(recipientHmac);\n if (removed) {\n await this.deps.audit.append({\n messageId: null,\n eventType: \"unsuppressed\",\n actor,\n detail: { recipientHmac },\n });\n }\n return removed;\n }\n\n async list(limit = 100, offset = 0): Promise<SuppressionEntry[]> {\n return this.deps.suppressions.list(limit, offset);\n }\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport type { CoreDeps } from \"./context.js\";\nimport type { ApiKey, ApiScope } from \"../domain/api-key.js\";\n\n/**\n * Hash an API key secret for storage. Keys are high-entropy random tokens\n * (not user passwords), so a fast one-way SHA-256 is appropriate and lets us\n * look the hash up directly. A slow password hash (bcrypt/argon2) buys nothing\n * against a 256-bit random secret and would break O(1) lookup.\n */\nexport function hashApiKey(secret: string): string {\n return createHash(\"sha256\").update(secret, \"utf8\").digest(\"hex\");\n}\n\n/** Generate an opaque, high-entropy key with a recognizable prefix. */\nexport function generateApiKeySecret(): string {\n return `opk_${randomBytes(32).toString(\"base64url\")}`;\n}\n\nexport interface CreatedApiKey {\n readonly id: string;\n readonly label: string;\n readonly scopes: readonly ApiScope[];\n readonly expiresAt: Date | null;\n /** The plaintext secret — shown ONCE, never stored, never recoverable. */\n readonly secret: string;\n}\n\n/**\n * ManageApiKey — admin-side key lifecycle (TDR §5.1, §3.12).\n *\n * Only the hash is stored. The plaintext is returned exactly once at creation.\n * Revocation takes effect immediately (no caching of key state beyond the\n * documented short window in the Authenticate use case).\n */\nexport class ManageApiKey {\n constructor(private readonly deps: CoreDeps) {}\n\n async create(input: {\n label: string;\n scopes: readonly ApiScope[];\n expiresAt?: Date | null;\n }): Promise<CreatedApiKey> {\n const secret = generateApiKeySecret();\n const key = await this.deps.apiKeys.insert({\n label: input.label,\n keyHash: hashApiKey(secret),\n scopes: input.scopes,\n expiresAt: input.expiresAt ?? null,\n });\n await this.deps.audit.append({\n messageId: null,\n eventType: \"key_created\",\n actor: \"admin\",\n detail: { keyId: key.id, label: key.label, scopes: key.scopes },\n });\n return {\n id: key.id,\n label: key.label,\n scopes: key.scopes,\n expiresAt: key.expiresAt,\n secret,\n };\n }\n\n async revoke(id: string): Promise<boolean> {\n const ok = await this.deps.apiKeys.revoke(id, this.deps.clock.now());\n if (ok) {\n await this.deps.audit.append({\n messageId: null,\n eventType: \"key_revoked\",\n actor: \"admin\",\n detail: { keyId: id },\n });\n }\n return ok;\n }\n\n /** Lists keys WITHOUT secrets (only hashes are stored anyway). */\n async list(): Promise<ApiKey[]> {\n return this.deps.apiKeys.list();\n }\n}\n","/**\n * API key domain types and scope model (TDR §5.1).\n *\n * Keys are opaque high-entropy secrets. Only a hash is ever stored; the\n * plaintext is shown once at creation. A key carries a label, optional expiry,\n * and a revoked flag — both enforced on every request. Scopes implement\n * least-privilege (a send-only key cannot manage suppressions).\n */\n\nexport const API_SCOPES = [\n \"messages:send\",\n \"messages:read\",\n \"messages:replay\",\n \"suppressions:read\",\n \"suppressions:write\",\n \"keys:manage\",\n \"admin\", // implies all of the above\n] as const;\n\nexport type ApiScope = (typeof API_SCOPES)[number];\n\nexport interface ApiKey {\n readonly id: string;\n /** Human label shown in the admin panel. */\n readonly label: string;\n /** Hash of the secret (never the secret itself). */\n readonly keyHash: string;\n readonly scopes: readonly ApiScope[];\n readonly expiresAt: Date | null;\n revokedAt: Date | null;\n readonly createdAt: Date;\n lastUsedAt: Date | null;\n}\n\n/** A key is usable iff it is not revoked and not past its expiry. */\nexport function isKeyActive(key: Pick<ApiKey, \"revokedAt\" | \"expiresAt\">, now: Date): boolean {\n if (key.revokedAt !== null) return false;\n if (key.expiresAt !== null && key.expiresAt.getTime() <= now.getTime()) return false;\n return true;\n}\n\n/** True when the key's scopes satisfy the required scope (admin implies all). */\nexport function hasScope(scopes: readonly ApiScope[], required: ApiScope): boolean {\n return scopes.includes(\"admin\") || scopes.includes(required);\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { ApiKey, ApiScope } from \"../domain/api-key.js\";\nimport { isKeyActive, hasScope } from \"../domain/api-key.js\";\nimport { UnauthorizedError, ForbiddenError } from \"../domain/errors.js\";\nimport { hashApiKey } from \"./manage-api-key.js\";\n\nexport interface AuthContext {\n readonly keyId: string;\n readonly scopes: readonly ApiScope[];\n}\n\n/**\n * Authenticate — validates an API key on every request (TDR §5.1).\n *\n * - Hashes the presented secret and looks up the stored hash.\n * - Rejects missing / unknown / expired / revoked keys with 401.\n * - Enforces the required scope (least privilege) with 403.\n * - Touches `last_used_at` for observability.\n *\n * Revocation/expiry are enforced on every call (no long-lived caching), so\n * they take effect immediately as the TDR requires.\n */\nexport class Authenticate {\n constructor(private readonly deps: CoreDeps) {}\n\n /** Resolve a bearer secret to an AuthContext or throw UnauthorizedError. */\n async resolve(presentedSecret: string | null | undefined): Promise<AuthContext> {\n if (!presentedSecret) throw new UnauthorizedError();\n const keyHash = hashApiKey(presentedSecret);\n const key = await this.deps.apiKeys.findByHash(keyHash);\n if (!key) throw new UnauthorizedError();\n if (!isKeyActive(key, this.deps.clock.now())) throw new UnauthorizedError();\n\n // Fire-and-forget last-used update; never block the request on it.\n void this.deps.apiKeys.touchLastUsed(key.id, this.deps.clock.now());\n\n return { keyId: key.id, scopes: key.scopes };\n }\n\n /** Resolve then assert the context carries the required scope. */\n async authorize(presentedSecret: string | null | undefined, required: ApiScope): Promise<AuthContext> {\n const ctx = await this.resolve(presentedSecret);\n if (!hasScope(ctx.scopes, required)) throw new ForbiddenError();\n return ctx;\n }\n\n /** Assert a scope on an already-resolved context. */\n static requireScope(ctx: AuthContext, required: ApiScope): void {\n if (!hasScope(ctx.scopes, required)) throw new ForbiddenError();\n }\n\n /** Helper to extract a bearer/x-outpost-key value from headers. */\n static extractKey(headers: Record<string, string | string[] | undefined>): string | null {\n const auth = headerValue(headers, \"authorization\");\n if (auth && /^bearer\\s+/i.test(auth)) return auth.replace(/^bearer\\s+/i, \"\").trim();\n return headerValue(headers, \"x-outpost-key\");\n }\n\n // Exposed for tests / admin tooling.\n async findKey(presentedSecret: string): Promise<ApiKey | null> {\n return this.deps.apiKeys.findByHash(hashApiKey(presentedSecret));\n }\n}\n\nfunction headerValue(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | null {\n const raw = headers[name] ?? headers[name.toLowerCase()];\n if (Array.isArray(raw)) return raw[0] ?? null;\n return raw ?? null;\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { Message } from \"../domain/message.js\";\nimport type { ListMessagesQuery } from \"../ports/repositories.js\";\nimport { NotFoundError, InvalidStateTransitionError } from \"../domain/errors.js\";\nimport { canTransition } from \"../domain/lifecycle.js\";\n\n/**\n * A read projection for APIs and the admin panel. The encrypted body and\n * recipient address are omitted. `subject`, `metadata`, and `lastError` are\n * stored in the clear, and `lastError` can include provider response text.\n */\nexport interface MessageView {\n readonly id: string;\n readonly idempotencyKey: string;\n readonly state: Message[\"state\"];\n readonly recipientHmac: string;\n readonly subject: string;\n readonly provider: string;\n readonly templateId: string | null;\n readonly templateVersion: number | null;\n readonly metadata: Record<string, unknown>;\n readonly attempts: number;\n readonly nextAttemptAt: string;\n readonly providerMessageId: string | null;\n readonly lastError: string | null;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\nexport function toView(m: Message): MessageView {\n return {\n id: m.id,\n idempotencyKey: m.idempotencyKey,\n state: m.state,\n recipientHmac: m.recipientHmac,\n subject: m.subject,\n provider: m.provider,\n templateId: m.templateId,\n templateVersion: m.templateVersion,\n metadata: m.metadata,\n attempts: m.attempts,\n nextAttemptAt: m.nextAttemptAt.toISOString(),\n providerMessageId: m.providerMessageId,\n lastError: m.lastError,\n createdAt: m.createdAt.toISOString(),\n updatedAt: m.updatedAt.toISOString(),\n };\n}\n\nexport class GetMessage {\n constructor(private readonly deps: CoreDeps) {}\n async execute(id: string): Promise<MessageView> {\n const m = await this.deps.outbox.findById(id);\n if (!m) throw new NotFoundError(`Message \"${id}\" not found`);\n return toView(m);\n }\n}\n\nconst DEFAULT_LIST_LIMIT = 50;\nconst MAX_LIST_LIMIT = 100;\n\nfunction boundedListLimit(limit: number | undefined): number {\n if (limit === undefined || !Number.isFinite(limit) || limit < 1) return DEFAULT_LIST_LIMIT;\n return Math.min(Math.floor(limit), MAX_LIST_LIMIT);\n}\n\nexport class ListMessages {\n constructor(private readonly deps: CoreDeps) {}\n async execute(query: ListMessagesQuery): Promise<MessageView[]> {\n const messages = await this.deps.outbox.list({\n ...query,\n limit: boundedListLimit(query.limit),\n offset: query.offset ?? 0,\n });\n return messages.map(toView);\n }\n}\n\n/**\n * ReplayMessage — re-enqueue a dead-lettered (`failed`) message from the DLQ\n * (TDR §3.4, §3.12). Resets the retry budget, clears the provider message id,\n * and schedules an immediate retry.\n */\nexport class ReplayMessage {\n constructor(private readonly deps: CoreDeps) {}\n async execute(id: string, actor: string): Promise<MessageView> {\n const m = await this.deps.outbox.findById(id);\n if (!m) throw new NotFoundError(`Message \"${id}\" not found`);\n if (!canTransition(m.state, \"queued\")) {\n throw new InvalidStateTransitionError(m.state, \"queued\");\n }\n await this.deps.outbox.updateState(id, {\n state: \"queued\",\n attempts: 0,\n nextAttemptAt: this.deps.clock.now(),\n lastError: null,\n providerMessageId: null,\n });\n await this.deps.audit.append({\n messageId: id,\n eventType: \"replayed\",\n actor,\n detail: { fromState: m.state },\n });\n const updated = await this.deps.outbox.findById(id);\n return toView(updated!);\n }\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { Message, MessageBody, DispatchableMessage } from \"../domain/message.js\";\nimport type { MessageStatePatch, SendingClaim } from \"../ports/repositories.js\";\nimport { classifyProviderFailure } from \"../domain/provider-failure.js\";\nimport { IngestWebhook } from \"./ingest-webhook.js\";\nimport { isExhausted, backoffMs } from \"./pipeline/retry-policy.js\";\nimport { validateRecipient, MxCache, extractDomain } from \"./pipeline/domain-validation.js\";\nimport { sanitizeRecipient, sanitizeSubject, assertBodyWithinLimits } from \"./pipeline/sanitize.js\";\n\n/** Provider text when the thrown value carries a string `message`; otherwise `String(err)`. */\nfunction failureReason(err: unknown): string {\n if (typeof err === \"object\" && err !== null) {\n const message = (err as { message?: unknown }).message;\n if (typeof message === \"string\") return message;\n }\n return String(err);\n}\n\nexport type DispatchOutcome =\n | { kind: \"sent\"; providerMessageId: string }\n | { kind: \"retry\"; nextAttemptAt: Date }\n | { kind: \"rate_limited\"; nextAttemptAt: Date }\n | { kind: \"failed\"; reason: string }\n | { kind: \"skipped\"; reason: string };\n\n/**\n * DispatchMessage — processes ONE message already claimed (state `sending`) by\n * the send worker. Implements the outbound pipeline (TDR §3.2):\n *\n * 1. Claim fence (still `sending` at the claimed `updatedAt`)\n * then `dispatch_started`. A failed append does not stop the send.\n * 2. Suppression check (stored HMAC, before decrypt)\n * 3. Decrypt PII (READ-side encryptor, only here)\n * 4. Recipient, subject, size (HTML sanitization already ran at enqueue)\n * 5. Domain validation (syntax + cached MX)\n * 6. Rate limiting (global / provider / domain)\n * 7. Dispatch (provider.send)\n * 8. State transition + audit\n *\n * Suppression is checked on the stored HMAC before decrypt. A listed\n * recipient moves `sending` → `suppressed` and is never opened or sent.\n * Decryption happens as late as possible — immediately before dispatch — so\n * plaintext never lives in the queue (TDR §5.4).\n */\nexport class DispatchMessage {\n private readonly mxCache: MxCache;\n private readonly webhooks: IngestWebhook;\n\n constructor(private readonly deps: CoreDeps) {\n this.mxCache = new MxCache(deps.config.domainValidation.mxCacheTtlMs ?? 3_600_000);\n this.webhooks = new IngestWebhook(deps);\n }\n\n async execute(message: Message): Promise<DispatchOutcome> {\n const claim: SendingClaim = { updatedAt: new Date(message.updatedAt.getTime()) };\n if (!this.deps.outbox.updateStateWhileSending) {\n throw new Error(\"OutboxRepository.updateStateWhileSending is required to dispatch\");\n }\n const { deps } = this;\n return deps.telemetry.span(\n \"outpost.dispatch\",\n { messageId: message.id, provider: message.provider },\n async () => {\n // 1. State guard — only act on a message we still own in `sending`.\n // The claim token is the updatedAt from the argument, not this reread.\n const fresh = await deps.outbox.findById(message.id);\n if (!fresh || fresh.state !== \"sending\") {\n return { kind: \"skipped\", reason: \"no longer in sending state\" };\n }\n\n try {\n await deps.audit.append({\n messageId: fresh.id,\n eventType: \"dispatch_started\",\n actor: \"system:dispatch\",\n detail: { provider: fresh.provider },\n });\n } catch (err) {\n this.logWrite(\"dispatch_started audit failed; dispatch continues\", fresh.id, err);\n }\n\n // 2. Suppression on the stored HMAC, before decrypt or the provider.\n let listed: boolean;\n try {\n listed = await deps.suppressions.isSuppressed(fresh.recipientHmac);\n } catch (err) {\n return this.handleError(fresh, claim, err);\n }\n if (listed) return this.suppressListed(fresh, claim);\n\n const provider = deps.providers.get(fresh.provider);\n if (!provider) {\n return this.fail(fresh, claim, `No provider registered for \"${fresh.provider}\"`);\n }\n\n let receipt: { providerMessageId: string };\n try {\n // 3. Decrypt (read-side) -----------------------------------------\n const to = await deps.openEncryptor.open(fresh.recipientSealed, {\n messageId: fresh.id,\n column: \"recipient\",\n });\n const bodyJson = await deps.openEncryptor.open(fresh.bodySealed, {\n messageId: fresh.id,\n column: \"body\",\n });\n const body = JSON.parse(bodyJson) as MessageBody;\n\n // 4. Recipient, subject, and body size --------------------------\n const cleanTo = sanitizeRecipient(to, deps.config.sanitize);\n const cleanSubject = sanitizeSubject(fresh.subject, deps.config.sanitize);\n assertBodyWithinLimits(body, deps.config.sanitize);\n\n // 5. Domain validation -------------------------------------------\n await validateRecipient(cleanTo, deps.config.domainValidation, {\n mxResolver: deps.mxResolver,\n mxCache: this.mxCache,\n nowMs: deps.clock.now().getTime(),\n });\n\n // 6. Rate limiting ------------------------------------------------\n const limited = await this.checkRateLimits(fresh.provider, cleanTo);\n if (limited) {\n return this.requeueRateLimited(fresh, claim);\n }\n\n // 7. Dispatch -----------------------------------------------------\n const dispatchable: DispatchableMessage = {\n id: fresh.id,\n to: cleanTo,\n subject: cleanSubject,\n body,\n headers: this.buildHeaders(),\n metadata: fresh.metadata,\n };\n receipt = await provider.send(dispatchable);\n } catch (err) {\n return this.handleError(fresh, claim, err);\n }\n\n // 8. Transition to `sent`. A lost claim or a later audit failure\n // must not classify the provider accept as a retry. Pending webhooks\n // for this provider id are applied after the accept audit attempt.\n const wrote = await this.commitWhileSending(\n fresh.id,\n {\n state: \"sent\",\n providerMessageId: receipt.providerMessageId,\n lastError: null,\n },\n claim,\n true,\n );\n if (!wrote) return { kind: \"skipped\", reason: \"claim lost\" };\n\n try {\n await deps.audit.append({\n messageId: fresh.id,\n eventType: \"dispatch_accepted\",\n actor: `provider:${fresh.provider}`,\n detail: { providerMessageId: receipt.providerMessageId },\n });\n } catch (err) {\n this.logWrite(\"dispatch audit failed after sent; message stays sent\", fresh.id, err);\n }\n try {\n await this.webhooks.applyPending(receipt.providerMessageId);\n } catch (err) {\n this.logWrite(\"pending webhook apply failed after sent; message stays sent\", fresh.id, err);\n }\n deps.telemetry.counter(\"outpost.dispatch.sent\", 1, { provider: fresh.provider });\n return { kind: \"sent\", providerMessageId: receipt.providerMessageId };\n },\n );\n }\n\n /**\n * Recipient was listed after enqueue. `sending` → `suppressed` on the\n * stored HMAC. Do not decrypt, call the provider, or add a suppression row.\n * A lost claim does not audit. An audit failure leaves the row suppressed.\n */\n private async suppressListed(message: Message, claim: SendingClaim): Promise<DispatchOutcome> {\n const wrote = await this.commitWhileSending(message.id, { state: \"suppressed\" }, claim);\n if (!wrote) return { kind: \"skipped\", reason: \"claim lost\" };\n\n try {\n await this.deps.audit.append({\n messageId: message.id,\n eventType: \"suppressed\",\n actor: \"system:dispatch\",\n detail: { reason: \"recipient_on_suppression_list\" },\n });\n } catch (err) {\n this.logWrite(\"dispatch audit failed after suppressed; message stays suppressed\", message.id, err);\n }\n return { kind: \"skipped\", reason: \"recipient suppressed\" };\n }\n\n /** Classify a provider or pipeline error and either retry or dead-letter. */\n private async handleError(message: Message, claim: SendingClaim, err: unknown): Promise<DispatchOutcome> {\n const permanent = classifyProviderFailure(err) === \"permanent\";\n const reason = failureReason(err);\n\n if (permanent) {\n return this.fail(message, claim, reason);\n }\n\n // Transient (or unknown → treated as transient). Increment attempts.\n const attempts = message.attempts + 1;\n if (isExhausted(attempts, this.deps.config.retry)) {\n return this.fail(message, claim, `Retries exhausted (${attempts}): ${reason}`, attempts);\n }\n\n const delay = backoffMs(attempts, this.deps.config.retry, this.deps.random());\n const nextAttemptAt = new Date(this.deps.clock.now().getTime() + delay);\n const wrote = await this.commitWhileSending(\n message.id,\n { state: \"queued\", attempts, nextAttemptAt, lastError: reason, providerMessageId: null },\n claim,\n );\n if (!wrote) return { kind: \"skipped\", reason: \"claim lost\" };\n\n try {\n await this.deps.audit.append({\n messageId: message.id,\n eventType: \"retry_scheduled\",\n actor: `provider:${message.provider}`,\n detail: { attempts, nextAttemptAt: nextAttemptAt.toISOString(), reason },\n });\n } catch (auditErr) {\n this.logWrite(\"retry audit failed after requeue\", message.id, auditErr);\n }\n this.deps.telemetry.counter(\"outpost.dispatch.retry\", 1, { provider: message.provider });\n return { kind: \"retry\", nextAttemptAt };\n }\n\n /** Move to `failed` (terminal) and record in the Dead Letter Queue. */\n private async fail(\n message: Message,\n claim: SendingClaim,\n reason: string,\n attempts?: number,\n ): Promise<DispatchOutcome> {\n const wrote = await this.commitWhileSending(\n message.id,\n { state: \"failed\", attempts: attempts ?? message.attempts, lastError: reason },\n claim,\n );\n if (!wrote) return { kind: \"skipped\", reason: \"claim lost\" };\n\n try {\n await this.deps.audit.append({\n messageId: message.id,\n eventType: \"dead_lettered\",\n actor: `provider:${message.provider}`,\n detail: { reason },\n });\n } catch (auditErr) {\n this.logWrite(\"dead-letter audit failed after failed\", message.id, auditErr);\n }\n this.deps.telemetry.counter(\"outpost.dispatch.failed\", 1, { provider: message.provider });\n return { kind: \"failed\", reason };\n }\n\n /** Re-queue without counting a failed attempt; short, jittered backoff. */\n private async requeueRateLimited(message: Message, claim: SendingClaim): Promise<DispatchOutcome> {\n const delay = 1_000 + Math.floor(this.deps.random() * 4_000); // 1–5s\n const nextAttemptAt = new Date(this.deps.clock.now().getTime() + delay);\n const wrote = await this.commitWhileSending(\n message.id,\n { state: \"queued\", nextAttemptAt, providerMessageId: null },\n claim,\n );\n if (!wrote) return { kind: \"skipped\", reason: \"claim lost\" };\n this.deps.telemetry.counter(\"outpost.dispatch.rate_limited\", 1, { provider: message.provider });\n return { kind: \"rate_limited\", nextAttemptAt };\n }\n\n /**\n * Fence write. `false` means the claim no longer owns the row, or the driver\n * threw. Neither path is a provider retry. When the provider may already\n * have accepted, the log says so and the caller leaves the row alone.\n */\n private async commitWhileSending(\n id: string,\n patch: MessageStatePatch,\n claim: SendingClaim,\n providerMayHaveAccepted = false,\n ): Promise<boolean> {\n const write = this.deps.outbox.updateStateWhileSending;\n if (!write) {\n throw new Error(\"OutboxRepository.updateStateWhileSending is required to dispatch\");\n }\n try {\n const wrote = await write.call(this.deps.outbox, id, patch, claim);\n if (!wrote && providerMayHaveAccepted) {\n this.deps.logger.log(\n \"error\",\n \"provider may already have accepted; claim lost and the row was left unchanged\",\n { messageId: id },\n );\n }\n return wrote;\n } catch (err) {\n this.logWrite(\n providerMayHaveAccepted\n ? \"provider may already have accepted; state write failed and the row was left unchanged\"\n : \"dispatch state write failed and the row was left unchanged\",\n id,\n err,\n );\n return false;\n }\n }\n\n private logWrite(message: string, messageId: string, err: unknown): void {\n this.deps.logger.log(\"error\", message, {\n messageId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n private async checkRateLimits(provider: string, to: string): Promise<boolean> {\n const scopes = [\n { kind: \"global\" as const },\n { kind: \"provider\" as const, key: provider },\n { kind: \"recipientDomain\" as const, key: extractDomain(to) },\n ];\n if (this.deps.rateLimiter.acquireAll) {\n return !(await this.deps.rateLimiter.acquireAll(scopes));\n }\n const results = await Promise.all(scopes.map((scope) => this.deps.rateLimiter.acquire(scope)));\n return results.some((ok) => ok === false);\n }\n\n /** No headers are added. List-Unsubscribe is not set. */\n private buildHeaders(): Record<string, string> {\n return {};\n }\n}\n","import type { CoreDeps } from \"../application/context.js\";\nimport { DispatchMessage, type DispatchOutcome } from \"../application/dispatch-message.js\";\n\nexport interface SendTickReport {\n readonly claimed: number;\n readonly outcomes: DispatchOutcome[];\n}\n\nexport interface SendWorkerOptions {\n /** Poll interval for the long-running loop, ms. Default 1000. */\n readonly intervalMs?: number;\n /** Max messages claimed per tick. Defaults to config.sendBatchSize. */\n readonly batchSize?: number;\n /** Max concurrent dispatches within a tick. Default 10. */\n readonly concurrency?: number;\n}\n\n/**\n * SendWorker — the polling outbound processor (TDR §3.2, decision #2).\n *\n * Polls the outbox (NEVER a dual-written queue), atomically claims a batch with\n * `FOR UPDATE SKIP LOCKED`, and runs each message through `DispatchMessage`.\n * Concurrent claims skip locked rows. A `sending` row past the lease can be\n * claimed again, so the provider can be called twice. The stale claim's later\n * write does not change the row.\n *\n * Two ways to run it:\n * - `start()` / `stop()` — long-running process (setInterval-style loop).\n * - `tick()` — one cycle; call it from a cron job or Next.js route handler\n * (e.g. a Vercel Cron hitting `/api/cron/outpost-send`).\n */\nexport class SendWorker {\n private readonly dispatch: DispatchMessage;\n private running = false;\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n private readonly deps: CoreDeps,\n private readonly options: SendWorkerOptions = {},\n ) {\n this.dispatch = new DispatchMessage(deps);\n }\n\n /** Process one batch. Returns what happened (for logging/metrics/tests). */\n async tick(): Promise<SendTickReport> {\n const now = this.deps.clock.now();\n const batchSize = this.options.batchSize ?? this.deps.config.sendBatchSize;\n const reclaimBefore = new Date(now.getTime() - this.deps.config.staleSendingLeaseMs);\n const claimed = await this.deps.outbox.claimBatchForSending(batchSize, now, reclaimBefore);\n\n this.deps.telemetry.gauge(\"outpost.send.claimed\", claimed.length);\n if (claimed.length === 0) return { claimed: 0, outcomes: [] };\n\n const concurrency = this.options.concurrency ?? 10;\n const outcomes = await runWithConcurrency(claimed, concurrency, (m) =>\n this.dispatch.execute(m).catch((err) => {\n // DispatchMessage handles its own errors; this guards against an\n // unexpected throw so one bad message can't kill the whole tick.\n this.deps.logger.log(\"error\", \"dispatch threw unexpectedly\", {\n messageId: m.id,\n error: err instanceof Error ? err.message : String(err),\n });\n return { kind: \"failed\", reason: \"unexpected error\" } as DispatchOutcome;\n }),\n );\n\n return { claimed: claimed.length, outcomes };\n }\n\n /** Start the long-running poll loop. Idempotent. */\n start(): void {\n if (this.running) return;\n this.running = true;\n const interval = this.options.intervalMs ?? 1000;\n const loop = async () => {\n if (!this.running) return;\n try {\n await this.tick();\n } catch (err) {\n this.deps.logger.log(\"error\", \"send worker tick failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n } finally {\n if (this.running) this.timer = setTimeout(loop, interval);\n }\n };\n void loop();\n }\n\n /** Stop the loop. In-flight dispatches complete; no new tick starts. */\n stop(): void {\n this.running = false;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n }\n}\n\n/** Run `fn` over items with a bounded concurrency, preserving input order. */\nasync function runWithConcurrency<T, R>(\n items: T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let cursor = 0;\n const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {\n for (;;) {\n const i = cursor++;\n if (i >= items.length) return;\n results[i] = await fn(items[i]!);\n }\n });\n await Promise.all(workers);\n return results;\n}\n","import type { CoreDeps } from \"./context.js\";\nimport { normalizeBatchPauseMs, purgeCutoff, waitForBatchPause } from \"../domain/retention.js\";\n\nexport interface PurgeReport {\n /** Outbox rows whose PII was redacted (or deleted if redactOnPurge=false). */\n readonly operationalProcessed: number;\n /** Audit rows deleted. */\n readonly auditDeleted: number;\n readonly redacted: boolean;\n}\n\n/**\n * PurgeRetention — the executor of the data-minimization policy (TDR §3.9, §5.5).\n *\n * Safety properties baked in here:\n * - Selects terminal rows older than the operational TTL and past the\n * webhook window (`purgeCutoff`). The purge write repeats that predicate\n * against the cutoff computed for this cycle.\n * - Calls `redactBatchIfEligible` or `deleteBatchIfEligible`. A repository\n * that does not implement both throws here, before any id-only write.\n * - Default action is REDACTION (wipe PII, keep audit metadata), not deletion.\n * - Works in batches. After a full batch it waits `batchPauseMs` before the\n * next claim. A short batch does not wait.\n * - Logs counts per cycle so operators can detect \"stopped cleaning\" and\n * \"cleaning too much\".\n */\nexport class PurgeRetention {\n constructor(private readonly deps: CoreDeps) {}\n\n async execute(): Promise<PurgeReport> {\n const { deps } = this;\n return deps.telemetry.span(\"outpost.retention.purge\", {}, async () => {\n const now = deps.clock.now();\n const policy = deps.config.retention;\n const cutoff = purgeCutoff(policy, now);\n const pauseMs = normalizeBatchPauseMs(policy.batchPauseMs);\n\n const redactEligible = deps.outbox.redactBatchIfEligible;\n const deleteEligible = deps.outbox.deleteBatchIfEligible;\n if (typeof redactEligible !== \"function\" || typeof deleteEligible !== \"function\") {\n throw new Error(\n \"OutboxRepository must implement redactBatchIfEligible and deleteBatchIfEligible. Retention throws before it writes and does not call redactBatch or deleteBatch.\",\n );\n }\n\n // 1. Operational data: redact or delete rows that still match the select.\n let operationalProcessed = 0;\n for (;;) {\n const batch = await deps.outbox.claimTerminalForPurge(cutoff, policy.batchSize);\n if (batch.length === 0) break;\n const ids = batch.map((m) => m.id);\n const count = policy.redactOnPurge\n ? await redactEligible.call(deps.outbox, ids, cutoff)\n : await deleteEligible.call(deps.outbox, ids, cutoff);\n operationalProcessed += count;\n\n await deps.audit.append({\n messageId: null,\n eventType: policy.redactOnPurge ? \"redacted\" : \"purged\",\n actor: \"system:retention\",\n detail: { count, cutoff: cutoff.toISOString() },\n });\n // A short batch means this claim already drained the eligible rows.\n if (batch.length < policy.batchSize) break;\n await waitForBatchPause(pauseMs);\n }\n\n // 2. Webhook rows of every disposition, using the same cutoff. A repository\n // without deleteOlderThan keeps its webhook rows; outbox purge still runs.\n const deleteWebhooks = deps.webhookEvents.deleteOlderThan;\n const webhooksDeleted =\n typeof deleteWebhooks === \"function\"\n ? await deleteWebhooks.call(deps.webhookEvents, cutoff)\n : 0;\n\n // 3. Audit data: independent, longer TTL.\n const auditCutoff = new Date(now.getTime() - policy.auditTtlDays * 24 * 60 * 60 * 1000);\n const auditDeleted = await deps.audit.purgeOlderThan(auditCutoff, policy.batchSize, pauseMs);\n\n deps.telemetry.gauge(\"outpost.retention.operational_processed\", operationalProcessed);\n deps.telemetry.gauge(\"outpost.retention.audit_deleted\", auditDeleted);\n deps.logger.log(\"info\", \"retention cycle complete\", {\n operationalProcessed,\n auditDeleted,\n webhooksDeleted,\n redacted: policy.redactOnPurge,\n });\n\n return { operationalProcessed, auditDeleted, redacted: policy.redactOnPurge };\n });\n }\n}\n","import type { CoreDeps } from \"../application/context.js\";\nimport { PurgeRetention, type PurgeReport } from \"../application/purge-retention.js\";\n\nexport interface RetentionWorkerOptions {\n /** Loop interval, ms. Default 1 hour. Retention is not latency-sensitive. */\n readonly intervalMs?: number;\n}\n\n/**\n * RetentionWorker — periodically enforces the retention/purge policy\n * (TDR §3.9). Like the send worker it offers both a long-running `start()`\n * loop and a single `tick()` for cron/route-handler deployments. It redacts or\n * deletes terminal, aged outbox rows, and deletes webhook rows older than the\n * same cutoff, so it is safe to run alongside the send worker.\n *\n * Loop lifecycle (`start` / `stop`) is serialized on this class only. A tick\n * already in flight is not cancelled by `stop()`, and a later `start()` does\n * not run a second tick while that work is pending. The next interval is always\n * armed with `setTimeout`, including `intervalMs` 0, so the loop yields.\n * `SendWorker` does not inherit this guarantee.\n */\nexport class RetentionWorker {\n private readonly purge: PurgeRetention;\n private running = false;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inFlight = false;\n\n constructor(\n private readonly deps: CoreDeps,\n private readonly options: RetentionWorkerOptions = {},\n ) {\n this.purge = new PurgeRetention(deps);\n }\n\n async tick(): Promise<PurgeReport> {\n return this.purge.execute();\n }\n\n start(): void {\n if (this.running) return;\n this.running = true;\n void this.runLoopTick();\n }\n\n stop(): void {\n this.running = false;\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n private intervalMs(): number {\n return this.options.intervalMs ?? 60 * 60 * 1000;\n }\n\n private async runLoopTick(): Promise<void> {\n if (this.inFlight) return;\n if (!this.running) return;\n this.inFlight = true;\n try {\n await this.tick();\n } catch (err) {\n this.deps.logger.log(\"error\", \"retention worker tick failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n } finally {\n this.inFlight = false;\n if (this.running) {\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.runLoopTick();\n }, this.intervalMs());\n }\n }\n }\n}\n","import type { CoreDeps } from \"../application/context.js\";\nimport { EnqueueMessage, type EnqueueInput, type EnqueueResult } from \"../application/enqueue-message.js\";\nimport { IngestWebhook, type IngestWebhookResult } from \"../application/ingest-webhook.js\";\nimport { ManageSuppression } from \"../application/manage-suppression.js\";\nimport { ManageApiKey } from \"../application/manage-api-key.js\";\nimport { Authenticate } from \"../application/authenticate.js\";\nimport {\n GetMessage,\n ListMessages,\n ReplayMessage,\n type MessageView,\n} from \"../application/message-queries.js\";\nimport type { ListMessagesQuery } from \"../ports/repositories.js\";\nimport type { SuppressionReason, SuppressionEntry } from \"../domain/suppression.js\";\nimport type { RawWebhook } from \"../ports/email-provider.js\";\nimport { SendWorker } from \"../workers/send-worker.js\";\nimport { RetentionWorker } from \"../workers/retention-worker.js\";\n\n/**\n * The high-level, typed programmatic client returned by `createOutpost`\n * (TDR §4.2). Server-side use within the same app calls these methods directly;\n * cross-service callers go through the HTTP handlers (which call the same use\n * cases under the hood).\n *\n * `actor` labels who performed an action in the audit trail. The programmatic\n * client defaults to `\"programmatic\"`; the HTTP layer passes the API key id.\n */\nexport class Outpost {\n readonly enqueueMessage: EnqueueMessage;\n readonly ingestWebhook: IngestWebhook;\n readonly suppression: ManageSuppression;\n readonly keys: ManageApiKey;\n readonly auth: Authenticate;\n readonly send_worker: SendWorker;\n readonly retention_worker: RetentionWorker;\n\n private readonly getMessage: GetMessage;\n private readonly listMessages: ListMessages;\n private readonly replayMessage: ReplayMessage;\n\n constructor(\n readonly deps: CoreDeps,\n private readonly defaultActor = \"programmatic\",\n ) {\n this.enqueueMessage = new EnqueueMessage(deps);\n this.ingestWebhook = new IngestWebhook(deps);\n this.suppression = new ManageSuppression(deps);\n this.keys = new ManageApiKey(deps);\n this.auth = new Authenticate(deps);\n this.getMessage = new GetMessage(deps);\n this.listMessages = new ListMessages(deps);\n this.replayMessage = new ReplayMessage(deps);\n this.send_worker = new SendWorker(deps);\n this.retention_worker = new RetentionWorker(deps);\n }\n\n /** Enqueue a message (persist-then-queue). Idempotent on `idempotencyKey`. */\n send(input: EnqueueInput, opts?: { actor?: string }): Promise<EnqueueResult> {\n return this.enqueueMessage.execute(input, opts?.actor ?? this.defaultActor);\n }\n\n /** Fetch lifecycle and metadata. The body and recipient address are omitted. */\n get(id: string): Promise<MessageView> {\n return this.getMessage.execute(id);\n }\n\n /** List messages by state / recipient hash / date. */\n list(query: ListMessagesQuery = {}): Promise<MessageView[]> {\n return this.listMessages.execute(query);\n }\n\n /** Re-enqueue a dead-lettered (failed) message from the DLQ. */\n replay(id: string, opts?: { actor?: string }): Promise<MessageView> {\n return this.replayMessage.execute(id, opts?.actor ?? this.defaultActor);\n }\n\n /** Check whether an address is on the suppression list. */\n isSuppressed(address: string): Promise<boolean> {\n return this.suppression.isSuppressed(address);\n }\n\n /** Add an address to the suppression list (audited). */\n suppress(\n address: string,\n reason: SuppressionReason = \"manual\",\n opts?: { note?: string; actor?: string },\n ): Promise<SuppressionEntry> {\n return this.suppression.suppress(address, reason, opts?.actor ?? this.defaultActor, opts?.note);\n }\n\n /** Remove an address from the suppression list (audited). */\n async unsuppress(address: string, opts?: { actor?: string }): Promise<boolean> {\n const hmac = this.deps.recipientHasher.hash(address);\n return this.suppression.unsuppressByHmac(hmac, opts?.actor ?? this.defaultActor);\n }\n\n /** Ingest a verified provider webhook (used by the HTTP webhook sink). */\n webhook(provider: string, raw: RawWebhook): Promise<IngestWebhookResult> {\n return this.ingestWebhook.execute(provider, raw);\n }\n\n /** Convenience: run one send-worker cycle (cron/route-handler deployments). */\n tickSend(): ReturnType<SendWorker[\"tick\"]> {\n return this.send_worker.tick();\n }\n\n /** Convenience: run one retention cycle. */\n tickRetention(): ReturnType<RetentionWorker[\"tick\"]> {\n return this.retention_worker.tick();\n }\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\nimport type { RecipientHasher } from \"../../ports/crypto.js\";\n\n/**\n * Keyed HMAC-SHA256 recipient hasher (TDR §5.4 condition 3).\n *\n * Deterministic (same address → same digest, so suppression/idempotency work)\n * and keyed (a leaked DB dump cannot be brute-forced into addresses without the\n * key). The key MUST live outside the database — pass it from KMS/Vault/secrets,\n * never store it in a column.\n *\n * Addresses are normalized (trim + lowercase) before hashing so casing/whitespace\n * variants of the same address collapse to one digest.\n */\nexport class HmacRecipientHasher implements RecipientHasher {\n private readonly key: Buffer;\n\n constructor(key: string | Buffer) {\n this.key = typeof key === \"string\" ? Buffer.from(key, \"utf8\") : key;\n if (this.key.length < 16) {\n throw new Error(\"Recipient HMAC key must be at least 16 bytes of entropy\");\n }\n }\n\n hash(address: string): string {\n const normalized = address.trim().toLowerCase();\n return createHmac(\"sha256\", this.key).update(normalized, \"utf8\").digest(\"hex\");\n }\n\n /** Constant-time comparison helper for callers that compare digests. */\n static equals(a: string, b: string): boolean {\n const ab = Buffer.from(a);\n const bb = Buffer.from(b);\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n }\n}\n","import {\n randomBytes,\n createCipheriv,\n createDecipheriv,\n publicEncrypt,\n privateDecrypt,\n constants as cryptoConstants,\n} from \"node:crypto\";\nimport type { Encryptor, SealContext } from \"../../ports/crypto.js\";\nimport type { Sealed } from \"../../domain/message.js\";\n\n/**\n * Encryptor implementations (TDR §5.4). All use vetted primitives — no\n * hand-rolled crypto. Three flavors:\n *\n * - NoopEncryptor — encryption disabled; `alg: \"plain\"`. Same column\n * shape so encryption can be turned on later with no\n * row-format migration.\n * - AesGcmEncryptor — symmetric AEAD (AES-256-GCM). One key seals+opens.\n * - Hybrid{Seal,Open} — asymmetric least-privilege split: the ingestion API\n * gets seal-only (public key), the send worker gets\n * open (private key). The web tier physically cannot\n * read plaintext back.\n *\n * For production, hold key material in KMS/Vault and implement `Encryptor`\n * against it (envelope encryption) — these local-key classes are the reference\n * and the dev/test default. See docs/security.md.\n */\n\nconst PLAIN_ALG = \"plain\";\n\nfunction aadBytes(context: SealContext): Buffer {\n return Buffer.from(`${context.messageId}:${context.column}`, \"utf8\");\n}\n\nfunction assertKeyId(sealed: Sealed, keyId: string): void {\n if (sealed.keyId !== undefined && sealed.keyId !== keyId) {\n throw new Error(\"Sealed value keyId does not match this encryptor\");\n }\n}\n\n/** No-op: stores base64(plaintext). Used when encryption is disabled. */\nexport class NoopEncryptor implements Encryptor {\n readonly alg = PLAIN_ALG;\n async seal(plaintext: string, _context?: SealContext): Promise<Sealed> {\n return { alg: PLAIN_ALG, ciphertext: Buffer.from(plaintext, \"utf8\").toString(\"base64\") };\n }\n async open(sealed: Sealed, _context?: SealContext): Promise<string> {\n return Buffer.from(sealed.ciphertext, \"base64\").toString(\"utf8\");\n }\n}\n\nconst AES_ALG = \"aes-256-gcm\";\n\n/** Symmetric AEAD. The 32-byte key MUST come from KMS/secrets, not the DB. */\nexport class AesGcmEncryptor implements Encryptor {\n readonly alg = AES_ALG;\n private readonly key: Buffer;\n\n constructor(key: Buffer, private readonly keyId = \"default\") {\n if (key.length !== 32) throw new Error(\"AES-256-GCM requires a 32-byte key\");\n this.key = key;\n }\n\n async seal(plaintext: string, context?: SealContext): Promise<Sealed> {\n const iv = randomBytes(12);\n const cipher = createCipheriv(AES_ALG, this.key, iv);\n if (context) cipher.setAAD(aadBytes(context));\n const ct = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n const tag = cipher.getAuthTag();\n return {\n alg: AES_ALG,\n ciphertext: ct.toString(\"base64\"),\n iv: iv.toString(\"base64\"),\n tag: tag.toString(\"base64\"),\n keyId: this.keyId,\n ...(context ? { bound: true } : {}),\n };\n }\n\n async open(sealed: Sealed, context?: SealContext): Promise<string> {\n if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);\n if (context) assertKeyId(sealed, this.keyId);\n if (sealed.bound && !context) {\n throw new Error(\"Sealed value is bound to a message and column\");\n }\n return decryptAes(this.key, sealed, sealed.bound ? context : undefined);\n }\n}\n\nconst HYBRID_ALG = \"hybrid-rsa-aes-256-gcm\";\n\nfunction rsaOaep(key: string) {\n return { key, padding: cryptoConstants.RSA_PKCS1_OAEP_PADDING, oaepHash: \"sha256\" } as const;\n}\n\n/**\n * Seal-only encryptor for the ingestion tier. Holds ONLY the public key:\n * generates a fresh AES data key per message, seals the payload with it, and\n * wraps the data key under RSA-OAEP. `open` throws — by construction the web\n * tier cannot decrypt (TDR §5.4 condition 2).\n */\nexport class HybridSealEncryptor implements Encryptor {\n readonly alg = HYBRID_ALG;\n constructor(private readonly publicKeyPem: string, private readonly keyId = \"default\") {}\n\n async seal(plaintext: string, context?: SealContext): Promise<Sealed> {\n const dataKey = randomBytes(32);\n const iv = randomBytes(12);\n const cipher = createCipheriv(AES_ALG, dataKey, iv);\n if (context) cipher.setAAD(aadBytes(context));\n const ct = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n const tag = cipher.getAuthTag();\n const wrappedKey = publicEncrypt(rsaOaep(this.publicKeyPem), dataKey);\n return {\n alg: HYBRID_ALG,\n ciphertext: ct.toString(\"base64\"),\n iv: iv.toString(\"base64\"),\n tag: tag.toString(\"base64\"),\n wrappedKey: wrappedKey.toString(\"base64\"),\n keyId: this.keyId,\n ...(context ? { bound: true } : {}),\n };\n }\n\n async open(): Promise<string> {\n throw new Error(\n \"HybridSealEncryptor cannot decrypt: the ingestion tier holds only the public key (by design)\",\n );\n }\n}\n\n/**\n * Open-capable encryptor for the send worker. Holds the private key; unwraps the\n * data key and decrypts. `seal` throws — the worker is not the writer.\n */\nexport class HybridOpenEncryptor implements Encryptor {\n readonly alg = HYBRID_ALG;\n constructor(\n private readonly privateKeyPem: string,\n private readonly keyId = \"default\",\n ) {}\n\n async seal(): Promise<Sealed> {\n throw new Error(\"HybridOpenEncryptor is read-only; use HybridSealEncryptor to seal\");\n }\n\n async open(sealed: Sealed, context?: SealContext): Promise<string> {\n if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);\n if (context) assertKeyId(sealed, this.keyId);\n if (sealed.bound && !context) {\n throw new Error(\"Sealed value is bound to a message and column\");\n }\n if (!sealed.wrappedKey || !sealed.iv || !sealed.tag) {\n throw new Error(\"Sealed value missing wrappedKey/iv/tag for hybrid open\");\n }\n const dataKey = privateDecrypt(\n rsaOaep(this.privateKeyPem),\n Buffer.from(sealed.wrappedKey, \"base64\"),\n );\n return decryptAes(dataKey, sealed, sealed.bound ? context : undefined);\n }\n}\n\nfunction decryptAes(key: Buffer, sealed: Sealed, context?: SealContext): string {\n if (!sealed.iv || !sealed.tag) throw new Error(\"Sealed value missing iv/tag\");\n const decipher = createDecipheriv(AES_ALG, key, Buffer.from(sealed.iv, \"base64\"));\n if (context) decipher.setAAD(aadBytes(context));\n decipher.setAuthTag(Buffer.from(sealed.tag, \"base64\"));\n const pt = Buffer.concat([\n decipher.update(Buffer.from(sealed.ciphertext, \"base64\")),\n decipher.final(),\n ]);\n return pt.toString(\"utf8\");\n}\n","import type { RateLimiter, RateLimitScope, Clock } from \"../../ports/services.js\";\nimport type { RateLimitConfig, RateBudget } from \"../../application/config.js\";\n\n/**\n * In-memory token-bucket rate limiter (TDR §3.2 step 4).\n *\n * Layered: a distinct bucket per (scope.kind + scope.key). A budget of\n * `{ max, windowMs }` refills `max` tokens over `windowMs`. `acquire` consumes\n * one token; returns false when the bucket is empty (caller re-queues).\n *\n * This is correct for a SINGLE process. For multiple send-worker instances,\n * implement the `RateLimiter` port against Redis (shared counters) — the port\n * is the seam, the core does not change.\n */\nexport class InMemoryRateLimiter implements RateLimiter {\n private readonly buckets = new Map<string, { tokens: number; lastRefill: number }>();\n\n constructor(\n private readonly config: RateLimitConfig,\n private readonly clock: Clock,\n ) {}\n\n async acquire(scope: RateLimitScope): Promise<boolean> {\n const budget = this.budgetFor(scope);\n if (!budget) return true; // unlimited when no budget configured\n\n const bucket = this.refill(`${scope.kind}:${scope.key ?? \"\"}`, budget, this.clock.now().getTime());\n\n if (bucket.tokens >= 1) {\n bucket.tokens -= 1;\n return true;\n }\n return false;\n }\n\n async acquireAll(scopes: readonly RateLimitScope[]): Promise<boolean> {\n const now = this.clock.now().getTime();\n const ready = new Map<string, { tokens: number; lastRefill: number }>();\n let allowed = true;\n for (const scope of scopes) {\n const budget = this.budgetFor(scope);\n if (!budget) continue;\n const key = `${scope.kind}:${scope.key ?? \"\"}`;\n const bucket = this.refill(key, budget, now);\n if (bucket.tokens < 1) allowed = false;\n else ready.set(key, bucket);\n }\n if (!allowed) return false;\n for (const bucket of ready.values()) bucket.tokens -= 1;\n return true;\n }\n\n private refill(\n key: string,\n budget: RateBudget,\n now: number,\n ): { tokens: number; lastRefill: number } {\n let bucket = this.buckets.get(key);\n if (!bucket) {\n bucket = { tokens: budget.max, lastRefill: now };\n this.buckets.set(key, bucket);\n return bucket;\n }\n const elapsed = now - bucket.lastRefill;\n bucket.tokens = Math.min(budget.max, bucket.tokens + elapsed * (budget.max / budget.windowMs));\n bucket.lastRefill = now;\n return bucket;\n }\n\n private budgetFor(scope: RateLimitScope): RateBudget | undefined {\n switch (scope.kind) {\n case \"global\":\n return this.config.global;\n case \"provider\":\n return this.config.perProvider;\n case \"recipientDomain\":\n return this.config.perRecipientDomain;\n }\n }\n}\n\n/** Always allows. Used when no rate limits are configured. */\nexport class UnlimitedRateLimiter implements RateLimiter {\n async acquire(): Promise<boolean> {\n return true;\n }\n\n async acquireAll(): Promise<boolean> {\n return true;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { resolveMx as dnsResolveMx } from \"node:dns/promises\";\nimport type { Clock, IdGenerator } from \"../../ports/services.js\";\nimport type { MxResolver } from \"../../application/pipeline/domain-validation.js\";\n\n/** Real wall-clock. Inject a fake `Clock` in tests for determinism. */\nexport class SystemClock implements Clock {\n now(): Date {\n return new Date();\n }\n}\n\n/** UUID v4 ids via node:crypto. */\nexport class UuidGenerator implements IdGenerator {\n generate(): string {\n return randomUUID();\n }\n}\n\n/** MX resolver backed by node:dns. Used only when domainValidation.mx is on. */\nexport class DnsMxResolver implements MxResolver {\n async resolveMx(domain: string): Promise<string[]> {\n const records = await dnsResolveMx(domain);\n return records\n .sort((a, b) => a.priority - b.priority)\n .map((r) => r.exchange);\n }\n}\n","import type { Logger, LogLevel } from \"../../ports/services.js\";\n\n/** Structured console logger (JSON lines). The default when none is provided. */\nexport class ConsoleLogger implements Logger {\n constructor(private readonly minLevel: LogLevel = \"info\") {}\n\n private static readonly RANK: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n };\n\n log(level: LogLevel, message: string, fields?: Record<string, unknown>): void {\n if (ConsoleLogger.RANK[level] < ConsoleLogger.RANK[this.minLevel]) return;\n const line = JSON.stringify({ level, message, ...fields });\n if (level === \"error\") console.error(line);\n else if (level === \"warn\") console.warn(line);\n else console.log(line);\n }\n}\n\n/** Drops everything. Useful in tests. */\nexport class NoopLogger implements Logger {\n log(): void {}\n}\n","import type { Telemetry } from \"../../ports/services.js\";\n\n/**\n * No-op telemetry. Used when observability is disabled. Still runs the wrapped\n * function so behavior is identical to the instrumented path.\n */\nexport class NoopTelemetry implements Telemetry {\n async span<T>(_name: string, _attrs: Record<string, unknown>, fn: () => Promise<T>): Promise<T> {\n return fn();\n }\n counter(): void {}\n gauge(): void {}\n}\n\n/**\n * OpenTelemetry-backed telemetry (TDR §8). `@opentelemetry/api` is an OPTIONAL\n * peer dependency: this adapter imports it lazily so the package works without\n * it installed. Wire the OTel SDK (exporters, providers) in your application;\n * this adapter only emits to whatever global meter/tracer is registered.\n *\n * Usage:\n * import { OtelTelemetry } from \"@tgoliveira/outpost/adapters\";\n * const telemetry = await OtelTelemetry.create();\n */\nexport class OtelTelemetry implements Telemetry {\n private constructor(\n // Loosely typed to avoid a hard dependency on @opentelemetry/api types.\n private readonly tracer: any,\n private readonly counters: Map<string, any>,\n private readonly gauges: Map<string, any>,\n private readonly meter: any,\n private readonly api: any,\n ) {}\n\n static async create(serviceName = \"outpost\"): Promise<Telemetry> {\n try {\n const api = await import(\"@opentelemetry/api\");\n const tracer = api.trace.getTracer(serviceName);\n const meter = api.metrics.getMeter(serviceName);\n return new OtelTelemetry(tracer, new Map(), new Map(), meter, api);\n } catch {\n // @opentelemetry/api not installed → degrade gracefully to no-op.\n return new NoopTelemetry();\n }\n }\n\n async span<T>(name: string, attrs: Record<string, unknown>, fn: () => Promise<T>): Promise<T> {\n return this.tracer.startActiveSpan(name, async (span: any) => {\n try {\n for (const [k, v] of Object.entries(attrs)) span.setAttribute(k, v as any);\n const result = await fn();\n span.setStatus({ code: this.api.SpanStatusCode.OK });\n return result;\n } catch (err) {\n span.recordException(err as Error);\n span.setStatus({\n code: this.api.SpanStatusCode.ERROR,\n message: err instanceof Error ? err.message : String(err),\n });\n throw err;\n } finally {\n span.end();\n }\n });\n }\n\n counter(name: string, value: number, attrs?: Record<string, unknown>): void {\n let c = this.counters.get(name);\n if (!c) {\n c = this.meter.createCounter(name);\n this.counters.set(name, c);\n }\n c.add(value, attrs);\n }\n\n gauge(name: string, value: number, attrs?: Record<string, unknown>): void {\n // Use a counter-style observation; for true gauges wire an observable\n // gauge in your SDK. Recorded as a histogram-friendly value here.\n let g = this.gauges.get(name);\n if (!g) {\n g = this.meter.createHistogram(name);\n this.gauges.set(name, g);\n }\n g.record(value, attrs);\n }\n}\n","import type { CoreDeps } from \"./application/context.js\";\nimport { resolveConfig, type ConfigOverrides, type RateLimitConfig } from \"./application/config.js\";\nimport { Outpost } from \"./client/outpost-client.js\";\nimport type {\n OutboxRepository,\n SuppressionRepository,\n AuditRepository,\n ApiKeyRepository,\n WebhookEventRepository,\n} from \"./ports/repositories.js\";\nimport type { EmailProvider } from \"./ports/email-provider.js\";\nimport type { Encryptor } from \"./ports/crypto.js\";\nimport type { Clock, IdGenerator, Logger, Telemetry, RateLimiter } from \"./ports/services.js\";\nimport type { TemplateRenderer } from \"./ports/template.js\";\nimport type { MxResolver } from \"./application/pipeline/domain-validation.js\";\n\nimport { HmacRecipientHasher } from \"./adapters/crypto/recipient-hasher.js\";\nimport {\n NoopEncryptor,\n AesGcmEncryptor,\n HybridSealEncryptor,\n HybridOpenEncryptor,\n} from \"./adapters/crypto/encryptors.js\";\nimport { InMemoryRateLimiter, UnlimitedRateLimiter } from \"./adapters/rate-limit/in-memory.js\";\nimport { SystemClock, UuidGenerator, DnsMxResolver } from \"./adapters/services/system.js\";\nimport { ConsoleLogger } from \"./adapters/observability/logger.js\";\nimport { NoopTelemetry } from \"./adapters/observability/telemetry.js\";\n\n/**\n * Encryption posture (TDR §5.4). Pick one:\n *\n * - `none` — encryption disabled (`alg: \"plain\"`). Dev default.\n * - `symmetric` — AES-256-GCM; one 32-byte key seals and opens. Simple,\n * single-process. Key MUST come from KMS/secrets.\n * - `asymmetric` — least-privilege split: the web tier seals with the\n * PUBLIC key and can never read back; the send worker opens\n * with the PRIVATE key. Omit `privateKey` on the web tier.\n * - bring-your-own `Encryptor` pair — back it with AWS KMS / GCP KMS / Vault.\n */\nexport type EncryptionOptions =\n | { mode: \"none\" }\n | { mode: \"symmetric\"; key: Buffer | string; keyId?: string }\n | { mode: \"asymmetric\"; publicKey: string; privateKey?: string; keyId?: string }\n | { sealEncryptor: Encryptor; openEncryptor: Encryptor };\n\nexport interface OutpostOptions extends ConfigOverrides {\n /**\n * Persistence. Build these from your Drizzle db via the helpers in\n * `@tgoliveira/outpost/drizzle`, or use the in-memory ones from\n * `@tgoliveira/outpost/testing`.\n */\n repositories: {\n outbox: OutboxRepository;\n suppressions: SuppressionRepository;\n audit: AuditRepository;\n apiKeys: ApiKeyRepository;\n webhookEvents: WebhookEventRepository;\n };\n\n /** One or more transport adapters. The first is the default unless overridden. */\n providers: EmailProvider[];\n defaultProvider?: string;\n\n /**\n * Key for the deterministic recipient HMAC (TDR §5.4). REQUIRED — it backs\n * suppression matching and recipient-keyed lookups even when encryption is\n * off. The constructor requires at least 16 bytes and does not measure\n * entropy. Keep the key outside the database.\n */\n recipientHmacKey: string | Buffer;\n\n /** Encryption-at-rest posture. Defaults to `{ mode: \"none\" }`. */\n encryption?: EncryptionOptions;\n\n rateLimits?: RateLimitConfig;\n\n /** Template renderer (e.g. InMemoryTemplateRenderer). Optional. */\n templates?: TemplateRenderer;\n\n /** Pre-built telemetry. For OTel: `telemetry: await OtelTelemetry.create()`. */\n telemetry?: Telemetry;\n logger?: Logger;\n clock?: Clock;\n ids?: IdGenerator;\n rateLimiter?: RateLimiter;\n mxResolver?: MxResolver;\n /** Strong HTML sanitizer (e.g. sanitize-html). Falls back to a built-in. */\n sanitizeHtml?: (html: string) => string;\n /** Random source for retry jitter. Defaults to Math.random. */\n random?: () => number;\n /** Default audit actor for programmatic calls. Default \"programmatic\". */\n defaultActor?: string;\n}\n\n/**\n * Composition root (TDR §6, Dependency Inversion). Resolves config, wires the\n * adapters into a `CoreDeps`, and returns the high-level `Outpost` client.\n *\n * This is the ONLY place concrete adapters are assembled — everything inward\n * depends on ports. Swapping a provider, storage backend, or KMS is a change\n * here, never in the core.\n */\nexport function createOutpost(options: OutpostOptions): Outpost {\n const config = resolveConfig({\n retry: options.retry,\n retention: options.retention,\n sanitize: options.sanitize,\n attachments: options.attachments,\n domainValidation: options.domainValidation,\n rateLimits: options.rateLimits,\n sendBatchSize: options.sendBatchSize,\n staleSendingLeaseMs: options.staleSendingLeaseMs,\n });\n\n if (options.providers.length === 0) {\n throw new Error(\"createOutpost requires at least one provider\");\n }\n const providers = new Map<string, EmailProvider>();\n for (const p of options.providers) providers.set(p.name, p);\n const defaultProvider = options.defaultProvider ?? options.providers[0]!.name;\n if (!providers.has(defaultProvider)) {\n throw new Error(`defaultProvider \"${defaultProvider}\" is not in the providers list`);\n }\n\n const { sealEncryptor, openEncryptor } = resolveEncryption(options.encryption ?? { mode: \"none\" });\n const recipientHasher = new HmacRecipientHasher(options.recipientHmacKey);\n\n const clock: Clock = options.clock ?? new SystemClock();\n const rateLimiter: RateLimiter =\n options.rateLimiter ??\n (options.rateLimits ? new InMemoryRateLimiter(options.rateLimits, clock) : new UnlimitedRateLimiter());\n\n const deps: CoreDeps = {\n config,\n outbox: options.repositories.outbox,\n suppressions: options.repositories.suppressions,\n audit: options.repositories.audit,\n apiKeys: options.repositories.apiKeys,\n webhookEvents: options.repositories.webhookEvents,\n providers,\n defaultProvider,\n sealEncryptor,\n openEncryptor,\n recipientHasher,\n rateLimiter,\n clock,\n ids: options.ids ?? new UuidGenerator(),\n logger: options.logger ?? new ConsoleLogger(),\n telemetry: options.telemetry ?? new NoopTelemetry(),\n templates: options.templates,\n mxResolver:\n options.mxResolver ?? (config.domainValidation.mx ? new DnsMxResolver() : undefined),\n sanitizeHtml: options.sanitizeHtml,\n random: options.random ?? Math.random,\n };\n\n return new Outpost(deps, options.defaultActor);\n}\n\nfunction resolveEncryption(enc: EncryptionOptions): {\n sealEncryptor: Encryptor;\n openEncryptor: Encryptor;\n} {\n if (\"sealEncryptor\" in enc) {\n return { sealEncryptor: enc.sealEncryptor, openEncryptor: enc.openEncryptor };\n }\n switch (enc.mode) {\n case \"none\": {\n const noop = new NoopEncryptor();\n return { sealEncryptor: noop, openEncryptor: noop };\n }\n case \"symmetric\": {\n const key = typeof enc.key === \"string\" ? Buffer.from(enc.key, \"base64\") : enc.key;\n const e = new AesGcmEncryptor(key, enc.keyId);\n return { sealEncryptor: e, openEncryptor: e };\n }\n case \"asymmetric\": {\n const seal = new HybridSealEncryptor(enc.publicKey, enc.keyId);\n // No private key (web tier) → an opener that refuses, preserving the\n // \"web tier cannot read\" invariant.\n const open = enc.privateKey ? new HybridOpenEncryptor(enc.privateKey, enc.keyId) : seal;\n return { sealEncryptor: seal, openEncryptor: open };\n }\n }\n}\n","/**\n * Suppression list domain types.\n *\n * The suppression list is the reputation guardrail: any address on it is never\n * dispatched to. Entries are keyed by the recipient HMAC (not plaintext) so the\n * list keeps working when recipients are encrypted at rest (TDR §3.6, §5.4).\n */\n\nexport const SUPPRESSION_REASONS = [\n \"hard_bounce\",\n \"complaint\",\n \"unsubscribe\",\n \"invalid\",\n \"manual\",\n] as const;\n\nexport type SuppressionReason = (typeof SUPPRESSION_REASONS)[number];\n\nexport interface SuppressionEntry {\n /** Keyed HMAC of the suppressed address. Unique. */\n readonly recipientHmac: string;\n readonly reason: SuppressionReason;\n /** api key id, provider name, or \"system\". For the audit trail. */\n readonly createdBy: string;\n readonly createdAt: Date;\n /** Optional free-text note (e.g. the provider bounce message). */\n readonly note?: string;\n}\n"]}
|