@tgoliveira/outpost 1.1.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.
Files changed (54) hide show
  1. package/AGENTS.md +268 -0
  2. package/LICENSE +21 -0
  3. package/README.md +117 -0
  4. package/dist/adapters/drizzle/index.cjs +405 -0
  5. package/dist/adapters/drizzle/index.cjs.map +1 -0
  6. package/dist/adapters/drizzle/index.d.cts +1765 -0
  7. package/dist/adapters/drizzle/index.d.ts +1765 -0
  8. package/dist/adapters/drizzle/index.js +387 -0
  9. package/dist/adapters/drizzle/index.js.map +1 -0
  10. package/dist/adapters/index.cjs +584 -0
  11. package/dist/adapters/index.cjs.map +1 -0
  12. package/dist/adapters/index.d.cts +232 -0
  13. package/dist/adapters/index.d.ts +232 -0
  14. package/dist/adapters/index.js +565 -0
  15. package/dist/adapters/index.js.map +1 -0
  16. package/dist/fake-BY6t7UXb.d.cts +30 -0
  17. package/dist/fake-en-oOdg0.d.ts +30 -0
  18. package/dist/http/index.cjs +224 -0
  19. package/dist/http/index.cjs.map +1 -0
  20. package/dist/http/index.d.cts +49 -0
  21. package/dist/http/index.d.ts +49 -0
  22. package/dist/http/index.js +221 -0
  23. package/dist/http/index.js.map +1 -0
  24. package/dist/index-CVUvaJms.d.ts +179 -0
  25. package/dist/index-Dmt-aLH2.d.cts +179 -0
  26. package/dist/index.cjs +1387 -0
  27. package/dist/index.cjs.map +1 -0
  28. package/dist/index.d.cts +153 -0
  29. package/dist/index.d.ts +153 -0
  30. package/dist/index.js +1331 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/outpost-client-yUijE00q.d.cts +271 -0
  33. package/dist/outpost-client-ymTJISpu.d.ts +271 -0
  34. package/dist/repositories-Bck6wJNS.d.ts +180 -0
  35. package/dist/repositories-DhUe8f2R.d.cts +180 -0
  36. package/dist/services-CQINhAGo.d.cts +90 -0
  37. package/dist/services-CfTEsetF.d.ts +90 -0
  38. package/dist/template-CREUq7bB.d.ts +260 -0
  39. package/dist/template-DxI_p2Ny.d.cts +260 -0
  40. package/dist/testing/index.cjs +321 -0
  41. package/dist/testing/index.cjs.map +1 -0
  42. package/dist/testing/index.d.cts +97 -0
  43. package/dist/testing/index.d.ts +97 -0
  44. package/dist/testing/index.js +312 -0
  45. package/dist/testing/index.js.map +1 -0
  46. package/dist/webhook-kp6CiXk-.d.cts +149 -0
  47. package/dist/webhook-kp6CiXk-.d.ts +149 -0
  48. package/dist/workers/index.cjs +430 -0
  49. package/dist/workers/index.cjs.map +1 -0
  50. package/dist/workers/index.d.cts +5 -0
  51. package/dist/workers/index.d.ts +5 -0
  52. package/dist/workers/index.js +427 -0
  53. package/dist/workers/index.js.map +1 -0
  54. package/package.json +114 -0
@@ -0,0 +1,430 @@
1
+ 'use strict';
2
+
3
+ // src/domain/errors.ts
4
+ var OutpostError = class extends Error {
5
+ code;
6
+ constructor(code, message, options) {
7
+ super(message, options);
8
+ this.name = new.target.name;
9
+ this.code = code;
10
+ }
11
+ };
12
+ var ValidationError = class extends OutpostError {
13
+ details;
14
+ constructor(message, details) {
15
+ super("validation_failed", message);
16
+ this.details = details;
17
+ }
18
+ };
19
+ var ProviderError = class _ProviderError extends OutpostError {
20
+ errorClass;
21
+ providerCode;
22
+ constructor(errorClass, message, options) {
23
+ super(`provider_${errorClass}`, message, options);
24
+ this.errorClass = errorClass;
25
+ this.providerCode = options?.providerCode;
26
+ }
27
+ static transient(message, options) {
28
+ return new _ProviderError("transient", message, options);
29
+ }
30
+ static permanent(message, options) {
31
+ return new _ProviderError("permanent", message, options);
32
+ }
33
+ };
34
+ function isExhausted(attempts, config) {
35
+ return attempts >= config.maxAttempts;
36
+ }
37
+ function backoffMs(attempts, config, jitter) {
38
+ const exp = Math.min(config.maxDelayMs, config.baseDelayMs * 2 ** Math.max(0, attempts - 1));
39
+ return Math.floor(exp * jitter);
40
+ }
41
+ var 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])?)+)$/;
42
+ function extractDomain(address) {
43
+ const at = address.lastIndexOf("@");
44
+ if (at < 0) throw new ValidationError("Address has no domain part");
45
+ return address.slice(at + 1).toLowerCase();
46
+ }
47
+ function validateSyntax(address) {
48
+ const m = ADDR_RE.exec(address);
49
+ if (!m) throw new ValidationError(`Recipient "${address}" is not a valid email address`);
50
+ return m[1].toLowerCase();
51
+ }
52
+ var MxCache = class {
53
+ constructor(ttlMs) {
54
+ this.ttlMs = ttlMs;
55
+ }
56
+ entries = /* @__PURE__ */ new Map();
57
+ get(domain, nowMs) {
58
+ const e = this.entries.get(domain);
59
+ if (!e) return void 0;
60
+ if (e.expiresAt <= nowMs) {
61
+ this.entries.delete(domain);
62
+ return void 0;
63
+ }
64
+ return e.hosts;
65
+ }
66
+ set(domain, hosts, nowMs) {
67
+ this.entries.set(domain, { hosts, expiresAt: nowMs + this.ttlMs });
68
+ }
69
+ };
70
+ async function validateRecipient(address, config, deps) {
71
+ if (config.syntax) {
72
+ const domain = validateSyntax(address);
73
+ if (config.mx && deps.mxResolver) {
74
+ const cached = deps.mxCache?.get(domain, deps.nowMs);
75
+ let hosts = cached;
76
+ if (hosts === void 0) {
77
+ try {
78
+ hosts = await deps.mxResolver.resolveMx(domain);
79
+ } catch {
80
+ hosts = [];
81
+ }
82
+ deps.mxCache?.set(domain, hosts, deps.nowMs);
83
+ }
84
+ if (hosts.length === 0) {
85
+ throw new ValidationError(`Recipient domain "${domain}" has no MX records`);
86
+ }
87
+ }
88
+ }
89
+ }
90
+
91
+ // src/application/pipeline/sanitize.ts
92
+ var DEFAULT_SANITIZE_LIMITS = {
93
+ maxSubjectBytes: 2e3,
94
+ maxBodyBytes: 5e6,
95
+ // 5 MB
96
+ maxRecipientBytes: 320,
97
+ // RFC 5321 max
98
+ maxHeaderValueBytes: 4e3
99
+ };
100
+ var byteLen = (s) => Buffer.byteLength(s, "utf8");
101
+ function assertNoHeaderInjection(field, value) {
102
+ for (let i = 0; i < value.length; i++) {
103
+ const code = value.charCodeAt(i);
104
+ if (code < 32 || code === 127) {
105
+ throw new ValidationError(`Illegal control character in "${field}" (header injection attempt)`);
106
+ }
107
+ }
108
+ }
109
+ function sanitizeSubject(subject, limits = DEFAULT_SANITIZE_LIMITS) {
110
+ assertNoHeaderInjection("subject", subject);
111
+ const trimmed = subject.trim();
112
+ if (byteLen(trimmed) > limits.maxSubjectBytes) {
113
+ throw new ValidationError(`Subject exceeds ${limits.maxSubjectBytes} bytes`);
114
+ }
115
+ return trimmed;
116
+ }
117
+ function sanitizeRecipient(to, limits = DEFAULT_SANITIZE_LIMITS) {
118
+ assertNoHeaderInjection("to", to);
119
+ const trimmed = to.trim();
120
+ if (byteLen(trimmed) > limits.maxRecipientBytes) {
121
+ throw new ValidationError(`Recipient exceeds ${limits.maxRecipientBytes} bytes`);
122
+ }
123
+ return trimmed;
124
+ }
125
+ function assertBodyWithinLimits(body, limits = DEFAULT_SANITIZE_LIMITS) {
126
+ const total = byteLen(body.html ?? "") + byteLen(body.text ?? "");
127
+ if (total === 0) {
128
+ throw new ValidationError("Message body is empty (provide html and/or text)");
129
+ }
130
+ if (total > limits.maxBodyBytes) {
131
+ throw new ValidationError(`Body exceeds ${limits.maxBodyBytes} bytes`);
132
+ }
133
+ }
134
+
135
+ // src/application/dispatch-message.ts
136
+ var DispatchMessage = class {
137
+ constructor(deps) {
138
+ this.deps = deps;
139
+ this.mxCache = new MxCache(deps.config.domainValidation.mxCacheTtlMs ?? 36e5);
140
+ }
141
+ mxCache;
142
+ async execute(message) {
143
+ const { deps } = this;
144
+ return deps.telemetry.span(
145
+ "outpost.dispatch",
146
+ { messageId: message.id, provider: message.provider },
147
+ async () => {
148
+ const fresh = await deps.outbox.findById(message.id);
149
+ if (!fresh || fresh.state !== "sending") {
150
+ return { kind: "skipped", reason: "no longer in sending state" };
151
+ }
152
+ const provider = deps.providers.get(fresh.provider);
153
+ if (!provider) {
154
+ return this.fail(fresh, `No provider registered for "${fresh.provider}"`);
155
+ }
156
+ try {
157
+ const to = await deps.openEncryptor.open(fresh.recipientSealed);
158
+ const bodyJson = await deps.openEncryptor.open(fresh.bodySealed);
159
+ const body = JSON.parse(bodyJson);
160
+ const cleanTo = sanitizeRecipient(to, deps.config.sanitize);
161
+ const cleanSubject = sanitizeSubject(fresh.subject, deps.config.sanitize);
162
+ assertBodyWithinLimits(body, deps.config.sanitize);
163
+ await validateRecipient(cleanTo, deps.config.domainValidation, {
164
+ mxResolver: deps.mxResolver,
165
+ mxCache: this.mxCache,
166
+ nowMs: deps.clock.now().getTime()
167
+ });
168
+ const limited = await this.checkRateLimits(fresh.provider, cleanTo);
169
+ if (limited) {
170
+ return this.requeueRateLimited(fresh);
171
+ }
172
+ const dispatchable = {
173
+ id: fresh.id,
174
+ to: cleanTo,
175
+ subject: cleanSubject,
176
+ body,
177
+ headers: this.buildHeaders(),
178
+ metadata: fresh.metadata
179
+ };
180
+ const receipt = await provider.send(dispatchable);
181
+ await deps.outbox.updateState(fresh.id, {
182
+ state: "sent",
183
+ providerMessageId: receipt.providerMessageId,
184
+ lastError: null
185
+ });
186
+ await deps.audit.append({
187
+ messageId: fresh.id,
188
+ eventType: "dispatch_accepted",
189
+ actor: `provider:${fresh.provider}`,
190
+ detail: { providerMessageId: receipt.providerMessageId }
191
+ });
192
+ deps.telemetry.counter("outpost.dispatch.sent", 1, { provider: fresh.provider });
193
+ return { kind: "sent", providerMessageId: receipt.providerMessageId };
194
+ } catch (err) {
195
+ return this.handleError(fresh, err);
196
+ }
197
+ }
198
+ );
199
+ }
200
+ /** Classify the error and either retry-with-backoff or dead-letter. */
201
+ async handleError(message, err) {
202
+ const permanent = err instanceof ProviderError && err.errorClass === "permanent";
203
+ const reason = err instanceof Error ? err.message : String(err);
204
+ if (permanent) {
205
+ return this.fail(message, reason);
206
+ }
207
+ const attempts = message.attempts + 1;
208
+ if (isExhausted(attempts, this.deps.config.retry)) {
209
+ return this.fail(message, `Retries exhausted (${attempts}): ${reason}`, attempts);
210
+ }
211
+ const delay = backoffMs(attempts, this.deps.config.retry, this.deps.random());
212
+ const nextAttemptAt = new Date(this.deps.clock.now().getTime() + delay);
213
+ await this.deps.outbox.updateState(message.id, {
214
+ state: "queued",
215
+ attempts,
216
+ nextAttemptAt,
217
+ lastError: reason
218
+ });
219
+ await this.deps.audit.append({
220
+ messageId: message.id,
221
+ eventType: "retry_scheduled",
222
+ actor: `provider:${message.provider}`,
223
+ detail: { attempts, nextAttemptAt: nextAttemptAt.toISOString(), reason }
224
+ });
225
+ this.deps.telemetry.counter("outpost.dispatch.retry", 1, { provider: message.provider });
226
+ return { kind: "retry", nextAttemptAt };
227
+ }
228
+ /** Move to `failed` (terminal) and record in the Dead Letter Queue. */
229
+ async fail(message, reason, attempts) {
230
+ await this.deps.outbox.updateState(message.id, {
231
+ state: "failed",
232
+ attempts: attempts ?? message.attempts,
233
+ lastError: reason
234
+ });
235
+ await this.deps.audit.append({
236
+ messageId: message.id,
237
+ eventType: "dead_lettered",
238
+ actor: `provider:${message.provider}`,
239
+ detail: { reason }
240
+ });
241
+ this.deps.telemetry.counter("outpost.dispatch.failed", 1, { provider: message.provider });
242
+ return { kind: "failed", reason };
243
+ }
244
+ /** Re-queue without counting a failed attempt; short, jittered backoff. */
245
+ async requeueRateLimited(message) {
246
+ const delay = 1e3 + Math.floor(this.deps.random() * 4e3);
247
+ const nextAttemptAt = new Date(this.deps.clock.now().getTime() + delay);
248
+ await this.deps.outbox.updateState(message.id, {
249
+ state: "queued",
250
+ nextAttemptAt
251
+ });
252
+ this.deps.telemetry.counter("outpost.dispatch.rate_limited", 1, { provider: message.provider });
253
+ return { kind: "rate_limited", nextAttemptAt };
254
+ }
255
+ async checkRateLimits(provider, to) {
256
+ const checks = [
257
+ this.deps.rateLimiter.acquire({ kind: "global" }),
258
+ this.deps.rateLimiter.acquire({ kind: "provider", key: provider }),
259
+ this.deps.rateLimiter.acquire({ kind: "recipientDomain", key: extractDomain(to) })
260
+ ];
261
+ const results = await Promise.all(checks);
262
+ return results.some((ok) => ok === false);
263
+ }
264
+ /** List-Unsubscribe and other always-on headers (TDR §3.11). */
265
+ buildHeaders() {
266
+ return {};
267
+ }
268
+ };
269
+
270
+ // src/workers/send-worker.ts
271
+ var SendWorker = class {
272
+ constructor(deps, options = {}) {
273
+ this.deps = deps;
274
+ this.options = options;
275
+ this.dispatch = new DispatchMessage(deps);
276
+ }
277
+ dispatch;
278
+ running = false;
279
+ timer = null;
280
+ /** Process one batch. Returns what happened (for logging/metrics/tests). */
281
+ async tick() {
282
+ const now = this.deps.clock.now();
283
+ const batchSize = this.options.batchSize ?? this.deps.config.sendBatchSize;
284
+ const reclaimBefore = new Date(now.getTime() - this.deps.config.staleSendingLeaseMs);
285
+ const claimed = await this.deps.outbox.claimBatchForSending(batchSize, now, reclaimBefore);
286
+ this.deps.telemetry.gauge("outpost.send.claimed", claimed.length);
287
+ if (claimed.length === 0) return { claimed: 0, outcomes: [] };
288
+ const concurrency = this.options.concurrency ?? 10;
289
+ const outcomes = await runWithConcurrency(
290
+ claimed,
291
+ concurrency,
292
+ (m) => this.dispatch.execute(m).catch((err) => {
293
+ this.deps.logger.log("error", "dispatch threw unexpectedly", {
294
+ messageId: m.id,
295
+ error: err instanceof Error ? err.message : String(err)
296
+ });
297
+ return { kind: "failed", reason: "unexpected error" };
298
+ })
299
+ );
300
+ return { claimed: claimed.length, outcomes };
301
+ }
302
+ /** Start the long-running poll loop. Idempotent. */
303
+ start() {
304
+ if (this.running) return;
305
+ this.running = true;
306
+ const interval = this.options.intervalMs ?? 1e3;
307
+ const loop = async () => {
308
+ if (!this.running) return;
309
+ try {
310
+ await this.tick();
311
+ } catch (err) {
312
+ this.deps.logger.log("error", "send worker tick failed", {
313
+ error: err instanceof Error ? err.message : String(err)
314
+ });
315
+ } finally {
316
+ if (this.running) this.timer = setTimeout(loop, interval);
317
+ }
318
+ };
319
+ void loop();
320
+ }
321
+ /** Stop the loop. In-flight dispatches complete; no new tick starts. */
322
+ stop() {
323
+ this.running = false;
324
+ if (this.timer) clearTimeout(this.timer);
325
+ this.timer = null;
326
+ }
327
+ };
328
+ async function runWithConcurrency(items, limit, fn) {
329
+ const results = new Array(items.length);
330
+ let cursor = 0;
331
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
332
+ for (; ; ) {
333
+ const i = cursor++;
334
+ if (i >= items.length) return;
335
+ results[i] = await fn(items[i]);
336
+ }
337
+ });
338
+ await Promise.all(workers);
339
+ return results;
340
+ }
341
+
342
+ // src/domain/retention.ts
343
+ function purgeCutoff(policy, now) {
344
+ const ttlCutoff = now.getTime() - policy.operationalTtlDays * 24 * 60 * 60 * 1e3;
345
+ const windowCutoff = now.getTime() - policy.webhookWindowHours * 60 * 60 * 1e3;
346
+ return new Date(Math.min(ttlCutoff, windowCutoff));
347
+ }
348
+
349
+ // src/application/purge-retention.ts
350
+ var PurgeRetention = class {
351
+ constructor(deps) {
352
+ this.deps = deps;
353
+ }
354
+ async execute() {
355
+ const { deps } = this;
356
+ return deps.telemetry.span("outpost.retention.purge", {}, async () => {
357
+ const now = deps.clock.now();
358
+ const policy = deps.config.retention;
359
+ const cutoff = purgeCutoff(policy, now);
360
+ let operationalProcessed = 0;
361
+ for (; ; ) {
362
+ const batch = await deps.outbox.claimTerminalForPurge(cutoff, policy.batchSize);
363
+ if (batch.length === 0) break;
364
+ const ids = batch.map((m) => m.id);
365
+ const count = policy.redactOnPurge ? await deps.outbox.redactBatch(ids) : await deps.outbox.deleteBatch(ids);
366
+ operationalProcessed += count;
367
+ await deps.audit.append({
368
+ messageId: null,
369
+ eventType: policy.redactOnPurge ? "redacted" : "purged",
370
+ actor: "system:retention",
371
+ detail: { count, cutoff: cutoff.toISOString() }
372
+ });
373
+ if (batch.length < policy.batchSize) break;
374
+ }
375
+ const auditCutoff = new Date(now.getTime() - policy.auditTtlDays * 24 * 60 * 60 * 1e3);
376
+ const auditDeleted = await deps.audit.purgeOlderThan(auditCutoff, policy.batchSize);
377
+ deps.telemetry.gauge("outpost.retention.operational_processed", operationalProcessed);
378
+ deps.telemetry.gauge("outpost.retention.audit_deleted", auditDeleted);
379
+ deps.logger.log("info", "retention cycle complete", {
380
+ operationalProcessed,
381
+ auditDeleted,
382
+ redacted: policy.redactOnPurge
383
+ });
384
+ return { operationalProcessed, auditDeleted, redacted: policy.redactOnPurge };
385
+ });
386
+ }
387
+ };
388
+
389
+ // src/workers/retention-worker.ts
390
+ var RetentionWorker = class {
391
+ constructor(deps, options = {}) {
392
+ this.deps = deps;
393
+ this.options = options;
394
+ this.purge = new PurgeRetention(deps);
395
+ }
396
+ purge;
397
+ running = false;
398
+ timer = null;
399
+ async tick() {
400
+ return this.purge.execute();
401
+ }
402
+ start() {
403
+ if (this.running) return;
404
+ this.running = true;
405
+ const interval = this.options.intervalMs ?? 60 * 60 * 1e3;
406
+ const loop = async () => {
407
+ if (!this.running) return;
408
+ try {
409
+ await this.tick();
410
+ } catch (err) {
411
+ this.deps.logger.log("error", "retention worker tick failed", {
412
+ error: err instanceof Error ? err.message : String(err)
413
+ });
414
+ } finally {
415
+ if (this.running) this.timer = setTimeout(loop, interval);
416
+ }
417
+ };
418
+ void loop();
419
+ }
420
+ stop() {
421
+ this.running = false;
422
+ if (this.timer) clearTimeout(this.timer);
423
+ this.timer = null;
424
+ }
425
+ };
426
+
427
+ exports.RetentionWorker = RetentionWorker;
428
+ exports.SendWorker = SendWorker;
429
+ //# sourceMappingURL=index.cjs.map
430
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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,cAA2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AAA,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"]}
@@ -0,0 +1,5 @@
1
+ export { R as RetentionWorker, c as RetentionWorkerOptions, d as SendTickReport, S as SendWorker, e as SendWorkerOptions } from '../index-Dmt-aLH2.cjs';
2
+ import '../repositories-DhUe8f2R.cjs';
3
+ import '../webhook-kp6CiXk-.cjs';
4
+ import '../services-CQINhAGo.cjs';
5
+ import '../template-DxI_p2Ny.cjs';
@@ -0,0 +1,5 @@
1
+ export { R as RetentionWorker, c as RetentionWorkerOptions, d as SendTickReport, S as SendWorker, e as SendWorkerOptions } from '../index-CVUvaJms.js';
2
+ import '../repositories-Bck6wJNS.js';
3
+ import '../webhook-kp6CiXk-.js';
4
+ import '../services-CfTEsetF.js';
5
+ import '../template-CREUq7bB.js';