@tgoliveira/outpost 1.2.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) 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 +38 -21
  36. package/dist/modules/ui/index.cjs.map +1 -1
  37. package/dist/modules/ui/index.js +38 -21
  38. package/dist/modules/ui/index.js.map +1 -1
  39. package/dist/modules/ui/pages/admin/admin-config-page.cjs +39 -20
  40. package/dist/modules/ui/pages/admin/admin-config-page.cjs.map +1 -1
  41. package/dist/modules/ui/pages/admin/admin-config-page.d.cts +23 -1
  42. package/dist/modules/ui/pages/admin/admin-config-page.d.ts +23 -1
  43. package/dist/modules/ui/pages/admin/admin-config-page.js +38 -20
  44. package/dist/modules/ui/pages/admin/admin-config-page.js.map +1 -1
  45. package/dist/modules/ui/pages/admin/admin-panel-page.cjs +1 -1
  46. package/dist/modules/ui/pages/admin/admin-panel-page.js +1 -1
  47. package/dist/modules/ui/pages/index.cjs +38 -21
  48. package/dist/modules/ui/pages/index.cjs.map +1 -1
  49. package/dist/modules/ui/pages/index.js +38 -21
  50. package/dist/modules/ui/pages/index.js.map +1 -1
  51. package/dist/{outpost-client-BItbgqIo.d.ts → outpost-client-BX3SsOFb.d.ts} +50 -21
  52. package/dist/{outpost-client-BlVf4gjo.d.cts → outpost-client-DhQgZY16.d.cts} +50 -21
  53. package/dist/react/index.cjs +38 -21
  54. package/dist/react/index.cjs.map +1 -1
  55. package/dist/react/index.js +38 -21
  56. package/dist/react/index.js.map +1 -1
  57. package/dist/repositories-DJYu4nGV.d.ts +322 -0
  58. package/dist/repositories-sMN6RHZJ.d.cts +322 -0
  59. package/dist/{services-CfTEsetF.d.ts → services-DZwZjDn_.d.cts} +9 -3
  60. package/dist/{services-CQINhAGo.d.cts → services-PoM2bxjP.d.ts} +9 -3
  61. package/dist/{template-DxI_p2Ny.d.cts → template-Dl1_ciRo.d.ts} +24 -4
  62. package/dist/{template-CREUq7bB.d.ts → template-Dny_7Ymi.d.cts} +24 -4
  63. package/dist/testing/index.cjs +200 -15
  64. package/dist/testing/index.cjs.map +1 -1
  65. package/dist/testing/index.d.cts +26 -7
  66. package/dist/testing/index.d.ts +26 -7
  67. package/dist/testing/index.js +200 -15
  68. package/dist/testing/index.js.map +1 -1
  69. package/dist/{webhook-kp6CiXk-.d.cts → webhook-B158Vi6p.d.cts} +20 -4
  70. package/dist/{webhook-kp6CiXk-.d.ts → webhook-B158Vi6p.d.ts} +20 -4
  71. package/dist/workers/index.cjs +471 -85
  72. package/dist/workers/index.cjs.map +1 -1
  73. package/dist/workers/index.d.cts +5 -5
  74. package/dist/workers/index.d.ts +5 -5
  75. package/dist/workers/index.js +471 -85
  76. package/dist/workers/index.js.map +1 -1
  77. package/package.json +6 -3
  78. package/dist/repositories-CHIOFGn3.d.cts +0 -182
  79. package/dist/repositories-WyhvxzyY.d.ts +0 -182
@@ -1,4 +1,4 @@
1
- import { D as DispatchableMessage, W as WebhookEvent } from './webhook-kp6CiXk-.cjs';
1
+ import { D as DispatchableMessage, W as WebhookEvent } from './webhook-B158Vi6p.js';
2
2
 
3
3
  /**
4
4
  * Receipt returned by a provider when it accepts a message for delivery.
@@ -35,11 +35,12 @@ interface EmailProvider {
35
35
  send(msg: DispatchableMessage): Promise<ProviderReceipt>;
36
36
  /**
37
37
  * Verify a raw inbound webhook and normalize it. Throws
38
- * `WebhookVerificationError` if the signature is invalid. Returning a
38
+ * `WebhookVerificationError` if the signature is invalid. `null` means the
39
+ * signature was valid and the event has no lifecycle effect. Returning a
39
40
  * uniform `WebhookEvent` is what enables provider fallback and one ingestion
40
41
  * path for all providers.
41
42
  */
42
- verifyWebhook(req: RawWebhook): Promise<WebhookEvent>;
43
+ verifyWebhook(req: RawWebhook): Promise<WebhookEvent | null>;
43
44
  }
44
45
 
45
46
  /**
@@ -59,6 +60,11 @@ interface RateLimitScope {
59
60
  */
60
61
  interface RateLimiter {
61
62
  acquire(scope: RateLimitScope): Promise<boolean>;
63
+ /**
64
+ * Take one token from every listed scope, or from none of them.
65
+ * A limiter without this method is still called once per scope.
66
+ */
67
+ acquireAll?(scopes: readonly RateLimitScope[]): Promise<boolean>;
62
68
  }
63
69
  /** Injectable clock — keeps use cases deterministic and testable. */
64
70
  interface Clock {
@@ -1,4 +1,4 @@
1
- import { S as Sealed, b as MessageBody } from './webhook-kp6CiXk-.cjs';
1
+ import { S as Sealed, b as MessageBody } from './webhook-B158Vi6p.js';
2
2
 
3
3
  /**
4
4
  * Encryption ports (TDR §5.4).
@@ -9,16 +9,27 @@ import { S as Sealed, b as MessageBody } from './webhook-kp6CiXk-.cjs';
9
9
  * the open-capable one (private key). Compromising the web API therefore can
10
10
  * never read plaintext bodies back.
11
11
  */
12
+ /** Column a sealed value is bound to. The address and the body are not part of this. */
13
+ type SealColumn = "recipient" | "body";
14
+ /**
15
+ * Binds a new ciphertext to one outbox row and one column.
16
+ * Omit it and seal/open keep the previous behavior, so an older envelope still opens.
17
+ */
18
+ interface SealContext {
19
+ readonly messageId: string;
20
+ readonly column: SealColumn;
21
+ }
12
22
  interface Encryptor {
13
23
  /** Algorithm tag stamped onto produced `Sealed` values. */
14
24
  readonly alg: string;
15
25
  /** Encrypt plaintext for storage at rest. */
16
- seal(plaintext: string): Promise<Sealed>;
26
+ seal(plaintext: string, context?: SealContext): Promise<Sealed>;
17
27
  /**
18
28
  * Decrypt a sealed value. Seal-only encryptors (public-key ingestion side)
19
29
  * reject this with an error — by construction they cannot read.
30
+ * When `context` is set, a bound envelope must match that message id and column.
20
31
  */
21
- open(sealed: Sealed): Promise<string>;
32
+ open(sealed: Sealed, context?: SealContext): Promise<string>;
22
33
  }
23
34
  /**
24
35
  * Deterministic keyed HMAC of a recipient address. Used as the searchable
@@ -182,8 +193,17 @@ interface RetentionPolicy {
182
193
  readonly webhookWindowHours: number;
183
194
  /** Rows deleted/redacted per batch, to avoid long table locks. */
184
195
  readonly batchSize: number;
196
+ /**
197
+ * Milliseconds to wait after a full batch before the next one.
198
+ * A short batch does not wait. A non-finite or non-positive value does not wait.
199
+ */
200
+ readonly batchPauseMs: number;
185
201
  }
186
202
  declare const DEFAULT_RETENTION: RetentionPolicy;
203
+ /** Pause used between full retention batches. Non-finite and non-positive values wait 0ms. */
204
+ declare function normalizeBatchPauseMs(ms: number): number;
205
+ /** Resolves immediately when `ms` is not a positive finite duration. */
206
+ declare function waitForBatchPause(ms: number): Promise<void>;
187
207
  /**
188
208
  * The cutoff before which a terminal message becomes eligible for purge:
189
209
  * it must be older than the operational TTL AND past the webhook window.
@@ -257,4 +277,4 @@ interface TemplateRenderer {
257
277
  }): Promise<RenderedTemplate>;
258
278
  }
259
279
 
260
- export { type AttachmentPolicy as A, validateRecipient as B, type ConfigOverrides as C, DEFAULT_ATTACHMENT_POLICY as D, type Encryptor as E, validateSyntax as F, type MxResolver as M, type RateLimitConfig as R, type SanitizeLimits as S, type TemplateRenderer as T, type AttachmentSpec as a, DEFAULT_DOMAIN_VALIDATION as b, DEFAULT_RETENTION as c, DEFAULT_RETRY as d, DEFAULT_SANITIZE_LIMITS as e, type DomainValidationConfig as f, MxCache as g, type RateBudget as h, type RecipientHasher as i, type RenderedTemplate as j, type ResolvedConfig as k, type RetentionPolicy as l, type RetryConfig as m, assertBodyWithinLimits as n, assertNoHeaderInjection as o, backoffMs as p, extractDomain as q, isExhausted as r, nextAttemptAt as s, purgeCutoff as t, resolveConfig as u, sanitizeHeaders as v, sanitizeRecipient as w, sanitizeSubject as x, stripDangerousHtml as y, validateAttachment as z };
280
+ export { type AttachmentPolicy as A, sanitizeSubject as B, type ConfigOverrides as C, DEFAULT_ATTACHMENT_POLICY as D, type Encryptor as E, stripDangerousHtml as F, validateAttachment as G, validateRecipient as H, validateSyntax as I, waitForBatchPause as J, type MxResolver as M, type RateLimitConfig as R, type SanitizeLimits as S, type TemplateRenderer as T, type AttachmentSpec as a, DEFAULT_DOMAIN_VALIDATION as b, DEFAULT_RETENTION as c, DEFAULT_RETRY as d, DEFAULT_SANITIZE_LIMITS as e, type DomainValidationConfig as f, MxCache as g, type RateBudget as h, type RecipientHasher as i, type RenderedTemplate as j, type ResolvedConfig as k, type RetentionPolicy as l, type RetryConfig as m, type SealColumn as n, type SealContext as o, assertBodyWithinLimits as p, assertNoHeaderInjection as q, backoffMs as r, extractDomain as s, isExhausted as t, nextAttemptAt as u, normalizeBatchPauseMs as v, purgeCutoff as w, resolveConfig as x, sanitizeHeaders as y, sanitizeRecipient as z };
@@ -1,4 +1,4 @@
1
- import { S as Sealed, b as MessageBody } from './webhook-kp6CiXk-.js';
1
+ import { S as Sealed, b as MessageBody } from './webhook-B158Vi6p.cjs';
2
2
 
3
3
  /**
4
4
  * Encryption ports (TDR §5.4).
@@ -9,16 +9,27 @@ import { S as Sealed, b as MessageBody } from './webhook-kp6CiXk-.js';
9
9
  * the open-capable one (private key). Compromising the web API therefore can
10
10
  * never read plaintext bodies back.
11
11
  */
12
+ /** Column a sealed value is bound to. The address and the body are not part of this. */
13
+ type SealColumn = "recipient" | "body";
14
+ /**
15
+ * Binds a new ciphertext to one outbox row and one column.
16
+ * Omit it and seal/open keep the previous behavior, so an older envelope still opens.
17
+ */
18
+ interface SealContext {
19
+ readonly messageId: string;
20
+ readonly column: SealColumn;
21
+ }
12
22
  interface Encryptor {
13
23
  /** Algorithm tag stamped onto produced `Sealed` values. */
14
24
  readonly alg: string;
15
25
  /** Encrypt plaintext for storage at rest. */
16
- seal(plaintext: string): Promise<Sealed>;
26
+ seal(plaintext: string, context?: SealContext): Promise<Sealed>;
17
27
  /**
18
28
  * Decrypt a sealed value. Seal-only encryptors (public-key ingestion side)
19
29
  * reject this with an error — by construction they cannot read.
30
+ * When `context` is set, a bound envelope must match that message id and column.
20
31
  */
21
- open(sealed: Sealed): Promise<string>;
32
+ open(sealed: Sealed, context?: SealContext): Promise<string>;
22
33
  }
23
34
  /**
24
35
  * Deterministic keyed HMAC of a recipient address. Used as the searchable
@@ -182,8 +193,17 @@ interface RetentionPolicy {
182
193
  readonly webhookWindowHours: number;
183
194
  /** Rows deleted/redacted per batch, to avoid long table locks. */
184
195
  readonly batchSize: number;
196
+ /**
197
+ * Milliseconds to wait after a full batch before the next one.
198
+ * A short batch does not wait. A non-finite or non-positive value does not wait.
199
+ */
200
+ readonly batchPauseMs: number;
185
201
  }
186
202
  declare const DEFAULT_RETENTION: RetentionPolicy;
203
+ /** Pause used between full retention batches. Non-finite and non-positive values wait 0ms. */
204
+ declare function normalizeBatchPauseMs(ms: number): number;
205
+ /** Resolves immediately when `ms` is not a positive finite duration. */
206
+ declare function waitForBatchPause(ms: number): Promise<void>;
187
207
  /**
188
208
  * The cutoff before which a terminal message becomes eligible for purge:
189
209
  * it must be older than the operational TTL AND past the webhook window.
@@ -257,4 +277,4 @@ interface TemplateRenderer {
257
277
  }): Promise<RenderedTemplate>;
258
278
  }
259
279
 
260
- export { type AttachmentPolicy as A, validateRecipient as B, type ConfigOverrides as C, DEFAULT_ATTACHMENT_POLICY as D, type Encryptor as E, validateSyntax as F, type MxResolver as M, type RateLimitConfig as R, type SanitizeLimits as S, type TemplateRenderer as T, type AttachmentSpec as a, DEFAULT_DOMAIN_VALIDATION as b, DEFAULT_RETENTION as c, DEFAULT_RETRY as d, DEFAULT_SANITIZE_LIMITS as e, type DomainValidationConfig as f, MxCache as g, type RateBudget as h, type RecipientHasher as i, type RenderedTemplate as j, type ResolvedConfig as k, type RetentionPolicy as l, type RetryConfig as m, assertBodyWithinLimits as n, assertNoHeaderInjection as o, backoffMs as p, extractDomain as q, isExhausted as r, nextAttemptAt as s, purgeCutoff as t, resolveConfig as u, sanitizeHeaders as v, sanitizeRecipient as w, sanitizeSubject as x, stripDangerousHtml as y, validateAttachment as z };
280
+ export { type AttachmentPolicy as A, sanitizeSubject as B, type ConfigOverrides as C, DEFAULT_ATTACHMENT_POLICY as D, type Encryptor as E, stripDangerousHtml as F, validateAttachment as G, validateRecipient as H, validateSyntax as I, waitForBatchPause as J, type MxResolver as M, type RateLimitConfig as R, type SanitizeLimits as S, type TemplateRenderer as T, type AttachmentSpec as a, DEFAULT_DOMAIN_VALIDATION as b, DEFAULT_RETENTION as c, DEFAULT_RETRY as d, DEFAULT_SANITIZE_LIMITS as e, type DomainValidationConfig as f, MxCache as g, type RateBudget as h, type RecipientHasher as i, type RenderedTemplate as j, type ResolvedConfig as k, type RetentionPolicy as l, type RetryConfig as m, type SealColumn as n, type SealContext as o, assertBodyWithinLimits as p, assertNoHeaderInjection as q, backoffMs as r, extractDomain as s, isExhausted as t, nextAttemptAt as u, normalizeBatchPauseMs as v, purgeCutoff as w, resolveConfig as x, sanitizeHeaders as y, sanitizeRecipient as z };
@@ -14,8 +14,22 @@ var TERMINAL_STATES = [
14
14
  ];
15
15
  new Set(TERMINAL_STATES);
16
16
 
17
+ // src/domain/retention.ts
18
+ function normalizeBatchPauseMs(ms) {
19
+ if (!Number.isFinite(ms) || ms <= 0) return 0;
20
+ return ms;
21
+ }
22
+ function waitForBatchPause(ms) {
23
+ const pause = normalizeBatchPauseMs(ms);
24
+ if (pause === 0) return Promise.resolve();
25
+ return new Promise((resolve) => {
26
+ setTimeout(resolve, pause);
27
+ });
28
+ }
29
+
17
30
  // src/testing/in-memory-repositories.ts
18
31
  var REDACTED = { alg: "redacted", ciphertext: "" };
32
+ var TERMINAL = new Set(TERMINAL_STATES);
19
33
  var InMemoryOutboxRepository = class {
20
34
  /** Optional injected clock so retention/lifecycle is deterministic in tests. */
21
35
  constructor(clock = () => /* @__PURE__ */ new Date()) {
@@ -25,7 +39,7 @@ var InMemoryOutboxRepository = class {
25
39
  async insert(msg) {
26
40
  const now = this.clock();
27
41
  const message = {
28
- id: crypto.randomUUID(),
42
+ id: msg.id ?? crypto.randomUUID(),
29
43
  idempotencyKey: msg.idempotencyKey,
30
44
  state: msg.state,
31
45
  recipientHmac: msg.recipientHmac,
@@ -101,6 +115,17 @@ var InMemoryOutboxRepository = class {
101
115
  async updateState(id, patch) {
102
116
  const m = this.messages.get(id);
103
117
  if (!m) return;
118
+ this.applyPatch(m, patch);
119
+ }
120
+ async updateStateWhileSending(id, patch, claim) {
121
+ const m = this.messages.get(id);
122
+ if (!m || m.state !== "sending" || m.updatedAt.getTime() !== claim.updatedAt.getTime()) {
123
+ return false;
124
+ }
125
+ this.applyPatch(m, patch);
126
+ return true;
127
+ }
128
+ applyPatch(m, patch) {
104
129
  m.state = patch.state;
105
130
  if (patch.attempts !== void 0) m.attempts = patch.attempts;
106
131
  if (patch.nextAttemptAt !== void 0) m.nextAttemptAt = patch.nextAttemptAt;
@@ -109,10 +134,7 @@ var InMemoryOutboxRepository = class {
109
134
  m.updatedAt = this.clock();
110
135
  }
111
136
  async claimTerminalForPurge(olderThan, limit) {
112
- const terminal = new Set(TERMINAL_STATES);
113
- return [...this.messages.values()].filter(
114
- (m) => terminal.has(m.state) && m.updatedAt < olderThan && m.bodySealed.alg !== "redacted"
115
- ).sort((a, b) => a.updatedAt.getTime() - b.updatedAt.getTime()).slice(0, limit).map((m) => ({ ...m }));
137
+ return [...this.messages.values()].filter((m) => this.isPurgeEligible(m, olderThan)).sort((a, b) => a.updatedAt.getTime() - b.updatedAt.getTime()).slice(0, limit).map((m) => ({ ...m }));
116
138
  }
117
139
  async redactBatch(ids) {
118
140
  let n = 0;
@@ -132,6 +154,34 @@ var InMemoryOutboxRepository = class {
132
154
  for (const id of ids) if (this.messages.delete(id)) n++;
133
155
  return n;
134
156
  }
157
+ async redactBatchIfEligible(ids, olderThan) {
158
+ if (ids.length === 0) return 0;
159
+ const wanted = new Set(ids);
160
+ let n = 0;
161
+ for (const message of this.messages.values()) {
162
+ if (!wanted.has(message.id) || !this.isPurgeEligible(message, olderThan)) continue;
163
+ message.recipientSealed = REDACTED;
164
+ message.bodySealed = REDACTED;
165
+ message.updatedAt = this.clock();
166
+ n++;
167
+ }
168
+ return n;
169
+ }
170
+ async deleteBatchIfEligible(ids, olderThan) {
171
+ if (ids.length === 0) return 0;
172
+ let n = 0;
173
+ for (const id of new Set(ids)) {
174
+ const message = this.messages.get(id);
175
+ if (!message || !this.isPurgeEligible(message, olderThan)) continue;
176
+ this.messages.delete(id);
177
+ n++;
178
+ }
179
+ return n;
180
+ }
181
+ /** Same strict predicate as `claimTerminalForPurge`. `olderThan` is the caller's cutoff. */
182
+ isPurgeEligible(message, olderThan) {
183
+ return TERMINAL.has(message.state) && message.updatedAt < olderThan && message.bodySealed.alg !== "redacted";
184
+ }
135
185
  };
136
186
  var InMemorySuppressionRepository = class {
137
187
  entries = /* @__PURE__ */ new Map();
@@ -175,12 +225,19 @@ var InMemoryAuditRepository = class {
175
225
  async listForMessage(messageId) {
176
226
  return this.events.filter((e) => e.messageId === messageId);
177
227
  }
178
- async purgeOlderThan(cutoff, _batchSize) {
179
- const before = this.events.length;
180
- for (let i = this.events.length - 1; i >= 0; i--) {
181
- if (this.events[i].at < cutoff) this.events.splice(i, 1);
228
+ async purgeOlderThan(cutoff, batchSize, pauseMs = 0) {
229
+ const doomed = this.events.filter((event) => event.at < cutoff);
230
+ const size = batchSize > 0 ? batchSize : doomed.length || 1;
231
+ let removed = 0;
232
+ for (let offset = 0; offset < doomed.length; offset += size) {
233
+ const ids = new Set(doomed.slice(offset, offset + size).map((event) => event.id));
234
+ for (let i = this.events.length - 1; i >= 0; i--) {
235
+ if (ids.has(this.events[i].id)) this.events.splice(i, 1);
236
+ }
237
+ removed += ids.size;
238
+ if (ids.size === size) await waitForBatchPause(pauseMs);
182
239
  }
183
- return before - this.events.length;
240
+ return removed;
184
241
  }
185
242
  };
186
243
  var InMemoryApiKeyRepository = class {
@@ -222,11 +279,87 @@ var InMemoryApiKeyRepository = class {
222
279
  }
223
280
  };
224
281
  var InMemoryWebhookEventRepository = class {
282
+ constructor(now) {
283
+ this.now = now;
284
+ }
225
285
  events = [];
226
- async record(event) {
227
- this.events.push(event);
286
+ rows = [];
287
+ async record(event, meta) {
288
+ const stored = withoutRecipient(event);
289
+ this.events.push(stored);
290
+ this.rows.push({
291
+ id: crypto.randomUUID(),
292
+ disposition: meta?.disposition ?? "pending",
293
+ receivedAt: (this.now ?? (() => /* @__PURE__ */ new Date()))(),
294
+ messageId: null,
295
+ event: stored
296
+ });
297
+ }
298
+ async findByIdentity(query) {
299
+ const row = this.rows.find((candidate) => webhookIdentityMatches(candidate, query));
300
+ return row ? toStoredWebhook(row) : null;
301
+ }
302
+ async listPendingByProviderMessageId(providerMessageId) {
303
+ return this.rows.filter(
304
+ (row) => row.event.providerMessageId === providerMessageId && row.disposition === "pending"
305
+ ).map(toStoredWebhook);
306
+ }
307
+ async setDisposition(id, disposition) {
308
+ const row = this.rows.find((candidate) => candidate.id === id);
309
+ if (row) row.disposition = disposition;
310
+ }
311
+ async deleteOlderThan(olderThan) {
312
+ const keep = this.rows.filter((row) => row.receivedAt.getTime() >= olderThan.getTime());
313
+ const removed = this.rows.length - keep.length;
314
+ const kept = new Set(keep.map((row) => row.event));
315
+ this.rows.length = 0;
316
+ this.rows.push(...keep);
317
+ const nextEvents = this.events.filter((event) => kept.has(event));
318
+ this.events.length = 0;
319
+ this.events.push(...nextEvents);
320
+ return removed;
228
321
  }
229
322
  };
323
+ function withoutRecipient(event) {
324
+ const { recipient: _recipient, ...stored } = event;
325
+ return stored;
326
+ }
327
+ function webhookIdentityMatches(row, query) {
328
+ const event = row.event;
329
+ switch (query.match) {
330
+ case "providerEvent":
331
+ return event.provider === query.provider && event.providerEventId === query.providerEventId;
332
+ case "providerMessage":
333
+ return event.provider === query.provider && event.providerMessageId === query.providerMessageId && event.type === query.type && sameInstant(event.occurredAt, query.occurredAt);
334
+ case "settledWithoutEventId":
335
+ return (event.providerEventId === void 0 || event.providerEventId === null) && event.provider === query.provider && event.providerMessageId === query.providerMessageId && event.type === query.type;
336
+ }
337
+ }
338
+ function sameInstant(stored, query) {
339
+ if (query === null) return stored === void 0;
340
+ if (stored === void 0) return false;
341
+ return stored.getTime() === query.getTime();
342
+ }
343
+ function toStoredWebhook(row) {
344
+ const event = row.event;
345
+ return {
346
+ id: row.id,
347
+ disposition: row.disposition,
348
+ receivedAt: new Date(row.receivedAt.getTime()),
349
+ messageId: null,
350
+ event: {
351
+ provider: event.provider,
352
+ type: event.type,
353
+ providerMessageId: event.providerMessageId,
354
+ ...event.recipient !== void 0 ? { recipient: event.recipient } : {},
355
+ isHardBounce: event.isHardBounce,
356
+ occurredAt: event.occurredAt === void 0 ? void 0 : new Date(event.occurredAt.getTime()),
357
+ providerEventId: event.providerEventId,
358
+ verifiedAt: event.verifiedAt === void 0 ? void 0 : new Date(event.verifiedAt.getTime()),
359
+ raw: event.raw
360
+ }
361
+ };
362
+ }
230
363
 
231
364
  // src/testing/in-memory-config-override-repository.ts
232
365
  var InMemoryConfigOverrideRepository = class {
@@ -312,16 +445,48 @@ var FakeEmailProvider = class {
312
445
  if (!parsed?.type || !parsed?.providerMessageId) {
313
446
  throw new WebhookVerificationError("fake webhook missing type/providerMessageId");
314
447
  }
448
+ const providerEventId = fakeProviderEventId(parsed.id);
449
+ const occurredAt = fakeOccurredAt(parsed.occurredAt);
315
450
  return {
316
451
  provider: this.name,
317
452
  type: parsed.type,
318
453
  providerMessageId: String(parsed.providerMessageId),
319
454
  recipient: parsed.recipient,
320
455
  isHardBounce: parsed.isHardBounce,
456
+ ...providerEventId !== void 0 ? { providerEventId } : {},
457
+ ...occurredAt !== void 0 ? { occurredAt } : {},
321
458
  raw: parsed
322
459
  };
323
460
  }
324
461
  };
462
+ function fakeProviderEventId(value) {
463
+ if (value === void 0 || value === null) return void 0;
464
+ if (typeof value !== "string") {
465
+ throw new WebhookVerificationError("fake webhook id must be a string");
466
+ }
467
+ return value;
468
+ }
469
+ function fakeOccurredAt(value) {
470
+ if (value === void 0 || value === null) return void 0;
471
+ if (typeof value === "number") {
472
+ if (!Number.isFinite(value)) {
473
+ throw new WebhookVerificationError("fake webhook occurredAt is invalid");
474
+ }
475
+ const at = new Date(value);
476
+ if (Number.isNaN(at.getTime())) {
477
+ throw new WebhookVerificationError("fake webhook occurredAt is invalid");
478
+ }
479
+ return at;
480
+ }
481
+ if (typeof value === "string") {
482
+ const at = new Date(value);
483
+ if (Number.isNaN(at.getTime())) {
484
+ throw new WebhookVerificationError("fake webhook occurredAt is invalid");
485
+ }
486
+ return at;
487
+ }
488
+ throw new WebhookVerificationError("fake webhook occurredAt is invalid");
489
+ }
325
490
 
326
491
  // src/testing/index.ts
327
492
  var FakeClock = class {
@@ -340,14 +505,34 @@ var FakeClock = class {
340
505
  };
341
506
  function inMemoryRepositories(clock) {
342
507
  const now = clock ? () => clock.now() : void 0;
508
+ const audit = new InMemoryAuditRepository(now);
343
509
  return {
344
- outbox: new InMemoryOutboxRepository(now),
510
+ outbox: wireInMemoryEnqueueAudit(new InMemoryOutboxRepository(now), audit),
345
511
  suppressions: new InMemorySuppressionRepository(),
346
- audit: new InMemoryAuditRepository(now),
512
+ audit,
347
513
  apiKeys: new InMemoryApiKeyRepository(),
348
- webhookEvents: new InMemoryWebhookEventRepository()
514
+ webhookEvents: new InMemoryWebhookEventRepository(now)
349
515
  };
350
516
  }
517
+ function wireInMemoryEnqueueAudit(outbox, audit) {
518
+ return Object.assign(outbox, {
519
+ insertWithEnqueueAudit: async (msg, write) => {
520
+ const message = await outbox.insert(msg);
521
+ try {
522
+ await audit.append({
523
+ messageId: message.id,
524
+ eventType: write.eventType,
525
+ actor: write.actor,
526
+ detail: write.detail ?? null
527
+ });
528
+ } catch (error) {
529
+ outbox.messages.delete(message.id);
530
+ throw error;
531
+ }
532
+ return { message, deduplicated: false };
533
+ }
534
+ });
535
+ }
351
536
 
352
537
  exports.FakeClock = FakeClock;
353
538
  exports.FakeEmailProvider = FakeEmailProvider;