@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
package/dist/index.cjs ADDED
@@ -0,0 +1,1387 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+ var promises = require('dns/promises');
5
+
6
+ // src/application/pipeline/retry-policy.ts
7
+ var DEFAULT_RETRY = {
8
+ maxAttempts: 5,
9
+ baseDelayMs: 3e4,
10
+ // 30s
11
+ maxDelayMs: 60 * 60 * 1e3
12
+ // 1h
13
+ };
14
+ function isExhausted(attempts, config) {
15
+ return attempts >= config.maxAttempts;
16
+ }
17
+ function backoffMs(attempts, config, jitter) {
18
+ const exp = Math.min(config.maxDelayMs, config.baseDelayMs * 2 ** Math.max(0, attempts - 1));
19
+ return Math.floor(exp * jitter);
20
+ }
21
+ function nextAttemptAt(attempts, config, jitter, now) {
22
+ return new Date(now.getTime() + backoffMs(attempts, config, jitter));
23
+ }
24
+
25
+ // src/domain/errors.ts
26
+ var OutpostError = class extends Error {
27
+ code;
28
+ constructor(code, message, options) {
29
+ super(message, options);
30
+ this.name = new.target.name;
31
+ this.code = code;
32
+ }
33
+ };
34
+ var UnauthorizedError = class extends OutpostError {
35
+ constructor(message = "Missing, expired, or revoked API key") {
36
+ super("unauthorized", message);
37
+ }
38
+ };
39
+ var ForbiddenError = class extends OutpostError {
40
+ constructor(message = "API key lacks the required scope") {
41
+ super("forbidden", message);
42
+ }
43
+ };
44
+ var ValidationError = class extends OutpostError {
45
+ details;
46
+ constructor(message, details) {
47
+ super("validation_failed", message);
48
+ this.details = details;
49
+ }
50
+ };
51
+ var NotFoundError = class extends OutpostError {
52
+ constructor(message = "Resource not found") {
53
+ super("not_found", message);
54
+ }
55
+ };
56
+ var InvalidStateTransitionError = class extends OutpostError {
57
+ constructor(from, to) {
58
+ super("invalid_transition", `Cannot transition message from "${from}" to "${to}"`);
59
+ }
60
+ };
61
+ var WebhookVerificationError = class extends OutpostError {
62
+ constructor(message = "Webhook signature verification failed") {
63
+ super("webhook_unverified", message);
64
+ }
65
+ };
66
+ var ProviderError = class _ProviderError extends OutpostError {
67
+ errorClass;
68
+ providerCode;
69
+ constructor(errorClass, message, options) {
70
+ super(`provider_${errorClass}`, message, options);
71
+ this.errorClass = errorClass;
72
+ this.providerCode = options?.providerCode;
73
+ }
74
+ static transient(message, options) {
75
+ return new _ProviderError("transient", message, options);
76
+ }
77
+ static permanent(message, options) {
78
+ return new _ProviderError("permanent", message, options);
79
+ }
80
+ };
81
+ function isTransient(err) {
82
+ return err instanceof ProviderError && err.errorClass === "transient";
83
+ }
84
+
85
+ // src/application/pipeline/sanitize.ts
86
+ var DEFAULT_SANITIZE_LIMITS = {
87
+ maxSubjectBytes: 2e3,
88
+ maxBodyBytes: 5e6,
89
+ // 5 MB
90
+ maxRecipientBytes: 320,
91
+ // RFC 5321 max
92
+ maxHeaderValueBytes: 4e3
93
+ };
94
+ var byteLen = (s) => Buffer.byteLength(s, "utf8");
95
+ function assertNoHeaderInjection(field, value) {
96
+ for (let i = 0; i < value.length; i++) {
97
+ const code = value.charCodeAt(i);
98
+ if (code < 32 || code === 127) {
99
+ throw new ValidationError(`Illegal control character in "${field}" (header injection attempt)`);
100
+ }
101
+ }
102
+ }
103
+ function sanitizeSubject(subject, limits = DEFAULT_SANITIZE_LIMITS) {
104
+ assertNoHeaderInjection("subject", subject);
105
+ const trimmed = subject.trim();
106
+ if (byteLen(trimmed) > limits.maxSubjectBytes) {
107
+ throw new ValidationError(`Subject exceeds ${limits.maxSubjectBytes} bytes`);
108
+ }
109
+ return trimmed;
110
+ }
111
+ function sanitizeRecipient(to, limits = DEFAULT_SANITIZE_LIMITS) {
112
+ assertNoHeaderInjection("to", to);
113
+ const trimmed = to.trim();
114
+ if (byteLen(trimmed) > limits.maxRecipientBytes) {
115
+ throw new ValidationError(`Recipient exceeds ${limits.maxRecipientBytes} bytes`);
116
+ }
117
+ return trimmed;
118
+ }
119
+ function sanitizeHeaders(headers, limits = DEFAULT_SANITIZE_LIMITS) {
120
+ for (const [k, v] of Object.entries(headers)) {
121
+ assertNoHeaderInjection(`header:${k}`, k);
122
+ assertNoHeaderInjection(`header:${k}`, v);
123
+ if (byteLen(v) > limits.maxHeaderValueBytes) {
124
+ throw new ValidationError(`Header "${k}" exceeds ${limits.maxHeaderValueBytes} bytes`);
125
+ }
126
+ }
127
+ return headers;
128
+ }
129
+ function assertBodyWithinLimits(body, limits = DEFAULT_SANITIZE_LIMITS) {
130
+ const total = byteLen(body.html ?? "") + byteLen(body.text ?? "");
131
+ if (total === 0) {
132
+ throw new ValidationError("Message body is empty (provide html and/or text)");
133
+ }
134
+ if (total > limits.maxBodyBytes) {
135
+ throw new ValidationError(`Body exceeds ${limits.maxBodyBytes} bytes`);
136
+ }
137
+ }
138
+ function stripDangerousHtml(html) {
139
+ return html.replace(/<\s*(script|style|iframe|object|embed)[\s\S]*?<\s*\/\s*\1\s*>/gi, "").replace(/<\s*(script|style|iframe|object|embed)\b[^>]*\/?\s*>/gi, "").replace(/\son\w+\s*=\s*"[^"]*"/gi, "").replace(/\son\w+\s*=\s*'[^']*'/gi, "").replace(/\son\w+\s*=\s*[^\s>]+/gi, "").replace(/(href|src)\s*=\s*("|')\s*javascript:[^"']*\2/gi, "$1=$2#$2");
140
+ }
141
+ var DEFAULT_ATTACHMENT_POLICY = {
142
+ allowedMimeTypes: [
143
+ "application/pdf",
144
+ "image/png",
145
+ "image/jpeg",
146
+ "image/gif",
147
+ "text/plain",
148
+ "text/csv"
149
+ ],
150
+ maxSizeBytes: 1e7
151
+ // 10 MB
152
+ };
153
+ function validateAttachment(att, policy = DEFAULT_ATTACHMENT_POLICY) {
154
+ assertNoHeaderInjection("attachment.filename", att.filename);
155
+ if (!policy.allowedMimeTypes.includes(att.contentType)) {
156
+ throw new ValidationError(`Attachment MIME type "${att.contentType}" is not allowed`);
157
+ }
158
+ if (att.sizeBytes > policy.maxSizeBytes) {
159
+ throw new ValidationError(`Attachment "${att.filename}" exceeds ${policy.maxSizeBytes} bytes`);
160
+ }
161
+ }
162
+
163
+ // src/application/pipeline/domain-validation.ts
164
+ var DEFAULT_DOMAIN_VALIDATION = {
165
+ syntax: true,
166
+ mx: false,
167
+ mailboxProbe: false,
168
+ mxCacheTtlMs: 60 * 60 * 1e3
169
+ };
170
+ 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])?)+)$/;
171
+ function extractDomain(address) {
172
+ const at = address.lastIndexOf("@");
173
+ if (at < 0) throw new ValidationError("Address has no domain part");
174
+ return address.slice(at + 1).toLowerCase();
175
+ }
176
+ function validateSyntax(address) {
177
+ const m = ADDR_RE.exec(address);
178
+ if (!m) throw new ValidationError(`Recipient "${address}" is not a valid email address`);
179
+ return m[1].toLowerCase();
180
+ }
181
+ var MxCache = class {
182
+ constructor(ttlMs) {
183
+ this.ttlMs = ttlMs;
184
+ }
185
+ entries = /* @__PURE__ */ new Map();
186
+ get(domain, nowMs) {
187
+ const e = this.entries.get(domain);
188
+ if (!e) return void 0;
189
+ if (e.expiresAt <= nowMs) {
190
+ this.entries.delete(domain);
191
+ return void 0;
192
+ }
193
+ return e.hosts;
194
+ }
195
+ set(domain, hosts, nowMs) {
196
+ this.entries.set(domain, { hosts, expiresAt: nowMs + this.ttlMs });
197
+ }
198
+ };
199
+ async function validateRecipient(address, config, deps) {
200
+ if (config.syntax) {
201
+ const domain = validateSyntax(address);
202
+ if (config.mx && deps.mxResolver) {
203
+ const cached = deps.mxCache?.get(domain, deps.nowMs);
204
+ let hosts = cached;
205
+ if (hosts === void 0) {
206
+ try {
207
+ hosts = await deps.mxResolver.resolveMx(domain);
208
+ } catch {
209
+ hosts = [];
210
+ }
211
+ deps.mxCache?.set(domain, hosts, deps.nowMs);
212
+ }
213
+ if (hosts.length === 0) {
214
+ throw new ValidationError(`Recipient domain "${domain}" has no MX records`);
215
+ }
216
+ }
217
+ }
218
+ }
219
+
220
+ // src/domain/retention.ts
221
+ var DEFAULT_RETENTION = {
222
+ operationalTtlDays: 30,
223
+ auditTtlDays: 365,
224
+ redactOnPurge: true,
225
+ webhookWindowHours: 72,
226
+ batchSize: 1e3
227
+ };
228
+ function purgeCutoff(policy, now) {
229
+ const ttlCutoff = now.getTime() - policy.operationalTtlDays * 24 * 60 * 60 * 1e3;
230
+ const windowCutoff = now.getTime() - policy.webhookWindowHours * 60 * 60 * 1e3;
231
+ return new Date(Math.min(ttlCutoff, windowCutoff));
232
+ }
233
+
234
+ // src/application/config.ts
235
+ function resolveConfig(overrides = {}) {
236
+ return {
237
+ retry: { ...DEFAULT_RETRY, ...overrides.retry },
238
+ retention: { ...DEFAULT_RETENTION, ...overrides.retention },
239
+ sanitize: { ...DEFAULT_SANITIZE_LIMITS, ...overrides.sanitize },
240
+ attachments: { ...DEFAULT_ATTACHMENT_POLICY, ...overrides.attachments },
241
+ domainValidation: {
242
+ ...DEFAULT_DOMAIN_VALIDATION,
243
+ ...overrides.domainValidation,
244
+ mailboxProbe: false
245
+ },
246
+ rateLimits: overrides.rateLimits ?? {},
247
+ sendBatchSize: overrides.sendBatchSize ?? 50,
248
+ staleSendingLeaseMs: overrides.staleSendingLeaseMs ?? 5 * 60 * 1e3
249
+ };
250
+ }
251
+
252
+ // src/application/enqueue-message.ts
253
+ var EnqueueMessage = class {
254
+ constructor(deps) {
255
+ this.deps = deps;
256
+ }
257
+ async execute(input, actor) {
258
+ const { deps } = this;
259
+ return deps.telemetry.span("outpost.enqueue", { idempotencyKey: input.idempotencyKey }, async () => {
260
+ if (!input.idempotencyKey || input.idempotencyKey.trim() === "") {
261
+ throw new ValidationError("idempotencyKey is required");
262
+ }
263
+ const to = sanitizeRecipient(input.to, deps.config.sanitize);
264
+ validateSyntax(to);
265
+ const { subject, body } = await this.resolveContent(input);
266
+ const cleanSubject = sanitizeSubject(subject, deps.config.sanitize);
267
+ const cleanBody = this.sanitizeBody(body);
268
+ assertBodyWithinLimits(cleanBody, deps.config.sanitize);
269
+ const recipientHmac = deps.recipientHasher.hash(to);
270
+ const provider = input.provider ?? deps.defaultProvider;
271
+ const existing = await deps.outbox.findByIdempotencyKey(input.idempotencyKey);
272
+ if (existing) {
273
+ deps.telemetry.counter("outpost.enqueue.deduplicated", 1);
274
+ return {
275
+ id: existing.id,
276
+ state: existing.state,
277
+ idempotencyKey: existing.idempotencyKey,
278
+ deduplicated: true
279
+ };
280
+ }
281
+ const suppressed = await deps.suppressions.isSuppressed(recipientHmac);
282
+ const [recipientSealed, bodySealed] = await Promise.all([
283
+ deps.sealEncryptor.seal(to),
284
+ deps.sealEncryptor.seal(JSON.stringify(cleanBody))
285
+ ]);
286
+ const now = deps.clock.now();
287
+ const message = await deps.outbox.insert({
288
+ idempotencyKey: input.idempotencyKey,
289
+ recipientHmac,
290
+ recipientSealed,
291
+ bodySealed,
292
+ subject: cleanSubject,
293
+ templateId: input.template?.id ?? null,
294
+ templateVersion: input.template?.version ?? null,
295
+ provider,
296
+ metadata: input.metadata ?? {},
297
+ state: suppressed ? "suppressed" : "queued",
298
+ scheduledFor: input.scheduledFor ?? null,
299
+ nextAttemptAt: input.scheduledFor ?? now
300
+ });
301
+ await deps.audit.append({
302
+ messageId: message.id,
303
+ eventType: suppressed ? "suppressed" : "enqueued",
304
+ actor,
305
+ detail: suppressed ? { reason: "recipient_on_suppression_list" } : { provider }
306
+ });
307
+ deps.telemetry.counter(suppressed ? "outpost.enqueue.suppressed" : "outpost.enqueue.queued", 1);
308
+ return {
309
+ id: message.id,
310
+ state: message.state,
311
+ idempotencyKey: message.idempotencyKey,
312
+ deduplicated: false
313
+ };
314
+ });
315
+ }
316
+ /** Resolve template or raw content into subject + body. */
317
+ async resolveContent(input) {
318
+ if (input.template) {
319
+ if (!this.deps.templates) {
320
+ throw new ValidationError("A template was supplied but no TemplateRenderer is configured");
321
+ }
322
+ const rendered = await this.deps.templates.render(input.template);
323
+ return { subject: input.subject ?? rendered.subject, body: rendered.body };
324
+ }
325
+ if (input.subject === void 0) {
326
+ throw new ValidationError("Either `template` or `subject` must be provided");
327
+ }
328
+ return { subject: input.subject, body: { html: input.html, text: input.text } };
329
+ }
330
+ /** Apply the configured strong sanitizer (or built-in fallback) to HTML. */
331
+ sanitizeBody(body) {
332
+ if (body.html === void 0) return body;
333
+ const clean = this.deps.sanitizeHtml ? this.deps.sanitizeHtml(body.html) : stripDangerousHtml(body.html);
334
+ return { ...body, html: clean };
335
+ }
336
+ };
337
+
338
+ // src/domain/webhook.ts
339
+ function webhookToState(type) {
340
+ switch (type) {
341
+ case "delivered":
342
+ return "delivered";
343
+ case "bounced":
344
+ return "bounced";
345
+ case "complained":
346
+ return "complained";
347
+ case "failed":
348
+ return "failed";
349
+ case "opened":
350
+ return null;
351
+ }
352
+ }
353
+
354
+ // src/domain/lifecycle.ts
355
+ var LIFECYCLE_STATES = [
356
+ "queued",
357
+ "sending",
358
+ "sent",
359
+ "delivered",
360
+ "bounced",
361
+ "complained",
362
+ "failed",
363
+ "suppressed"
364
+ ];
365
+ var TERMINAL_STATES = [
366
+ "delivered",
367
+ "bounced",
368
+ "complained",
369
+ "failed",
370
+ "suppressed"
371
+ ];
372
+ var TERMINAL_SET = new Set(TERMINAL_STATES);
373
+ function isTerminal(state) {
374
+ return TERMINAL_SET.has(state);
375
+ }
376
+ var ALLOWED_TRANSITIONS = {
377
+ queued: ["sending", "suppressed", "failed"],
378
+ // `sending` can fall back to `queued` on a transient error (retry).
379
+ sending: ["sent", "queued", "failed", "suppressed"],
380
+ sent: ["delivered", "bounced", "complained", "failed"],
381
+ delivered: [],
382
+ bounced: [],
383
+ complained: [],
384
+ failed: ["queued"],
385
+ // DLQ replay re-enqueues a failed message
386
+ suppressed: []
387
+ };
388
+ function canTransition(from, to) {
389
+ return ALLOWED_TRANSITIONS[from].includes(to);
390
+ }
391
+ function shouldSuppressOn(state) {
392
+ return state === "bounced" || state === "complained";
393
+ }
394
+
395
+ // src/application/ingest-webhook.ts
396
+ var IngestWebhook = class {
397
+ constructor(deps) {
398
+ this.deps = deps;
399
+ }
400
+ async execute(providerName, raw) {
401
+ const { deps } = this;
402
+ const provider = deps.providers.get(providerName);
403
+ if (!provider) {
404
+ throw new WebhookVerificationError(`Unknown provider "${providerName}"`);
405
+ }
406
+ return deps.telemetry.span("outpost.webhook.ingest", { provider: providerName }, async () => {
407
+ const event = await provider.verifyWebhook(raw);
408
+ await deps.webhookEvents.record(event);
409
+ deps.telemetry.counter("outpost.webhook.received", 1, {
410
+ provider: providerName,
411
+ type: event.type
412
+ });
413
+ const message = await deps.outbox.findByProviderMessageId(event.providerMessageId);
414
+ if (!message) {
415
+ return {
416
+ accepted: true,
417
+ eventType: event.type,
418
+ messageId: null,
419
+ note: "no matching message for providerMessageId"
420
+ };
421
+ }
422
+ const target = webhookToState(event.type);
423
+ if (target && canTransition(message.state, target)) {
424
+ await deps.outbox.updateState(message.id, { state: target });
425
+ }
426
+ if (target && shouldSuppressOn(target) && this.isSuppressable(event)) {
427
+ await deps.suppressions.add({
428
+ recipientHmac: message.recipientHmac,
429
+ reason: target === "bounced" ? "hard_bounce" : "complaint",
430
+ createdBy: `provider:${providerName}`,
431
+ note: `webhook ${event.type}`
432
+ });
433
+ }
434
+ await deps.audit.append({
435
+ messageId: message.id,
436
+ eventType: this.auditType(event.type),
437
+ actor: `provider:${providerName}`,
438
+ detail: { type: event.type, occurredAt: event.occurredAt?.toISOString() ?? null }
439
+ });
440
+ return { accepted: true, eventType: event.type, messageId: message.id };
441
+ });
442
+ }
443
+ /** A soft bounce must not suppress; only hard bounces and complaints do. */
444
+ isSuppressable(event) {
445
+ if (event.type === "complained") return true;
446
+ if (event.type === "bounced") return event.isHardBounce !== false;
447
+ return false;
448
+ }
449
+ auditType(type) {
450
+ switch (type) {
451
+ case "delivered":
452
+ return "webhook_delivered";
453
+ case "bounced":
454
+ return "webhook_bounced";
455
+ case "complained":
456
+ return "webhook_complained";
457
+ case "opened":
458
+ return "webhook_opened";
459
+ case "failed":
460
+ return "dispatch_failed";
461
+ }
462
+ }
463
+ };
464
+
465
+ // src/application/manage-suppression.ts
466
+ var ManageSuppression = class {
467
+ constructor(deps) {
468
+ this.deps = deps;
469
+ }
470
+ async isSuppressed(address) {
471
+ return this.deps.suppressions.isSuppressed(this.deps.recipientHasher.hash(address));
472
+ }
473
+ /** Lookup by precomputed HMAC (the form the HTTP API exposes). */
474
+ async getByHmac(recipientHmac) {
475
+ return this.deps.suppressions.get(recipientHmac);
476
+ }
477
+ async suppress(address, reason, actor, note) {
478
+ const recipientHmac = this.deps.recipientHasher.hash(address);
479
+ const entry = await this.deps.suppressions.add({ recipientHmac, reason, createdBy: actor, note });
480
+ await this.deps.audit.append({
481
+ messageId: null,
482
+ eventType: "suppressed",
483
+ actor,
484
+ detail: { recipientHmac, reason }
485
+ });
486
+ this.deps.telemetry.counter("outpost.suppression.added", 1, { reason });
487
+ return entry;
488
+ }
489
+ /** Remove by HMAC (what the DELETE endpoint receives). Audited. */
490
+ async unsuppressByHmac(recipientHmac, actor) {
491
+ const removed = await this.deps.suppressions.remove(recipientHmac);
492
+ if (removed) {
493
+ await this.deps.audit.append({
494
+ messageId: null,
495
+ eventType: "unsuppressed",
496
+ actor,
497
+ detail: { recipientHmac }
498
+ });
499
+ }
500
+ return removed;
501
+ }
502
+ async list(limit = 100, offset = 0) {
503
+ return this.deps.suppressions.list(limit, offset);
504
+ }
505
+ };
506
+ function hashApiKey(secret) {
507
+ return crypto.createHash("sha256").update(secret, "utf8").digest("hex");
508
+ }
509
+ function generateApiKeySecret() {
510
+ return `opk_${crypto.randomBytes(32).toString("base64url")}`;
511
+ }
512
+ var ManageApiKey = class {
513
+ constructor(deps) {
514
+ this.deps = deps;
515
+ }
516
+ async create(input) {
517
+ const secret = generateApiKeySecret();
518
+ const key = await this.deps.apiKeys.insert({
519
+ label: input.label,
520
+ keyHash: hashApiKey(secret),
521
+ scopes: input.scopes,
522
+ expiresAt: input.expiresAt ?? null
523
+ });
524
+ await this.deps.audit.append({
525
+ messageId: null,
526
+ eventType: "key_created",
527
+ actor: "admin",
528
+ detail: { keyId: key.id, label: key.label, scopes: key.scopes }
529
+ });
530
+ return {
531
+ id: key.id,
532
+ label: key.label,
533
+ scopes: key.scopes,
534
+ expiresAt: key.expiresAt,
535
+ secret
536
+ };
537
+ }
538
+ async revoke(id) {
539
+ const ok = await this.deps.apiKeys.revoke(id, this.deps.clock.now());
540
+ if (ok) {
541
+ await this.deps.audit.append({
542
+ messageId: null,
543
+ eventType: "key_revoked",
544
+ actor: "admin",
545
+ detail: { keyId: id }
546
+ });
547
+ }
548
+ return ok;
549
+ }
550
+ /** Lists keys WITHOUT secrets (only hashes are stored anyway). */
551
+ async list() {
552
+ return this.deps.apiKeys.list();
553
+ }
554
+ };
555
+
556
+ // src/domain/api-key.ts
557
+ var API_SCOPES = [
558
+ "messages:send",
559
+ "messages:read",
560
+ "messages:replay",
561
+ "suppressions:read",
562
+ "suppressions:write",
563
+ "keys:manage",
564
+ "admin"
565
+ // implies all of the above
566
+ ];
567
+ function isKeyActive(key, now) {
568
+ if (key.revokedAt !== null) return false;
569
+ if (key.expiresAt !== null && key.expiresAt.getTime() <= now.getTime()) return false;
570
+ return true;
571
+ }
572
+ function hasScope(scopes, required) {
573
+ return scopes.includes("admin") || scopes.includes(required);
574
+ }
575
+
576
+ // src/application/authenticate.ts
577
+ var Authenticate = class {
578
+ constructor(deps) {
579
+ this.deps = deps;
580
+ }
581
+ /** Resolve a bearer secret to an AuthContext or throw UnauthorizedError. */
582
+ async resolve(presentedSecret) {
583
+ if (!presentedSecret) throw new UnauthorizedError();
584
+ const keyHash = hashApiKey(presentedSecret);
585
+ const key = await this.deps.apiKeys.findByHash(keyHash);
586
+ if (!key) throw new UnauthorizedError();
587
+ if (!isKeyActive(key, this.deps.clock.now())) throw new UnauthorizedError();
588
+ void this.deps.apiKeys.touchLastUsed(key.id, this.deps.clock.now());
589
+ return { keyId: key.id, scopes: key.scopes };
590
+ }
591
+ /** Resolve then assert the context carries the required scope. */
592
+ async authorize(presentedSecret, required) {
593
+ const ctx = await this.resolve(presentedSecret);
594
+ if (!hasScope(ctx.scopes, required)) throw new ForbiddenError();
595
+ return ctx;
596
+ }
597
+ /** Assert a scope on an already-resolved context. */
598
+ static requireScope(ctx, required) {
599
+ if (!hasScope(ctx.scopes, required)) throw new ForbiddenError();
600
+ }
601
+ /** Helper to extract a bearer/x-outpost-key value from headers. */
602
+ static extractKey(headers) {
603
+ const auth = headerValue(headers, "authorization");
604
+ if (auth && /^bearer\s+/i.test(auth)) return auth.replace(/^bearer\s+/i, "").trim();
605
+ return headerValue(headers, "x-outpost-key");
606
+ }
607
+ // Exposed for tests / admin tooling.
608
+ async findKey(presentedSecret) {
609
+ return this.deps.apiKeys.findByHash(hashApiKey(presentedSecret));
610
+ }
611
+ };
612
+ function headerValue(headers, name) {
613
+ const raw = headers[name] ?? headers[name.toLowerCase()];
614
+ if (Array.isArray(raw)) return raw[0] ?? null;
615
+ return raw ?? null;
616
+ }
617
+
618
+ // src/application/message-queries.ts
619
+ function toView(m) {
620
+ return {
621
+ id: m.id,
622
+ idempotencyKey: m.idempotencyKey,
623
+ state: m.state,
624
+ recipientHmac: m.recipientHmac,
625
+ subject: m.subject,
626
+ provider: m.provider,
627
+ templateId: m.templateId,
628
+ templateVersion: m.templateVersion,
629
+ metadata: m.metadata,
630
+ attempts: m.attempts,
631
+ nextAttemptAt: m.nextAttemptAt.toISOString(),
632
+ providerMessageId: m.providerMessageId,
633
+ lastError: m.lastError,
634
+ createdAt: m.createdAt.toISOString(),
635
+ updatedAt: m.updatedAt.toISOString()
636
+ };
637
+ }
638
+ var GetMessage = class {
639
+ constructor(deps) {
640
+ this.deps = deps;
641
+ }
642
+ async execute(id) {
643
+ const m = await this.deps.outbox.findById(id);
644
+ if (!m) throw new NotFoundError(`Message "${id}" not found`);
645
+ return toView(m);
646
+ }
647
+ };
648
+ var ListMessages = class {
649
+ constructor(deps) {
650
+ this.deps = deps;
651
+ }
652
+ async execute(query) {
653
+ const messages = await this.deps.outbox.list({ limit: 50, offset: 0, ...query });
654
+ return messages.map(toView);
655
+ }
656
+ };
657
+ var ReplayMessage = class {
658
+ constructor(deps) {
659
+ this.deps = deps;
660
+ }
661
+ async execute(id, actor) {
662
+ const m = await this.deps.outbox.findById(id);
663
+ if (!m) throw new NotFoundError(`Message "${id}" not found`);
664
+ if (!canTransition(m.state, "queued")) {
665
+ throw new InvalidStateTransitionError(m.state, "queued");
666
+ }
667
+ await this.deps.outbox.updateState(id, {
668
+ state: "queued",
669
+ attempts: 0,
670
+ nextAttemptAt: this.deps.clock.now(),
671
+ lastError: null
672
+ });
673
+ await this.deps.audit.append({
674
+ messageId: id,
675
+ eventType: "replayed",
676
+ actor,
677
+ detail: { fromState: m.state }
678
+ });
679
+ const updated = await this.deps.outbox.findById(id);
680
+ return toView(updated);
681
+ }
682
+ };
683
+
684
+ // src/application/dispatch-message.ts
685
+ var DispatchMessage = class {
686
+ constructor(deps) {
687
+ this.deps = deps;
688
+ this.mxCache = new MxCache(deps.config.domainValidation.mxCacheTtlMs ?? 36e5);
689
+ }
690
+ mxCache;
691
+ async execute(message) {
692
+ const { deps } = this;
693
+ return deps.telemetry.span(
694
+ "outpost.dispatch",
695
+ { messageId: message.id, provider: message.provider },
696
+ async () => {
697
+ const fresh = await deps.outbox.findById(message.id);
698
+ if (!fresh || fresh.state !== "sending") {
699
+ return { kind: "skipped", reason: "no longer in sending state" };
700
+ }
701
+ const provider = deps.providers.get(fresh.provider);
702
+ if (!provider) {
703
+ return this.fail(fresh, `No provider registered for "${fresh.provider}"`);
704
+ }
705
+ try {
706
+ const to = await deps.openEncryptor.open(fresh.recipientSealed);
707
+ const bodyJson = await deps.openEncryptor.open(fresh.bodySealed);
708
+ const body = JSON.parse(bodyJson);
709
+ const cleanTo = sanitizeRecipient(to, deps.config.sanitize);
710
+ const cleanSubject = sanitizeSubject(fresh.subject, deps.config.sanitize);
711
+ assertBodyWithinLimits(body, deps.config.sanitize);
712
+ await validateRecipient(cleanTo, deps.config.domainValidation, {
713
+ mxResolver: deps.mxResolver,
714
+ mxCache: this.mxCache,
715
+ nowMs: deps.clock.now().getTime()
716
+ });
717
+ const limited = await this.checkRateLimits(fresh.provider, cleanTo);
718
+ if (limited) {
719
+ return this.requeueRateLimited(fresh);
720
+ }
721
+ const dispatchable = {
722
+ id: fresh.id,
723
+ to: cleanTo,
724
+ subject: cleanSubject,
725
+ body,
726
+ headers: this.buildHeaders(),
727
+ metadata: fresh.metadata
728
+ };
729
+ const receipt = await provider.send(dispatchable);
730
+ await deps.outbox.updateState(fresh.id, {
731
+ state: "sent",
732
+ providerMessageId: receipt.providerMessageId,
733
+ lastError: null
734
+ });
735
+ await deps.audit.append({
736
+ messageId: fresh.id,
737
+ eventType: "dispatch_accepted",
738
+ actor: `provider:${fresh.provider}`,
739
+ detail: { providerMessageId: receipt.providerMessageId }
740
+ });
741
+ deps.telemetry.counter("outpost.dispatch.sent", 1, { provider: fresh.provider });
742
+ return { kind: "sent", providerMessageId: receipt.providerMessageId };
743
+ } catch (err) {
744
+ return this.handleError(fresh, err);
745
+ }
746
+ }
747
+ );
748
+ }
749
+ /** Classify the error and either retry-with-backoff or dead-letter. */
750
+ async handleError(message, err) {
751
+ const permanent = err instanceof ProviderError && err.errorClass === "permanent";
752
+ const reason = err instanceof Error ? err.message : String(err);
753
+ if (permanent) {
754
+ return this.fail(message, reason);
755
+ }
756
+ const attempts = message.attempts + 1;
757
+ if (isExhausted(attempts, this.deps.config.retry)) {
758
+ return this.fail(message, `Retries exhausted (${attempts}): ${reason}`, attempts);
759
+ }
760
+ const delay = backoffMs(attempts, this.deps.config.retry, this.deps.random());
761
+ const nextAttemptAt2 = new Date(this.deps.clock.now().getTime() + delay);
762
+ await this.deps.outbox.updateState(message.id, {
763
+ state: "queued",
764
+ attempts,
765
+ nextAttemptAt: nextAttemptAt2,
766
+ lastError: reason
767
+ });
768
+ await this.deps.audit.append({
769
+ messageId: message.id,
770
+ eventType: "retry_scheduled",
771
+ actor: `provider:${message.provider}`,
772
+ detail: { attempts, nextAttemptAt: nextAttemptAt2.toISOString(), reason }
773
+ });
774
+ this.deps.telemetry.counter("outpost.dispatch.retry", 1, { provider: message.provider });
775
+ return { kind: "retry", nextAttemptAt: nextAttemptAt2 };
776
+ }
777
+ /** Move to `failed` (terminal) and record in the Dead Letter Queue. */
778
+ async fail(message, reason, attempts) {
779
+ await this.deps.outbox.updateState(message.id, {
780
+ state: "failed",
781
+ attempts: attempts ?? message.attempts,
782
+ lastError: reason
783
+ });
784
+ await this.deps.audit.append({
785
+ messageId: message.id,
786
+ eventType: "dead_lettered",
787
+ actor: `provider:${message.provider}`,
788
+ detail: { reason }
789
+ });
790
+ this.deps.telemetry.counter("outpost.dispatch.failed", 1, { provider: message.provider });
791
+ return { kind: "failed", reason };
792
+ }
793
+ /** Re-queue without counting a failed attempt; short, jittered backoff. */
794
+ async requeueRateLimited(message) {
795
+ const delay = 1e3 + Math.floor(this.deps.random() * 4e3);
796
+ const nextAttemptAt2 = new Date(this.deps.clock.now().getTime() + delay);
797
+ await this.deps.outbox.updateState(message.id, {
798
+ state: "queued",
799
+ nextAttemptAt: nextAttemptAt2
800
+ });
801
+ this.deps.telemetry.counter("outpost.dispatch.rate_limited", 1, { provider: message.provider });
802
+ return { kind: "rate_limited", nextAttemptAt: nextAttemptAt2 };
803
+ }
804
+ async checkRateLimits(provider, to) {
805
+ const checks = [
806
+ this.deps.rateLimiter.acquire({ kind: "global" }),
807
+ this.deps.rateLimiter.acquire({ kind: "provider", key: provider }),
808
+ this.deps.rateLimiter.acquire({ kind: "recipientDomain", key: extractDomain(to) })
809
+ ];
810
+ const results = await Promise.all(checks);
811
+ return results.some((ok) => ok === false);
812
+ }
813
+ /** List-Unsubscribe and other always-on headers (TDR §3.11). */
814
+ buildHeaders() {
815
+ return {};
816
+ }
817
+ };
818
+
819
+ // src/workers/send-worker.ts
820
+ var SendWorker = class {
821
+ constructor(deps, options = {}) {
822
+ this.deps = deps;
823
+ this.options = options;
824
+ this.dispatch = new DispatchMessage(deps);
825
+ }
826
+ dispatch;
827
+ running = false;
828
+ timer = null;
829
+ /** Process one batch. Returns what happened (for logging/metrics/tests). */
830
+ async tick() {
831
+ const now = this.deps.clock.now();
832
+ const batchSize = this.options.batchSize ?? this.deps.config.sendBatchSize;
833
+ const reclaimBefore = new Date(now.getTime() - this.deps.config.staleSendingLeaseMs);
834
+ const claimed = await this.deps.outbox.claimBatchForSending(batchSize, now, reclaimBefore);
835
+ this.deps.telemetry.gauge("outpost.send.claimed", claimed.length);
836
+ if (claimed.length === 0) return { claimed: 0, outcomes: [] };
837
+ const concurrency = this.options.concurrency ?? 10;
838
+ const outcomes = await runWithConcurrency(
839
+ claimed,
840
+ concurrency,
841
+ (m) => this.dispatch.execute(m).catch((err) => {
842
+ this.deps.logger.log("error", "dispatch threw unexpectedly", {
843
+ messageId: m.id,
844
+ error: err instanceof Error ? err.message : String(err)
845
+ });
846
+ return { kind: "failed", reason: "unexpected error" };
847
+ })
848
+ );
849
+ return { claimed: claimed.length, outcomes };
850
+ }
851
+ /** Start the long-running poll loop. Idempotent. */
852
+ start() {
853
+ if (this.running) return;
854
+ this.running = true;
855
+ const interval = this.options.intervalMs ?? 1e3;
856
+ const loop = async () => {
857
+ if (!this.running) return;
858
+ try {
859
+ await this.tick();
860
+ } catch (err) {
861
+ this.deps.logger.log("error", "send worker tick failed", {
862
+ error: err instanceof Error ? err.message : String(err)
863
+ });
864
+ } finally {
865
+ if (this.running) this.timer = setTimeout(loop, interval);
866
+ }
867
+ };
868
+ void loop();
869
+ }
870
+ /** Stop the loop. In-flight dispatches complete; no new tick starts. */
871
+ stop() {
872
+ this.running = false;
873
+ if (this.timer) clearTimeout(this.timer);
874
+ this.timer = null;
875
+ }
876
+ };
877
+ async function runWithConcurrency(items, limit, fn) {
878
+ const results = new Array(items.length);
879
+ let cursor = 0;
880
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
881
+ for (; ; ) {
882
+ const i = cursor++;
883
+ if (i >= items.length) return;
884
+ results[i] = await fn(items[i]);
885
+ }
886
+ });
887
+ await Promise.all(workers);
888
+ return results;
889
+ }
890
+
891
+ // src/application/purge-retention.ts
892
+ var PurgeRetention = class {
893
+ constructor(deps) {
894
+ this.deps = deps;
895
+ }
896
+ async execute() {
897
+ const { deps } = this;
898
+ return deps.telemetry.span("outpost.retention.purge", {}, async () => {
899
+ const now = deps.clock.now();
900
+ const policy = deps.config.retention;
901
+ const cutoff = purgeCutoff(policy, now);
902
+ let operationalProcessed = 0;
903
+ for (; ; ) {
904
+ const batch = await deps.outbox.claimTerminalForPurge(cutoff, policy.batchSize);
905
+ if (batch.length === 0) break;
906
+ const ids = batch.map((m) => m.id);
907
+ const count = policy.redactOnPurge ? await deps.outbox.redactBatch(ids) : await deps.outbox.deleteBatch(ids);
908
+ operationalProcessed += count;
909
+ await deps.audit.append({
910
+ messageId: null,
911
+ eventType: policy.redactOnPurge ? "redacted" : "purged",
912
+ actor: "system:retention",
913
+ detail: { count, cutoff: cutoff.toISOString() }
914
+ });
915
+ if (batch.length < policy.batchSize) break;
916
+ }
917
+ const auditCutoff = new Date(now.getTime() - policy.auditTtlDays * 24 * 60 * 60 * 1e3);
918
+ const auditDeleted = await deps.audit.purgeOlderThan(auditCutoff, policy.batchSize);
919
+ deps.telemetry.gauge("outpost.retention.operational_processed", operationalProcessed);
920
+ deps.telemetry.gauge("outpost.retention.audit_deleted", auditDeleted);
921
+ deps.logger.log("info", "retention cycle complete", {
922
+ operationalProcessed,
923
+ auditDeleted,
924
+ redacted: policy.redactOnPurge
925
+ });
926
+ return { operationalProcessed, auditDeleted, redacted: policy.redactOnPurge };
927
+ });
928
+ }
929
+ };
930
+
931
+ // src/workers/retention-worker.ts
932
+ var RetentionWorker = class {
933
+ constructor(deps, options = {}) {
934
+ this.deps = deps;
935
+ this.options = options;
936
+ this.purge = new PurgeRetention(deps);
937
+ }
938
+ purge;
939
+ running = false;
940
+ timer = null;
941
+ async tick() {
942
+ return this.purge.execute();
943
+ }
944
+ start() {
945
+ if (this.running) return;
946
+ this.running = true;
947
+ const interval = this.options.intervalMs ?? 60 * 60 * 1e3;
948
+ const loop = async () => {
949
+ if (!this.running) return;
950
+ try {
951
+ await this.tick();
952
+ } catch (err) {
953
+ this.deps.logger.log("error", "retention worker tick failed", {
954
+ error: err instanceof Error ? err.message : String(err)
955
+ });
956
+ } finally {
957
+ if (this.running) this.timer = setTimeout(loop, interval);
958
+ }
959
+ };
960
+ void loop();
961
+ }
962
+ stop() {
963
+ this.running = false;
964
+ if (this.timer) clearTimeout(this.timer);
965
+ this.timer = null;
966
+ }
967
+ };
968
+
969
+ // src/client/outpost-client.ts
970
+ var Outpost = class {
971
+ constructor(deps, defaultActor = "programmatic") {
972
+ this.deps = deps;
973
+ this.defaultActor = defaultActor;
974
+ this.enqueueMessage = new EnqueueMessage(deps);
975
+ this.ingestWebhook = new IngestWebhook(deps);
976
+ this.suppression = new ManageSuppression(deps);
977
+ this.keys = new ManageApiKey(deps);
978
+ this.auth = new Authenticate(deps);
979
+ this.getMessage = new GetMessage(deps);
980
+ this.listMessages = new ListMessages(deps);
981
+ this.replayMessage = new ReplayMessage(deps);
982
+ this.send_worker = new SendWorker(deps);
983
+ this.retention_worker = new RetentionWorker(deps);
984
+ }
985
+ enqueueMessage;
986
+ ingestWebhook;
987
+ suppression;
988
+ keys;
989
+ auth;
990
+ send_worker;
991
+ retention_worker;
992
+ getMessage;
993
+ listMessages;
994
+ replayMessage;
995
+ /** Enqueue a message (persist-then-queue). Idempotent on `idempotencyKey`. */
996
+ send(input, opts) {
997
+ return this.enqueueMessage.execute(input, opts?.actor ?? this.defaultActor);
998
+ }
999
+ /** Fetch a message's lifecycle + metadata (PII-free view). */
1000
+ get(id) {
1001
+ return this.getMessage.execute(id);
1002
+ }
1003
+ /** List messages by state / recipient hash / date. */
1004
+ list(query = {}) {
1005
+ return this.listMessages.execute(query);
1006
+ }
1007
+ /** Re-enqueue a dead-lettered (failed) message from the DLQ. */
1008
+ replay(id, opts) {
1009
+ return this.replayMessage.execute(id, opts?.actor ?? this.defaultActor);
1010
+ }
1011
+ /** Check whether an address is on the suppression list. */
1012
+ isSuppressed(address) {
1013
+ return this.suppression.isSuppressed(address);
1014
+ }
1015
+ /** Add an address to the suppression list (audited). */
1016
+ suppress(address, reason = "manual", opts) {
1017
+ return this.suppression.suppress(address, reason, opts?.actor ?? this.defaultActor, opts?.note);
1018
+ }
1019
+ /** Remove an address from the suppression list (audited). */
1020
+ async unsuppress(address, opts) {
1021
+ const hmac = this.deps.recipientHasher.hash(address);
1022
+ return this.suppression.unsuppressByHmac(hmac, opts?.actor ?? this.defaultActor);
1023
+ }
1024
+ /** Ingest a verified provider webhook (used by the HTTP webhook sink). */
1025
+ webhook(provider, raw) {
1026
+ return this.ingestWebhook.execute(provider, raw);
1027
+ }
1028
+ /** Convenience: run one send-worker cycle (cron/route-handler deployments). */
1029
+ tickSend() {
1030
+ return this.send_worker.tick();
1031
+ }
1032
+ /** Convenience: run one retention cycle. */
1033
+ tickRetention() {
1034
+ return this.retention_worker.tick();
1035
+ }
1036
+ };
1037
+ var HmacRecipientHasher = class {
1038
+ key;
1039
+ constructor(key) {
1040
+ this.key = typeof key === "string" ? Buffer.from(key, "utf8") : key;
1041
+ if (this.key.length < 16) {
1042
+ throw new Error("Recipient HMAC key must be at least 16 bytes of entropy");
1043
+ }
1044
+ }
1045
+ hash(address) {
1046
+ const normalized = address.trim().toLowerCase();
1047
+ return crypto.createHmac("sha256", this.key).update(normalized, "utf8").digest("hex");
1048
+ }
1049
+ /** Constant-time comparison helper for callers that compare digests. */
1050
+ static equals(a, b) {
1051
+ const ab = Buffer.from(a);
1052
+ const bb = Buffer.from(b);
1053
+ if (ab.length !== bb.length) return false;
1054
+ return crypto.timingSafeEqual(ab, bb);
1055
+ }
1056
+ };
1057
+ var PLAIN_ALG = "plain";
1058
+ var NoopEncryptor = class {
1059
+ alg = PLAIN_ALG;
1060
+ async seal(plaintext) {
1061
+ return { alg: PLAIN_ALG, ciphertext: Buffer.from(plaintext, "utf8").toString("base64") };
1062
+ }
1063
+ async open(sealed) {
1064
+ return Buffer.from(sealed.ciphertext, "base64").toString("utf8");
1065
+ }
1066
+ };
1067
+ var AES_ALG = "aes-256-gcm";
1068
+ var AesGcmEncryptor = class {
1069
+ constructor(key, keyId = "default") {
1070
+ this.keyId = keyId;
1071
+ if (key.length !== 32) throw new Error("AES-256-GCM requires a 32-byte key");
1072
+ this.key = key;
1073
+ }
1074
+ alg = AES_ALG;
1075
+ key;
1076
+ async seal(plaintext) {
1077
+ const iv = crypto.randomBytes(12);
1078
+ const cipher = crypto.createCipheriv(AES_ALG, this.key, iv);
1079
+ const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
1080
+ const tag = cipher.getAuthTag();
1081
+ return {
1082
+ alg: AES_ALG,
1083
+ ciphertext: ct.toString("base64"),
1084
+ iv: iv.toString("base64"),
1085
+ tag: tag.toString("base64"),
1086
+ keyId: this.keyId
1087
+ };
1088
+ }
1089
+ async open(sealed) {
1090
+ if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);
1091
+ if (!sealed.iv || !sealed.tag) throw new Error("Sealed value missing iv/tag");
1092
+ const decipher = crypto.createDecipheriv(AES_ALG, this.key, Buffer.from(sealed.iv, "base64"));
1093
+ decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
1094
+ const pt = Buffer.concat([
1095
+ decipher.update(Buffer.from(sealed.ciphertext, "base64")),
1096
+ decipher.final()
1097
+ ]);
1098
+ return pt.toString("utf8");
1099
+ }
1100
+ };
1101
+ var HYBRID_ALG = "hybrid-rsa-aes-256-gcm";
1102
+ function rsaOaep(key) {
1103
+ return { key, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" };
1104
+ }
1105
+ var HybridSealEncryptor = class {
1106
+ constructor(publicKeyPem, keyId = "default") {
1107
+ this.publicKeyPem = publicKeyPem;
1108
+ this.keyId = keyId;
1109
+ }
1110
+ alg = HYBRID_ALG;
1111
+ async seal(plaintext) {
1112
+ const dataKey = crypto.randomBytes(32);
1113
+ const iv = crypto.randomBytes(12);
1114
+ const cipher = crypto.createCipheriv(AES_ALG, dataKey, iv);
1115
+ const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
1116
+ const tag = cipher.getAuthTag();
1117
+ const wrappedKey = crypto.publicEncrypt(rsaOaep(this.publicKeyPem), dataKey);
1118
+ return {
1119
+ alg: HYBRID_ALG,
1120
+ ciphertext: ct.toString("base64"),
1121
+ iv: iv.toString("base64"),
1122
+ tag: tag.toString("base64"),
1123
+ wrappedKey: wrappedKey.toString("base64"),
1124
+ keyId: this.keyId
1125
+ };
1126
+ }
1127
+ async open() {
1128
+ throw new Error(
1129
+ "HybridSealEncryptor cannot decrypt: the ingestion tier holds only the public key (by design)"
1130
+ );
1131
+ }
1132
+ };
1133
+ var HybridOpenEncryptor = class {
1134
+ constructor(privateKeyPem) {
1135
+ this.privateKeyPem = privateKeyPem;
1136
+ }
1137
+ alg = HYBRID_ALG;
1138
+ async seal() {
1139
+ throw new Error("HybridOpenEncryptor is read-only; use HybridSealEncryptor to seal");
1140
+ }
1141
+ async open(sealed) {
1142
+ if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);
1143
+ if (!sealed.wrappedKey || !sealed.iv || !sealed.tag) {
1144
+ throw new Error("Sealed value missing wrappedKey/iv/tag for hybrid open");
1145
+ }
1146
+ const dataKey = crypto.privateDecrypt(
1147
+ rsaOaep(this.privateKeyPem),
1148
+ Buffer.from(sealed.wrappedKey, "base64")
1149
+ );
1150
+ const decipher = crypto.createDecipheriv(AES_ALG, dataKey, Buffer.from(sealed.iv, "base64"));
1151
+ decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
1152
+ const pt = Buffer.concat([
1153
+ decipher.update(Buffer.from(sealed.ciphertext, "base64")),
1154
+ decipher.final()
1155
+ ]);
1156
+ return pt.toString("utf8");
1157
+ }
1158
+ };
1159
+
1160
+ // src/adapters/rate-limit/in-memory.ts
1161
+ var InMemoryRateLimiter = class {
1162
+ constructor(config, clock) {
1163
+ this.config = config;
1164
+ this.clock = clock;
1165
+ }
1166
+ buckets = /* @__PURE__ */ new Map();
1167
+ async acquire(scope) {
1168
+ const budget = this.budgetFor(scope);
1169
+ if (!budget) return true;
1170
+ const key = `${scope.kind}:${scope.key ?? ""}`;
1171
+ const now = this.clock.now().getTime();
1172
+ const refillRate = budget.max / budget.windowMs;
1173
+ let bucket = this.buckets.get(key);
1174
+ if (!bucket) {
1175
+ bucket = { tokens: budget.max, lastRefill: now };
1176
+ this.buckets.set(key, bucket);
1177
+ } else {
1178
+ const elapsed = now - bucket.lastRefill;
1179
+ bucket.tokens = Math.min(budget.max, bucket.tokens + elapsed * refillRate);
1180
+ bucket.lastRefill = now;
1181
+ }
1182
+ if (bucket.tokens >= 1) {
1183
+ bucket.tokens -= 1;
1184
+ return true;
1185
+ }
1186
+ return false;
1187
+ }
1188
+ budgetFor(scope) {
1189
+ switch (scope.kind) {
1190
+ case "global":
1191
+ return this.config.global;
1192
+ case "provider":
1193
+ return this.config.perProvider;
1194
+ case "recipientDomain":
1195
+ return this.config.perRecipientDomain;
1196
+ }
1197
+ }
1198
+ };
1199
+ var UnlimitedRateLimiter = class {
1200
+ async acquire() {
1201
+ return true;
1202
+ }
1203
+ };
1204
+ var SystemClock = class {
1205
+ now() {
1206
+ return /* @__PURE__ */ new Date();
1207
+ }
1208
+ };
1209
+ var UuidGenerator = class {
1210
+ generate() {
1211
+ return crypto.randomUUID();
1212
+ }
1213
+ };
1214
+ var DnsMxResolver = class {
1215
+ async resolveMx(domain) {
1216
+ const records = await promises.resolveMx(domain);
1217
+ return records.sort((a, b) => a.priority - b.priority).map((r) => r.exchange);
1218
+ }
1219
+ };
1220
+
1221
+ // src/adapters/observability/logger.ts
1222
+ var ConsoleLogger = class _ConsoleLogger {
1223
+ constructor(minLevel = "info") {
1224
+ this.minLevel = minLevel;
1225
+ }
1226
+ static RANK = {
1227
+ debug: 10,
1228
+ info: 20,
1229
+ warn: 30,
1230
+ error: 40
1231
+ };
1232
+ log(level, message, fields) {
1233
+ if (_ConsoleLogger.RANK[level] < _ConsoleLogger.RANK[this.minLevel]) return;
1234
+ const line = JSON.stringify({ level, message, ...fields });
1235
+ if (level === "error") console.error(line);
1236
+ else if (level === "warn") console.warn(line);
1237
+ else console.log(line);
1238
+ }
1239
+ };
1240
+
1241
+ // src/adapters/observability/telemetry.ts
1242
+ var NoopTelemetry = class {
1243
+ async span(_name, _attrs, fn) {
1244
+ return fn();
1245
+ }
1246
+ counter() {
1247
+ }
1248
+ gauge() {
1249
+ }
1250
+ };
1251
+
1252
+ // src/create-outpost.ts
1253
+ function createOutpost(options) {
1254
+ const config = resolveConfig({
1255
+ retry: options.retry,
1256
+ retention: options.retention,
1257
+ sanitize: options.sanitize,
1258
+ attachments: options.attachments,
1259
+ domainValidation: options.domainValidation,
1260
+ rateLimits: options.rateLimits,
1261
+ sendBatchSize: options.sendBatchSize
1262
+ });
1263
+ if (options.providers.length === 0) {
1264
+ throw new Error("createOutpost requires at least one provider");
1265
+ }
1266
+ const providers = /* @__PURE__ */ new Map();
1267
+ for (const p of options.providers) providers.set(p.name, p);
1268
+ const defaultProvider = options.defaultProvider ?? options.providers[0].name;
1269
+ if (!providers.has(defaultProvider)) {
1270
+ throw new Error(`defaultProvider "${defaultProvider}" is not in the providers list`);
1271
+ }
1272
+ const { sealEncryptor, openEncryptor } = resolveEncryption(options.encryption ?? { mode: "none" });
1273
+ const recipientHasher = new HmacRecipientHasher(options.recipientHmacKey);
1274
+ const clock = options.clock ?? new SystemClock();
1275
+ const rateLimiter = options.rateLimiter ?? (options.rateLimits ? new InMemoryRateLimiter(options.rateLimits, clock) : new UnlimitedRateLimiter());
1276
+ const deps = {
1277
+ config,
1278
+ outbox: options.repositories.outbox,
1279
+ suppressions: options.repositories.suppressions,
1280
+ audit: options.repositories.audit,
1281
+ apiKeys: options.repositories.apiKeys,
1282
+ webhookEvents: options.repositories.webhookEvents,
1283
+ providers,
1284
+ defaultProvider,
1285
+ sealEncryptor,
1286
+ openEncryptor,
1287
+ recipientHasher,
1288
+ rateLimiter,
1289
+ clock,
1290
+ ids: options.ids ?? new UuidGenerator(),
1291
+ logger: options.logger ?? new ConsoleLogger(),
1292
+ telemetry: options.telemetry ?? new NoopTelemetry(),
1293
+ templates: options.templates,
1294
+ mxResolver: options.mxResolver ?? (config.domainValidation.mx ? new DnsMxResolver() : void 0),
1295
+ sanitizeHtml: options.sanitizeHtml,
1296
+ random: options.random ?? Math.random
1297
+ };
1298
+ return new Outpost(deps, options.defaultActor);
1299
+ }
1300
+ function resolveEncryption(enc) {
1301
+ if ("sealEncryptor" in enc) {
1302
+ return { sealEncryptor: enc.sealEncryptor, openEncryptor: enc.openEncryptor };
1303
+ }
1304
+ switch (enc.mode) {
1305
+ case "none": {
1306
+ const noop = new NoopEncryptor();
1307
+ return { sealEncryptor: noop, openEncryptor: noop };
1308
+ }
1309
+ case "symmetric": {
1310
+ const key = typeof enc.key === "string" ? Buffer.from(enc.key, "base64") : enc.key;
1311
+ const e = new AesGcmEncryptor(key, enc.keyId);
1312
+ return { sealEncryptor: e, openEncryptor: e };
1313
+ }
1314
+ case "asymmetric": {
1315
+ const seal = new HybridSealEncryptor(enc.publicKey, enc.keyId);
1316
+ const open = enc.privateKey ? new HybridOpenEncryptor(enc.privateKey) : seal;
1317
+ return { sealEncryptor: seal, openEncryptor: open };
1318
+ }
1319
+ }
1320
+ }
1321
+
1322
+ // src/domain/suppression.ts
1323
+ var SUPPRESSION_REASONS = [
1324
+ "hard_bounce",
1325
+ "complaint",
1326
+ "unsubscribe",
1327
+ "invalid",
1328
+ "manual"
1329
+ ];
1330
+
1331
+ exports.API_SCOPES = API_SCOPES;
1332
+ exports.Authenticate = Authenticate;
1333
+ exports.DEFAULT_ATTACHMENT_POLICY = DEFAULT_ATTACHMENT_POLICY;
1334
+ exports.DEFAULT_DOMAIN_VALIDATION = DEFAULT_DOMAIN_VALIDATION;
1335
+ exports.DEFAULT_RETENTION = DEFAULT_RETENTION;
1336
+ exports.DEFAULT_RETRY = DEFAULT_RETRY;
1337
+ exports.DEFAULT_SANITIZE_LIMITS = DEFAULT_SANITIZE_LIMITS;
1338
+ exports.DispatchMessage = DispatchMessage;
1339
+ exports.EnqueueMessage = EnqueueMessage;
1340
+ exports.ForbiddenError = ForbiddenError;
1341
+ exports.GetMessage = GetMessage;
1342
+ exports.IngestWebhook = IngestWebhook;
1343
+ exports.InvalidStateTransitionError = InvalidStateTransitionError;
1344
+ exports.LIFECYCLE_STATES = LIFECYCLE_STATES;
1345
+ exports.ListMessages = ListMessages;
1346
+ exports.ManageApiKey = ManageApiKey;
1347
+ exports.ManageSuppression = ManageSuppression;
1348
+ exports.MxCache = MxCache;
1349
+ exports.NotFoundError = NotFoundError;
1350
+ exports.Outpost = Outpost;
1351
+ exports.OutpostError = OutpostError;
1352
+ exports.ProviderError = ProviderError;
1353
+ exports.PurgeRetention = PurgeRetention;
1354
+ exports.ReplayMessage = ReplayMessage;
1355
+ exports.SUPPRESSION_REASONS = SUPPRESSION_REASONS;
1356
+ exports.TERMINAL_STATES = TERMINAL_STATES;
1357
+ exports.UnauthorizedError = UnauthorizedError;
1358
+ exports.ValidationError = ValidationError;
1359
+ exports.WebhookVerificationError = WebhookVerificationError;
1360
+ exports.assertBodyWithinLimits = assertBodyWithinLimits;
1361
+ exports.assertNoHeaderInjection = assertNoHeaderInjection;
1362
+ exports.backoffMs = backoffMs;
1363
+ exports.canTransition = canTransition;
1364
+ exports.createOutpost = createOutpost;
1365
+ exports.extractDomain = extractDomain;
1366
+ exports.generateApiKeySecret = generateApiKeySecret;
1367
+ exports.hasScope = hasScope;
1368
+ exports.hashApiKey = hashApiKey;
1369
+ exports.isExhausted = isExhausted;
1370
+ exports.isKeyActive = isKeyActive;
1371
+ exports.isTerminal = isTerminal;
1372
+ exports.isTransient = isTransient;
1373
+ exports.nextAttemptAt = nextAttemptAt;
1374
+ exports.purgeCutoff = purgeCutoff;
1375
+ exports.resolveConfig = resolveConfig;
1376
+ exports.sanitizeHeaders = sanitizeHeaders;
1377
+ exports.sanitizeRecipient = sanitizeRecipient;
1378
+ exports.sanitizeSubject = sanitizeSubject;
1379
+ exports.shouldSuppressOn = shouldSuppressOn;
1380
+ exports.stripDangerousHtml = stripDangerousHtml;
1381
+ exports.toView = toView;
1382
+ exports.validateAttachment = validateAttachment;
1383
+ exports.validateRecipient = validateRecipient;
1384
+ exports.validateSyntax = validateSyntax;
1385
+ exports.webhookToState = webhookToState;
1386
+ //# sourceMappingURL=index.cjs.map
1387
+ //# sourceMappingURL=index.cjs.map