@tgoliveira/outpost 1.2.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/AGENTS.md +172 -18
  2. package/README.md +17 -12
  3. package/dist/adapters/drizzle/index.cjs +194 -15
  4. package/dist/adapters/drizzle/index.cjs.map +1 -1
  5. package/dist/adapters/drizzle/index.d.cts +124 -7
  6. package/dist/adapters/drizzle/index.d.ts +124 -7
  7. package/dist/adapters/drizzle/index.js +194 -15
  8. package/dist/adapters/drizzle/index.js.map +1 -1
  9. package/dist/adapters/index.cjs +148 -38
  10. package/dist/adapters/index.cjs.map +1 -1
  11. package/dist/adapters/index.d.cts +21 -13
  12. package/dist/adapters/index.d.ts +21 -13
  13. package/dist/adapters/index.js +149 -39
  14. package/dist/adapters/index.js.map +1 -1
  15. package/dist/admin/index.cjs +10 -3
  16. package/dist/admin/index.cjs.map +1 -1
  17. package/dist/admin/index.d.cts +7 -7
  18. package/dist/admin/index.d.ts +7 -7
  19. package/dist/admin/index.js +10 -3
  20. package/dist/admin/index.js.map +1 -1
  21. package/dist/{fake-BY6t7UXb.d.cts → fake-B6OIEdod.d.ts} +6 -4
  22. package/dist/{fake-en-oOdg0.d.ts → fake-CpQc9p0N.d.cts} +6 -4
  23. package/dist/http/index.cjs.map +1 -1
  24. package/dist/http/index.d.cts +6 -6
  25. package/dist/http/index.d.ts +6 -6
  26. package/dist/http/index.js.map +1 -1
  27. package/dist/{index-c6caPsUG.d.ts → index-B4F7euCt.d.cts} +53 -21
  28. package/dist/{index-BO0GiZmP.d.cts → index-Cn1YsmGe.d.ts} +53 -21
  29. package/dist/index.cjs +509 -146
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +17 -15
  32. package/dist/index.d.ts +17 -15
  33. package/dist/index.js +509 -148
  34. package/dist/index.js.map +1 -1
  35. package/dist/modules/ui/index.cjs +3 -3
  36. package/dist/modules/ui/index.cjs.map +1 -1
  37. package/dist/modules/ui/index.js +3 -3
  38. package/dist/modules/ui/index.js.map +1 -1
  39. package/dist/modules/ui/pages/admin/admin-config-page.cjs +2 -2
  40. package/dist/modules/ui/pages/admin/admin-config-page.cjs.map +1 -1
  41. package/dist/modules/ui/pages/admin/admin-config-page.js +2 -2
  42. package/dist/modules/ui/pages/admin/admin-config-page.js.map +1 -1
  43. package/dist/modules/ui/pages/admin/admin-panel-page.cjs +1 -1
  44. package/dist/modules/ui/pages/admin/admin-panel-page.js +1 -1
  45. package/dist/modules/ui/pages/index.cjs +3 -3
  46. package/dist/modules/ui/pages/index.cjs.map +1 -1
  47. package/dist/modules/ui/pages/index.js +3 -3
  48. package/dist/modules/ui/pages/index.js.map +1 -1
  49. package/dist/{outpost-client-BItbgqIo.d.ts → outpost-client-BX3SsOFb.d.ts} +50 -21
  50. package/dist/{outpost-client-BlVf4gjo.d.cts → outpost-client-DhQgZY16.d.cts} +50 -21
  51. package/dist/react/index.cjs +3 -3
  52. package/dist/react/index.cjs.map +1 -1
  53. package/dist/react/index.js +3 -3
  54. package/dist/react/index.js.map +1 -1
  55. package/dist/repositories-DJYu4nGV.d.ts +322 -0
  56. package/dist/repositories-sMN6RHZJ.d.cts +322 -0
  57. package/dist/{services-CfTEsetF.d.ts → services-DZwZjDn_.d.cts} +9 -3
  58. package/dist/{services-CQINhAGo.d.cts → services-PoM2bxjP.d.ts} +9 -3
  59. package/dist/{template-DxI_p2Ny.d.cts → template-Dl1_ciRo.d.ts} +24 -4
  60. package/dist/{template-CREUq7bB.d.ts → template-Dny_7Ymi.d.cts} +24 -4
  61. package/dist/testing/index.cjs +200 -15
  62. package/dist/testing/index.cjs.map +1 -1
  63. package/dist/testing/index.d.cts +26 -7
  64. package/dist/testing/index.d.ts +26 -7
  65. package/dist/testing/index.js +200 -15
  66. package/dist/testing/index.js.map +1 -1
  67. package/dist/{webhook-kp6CiXk-.d.cts → webhook-B158Vi6p.d.cts} +20 -4
  68. package/dist/{webhook-kp6CiXk-.d.ts → webhook-B158Vi6p.d.ts} +20 -4
  69. package/dist/workers/index.cjs +471 -85
  70. package/dist/workers/index.cjs.map +1 -1
  71. package/dist/workers/index.d.cts +5 -5
  72. package/dist/workers/index.d.ts +5 -5
  73. package/dist/workers/index.js +471 -85
  74. package/dist/workers/index.js.map +1 -1
  75. package/package.json +6 -3
  76. package/dist/repositories-CHIOFGn3.d.cts +0 -182
  77. package/dist/repositories-WyhvxzyY.d.ts +0 -182
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createHash, randomBytes, createHmac, timingSafeEqual, randomUUID, createCipheriv, publicEncrypt, privateDecrypt, createDecipheriv, constants } from 'crypto';
1
+ import { createHash, randomBytes, createHmac, timingSafeEqual, randomUUID, createCipheriv, publicEncrypt, privateDecrypt, constants, createDecipheriv } from 'crypto';
2
2
  import { resolveMx } from 'dns/promises';
3
3
 
4
4
  // src/application/pipeline/retry-policy.ts
@@ -20,6 +20,16 @@ function nextAttemptAt(attempts, config, jitter, now) {
20
20
  return new Date(now.getTime() + backoffMs(attempts, config, jitter));
21
21
  }
22
22
 
23
+ // src/domain/provider-failure.ts
24
+ function classifyProviderFailure(err) {
25
+ if (typeof err !== "object" || err === null) return void 0;
26
+ const errorClass = err.errorClass;
27
+ const code = err.code;
28
+ if (errorClass === "permanent" && code === "provider_permanent") return "permanent";
29
+ if (errorClass === "transient" && code === "provider_transient") return "transient";
30
+ return void 0;
31
+ }
32
+
23
33
  // src/domain/errors.ts
24
34
  var OutpostError = class extends Error {
25
35
  code;
@@ -77,7 +87,7 @@ var ProviderError = class _ProviderError extends OutpostError {
77
87
  }
78
88
  };
79
89
  function isTransient(err) {
80
- return err instanceof ProviderError && err.errorClass === "transient";
90
+ return classifyProviderFailure(err) === "transient";
81
91
  }
82
92
 
83
93
  // src/application/pipeline/sanitize.ts
@@ -201,11 +211,7 @@ async function validateRecipient(address, config, deps) {
201
211
  const cached = deps.mxCache?.get(domain, deps.nowMs);
202
212
  let hosts = cached;
203
213
  if (hosts === void 0) {
204
- try {
205
- hosts = await deps.mxResolver.resolveMx(domain);
206
- } catch {
207
- hosts = [];
208
- }
214
+ hosts = await deps.mxResolver.resolveMx(domain);
209
215
  deps.mxCache?.set(domain, hosts, deps.nowMs);
210
216
  }
211
217
  if (hosts.length === 0) {
@@ -221,8 +227,20 @@ var DEFAULT_RETENTION = {
221
227
  auditTtlDays: 365,
222
228
  redactOnPurge: true,
223
229
  webhookWindowHours: 72,
224
- batchSize: 1e3
230
+ batchSize: 1e3,
231
+ batchPauseMs: 50
225
232
  };
233
+ function normalizeBatchPauseMs(ms) {
234
+ if (!Number.isFinite(ms) || ms <= 0) return 0;
235
+ return ms;
236
+ }
237
+ function waitForBatchPause(ms) {
238
+ const pause = normalizeBatchPauseMs(ms);
239
+ if (pause === 0) return Promise.resolve();
240
+ return new Promise((resolve) => {
241
+ setTimeout(resolve, pause);
242
+ });
243
+ }
226
244
  function purgeCutoff(policy, now) {
227
245
  const ttlCutoff = now.getTime() - policy.operationalTtlDays * 24 * 60 * 60 * 1e3;
228
246
  const windowCutoff = now.getTime() - policy.webhookWindowHours * 60 * 60 * 1e3;
@@ -277,12 +295,14 @@ var EnqueueMessage = class {
277
295
  };
278
296
  }
279
297
  const suppressed = await deps.suppressions.isSuppressed(recipientHmac);
298
+ const id = deps.ids.generate();
280
299
  const [recipientSealed, bodySealed] = await Promise.all([
281
- deps.sealEncryptor.seal(to),
282
- deps.sealEncryptor.seal(JSON.stringify(cleanBody))
300
+ deps.sealEncryptor.seal(to, { messageId: id, column: "recipient" }),
301
+ deps.sealEncryptor.seal(JSON.stringify(cleanBody), { messageId: id, column: "body" })
283
302
  ]);
284
303
  const now = deps.clock.now();
285
- const message = await deps.outbox.insert({
304
+ const draft = {
305
+ id,
286
306
  idempotencyKey: input.idempotencyKey,
287
307
  recipientHmac,
288
308
  recipientSealed,
@@ -295,12 +315,37 @@ var EnqueueMessage = class {
295
315
  state: suppressed ? "suppressed" : "queued",
296
316
  scheduledFor: input.scheduledFor ?? null,
297
317
  nextAttemptAt: input.scheduledFor ?? now
298
- });
299
- await deps.audit.append({
300
- messageId: message.id,
318
+ };
319
+ const audit = {
301
320
  eventType: suppressed ? "suppressed" : "enqueued",
302
321
  actor,
303
322
  detail: suppressed ? { reason: "recipient_on_suppression_list" } : { provider }
323
+ };
324
+ if (deps.outbox.insertWithEnqueueAudit) {
325
+ const written = await deps.outbox.insertWithEnqueueAudit(draft, audit);
326
+ if (written.deduplicated) {
327
+ deps.telemetry.counter("outpost.enqueue.deduplicated", 1);
328
+ return {
329
+ id: written.message.id,
330
+ state: written.message.state,
331
+ idempotencyKey: written.message.idempotencyKey,
332
+ deduplicated: true
333
+ };
334
+ }
335
+ deps.telemetry.counter(suppressed ? "outpost.enqueue.suppressed" : "outpost.enqueue.queued", 1);
336
+ return {
337
+ id: written.message.id,
338
+ state: written.message.state,
339
+ idempotencyKey: written.message.idempotencyKey,
340
+ deduplicated: false
341
+ };
342
+ }
343
+ const message = await deps.outbox.insert(draft);
344
+ await deps.audit.append({
345
+ messageId: message.id,
346
+ eventType: audit.eventType,
347
+ actor: audit.actor,
348
+ detail: audit.detail
304
349
  });
305
350
  deps.telemetry.counter(suppressed ? "outpost.enqueue.suppressed" : "outpost.enqueue.queued", 1);
306
351
  return {
@@ -372,7 +417,8 @@ function isTerminal(state) {
372
417
  return TERMINAL_SET.has(state);
373
418
  }
374
419
  var ALLOWED_TRANSITIONS = {
375
- queued: ["sending", "suppressed", "failed"],
420
+ // Dead-letter is `sending` → `failed`, or a `failed` webhook from `sent`.
421
+ queued: ["sending", "suppressed"],
376
422
  // `sending` can fall back to `queued` on a transient error (retry).
377
423
  sending: ["sent", "queued", "failed", "suppressed"],
378
424
  sent: ["delivered", "bounced", "complained", "failed"],
@@ -391,6 +437,7 @@ function shouldSuppressOn(state) {
391
437
  }
392
438
 
393
439
  // src/application/ingest-webhook.ts
440
+ var WEBHOOK_FRESHNESS_WINDOW_MS = 3e5;
394
441
  var IngestWebhook = class {
395
442
  constructor(deps) {
396
443
  this.deps = deps;
@@ -403,13 +450,29 @@ var IngestWebhook = class {
403
450
  }
404
451
  return deps.telemetry.span("outpost.webhook.ingest", { provider: providerName }, async () => {
405
452
  const event = await provider.verifyWebhook(raw);
406
- await deps.webhookEvents.record(event);
407
- deps.telemetry.counter("outpost.webhook.received", 1, {
408
- provider: providerName,
409
- type: event.type
410
- });
453
+ if (!event) {
454
+ return { accepted: true, messageId: null, note: "ignored" };
455
+ }
456
+ this.assertFresh(event);
457
+ const duplicate = await deps.webhookEvents.findByIdentity?.(identityQuery(event));
458
+ if (duplicate) return this.duplicateResult(event);
411
459
  const message = await deps.outbox.findByProviderMessageId(event.providerMessageId);
412
460
  if (!message) {
461
+ const settled = event.providerEventId ? null : await deps.webhookEvents.findByIdentity?.({
462
+ match: "settledWithoutEventId",
463
+ provider: event.provider,
464
+ providerMessageId: event.providerMessageId,
465
+ type: event.type
466
+ });
467
+ if (settled) {
468
+ return {
469
+ accepted: true,
470
+ eventType: event.type,
471
+ messageId: null,
472
+ note: "duplicate provider event"
473
+ };
474
+ }
475
+ await this.store(event, "pending", providerName);
413
476
  return {
414
477
  accepted: true,
415
478
  eventType: event.type,
@@ -417,25 +480,110 @@ var IngestWebhook = class {
417
480
  note: "no matching message for providerMessageId"
418
481
  };
419
482
  }
420
- const target = webhookToState(event.type);
421
- if (target && canTransition(message.state, target)) {
422
- await deps.outbox.updateState(message.id, { state: target });
423
- }
424
- if (target && shouldSuppressOn(target) && this.isSuppressable(event)) {
425
- await deps.suppressions.add({
426
- recipientHmac: message.recipientHmac,
427
- reason: target === "bounced" ? "hard_bounce" : "complaint",
428
- createdBy: `provider:${providerName}`,
429
- note: `webhook ${event.type}`
430
- });
431
- }
432
- await deps.audit.append({
433
- messageId: message.id,
434
- eventType: this.auditType(event.type),
435
- actor: `provider:${providerName}`,
436
- detail: { type: event.type, occurredAt: event.occurredAt?.toISOString() ?? null }
483
+ const effect = await this.applyEffects(event, message);
484
+ await this.store(event, effect.disposition, providerName);
485
+ return effect.result;
486
+ });
487
+ }
488
+ /**
489
+ * Apply pending rows for a provider message id, oldest `receivedAt` first.
490
+ * No freshness check. Skips the call when the repository has no list method.
491
+ * Does not store another row or increment `outpost.webhook.received`.
492
+ */
493
+ async applyPending(providerMessageId) {
494
+ const list = this.deps.webhookEvents.listPendingByProviderMessageId;
495
+ if (!list) return;
496
+ const rows = await list.call(this.deps.webhookEvents, providerMessageId);
497
+ const ordered = [...rows].sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime());
498
+ for (const row of ordered) {
499
+ if (row.disposition !== "pending") continue;
500
+ const message = await this.deps.outbox.findByProviderMessageId(providerMessageId);
501
+ if (!message) continue;
502
+ const effect = await this.applyEffects(row.event, message);
503
+ await this.deps.webhookEvents.setDisposition?.(row.id, effect.disposition);
504
+ }
505
+ }
506
+ /** `verifiedAt` wins. Otherwise `occurredAt`. Neither present: do not reject. */
507
+ assertFresh(event) {
508
+ const timestamp = event.verifiedAt !== void 0 ? event.verifiedAt : event.occurredAt;
509
+ if (timestamp === void 0) return;
510
+ const skew = Math.abs(this.deps.clock.now().getTime() - timestamp.getTime());
511
+ if (skew > WEBHOOK_FRESHNESS_WINDOW_MS) {
512
+ throw new WebhookVerificationError("Webhook timestamp is stale");
513
+ }
514
+ }
515
+ async duplicateResult(event) {
516
+ const message = await this.deps.outbox.findByProviderMessageId(event.providerMessageId);
517
+ return {
518
+ accepted: true,
519
+ eventType: event.type,
520
+ messageId: message?.id ?? null,
521
+ note: "duplicate provider event"
522
+ };
523
+ }
524
+ /**
525
+ * State change, suppression, and one audit. Disposition is the caller's
526
+ * to persist: `applied` after a committed effect, `rejected` when the
527
+ * transition is not allowed.
528
+ */
529
+ async applyEffects(event, message) {
530
+ const target = webhookToState(event.type);
531
+ if (target === null) {
532
+ await this.appendAudit(event, message.id);
533
+ return {
534
+ disposition: "applied",
535
+ result: { accepted: true, eventType: event.type, messageId: message.id }
536
+ };
537
+ }
538
+ if (!canTransition(message.state, target)) {
539
+ return {
540
+ disposition: "rejected",
541
+ result: {
542
+ accepted: true,
543
+ eventType: event.type,
544
+ messageId: message.id,
545
+ note: "transition rejected"
546
+ }
547
+ };
548
+ }
549
+ await this.deps.outbox.updateState(message.id, { state: target });
550
+ if (shouldSuppressOn(target) && this.isSuppressable(event)) {
551
+ const reason = target === "bounced" ? "hard_bounce" : "complaint";
552
+ const already = await this.deps.suppressions.get(message.recipientHmac);
553
+ await this.deps.suppressions.add({
554
+ recipientHmac: message.recipientHmac,
555
+ reason,
556
+ createdBy: `provider:${event.provider}`,
557
+ note: `webhook ${event.type}`
437
558
  });
438
- return { accepted: true, eventType: event.type, messageId: message.id };
559
+ if (!already) {
560
+ this.deps.telemetry.counter("outpost.suppression.added", 1, { reason });
561
+ }
562
+ }
563
+ await this.appendAudit(event, message.id);
564
+ return {
565
+ disposition: "applied",
566
+ result: { accepted: true, eventType: event.type, messageId: message.id }
567
+ };
568
+ }
569
+ async store(event, disposition, providerName) {
570
+ await this.deps.webhookEvents.record(event, { disposition });
571
+ this.deps.telemetry.counter("outpost.webhook.received", 1, {
572
+ provider: providerName,
573
+ type: event.type
574
+ });
575
+ }
576
+ async appendAudit(event, messageId) {
577
+ const detail = {
578
+ type: event.type,
579
+ occurredAt: event.occurredAt?.toISOString() ?? null
580
+ };
581
+ if (event.providerEventId) detail.providerEventId = event.providerEventId;
582
+ await this.deps.audit.append({
583
+ messageId,
584
+ eventType: this.auditType(event.type),
585
+ actor: `provider:${event.provider}`,
586
+ detail
439
587
  });
440
588
  }
441
589
  /** A soft bounce must not suppress; only hard bounces and complaints do. */
@@ -459,6 +607,22 @@ var IngestWebhook = class {
459
607
  }
460
608
  }
461
609
  };
610
+ function identityQuery(event) {
611
+ if (event.providerEventId) {
612
+ return {
613
+ match: "providerEvent",
614
+ provider: event.provider,
615
+ providerEventId: event.providerEventId
616
+ };
617
+ }
618
+ return {
619
+ match: "providerMessage",
620
+ provider: event.provider,
621
+ providerMessageId: event.providerMessageId,
622
+ type: event.type,
623
+ occurredAt: event.occurredAt ?? null
624
+ };
625
+ }
462
626
 
463
627
  // src/application/manage-suppression.ts
464
628
  var ManageSuppression = class {
@@ -643,12 +807,22 @@ var GetMessage = class {
643
807
  return toView(m);
644
808
  }
645
809
  };
810
+ var DEFAULT_LIST_LIMIT = 50;
811
+ var MAX_LIST_LIMIT = 100;
812
+ function boundedListLimit(limit) {
813
+ if (limit === void 0 || !Number.isFinite(limit) || limit < 1) return DEFAULT_LIST_LIMIT;
814
+ return Math.min(Math.floor(limit), MAX_LIST_LIMIT);
815
+ }
646
816
  var ListMessages = class {
647
817
  constructor(deps) {
648
818
  this.deps = deps;
649
819
  }
650
820
  async execute(query) {
651
- const messages = await this.deps.outbox.list({ limit: 50, offset: 0, ...query });
821
+ const messages = await this.deps.outbox.list({
822
+ ...query,
823
+ limit: boundedListLimit(query.limit),
824
+ offset: query.offset ?? 0
825
+ });
652
826
  return messages.map(toView);
653
827
  }
654
828
  };
@@ -666,7 +840,8 @@ var ReplayMessage = class {
666
840
  state: "queued",
667
841
  attempts: 0,
668
842
  nextAttemptAt: this.deps.clock.now(),
669
- lastError: null
843
+ lastError: null,
844
+ providerMessageId: null
670
845
  });
671
846
  await this.deps.audit.append({
672
847
  messageId: id,
@@ -680,13 +855,26 @@ var ReplayMessage = class {
680
855
  };
681
856
 
682
857
  // src/application/dispatch-message.ts
858
+ function failureReason(err) {
859
+ if (typeof err === "object" && err !== null) {
860
+ const message = err.message;
861
+ if (typeof message === "string") return message;
862
+ }
863
+ return String(err);
864
+ }
683
865
  var DispatchMessage = class {
684
866
  constructor(deps) {
685
867
  this.deps = deps;
686
868
  this.mxCache = new MxCache(deps.config.domainValidation.mxCacheTtlMs ?? 36e5);
869
+ this.webhooks = new IngestWebhook(deps);
687
870
  }
688
871
  mxCache;
872
+ webhooks;
689
873
  async execute(message) {
874
+ const claim = { updatedAt: new Date(message.updatedAt.getTime()) };
875
+ if (!this.deps.outbox.updateStateWhileSending) {
876
+ throw new Error("OutboxRepository.updateStateWhileSending is required to dispatch");
877
+ }
690
878
  const { deps } = this;
691
879
  return deps.telemetry.span(
692
880
  "outpost.dispatch",
@@ -696,13 +884,37 @@ var DispatchMessage = class {
696
884
  if (!fresh || fresh.state !== "sending") {
697
885
  return { kind: "skipped", reason: "no longer in sending state" };
698
886
  }
887
+ try {
888
+ await deps.audit.append({
889
+ messageId: fresh.id,
890
+ eventType: "dispatch_started",
891
+ actor: "system:dispatch",
892
+ detail: { provider: fresh.provider }
893
+ });
894
+ } catch (err) {
895
+ this.logWrite("dispatch_started audit failed; dispatch continues", fresh.id, err);
896
+ }
897
+ let listed;
898
+ try {
899
+ listed = await deps.suppressions.isSuppressed(fresh.recipientHmac);
900
+ } catch (err) {
901
+ return this.handleError(fresh, claim, err);
902
+ }
903
+ if (listed) return this.suppressListed(fresh, claim);
699
904
  const provider = deps.providers.get(fresh.provider);
700
905
  if (!provider) {
701
- return this.fail(fresh, `No provider registered for "${fresh.provider}"`);
906
+ return this.fail(fresh, claim, `No provider registered for "${fresh.provider}"`);
702
907
  }
908
+ let receipt;
703
909
  try {
704
- const to = await deps.openEncryptor.open(fresh.recipientSealed);
705
- const bodyJson = await deps.openEncryptor.open(fresh.bodySealed);
910
+ const to = await deps.openEncryptor.open(fresh.recipientSealed, {
911
+ messageId: fresh.id,
912
+ column: "recipient"
913
+ });
914
+ const bodyJson = await deps.openEncryptor.open(fresh.bodySealed, {
915
+ messageId: fresh.id,
916
+ column: "body"
917
+ });
706
918
  const body = JSON.parse(bodyJson);
707
919
  const cleanTo = sanitizeRecipient(to, deps.config.sanitize);
708
920
  const cleanSubject = sanitizeSubject(fresh.subject, deps.config.sanitize);
@@ -714,7 +926,7 @@ var DispatchMessage = class {
714
926
  });
715
927
  const limited = await this.checkRateLimits(fresh.provider, cleanTo);
716
928
  if (limited) {
717
- return this.requeueRateLimited(fresh);
929
+ return this.requeueRateLimited(fresh, claim);
718
930
  }
719
931
  const dispatchable = {
720
932
  id: fresh.id,
@@ -724,91 +936,175 @@ var DispatchMessage = class {
724
936
  headers: this.buildHeaders(),
725
937
  metadata: fresh.metadata
726
938
  };
727
- const receipt = await provider.send(dispatchable);
728
- await deps.outbox.updateState(fresh.id, {
939
+ receipt = await provider.send(dispatchable);
940
+ } catch (err) {
941
+ return this.handleError(fresh, claim, err);
942
+ }
943
+ const wrote = await this.commitWhileSending(
944
+ fresh.id,
945
+ {
729
946
  state: "sent",
730
947
  providerMessageId: receipt.providerMessageId,
731
948
  lastError: null
732
- });
949
+ },
950
+ claim,
951
+ true
952
+ );
953
+ if (!wrote) return { kind: "skipped", reason: "claim lost" };
954
+ try {
733
955
  await deps.audit.append({
734
956
  messageId: fresh.id,
735
957
  eventType: "dispatch_accepted",
736
958
  actor: `provider:${fresh.provider}`,
737
959
  detail: { providerMessageId: receipt.providerMessageId }
738
960
  });
739
- deps.telemetry.counter("outpost.dispatch.sent", 1, { provider: fresh.provider });
740
- return { kind: "sent", providerMessageId: receipt.providerMessageId };
741
961
  } catch (err) {
742
- return this.handleError(fresh, err);
962
+ this.logWrite("dispatch audit failed after sent; message stays sent", fresh.id, err);
963
+ }
964
+ try {
965
+ await this.webhooks.applyPending(receipt.providerMessageId);
966
+ } catch (err) {
967
+ this.logWrite("pending webhook apply failed after sent; message stays sent", fresh.id, err);
743
968
  }
969
+ deps.telemetry.counter("outpost.dispatch.sent", 1, { provider: fresh.provider });
970
+ return { kind: "sent", providerMessageId: receipt.providerMessageId };
744
971
  }
745
972
  );
746
973
  }
747
- /** Classify the error and either retry-with-backoff or dead-letter. */
748
- async handleError(message, err) {
749
- const permanent = err instanceof ProviderError && err.errorClass === "permanent";
750
- const reason = err instanceof Error ? err.message : String(err);
974
+ /**
975
+ * Recipient was listed after enqueue. `sending` → `suppressed` on the
976
+ * stored HMAC. Do not decrypt, call the provider, or add a suppression row.
977
+ * A lost claim does not audit. An audit failure leaves the row suppressed.
978
+ */
979
+ async suppressListed(message, claim) {
980
+ const wrote = await this.commitWhileSending(message.id, { state: "suppressed" }, claim);
981
+ if (!wrote) return { kind: "skipped", reason: "claim lost" };
982
+ try {
983
+ await this.deps.audit.append({
984
+ messageId: message.id,
985
+ eventType: "suppressed",
986
+ actor: "system:dispatch",
987
+ detail: { reason: "recipient_on_suppression_list" }
988
+ });
989
+ } catch (err) {
990
+ this.logWrite("dispatch audit failed after suppressed; message stays suppressed", message.id, err);
991
+ }
992
+ return { kind: "skipped", reason: "recipient suppressed" };
993
+ }
994
+ /** Classify a provider or pipeline error and either retry or dead-letter. */
995
+ async handleError(message, claim, err) {
996
+ const permanent = classifyProviderFailure(err) === "permanent";
997
+ const reason = failureReason(err);
751
998
  if (permanent) {
752
- return this.fail(message, reason);
999
+ return this.fail(message, claim, reason);
753
1000
  }
754
1001
  const attempts = message.attempts + 1;
755
1002
  if (isExhausted(attempts, this.deps.config.retry)) {
756
- return this.fail(message, `Retries exhausted (${attempts}): ${reason}`, attempts);
1003
+ return this.fail(message, claim, `Retries exhausted (${attempts}): ${reason}`, attempts);
757
1004
  }
758
1005
  const delay = backoffMs(attempts, this.deps.config.retry, this.deps.random());
759
1006
  const nextAttemptAt2 = new Date(this.deps.clock.now().getTime() + delay);
760
- await this.deps.outbox.updateState(message.id, {
761
- state: "queued",
762
- attempts,
763
- nextAttemptAt: nextAttemptAt2,
764
- lastError: reason
765
- });
766
- await this.deps.audit.append({
767
- messageId: message.id,
768
- eventType: "retry_scheduled",
769
- actor: `provider:${message.provider}`,
770
- detail: { attempts, nextAttemptAt: nextAttemptAt2.toISOString(), reason }
771
- });
1007
+ const wrote = await this.commitWhileSending(
1008
+ message.id,
1009
+ { state: "queued", attempts, nextAttemptAt: nextAttemptAt2, lastError: reason, providerMessageId: null },
1010
+ claim
1011
+ );
1012
+ if (!wrote) return { kind: "skipped", reason: "claim lost" };
1013
+ try {
1014
+ await this.deps.audit.append({
1015
+ messageId: message.id,
1016
+ eventType: "retry_scheduled",
1017
+ actor: `provider:${message.provider}`,
1018
+ detail: { attempts, nextAttemptAt: nextAttemptAt2.toISOString(), reason }
1019
+ });
1020
+ } catch (auditErr) {
1021
+ this.logWrite("retry audit failed after requeue", message.id, auditErr);
1022
+ }
772
1023
  this.deps.telemetry.counter("outpost.dispatch.retry", 1, { provider: message.provider });
773
1024
  return { kind: "retry", nextAttemptAt: nextAttemptAt2 };
774
1025
  }
775
1026
  /** Move to `failed` (terminal) and record in the Dead Letter Queue. */
776
- async fail(message, reason, attempts) {
777
- await this.deps.outbox.updateState(message.id, {
778
- state: "failed",
779
- attempts: attempts ?? message.attempts,
780
- lastError: reason
781
- });
782
- await this.deps.audit.append({
783
- messageId: message.id,
784
- eventType: "dead_lettered",
785
- actor: `provider:${message.provider}`,
786
- detail: { reason }
787
- });
1027
+ async fail(message, claim, reason, attempts) {
1028
+ const wrote = await this.commitWhileSending(
1029
+ message.id,
1030
+ { state: "failed", attempts: attempts ?? message.attempts, lastError: reason },
1031
+ claim
1032
+ );
1033
+ if (!wrote) return { kind: "skipped", reason: "claim lost" };
1034
+ try {
1035
+ await this.deps.audit.append({
1036
+ messageId: message.id,
1037
+ eventType: "dead_lettered",
1038
+ actor: `provider:${message.provider}`,
1039
+ detail: { reason }
1040
+ });
1041
+ } catch (auditErr) {
1042
+ this.logWrite("dead-letter audit failed after failed", message.id, auditErr);
1043
+ }
788
1044
  this.deps.telemetry.counter("outpost.dispatch.failed", 1, { provider: message.provider });
789
1045
  return { kind: "failed", reason };
790
1046
  }
791
1047
  /** Re-queue without counting a failed attempt; short, jittered backoff. */
792
- async requeueRateLimited(message) {
1048
+ async requeueRateLimited(message, claim) {
793
1049
  const delay = 1e3 + Math.floor(this.deps.random() * 4e3);
794
1050
  const nextAttemptAt2 = new Date(this.deps.clock.now().getTime() + delay);
795
- await this.deps.outbox.updateState(message.id, {
796
- state: "queued",
797
- nextAttemptAt: nextAttemptAt2
798
- });
1051
+ const wrote = await this.commitWhileSending(
1052
+ message.id,
1053
+ { state: "queued", nextAttemptAt: nextAttemptAt2, providerMessageId: null },
1054
+ claim
1055
+ );
1056
+ if (!wrote) return { kind: "skipped", reason: "claim lost" };
799
1057
  this.deps.telemetry.counter("outpost.dispatch.rate_limited", 1, { provider: message.provider });
800
1058
  return { kind: "rate_limited", nextAttemptAt: nextAttemptAt2 };
801
1059
  }
1060
+ /**
1061
+ * Fence write. `false` means the claim no longer owns the row, or the driver
1062
+ * threw. Neither path is a provider retry. When the provider may already
1063
+ * have accepted, the log says so and the caller leaves the row alone.
1064
+ */
1065
+ async commitWhileSending(id, patch, claim, providerMayHaveAccepted = false) {
1066
+ const write = this.deps.outbox.updateStateWhileSending;
1067
+ if (!write) {
1068
+ throw new Error("OutboxRepository.updateStateWhileSending is required to dispatch");
1069
+ }
1070
+ try {
1071
+ const wrote = await write.call(this.deps.outbox, id, patch, claim);
1072
+ if (!wrote && providerMayHaveAccepted) {
1073
+ this.deps.logger.log(
1074
+ "error",
1075
+ "provider may already have accepted; claim lost and the row was left unchanged",
1076
+ { messageId: id }
1077
+ );
1078
+ }
1079
+ return wrote;
1080
+ } catch (err) {
1081
+ this.logWrite(
1082
+ providerMayHaveAccepted ? "provider may already have accepted; state write failed and the row was left unchanged" : "dispatch state write failed and the row was left unchanged",
1083
+ id,
1084
+ err
1085
+ );
1086
+ return false;
1087
+ }
1088
+ }
1089
+ logWrite(message, messageId, err) {
1090
+ this.deps.logger.log("error", message, {
1091
+ messageId,
1092
+ error: err instanceof Error ? err.message : String(err)
1093
+ });
1094
+ }
802
1095
  async checkRateLimits(provider, to) {
803
- const checks = [
804
- this.deps.rateLimiter.acquire({ kind: "global" }),
805
- this.deps.rateLimiter.acquire({ kind: "provider", key: provider }),
806
- this.deps.rateLimiter.acquire({ kind: "recipientDomain", key: extractDomain(to) })
1096
+ const scopes = [
1097
+ { kind: "global" },
1098
+ { kind: "provider", key: provider },
1099
+ { kind: "recipientDomain", key: extractDomain(to) }
807
1100
  ];
808
- const results = await Promise.all(checks);
1101
+ if (this.deps.rateLimiter.acquireAll) {
1102
+ return !await this.deps.rateLimiter.acquireAll(scopes);
1103
+ }
1104
+ const results = await Promise.all(scopes.map((scope) => this.deps.rateLimiter.acquire(scope)));
809
1105
  return results.some((ok) => ok === false);
810
1106
  }
811
- /** List-Unsubscribe and other always-on headers (TDR §3.11). */
1107
+ /** No headers are added. List-Unsubscribe is not set. */
812
1108
  buildHeaders() {
813
1109
  return {};
814
1110
  }
@@ -897,12 +1193,20 @@ var PurgeRetention = class {
897
1193
  const now = deps.clock.now();
898
1194
  const policy = deps.config.retention;
899
1195
  const cutoff = purgeCutoff(policy, now);
1196
+ const pauseMs = normalizeBatchPauseMs(policy.batchPauseMs);
1197
+ const redactEligible = deps.outbox.redactBatchIfEligible;
1198
+ const deleteEligible = deps.outbox.deleteBatchIfEligible;
1199
+ if (typeof redactEligible !== "function" || typeof deleteEligible !== "function") {
1200
+ throw new Error(
1201
+ "OutboxRepository must implement redactBatchIfEligible and deleteBatchIfEligible. Retention throws before it writes and does not call redactBatch or deleteBatch."
1202
+ );
1203
+ }
900
1204
  let operationalProcessed = 0;
901
1205
  for (; ; ) {
902
1206
  const batch = await deps.outbox.claimTerminalForPurge(cutoff, policy.batchSize);
903
1207
  if (batch.length === 0) break;
904
1208
  const ids = batch.map((m) => m.id);
905
- const count = policy.redactOnPurge ? await deps.outbox.redactBatch(ids) : await deps.outbox.deleteBatch(ids);
1209
+ const count = policy.redactOnPurge ? await redactEligible.call(deps.outbox, ids, cutoff) : await deleteEligible.call(deps.outbox, ids, cutoff);
906
1210
  operationalProcessed += count;
907
1211
  await deps.audit.append({
908
1212
  messageId: null,
@@ -911,14 +1215,18 @@ var PurgeRetention = class {
911
1215
  detail: { count, cutoff: cutoff.toISOString() }
912
1216
  });
913
1217
  if (batch.length < policy.batchSize) break;
1218
+ await waitForBatchPause(pauseMs);
914
1219
  }
1220
+ const deleteWebhooks = deps.webhookEvents.deleteOlderThan;
1221
+ const webhooksDeleted = typeof deleteWebhooks === "function" ? await deleteWebhooks.call(deps.webhookEvents, cutoff) : 0;
915
1222
  const auditCutoff = new Date(now.getTime() - policy.auditTtlDays * 24 * 60 * 60 * 1e3);
916
- const auditDeleted = await deps.audit.purgeOlderThan(auditCutoff, policy.batchSize);
1223
+ const auditDeleted = await deps.audit.purgeOlderThan(auditCutoff, policy.batchSize, pauseMs);
917
1224
  deps.telemetry.gauge("outpost.retention.operational_processed", operationalProcessed);
918
1225
  deps.telemetry.gauge("outpost.retention.audit_deleted", auditDeleted);
919
1226
  deps.logger.log("info", "retention cycle complete", {
920
1227
  operationalProcessed,
921
1228
  auditDeleted,
1229
+ webhooksDeleted,
922
1230
  redacted: policy.redactOnPurge
923
1231
  });
924
1232
  return { operationalProcessed, auditDeleted, redacted: policy.redactOnPurge };
@@ -936,31 +1244,44 @@ var RetentionWorker = class {
936
1244
  purge;
937
1245
  running = false;
938
1246
  timer = null;
1247
+ inFlight = false;
939
1248
  async tick() {
940
1249
  return this.purge.execute();
941
1250
  }
942
1251
  start() {
943
1252
  if (this.running) return;
944
1253
  this.running = true;
945
- const interval = this.options.intervalMs ?? 60 * 60 * 1e3;
946
- const loop = async () => {
947
- if (!this.running) return;
948
- try {
949
- await this.tick();
950
- } catch (err) {
951
- this.deps.logger.log("error", "retention worker tick failed", {
952
- error: err instanceof Error ? err.message : String(err)
953
- });
954
- } finally {
955
- if (this.running) this.timer = setTimeout(loop, interval);
956
- }
957
- };
958
- void loop();
1254
+ void this.runLoopTick();
959
1255
  }
960
1256
  stop() {
961
1257
  this.running = false;
962
- if (this.timer) clearTimeout(this.timer);
963
- this.timer = null;
1258
+ if (this.timer !== null) {
1259
+ clearTimeout(this.timer);
1260
+ this.timer = null;
1261
+ }
1262
+ }
1263
+ intervalMs() {
1264
+ return this.options.intervalMs ?? 60 * 60 * 1e3;
1265
+ }
1266
+ async runLoopTick() {
1267
+ if (this.inFlight) return;
1268
+ if (!this.running) return;
1269
+ this.inFlight = true;
1270
+ try {
1271
+ await this.tick();
1272
+ } catch (err) {
1273
+ this.deps.logger.log("error", "retention worker tick failed", {
1274
+ error: err instanceof Error ? err.message : String(err)
1275
+ });
1276
+ } finally {
1277
+ this.inFlight = false;
1278
+ if (this.running) {
1279
+ this.timer = setTimeout(() => {
1280
+ this.timer = null;
1281
+ void this.runLoopTick();
1282
+ }, this.intervalMs());
1283
+ }
1284
+ }
964
1285
  }
965
1286
  };
966
1287
 
@@ -994,7 +1315,7 @@ var Outpost = class {
994
1315
  send(input, opts) {
995
1316
  return this.enqueueMessage.execute(input, opts?.actor ?? this.defaultActor);
996
1317
  }
997
- /** Fetch a message's lifecycle + metadata (PII-free view). */
1318
+ /** Fetch lifecycle and metadata. The body and recipient address are omitted. */
998
1319
  get(id) {
999
1320
  return this.getMessage.execute(id);
1000
1321
  }
@@ -1053,12 +1374,20 @@ var HmacRecipientHasher = class {
1053
1374
  }
1054
1375
  };
1055
1376
  var PLAIN_ALG = "plain";
1377
+ function aadBytes(context) {
1378
+ return Buffer.from(`${context.messageId}:${context.column}`, "utf8");
1379
+ }
1380
+ function assertKeyId(sealed, keyId) {
1381
+ if (sealed.keyId !== void 0 && sealed.keyId !== keyId) {
1382
+ throw new Error("Sealed value keyId does not match this encryptor");
1383
+ }
1384
+ }
1056
1385
  var NoopEncryptor = class {
1057
1386
  alg = PLAIN_ALG;
1058
- async seal(plaintext) {
1387
+ async seal(plaintext, _context) {
1059
1388
  return { alg: PLAIN_ALG, ciphertext: Buffer.from(plaintext, "utf8").toString("base64") };
1060
1389
  }
1061
- async open(sealed) {
1390
+ async open(sealed, _context) {
1062
1391
  return Buffer.from(sealed.ciphertext, "base64").toString("utf8");
1063
1392
  }
1064
1393
  };
@@ -1071,9 +1400,10 @@ var AesGcmEncryptor = class {
1071
1400
  }
1072
1401
  alg = AES_ALG;
1073
1402
  key;
1074
- async seal(plaintext) {
1403
+ async seal(plaintext, context) {
1075
1404
  const iv = randomBytes(12);
1076
1405
  const cipher = createCipheriv(AES_ALG, this.key, iv);
1406
+ if (context) cipher.setAAD(aadBytes(context));
1077
1407
  const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
1078
1408
  const tag = cipher.getAuthTag();
1079
1409
  return {
@@ -1081,19 +1411,17 @@ var AesGcmEncryptor = class {
1081
1411
  ciphertext: ct.toString("base64"),
1082
1412
  iv: iv.toString("base64"),
1083
1413
  tag: tag.toString("base64"),
1084
- keyId: this.keyId
1414
+ keyId: this.keyId,
1415
+ ...context ? { bound: true } : {}
1085
1416
  };
1086
1417
  }
1087
- async open(sealed) {
1418
+ async open(sealed, context) {
1088
1419
  if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);
1089
- if (!sealed.iv || !sealed.tag) throw new Error("Sealed value missing iv/tag");
1090
- const decipher = createDecipheriv(AES_ALG, this.key, Buffer.from(sealed.iv, "base64"));
1091
- decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
1092
- const pt = Buffer.concat([
1093
- decipher.update(Buffer.from(sealed.ciphertext, "base64")),
1094
- decipher.final()
1095
- ]);
1096
- return pt.toString("utf8");
1420
+ if (context) assertKeyId(sealed, this.keyId);
1421
+ if (sealed.bound && !context) {
1422
+ throw new Error("Sealed value is bound to a message and column");
1423
+ }
1424
+ return decryptAes(this.key, sealed, sealed.bound ? context : void 0);
1097
1425
  }
1098
1426
  };
1099
1427
  var HYBRID_ALG = "hybrid-rsa-aes-256-gcm";
@@ -1106,10 +1434,11 @@ var HybridSealEncryptor = class {
1106
1434
  this.keyId = keyId;
1107
1435
  }
1108
1436
  alg = HYBRID_ALG;
1109
- async seal(plaintext) {
1437
+ async seal(plaintext, context) {
1110
1438
  const dataKey = randomBytes(32);
1111
1439
  const iv = randomBytes(12);
1112
1440
  const cipher = createCipheriv(AES_ALG, dataKey, iv);
1441
+ if (context) cipher.setAAD(aadBytes(context));
1113
1442
  const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
1114
1443
  const tag = cipher.getAuthTag();
1115
1444
  const wrappedKey = publicEncrypt(rsaOaep(this.publicKeyPem), dataKey);
@@ -1119,7 +1448,8 @@ var HybridSealEncryptor = class {
1119
1448
  iv: iv.toString("base64"),
1120
1449
  tag: tag.toString("base64"),
1121
1450
  wrappedKey: wrappedKey.toString("base64"),
1122
- keyId: this.keyId
1451
+ keyId: this.keyId,
1452
+ ...context ? { bound: true } : {}
1123
1453
  };
1124
1454
  }
1125
1455
  async open() {
@@ -1129,15 +1459,20 @@ var HybridSealEncryptor = class {
1129
1459
  }
1130
1460
  };
1131
1461
  var HybridOpenEncryptor = class {
1132
- constructor(privateKeyPem) {
1462
+ constructor(privateKeyPem, keyId = "default") {
1133
1463
  this.privateKeyPem = privateKeyPem;
1464
+ this.keyId = keyId;
1134
1465
  }
1135
1466
  alg = HYBRID_ALG;
1136
1467
  async seal() {
1137
1468
  throw new Error("HybridOpenEncryptor is read-only; use HybridSealEncryptor to seal");
1138
1469
  }
1139
- async open(sealed) {
1470
+ async open(sealed, context) {
1140
1471
  if (sealed.alg === PLAIN_ALG) return new NoopEncryptor().open(sealed);
1472
+ if (context) assertKeyId(sealed, this.keyId);
1473
+ if (sealed.bound && !context) {
1474
+ throw new Error("Sealed value is bound to a message and column");
1475
+ }
1141
1476
  if (!sealed.wrappedKey || !sealed.iv || !sealed.tag) {
1142
1477
  throw new Error("Sealed value missing wrappedKey/iv/tag for hybrid open");
1143
1478
  }
@@ -1145,15 +1480,20 @@ var HybridOpenEncryptor = class {
1145
1480
  rsaOaep(this.privateKeyPem),
1146
1481
  Buffer.from(sealed.wrappedKey, "base64")
1147
1482
  );
1148
- const decipher = createDecipheriv(AES_ALG, dataKey, Buffer.from(sealed.iv, "base64"));
1149
- decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
1150
- const pt = Buffer.concat([
1151
- decipher.update(Buffer.from(sealed.ciphertext, "base64")),
1152
- decipher.final()
1153
- ]);
1154
- return pt.toString("utf8");
1483
+ return decryptAes(dataKey, sealed, sealed.bound ? context : void 0);
1155
1484
  }
1156
1485
  };
1486
+ function decryptAes(key, sealed, context) {
1487
+ if (!sealed.iv || !sealed.tag) throw new Error("Sealed value missing iv/tag");
1488
+ const decipher = createDecipheriv(AES_ALG, key, Buffer.from(sealed.iv, "base64"));
1489
+ if (context) decipher.setAAD(aadBytes(context));
1490
+ decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
1491
+ const pt = Buffer.concat([
1492
+ decipher.update(Buffer.from(sealed.ciphertext, "base64")),
1493
+ decipher.final()
1494
+ ]);
1495
+ return pt.toString("utf8");
1496
+ }
1157
1497
 
1158
1498
  // src/adapters/rate-limit/in-memory.ts
1159
1499
  var InMemoryRateLimiter = class {
@@ -1165,23 +1505,40 @@ var InMemoryRateLimiter = class {
1165
1505
  async acquire(scope) {
1166
1506
  const budget = this.budgetFor(scope);
1167
1507
  if (!budget) return true;
1168
- const key = `${scope.kind}:${scope.key ?? ""}`;
1508
+ const bucket = this.refill(`${scope.kind}:${scope.key ?? ""}`, budget, this.clock.now().getTime());
1509
+ if (bucket.tokens >= 1) {
1510
+ bucket.tokens -= 1;
1511
+ return true;
1512
+ }
1513
+ return false;
1514
+ }
1515
+ async acquireAll(scopes) {
1169
1516
  const now = this.clock.now().getTime();
1170
- const refillRate = budget.max / budget.windowMs;
1517
+ const ready = /* @__PURE__ */ new Map();
1518
+ let allowed = true;
1519
+ for (const scope of scopes) {
1520
+ const budget = this.budgetFor(scope);
1521
+ if (!budget) continue;
1522
+ const key = `${scope.kind}:${scope.key ?? ""}`;
1523
+ const bucket = this.refill(key, budget, now);
1524
+ if (bucket.tokens < 1) allowed = false;
1525
+ else ready.set(key, bucket);
1526
+ }
1527
+ if (!allowed) return false;
1528
+ for (const bucket of ready.values()) bucket.tokens -= 1;
1529
+ return true;
1530
+ }
1531
+ refill(key, budget, now) {
1171
1532
  let bucket = this.buckets.get(key);
1172
1533
  if (!bucket) {
1173
1534
  bucket = { tokens: budget.max, lastRefill: now };
1174
1535
  this.buckets.set(key, bucket);
1175
- } else {
1176
- const elapsed = now - bucket.lastRefill;
1177
- bucket.tokens = Math.min(budget.max, bucket.tokens + elapsed * refillRate);
1178
- bucket.lastRefill = now;
1179
- }
1180
- if (bucket.tokens >= 1) {
1181
- bucket.tokens -= 1;
1182
- return true;
1536
+ return bucket;
1183
1537
  }
1184
- return false;
1538
+ const elapsed = now - bucket.lastRefill;
1539
+ bucket.tokens = Math.min(budget.max, bucket.tokens + elapsed * (budget.max / budget.windowMs));
1540
+ bucket.lastRefill = now;
1541
+ return bucket;
1185
1542
  }
1186
1543
  budgetFor(scope) {
1187
1544
  switch (scope.kind) {
@@ -1198,6 +1555,9 @@ var UnlimitedRateLimiter = class {
1198
1555
  async acquire() {
1199
1556
  return true;
1200
1557
  }
1558
+ async acquireAll() {
1559
+ return true;
1560
+ }
1201
1561
  };
1202
1562
  var SystemClock = class {
1203
1563
  now() {
@@ -1256,7 +1616,8 @@ function createOutpost(options) {
1256
1616
  attachments: options.attachments,
1257
1617
  domainValidation: options.domainValidation,
1258
1618
  rateLimits: options.rateLimits,
1259
- sendBatchSize: options.sendBatchSize
1619
+ sendBatchSize: options.sendBatchSize,
1620
+ staleSendingLeaseMs: options.staleSendingLeaseMs
1260
1621
  });
1261
1622
  if (options.providers.length === 0) {
1262
1623
  throw new Error("createOutpost requires at least one provider");
@@ -1311,7 +1672,7 @@ function resolveEncryption(enc) {
1311
1672
  }
1312
1673
  case "asymmetric": {
1313
1674
  const seal = new HybridSealEncryptor(enc.publicKey, enc.keyId);
1314
- const open = enc.privateKey ? new HybridOpenEncryptor(enc.privateKey) : seal;
1675
+ const open = enc.privateKey ? new HybridOpenEncryptor(enc.privateKey, enc.keyId) : seal;
1315
1676
  return { sealEncryptor: seal, openEncryptor: open };
1316
1677
  }
1317
1678
  }
@@ -1326,6 +1687,6 @@ var SUPPRESSION_REASONS = [
1326
1687
  "manual"
1327
1688
  ];
1328
1689
 
1329
- export { API_SCOPES, Authenticate, DEFAULT_ATTACHMENT_POLICY, DEFAULT_DOMAIN_VALIDATION, DEFAULT_RETENTION, DEFAULT_RETRY, DEFAULT_SANITIZE_LIMITS, DispatchMessage, EnqueueMessage, ForbiddenError, GetMessage, IngestWebhook, InvalidStateTransitionError, LIFECYCLE_STATES, ListMessages, ManageApiKey, ManageSuppression, MxCache, NotFoundError, Outpost, OutpostError, ProviderError, PurgeRetention, ReplayMessage, SUPPRESSION_REASONS, TERMINAL_STATES, UnauthorizedError, ValidationError, WebhookVerificationError, assertBodyWithinLimits, assertNoHeaderInjection, backoffMs, canTransition, createOutpost, extractDomain, generateApiKeySecret, hasScope, hashApiKey, isExhausted, isKeyActive, isTerminal, isTransient, nextAttemptAt, purgeCutoff, resolveConfig, sanitizeHeaders, sanitizeRecipient, sanitizeSubject, shouldSuppressOn, stripDangerousHtml, toView, validateAttachment, validateRecipient, validateSyntax, webhookToState };
1690
+ export { API_SCOPES, Authenticate, DEFAULT_ATTACHMENT_POLICY, DEFAULT_DOMAIN_VALIDATION, DEFAULT_RETENTION, DEFAULT_RETRY, DEFAULT_SANITIZE_LIMITS, DispatchMessage, EnqueueMessage, ForbiddenError, GetMessage, IngestWebhook, InvalidStateTransitionError, LIFECYCLE_STATES, ListMessages, ManageApiKey, ManageSuppression, MxCache, NotFoundError, Outpost, OutpostError, ProviderError, PurgeRetention, ReplayMessage, SUPPRESSION_REASONS, TERMINAL_STATES, UnauthorizedError, ValidationError, WebhookVerificationError, assertBodyWithinLimits, assertNoHeaderInjection, backoffMs, canTransition, createOutpost, extractDomain, generateApiKeySecret, hasScope, hashApiKey, isExhausted, isKeyActive, isTerminal, isTransient, nextAttemptAt, normalizeBatchPauseMs, purgeCutoff, resolveConfig, sanitizeHeaders, sanitizeRecipient, sanitizeSubject, shouldSuppressOn, stripDangerousHtml, toView, validateAttachment, validateRecipient, validateSyntax, waitForBatchPause, webhookToState };
1330
1691
  //# sourceMappingURL=index.js.map
1331
1692
  //# sourceMappingURL=index.js.map