@tgoliveira/outpost 1.2.1 → 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 +38 -21
- package/dist/modules/ui/index.cjs.map +1 -1
- package/dist/modules/ui/index.js +38 -21
- package/dist/modules/ui/index.js.map +1 -1
- package/dist/modules/ui/pages/admin/admin-config-page.cjs +39 -20
- package/dist/modules/ui/pages/admin/admin-config-page.cjs.map +1 -1
- package/dist/modules/ui/pages/admin/admin-config-page.d.cts +23 -1
- package/dist/modules/ui/pages/admin/admin-config-page.d.ts +23 -1
- package/dist/modules/ui/pages/admin/admin-config-page.js +38 -20
- 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 +38 -21
- package/dist/modules/ui/pages/index.cjs.map +1 -1
- package/dist/modules/ui/pages/index.js +38 -21
- 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 +38 -21
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.js +38 -21
- 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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/domain/errors.ts","../../src/application/pipeline/retry-policy.ts","../../src/application/pipeline/domain-validation.ts","../../src/application/pipeline/sanitize.ts","../../src/application/dispatch-message.ts","../../src/workers/send-worker.ts","../../src/domain/retention.ts","../../src/application/purge-retention.ts","../../src/workers/retention-worker.ts"],"names":[],"mappings":";;;AAWO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,IAAA;AAAA,EACT,WAAA,CAAY,IAAA,EAAc,OAAA,EAAiB,OAAA,EAA+B;AACxE,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AACvB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF,CAAA;AAiBO,IAAM,eAAA,GAAN,cAA8B,YAAA,CAAa;AAAA,EACvC,OAAA;AAAA,EACT,WAAA,CAAY,SAAiB,OAAA,EAAmB;AAC9C,IAAA,KAAA,CAAM,qBAAqB,OAAO,CAAA;AAClC,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF,CAAA;AA4BO,IAAM,aAAA,GAAN,MAAM,cAAA,SAAsB,YAAA,CAAa;AAAA,EACrC,UAAA;AAAA,EACA,YAAA;AAAA,EACT,WAAA,CACE,UAAA,EACA,OAAA,EACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,CAAA,SAAA,EAAY,UAAU,CAAA,CAAA,EAAI,OAAA,EAAS,OAAO,CAAA;AAChD,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAClB,IAAA,IAAA,CAAK,eAAe,OAA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K,MAAM,OAAA,EAAQ;AAAA,EAC5B;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAAI,KAAK,OAAA,EAAS;AAClB,IAAA,IAAA,CAAK,OAAA,GAAU,IAAA;AACf,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,OAAA,CAAQ,UAAA,IAAc,KAAK,EAAA,GAAK,GAAA;AACtD,IAAA,MAAM,OAAO,YAAY;AACvB,MAAA,IAAI,CAAC,KAAK,OAAA,EAAS;AACnB,MAAA,IAAI;AACF,QAAA,MAAM,KAAK,IAAA,EAAK;AAAA,MAClB,SAAS,GAAA,EAAK;AACZ,QAAA,IAAA,CAAK,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,OAAA,EAAS,8BAAA,EAAgC;AAAA,UAC5D,OAAO,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG;AAAA,SACvD,CAAA;AAAA,MACH,CAAA,SAAE;AACA,QAAA,IAAI,KAAK,OAAA,EAAS,IAAA,CAAK,KAAA,GAAQ,UAAA,CAAW,MAAM,QAAQ,CAAA;AAAA,MAC1D;AAAA,IACF,CAAA;AACA,IAAA,KAAK,IAAA,EAAK;AAAA,EACZ;AAAA,EAEA,IAAA,GAAa;AACX,IAAA,IAAA,CAAK,OAAA,GAAU,KAAA;AACf,IAAA,IAAI,IAAA,CAAK,KAAA,EAAO,YAAA,CAAa,IAAA,CAAK,KAAK,CAAA;AACvC,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAA;AAAA,EACf;AACF","file":"index.cjs","sourcesContent":["/**\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","/**\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","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","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 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","/**\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 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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/domain/provider-failure.ts","../../src/domain/webhook.ts","../../src/domain/lifecycle.ts","../../src/domain/errors.ts","../../src/application/ingest-webhook.ts","../../src/application/pipeline/retry-policy.ts","../../src/application/pipeline/domain-validation.ts","../../src/application/pipeline/sanitize.ts","../../src/application/dispatch-message.ts","../../src/workers/send-worker.ts","../../src/domain/retention.ts","../../src/application/purge-retention.ts","../../src/workers/retention-worker.ts"],"names":[],"mappings":";;;AAUO,SAAS,wBAAwB,GAAA,EAAqD;AAC3F,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,MAAM,OAAO,MAAA;AACpD,EAAA,MAAM,aAAc,GAAA,CAAiC,UAAA;AACrD,EAAA,MAAM,OAAQ,GAAA,CAA2B,IAAA;AACzC,EAAA,IAAI,UAAA,KAAe,WAAA,IAAe,IAAA,KAAS,oBAAA,EAAsB,OAAO,WAAA;AACxE,EAAA,IAAI,UAAA,KAAe,WAAA,IAAe,IAAA,KAAS,oBAAA,EAAsB,OAAO,WAAA;AACxE,EAAA,OAAO,MAAA;AACT;;;AC2BO,SAAS,eAAe,IAAA,EAA+C;AAC5E,EAAA,QAAQ,IAAA;AAAM,IACZ,KAAK,WAAA;AACH,MAAA,OAAO,WAAA;AAAA,IACT,KAAK,SAAA;AACH,MAAA,OAAO,SAAA;AAAA,IACT,KAAK,YAAA;AACH,MAAA,OAAO,YAAA;AAAA,IACT,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AAA,CAAK,QAAA,GAAW,IAAA;AAChB,IAAA,IAAI;AACF,MAAA,MAAM,KAAK,IAAA,EAAK;AAAA,IAClB,SAAS,GAAA,EAAK;AACZ,MAAA,IAAA,CAAK,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,OAAA,EAAS,8BAAA,EAAgC;AAAA,QAC5D,OAAO,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG;AAAA,OACvD,CAAA;AAAA,IACH,CAAA,SAAE;AACA,MAAA,IAAA,CAAK,QAAA,GAAW,KAAA;AAChB,MAAA,IAAI,KAAK,OAAA,EAAS;AAChB,QAAA,IAAA,CAAK,KAAA,GAAQ,WAAW,MAAM;AAC5B,UAAA,IAAA,CAAK,KAAA,GAAQ,IAAA;AACb,UAAA,KAAK,KAAK,WAAA,EAAY;AAAA,QACxB,CAAA,EAAG,IAAA,CAAK,UAAA,EAAY,CAAA;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\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","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","/**\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 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","/**\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","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","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 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","/**\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 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"]}
|
package/dist/workers/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { R as RetentionWorker, c as RetentionWorkerOptions, d as SendTickReport, S as SendWorker, e as SendWorkerOptions } from '../index-
|
|
2
|
-
import '../repositories-
|
|
3
|
-
import '../webhook-
|
|
4
|
-
import '../services-
|
|
5
|
-
import '../template-
|
|
1
|
+
export { R as RetentionWorker, c as RetentionWorkerOptions, d as SendTickReport, S as SendWorker, e as SendWorkerOptions } from '../index-B4F7euCt.cjs';
|
|
2
|
+
import '../repositories-sMN6RHZJ.cjs';
|
|
3
|
+
import '../webhook-B158Vi6p.cjs';
|
|
4
|
+
import '../services-DZwZjDn_.cjs';
|
|
5
|
+
import '../template-Dny_7Ymi.cjs';
|
package/dist/workers/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { R as RetentionWorker, c as RetentionWorkerOptions, d as SendTickReport, S as SendWorker, e as SendWorkerOptions } from '../index-
|
|
2
|
-
import '../repositories-
|
|
3
|
-
import '../webhook-
|
|
4
|
-
import '../services-
|
|
5
|
-
import '../template-
|
|
1
|
+
export { R as RetentionWorker, c as RetentionWorkerOptions, d as SendTickReport, S as SendWorker, e as SendWorkerOptions } from '../index-Cn1YsmGe.js';
|
|
2
|
+
import '../repositories-DJYu4nGV.js';
|
|
3
|
+
import '../webhook-B158Vi6p.js';
|
|
4
|
+
import '../services-PoM2bxjP.js';
|
|
5
|
+
import '../template-Dl1_ciRo.js';
|