@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
@@ -0,0 +1,322 @@
1
+ import { S as Sealed, a as LifecycleState, M as Message, W as WebhookEvent } from './webhook-B158Vi6p.js';
2
+
3
+ /**
4
+ * Suppression list domain types.
5
+ *
6
+ * The suppression list is the reputation guardrail: any address on it is never
7
+ * dispatched to. Entries are keyed by the recipient HMAC (not plaintext) so the
8
+ * list keeps working when recipients are encrypted at rest (TDR §3.6, §5.4).
9
+ */
10
+ declare const SUPPRESSION_REASONS: readonly ["hard_bounce", "complaint", "unsubscribe", "invalid", "manual"];
11
+ type SuppressionReason = (typeof SUPPRESSION_REASONS)[number];
12
+ interface SuppressionEntry {
13
+ /** Keyed HMAC of the suppressed address. Unique. */
14
+ readonly recipientHmac: string;
15
+ readonly reason: SuppressionReason;
16
+ /** api key id, provider name, or "system". For the audit trail. */
17
+ readonly createdBy: string;
18
+ readonly createdAt: Date;
19
+ /** Optional free-text note (e.g. the provider bounce message). */
20
+ readonly note?: string;
21
+ }
22
+
23
+ /**
24
+ * API key domain types and scope model (TDR §5.1).
25
+ *
26
+ * Keys are opaque high-entropy secrets. Only a hash is ever stored; the
27
+ * plaintext is shown once at creation. A key carries a label, optional expiry,
28
+ * and a revoked flag — both enforced on every request. Scopes implement
29
+ * least-privilege (a send-only key cannot manage suppressions).
30
+ */
31
+ declare const API_SCOPES: readonly ["messages:send", "messages:read", "messages:replay", "suppressions:read", "suppressions:write", "keys:manage", "admin"];
32
+ type ApiScope = (typeof API_SCOPES)[number];
33
+ interface ApiKey {
34
+ readonly id: string;
35
+ /** Human label shown in the admin panel. */
36
+ readonly label: string;
37
+ /** Hash of the secret (never the secret itself). */
38
+ readonly keyHash: string;
39
+ readonly scopes: readonly ApiScope[];
40
+ readonly expiresAt: Date | null;
41
+ revokedAt: Date | null;
42
+ readonly createdAt: Date;
43
+ lastUsedAt: Date | null;
44
+ }
45
+ /** A key is usable iff it is not revoked and not past its expiry. */
46
+ declare function isKeyActive(key: Pick<ApiKey, "revokedAt" | "expiresAt">, now: Date): boolean;
47
+ /** True when the key's scopes satisfy the required scope (admin implies all). */
48
+ declare function hasScope(scopes: readonly ApiScope[], required: ApiScope): boolean;
49
+
50
+ /**
51
+ * Append-only audit trail types (TDR §3, §8).
52
+ *
53
+ * The audit trail is the durable "who did what when" record. It is append-only:
54
+ * use cases write an event on every meaningful state change. It outlives the
55
+ * operational outbox row (longer TTL) and survives PII redaction.
56
+ */
57
+ type AuditEventType = "enqueued" | "dispatch_started" | "dispatch_accepted" | "dispatch_failed" | "retry_scheduled" | "dead_lettered" | "replayed" | "webhook_delivered" | "webhook_bounced" | "webhook_complained" | "webhook_opened" | "suppressed" | "unsuppressed" | "redacted" | "purged" | "key_created" | "key_revoked";
58
+ interface AuditEvent {
59
+ readonly id: string;
60
+ /** Null for events not tied to a single message (e.g. key_created). */
61
+ readonly messageId: string | null;
62
+ readonly eventType: AuditEventType;
63
+ /** api key id, provider name, or "system". */
64
+ readonly actor: string;
65
+ /** Redactable provider response / detail blob. Never raw PII bodies. */
66
+ readonly detail: Record<string, unknown> | null;
67
+ readonly at: Date;
68
+ }
69
+ /** Shape a use case passes to the repository; id + timestamp are assigned there. */
70
+ interface NewAuditEvent {
71
+ readonly messageId: string | null;
72
+ readonly eventType: AuditEventType;
73
+ readonly actor: string;
74
+ readonly detail?: Record<string, unknown> | null;
75
+ }
76
+
77
+ /**
78
+ * Persistence ports (TDR §6). Use cases depend on these interfaces; concrete
79
+ * Drizzle/Postgres implementations are injected at the edge (Dependency
80
+ * Inversion). Ports are deliberately narrow (Interface Segregation): a
81
+ * send-only consumer never has to depend on suppression-management methods.
82
+ */
83
+ /**
84
+ * Fields required to create a new outbox row. Timestamps are assigned by the
85
+ * implementation. `id` is stored when the caller supplies it; otherwise the
86
+ * implementation generates one.
87
+ */
88
+ interface NewMessage {
89
+ readonly id?: string;
90
+ readonly idempotencyKey: string;
91
+ readonly recipientHmac: string;
92
+ readonly recipientSealed: Sealed;
93
+ readonly bodySealed: Sealed;
94
+ readonly subject: string;
95
+ readonly templateId: string | null;
96
+ readonly templateVersion: number | null;
97
+ readonly provider: string;
98
+ readonly metadata: Record<string, unknown>;
99
+ readonly state: LifecycleState;
100
+ readonly scheduledFor: Date | null;
101
+ readonly nextAttemptAt: Date;
102
+ }
103
+ interface ListMessagesQuery {
104
+ readonly state?: LifecycleState;
105
+ readonly recipientHmac?: string;
106
+ readonly provider?: string;
107
+ readonly createdAfter?: Date;
108
+ readonly createdBefore?: Date;
109
+ readonly limit?: number;
110
+ readonly offset?: number;
111
+ }
112
+ /** Patch applied during a state transition; impl bumps `updatedAt`. */
113
+ interface MessageStatePatch {
114
+ readonly state: LifecycleState;
115
+ readonly attempts?: number;
116
+ readonly nextAttemptAt?: Date;
117
+ readonly providerMessageId?: string | null;
118
+ readonly lastError?: string | null;
119
+ }
120
+ /**
121
+ * `updatedAt` written by this generation of `claimBatchForSending`.
122
+ * Dispatch uses it so a stale worker cannot overwrite a newer row.
123
+ */
124
+ interface SendingClaim {
125
+ readonly updatedAt: Date;
126
+ }
127
+ /** Audit written with a new outbox row. The repository assigns `messageId`. */
128
+ interface EnqueueAuditWrite {
129
+ readonly eventType: "enqueued" | "suppressed";
130
+ readonly actor: string;
131
+ readonly detail?: Record<string, unknown> | null;
132
+ }
133
+ interface EnqueueWriteResult {
134
+ readonly message: Message;
135
+ readonly deduplicated: boolean;
136
+ }
137
+ interface OutboxRepository {
138
+ insert(msg: NewMessage): Promise<Message>;
139
+ /**
140
+ * Insert the outbox row and its enqueue audit as one write.
141
+ * When this is omitted, enqueue inserts and then appends the audit as two
142
+ * steps. `deduplicated` is true when the idempotency unique index already
143
+ * holds the key and the existing row is returned.
144
+ */
145
+ insertWithEnqueueAudit?(msg: NewMessage, audit: EnqueueAuditWrite): Promise<EnqueueWriteResult>;
146
+ findById(id: string): Promise<Message | null>;
147
+ findByIdempotencyKey(key: string): Promise<Message | null>;
148
+ /** Correlate an inbound webhook back to its outbox row. */
149
+ findByProviderMessageId(providerMessageId: string): Promise<Message | null>;
150
+ list(query: ListMessagesQuery): Promise<Message[]>;
151
+ /** Count rows grouped by lifecycle state (admin observability). */
152
+ countByState(): Promise<Record<LifecycleState, number>>;
153
+ /**
154
+ * Atomically claim a batch of ready messages for sending and mark them
155
+ * `sending`, so concurrent send workers never grab the same row. Postgres
156
+ * impl uses `FOR UPDATE SKIP LOCKED`.
157
+ *
158
+ * Eligible rows are EITHER:
159
+ * - `queued` with `next_attempt_at <= now` and no future `scheduled_for`, OR
160
+ * - `sending` last updated before `reclaimBefore` — i.e. abandoned by a
161
+ * worker that crashed mid-dispatch (lease expiry). This makes dispatch
162
+ * crash-safe: a stuck row is retried rather than lost forever.
163
+ */
164
+ claimBatchForSending(limit: number, now: Date, reclaimBefore: Date): Promise<Message[]>;
165
+ /** Apply a validated state transition + persist the patch. */
166
+ updateState(id: string, patch: MessageStatePatch): Promise<void>;
167
+ /**
168
+ * Dispatch-only transition out of `sending`. Writes only when the row is
169
+ * still `sending` and `updatedAt` is still this claim's timestamp.
170
+ * Returns false when zero rows match. Optional so existing repository
171
+ * implementations keep typechecking; the shipped adapters implement it.
172
+ */
173
+ updateStateWhileSending?(id: string, patch: MessageStatePatch, claim: SendingClaim): Promise<boolean>;
174
+ /**
175
+ * Rows eligible for a retention select: state is one of `TERMINAL_STATES`,
176
+ * `updatedAt` is strictly before `olderThan`, and the body seal is not
177
+ * already `redacted`. The caller passes the cutoff it computed for the
178
+ * cycle. The purge write repeats this predicate.
179
+ */
180
+ claimTerminalForPurge(olderThan: Date, limit: number): Promise<Message[]>;
181
+ /**
182
+ * Wipe PII columns by id only (keep the row, metadata, and HMAC). Returns
183
+ * the number of rows written. This does not re-check state, age, or an
184
+ * existing tombstone. Retention does not call it.
185
+ */
186
+ redactBatch(ids: readonly string[]): Promise<number>;
187
+ /**
188
+ * Hard-delete rows by id only. Returns the number of rows removed. This
189
+ * does not re-check eligibility. Retention does not call it.
190
+ */
191
+ deleteBatch(ids: readonly string[]): Promise<number>;
192
+ /**
193
+ * Redact PII only for ids that still match the `claimTerminalForPurge`
194
+ * predicate against `olderThan`: terminal state, `updatedAt` strictly
195
+ * before that cutoff, and a body seal whose `alg` is not `redacted`.
196
+ * `olderThan` is the cutoff the caller already computed; do not read the
197
+ * clock again. Writes only the recipient and body seals to
198
+ * `{ alg: "redacted", ciphertext: "" }` and refreshes `updatedAt`. Returns
199
+ * the matched count (0 for an empty id list). Optional so existing
200
+ * repositories keep typechecking. Retention calls this and throws before
201
+ * it writes when the method is missing.
202
+ */
203
+ redactBatchIfEligible?(ids: readonly string[], olderThan: Date): Promise<number>;
204
+ /**
205
+ * Delete only ids that match the same predicate as `redactBatchIfEligible`.
206
+ * Returns the matched count (0 for an empty id list). Retention calls this
207
+ * and throws before it writes when the method is missing.
208
+ */
209
+ deleteBatchIfEligible?(ids: readonly string[], olderThan: Date): Promise<number>;
210
+ }
211
+ interface SuppressionRepository {
212
+ isSuppressed(recipientHmac: string): Promise<boolean>;
213
+ get(recipientHmac: string): Promise<SuppressionEntry | null>;
214
+ add(entry: {
215
+ recipientHmac: string;
216
+ reason: SuppressionReason;
217
+ createdBy: string;
218
+ note?: string;
219
+ }): Promise<SuppressionEntry>;
220
+ remove(recipientHmac: string): Promise<boolean>;
221
+ list(limit: number, offset: number): Promise<SuppressionEntry[]>;
222
+ }
223
+ interface AuditRepository {
224
+ append(event: NewAuditEvent): Promise<AuditEvent>;
225
+ listForMessage(messageId: string): Promise<AuditEvent[]>;
226
+ /**
227
+ * Delete audit rows older than the cutoff, in batches. Returns count.
228
+ * `pauseMs`, when positive, is the wait after a full batch. Implementations
229
+ * may ignore it.
230
+ */
231
+ purgeOlderThan(cutoff: Date, batchSize: number, pauseMs?: number): Promise<number>;
232
+ }
233
+ interface NewApiKey {
234
+ readonly label: string;
235
+ readonly keyHash: string;
236
+ readonly scopes: readonly ApiScope[];
237
+ readonly expiresAt: Date | null;
238
+ }
239
+ interface ApiKeyRepository {
240
+ insert(key: NewApiKey): Promise<ApiKey>;
241
+ findByHash(keyHash: string): Promise<ApiKey | null>;
242
+ findById(id: string): Promise<ApiKey | null>;
243
+ list(): Promise<ApiKey[]>;
244
+ revoke(id: string, at: Date): Promise<boolean>;
245
+ touchLastUsed(id: string, at: Date): Promise<void>;
246
+ }
247
+ /** How a stored webhook row was settled. */
248
+ type WebhookDisposition = "pending" | "applied" | "rejected";
249
+ /**
250
+ * Optional insert metadata. See `WebhookEventRepository.record`.
251
+ * Adapters that persist disposition default to `pending` when this is
252
+ * omitted or `disposition` is absent.
253
+ */
254
+ interface WebhookRecordMeta {
255
+ readonly disposition?: WebhookDisposition;
256
+ }
257
+ /** One stored webhook row. `messageId` is the correlated outbox id when known. */
258
+ interface StoredWebhookEvent {
259
+ readonly id: string;
260
+ readonly disposition: WebhookDisposition;
261
+ readonly receivedAt: Date;
262
+ readonly messageId: string | null;
263
+ readonly event: WebhookEvent;
264
+ }
265
+ /**
266
+ * Identity lookup. Any disposition is a hit. Return one matching row, or null.
267
+ *
268
+ * - `providerEvent`: (provider, providerEventId).
269
+ * - `providerMessage`: (provider, providerMessageId, type, occurredAt).
270
+ * Compare instants. A null `occurredAt` matches only a stored null timestamp.
271
+ * - `settledWithoutEventId`: a stored row whose providerEventId is null and
272
+ * whose (provider, providerMessageId, type) matches, ignoring occurredAt.
273
+ * The use case calls this only when the incoming event has no provider
274
+ * event id, so a new id is stored even if an older row of that type exists.
275
+ */
276
+ type WebhookIdentityQuery = {
277
+ readonly match: "providerEvent";
278
+ readonly provider: string;
279
+ readonly providerEventId: string;
280
+ } | {
281
+ readonly match: "providerMessage";
282
+ readonly provider: string;
283
+ readonly providerMessageId: string;
284
+ readonly type: WebhookEvent["type"];
285
+ readonly occurredAt: Date | null;
286
+ } | {
287
+ readonly match: "settledWithoutEventId";
288
+ readonly provider: string;
289
+ readonly providerMessageId: string;
290
+ readonly type: WebhookEvent["type"];
291
+ };
292
+ /**
293
+ * Raw verified webhook events, kept for traceability until the retention cutoff.
294
+ * The shipped Drizzle and in-memory adapters implement the optional methods.
295
+ * A custom repository may omit them; the use case then skips dedupe and
296
+ * pending apply, and retention skips webhook deletion. Transition, suppression,
297
+ * and audit still run. Suppression uses the outbox HMAC, not a stored address.
298
+ */
299
+ interface WebhookEventRepository {
300
+ /**
301
+ * Persist a verified event. `meta.disposition` defaults to `pending` when
302
+ * the adapter stores disposition and the argument is omitted.
303
+ */
304
+ record(event: WebhookEvent, meta?: WebhookRecordMeta): Promise<void>;
305
+ /** Dedupe lookup. Absent means the use case skips identity dedupe. */
306
+ findByIdentity?(query: WebhookIdentityQuery): Promise<StoredWebhookEvent | null>;
307
+ /**
308
+ * Pending rows for this provider message id. The use case sorts by
309
+ * `receivedAt` ascending. Absent means pending apply is skipped.
310
+ */
311
+ listPendingByProviderMessageId?(providerMessageId: string): Promise<readonly StoredWebhookEvent[]>;
312
+ /** Set disposition on an existing row after its effect is decided. */
313
+ setDisposition?(id: string, disposition: WebhookDisposition): Promise<void>;
314
+ /**
315
+ * Delete every row whose `receivedAt` is strictly before `olderThan`.
316
+ * Disposition is not a filter. Absent means retention skips this delete
317
+ * and still redacts or deletes eligible outbox rows.
318
+ */
319
+ deleteOlderThan?(olderThan: Date): Promise<number>;
320
+ }
321
+
322
+ export { type AuditRepository as A, type EnqueueAuditWrite as E, type ListMessagesQuery as L, type MessageStatePatch as M, type NewApiKey as N, type OutboxRepository as O, type SuppressionRepository as S, type WebhookEventRepository as W, type ApiKeyRepository as a, API_SCOPES as b, type ApiKey as c, type ApiScope as d, type AuditEvent as e, type AuditEventType as f, type EnqueueWriteResult as g, type NewAuditEvent as h, type NewMessage as i, SUPPRESSION_REASONS as j, type SendingClaim as k, type StoredWebhookEvent as l, type SuppressionEntry as m, type SuppressionReason as n, type WebhookDisposition as o, type WebhookIdentityQuery as p, type WebhookRecordMeta as q, hasScope as r, isKeyActive as s };
@@ -0,0 +1,322 @@
1
+ import { S as Sealed, a as LifecycleState, M as Message, W as WebhookEvent } from './webhook-B158Vi6p.cjs';
2
+
3
+ /**
4
+ * Suppression list domain types.
5
+ *
6
+ * The suppression list is the reputation guardrail: any address on it is never
7
+ * dispatched to. Entries are keyed by the recipient HMAC (not plaintext) so the
8
+ * list keeps working when recipients are encrypted at rest (TDR §3.6, §5.4).
9
+ */
10
+ declare const SUPPRESSION_REASONS: readonly ["hard_bounce", "complaint", "unsubscribe", "invalid", "manual"];
11
+ type SuppressionReason = (typeof SUPPRESSION_REASONS)[number];
12
+ interface SuppressionEntry {
13
+ /** Keyed HMAC of the suppressed address. Unique. */
14
+ readonly recipientHmac: string;
15
+ readonly reason: SuppressionReason;
16
+ /** api key id, provider name, or "system". For the audit trail. */
17
+ readonly createdBy: string;
18
+ readonly createdAt: Date;
19
+ /** Optional free-text note (e.g. the provider bounce message). */
20
+ readonly note?: string;
21
+ }
22
+
23
+ /**
24
+ * API key domain types and scope model (TDR §5.1).
25
+ *
26
+ * Keys are opaque high-entropy secrets. Only a hash is ever stored; the
27
+ * plaintext is shown once at creation. A key carries a label, optional expiry,
28
+ * and a revoked flag — both enforced on every request. Scopes implement
29
+ * least-privilege (a send-only key cannot manage suppressions).
30
+ */
31
+ declare const API_SCOPES: readonly ["messages:send", "messages:read", "messages:replay", "suppressions:read", "suppressions:write", "keys:manage", "admin"];
32
+ type ApiScope = (typeof API_SCOPES)[number];
33
+ interface ApiKey {
34
+ readonly id: string;
35
+ /** Human label shown in the admin panel. */
36
+ readonly label: string;
37
+ /** Hash of the secret (never the secret itself). */
38
+ readonly keyHash: string;
39
+ readonly scopes: readonly ApiScope[];
40
+ readonly expiresAt: Date | null;
41
+ revokedAt: Date | null;
42
+ readonly createdAt: Date;
43
+ lastUsedAt: Date | null;
44
+ }
45
+ /** A key is usable iff it is not revoked and not past its expiry. */
46
+ declare function isKeyActive(key: Pick<ApiKey, "revokedAt" | "expiresAt">, now: Date): boolean;
47
+ /** True when the key's scopes satisfy the required scope (admin implies all). */
48
+ declare function hasScope(scopes: readonly ApiScope[], required: ApiScope): boolean;
49
+
50
+ /**
51
+ * Append-only audit trail types (TDR §3, §8).
52
+ *
53
+ * The audit trail is the durable "who did what when" record. It is append-only:
54
+ * use cases write an event on every meaningful state change. It outlives the
55
+ * operational outbox row (longer TTL) and survives PII redaction.
56
+ */
57
+ type AuditEventType = "enqueued" | "dispatch_started" | "dispatch_accepted" | "dispatch_failed" | "retry_scheduled" | "dead_lettered" | "replayed" | "webhook_delivered" | "webhook_bounced" | "webhook_complained" | "webhook_opened" | "suppressed" | "unsuppressed" | "redacted" | "purged" | "key_created" | "key_revoked";
58
+ interface AuditEvent {
59
+ readonly id: string;
60
+ /** Null for events not tied to a single message (e.g. key_created). */
61
+ readonly messageId: string | null;
62
+ readonly eventType: AuditEventType;
63
+ /** api key id, provider name, or "system". */
64
+ readonly actor: string;
65
+ /** Redactable provider response / detail blob. Never raw PII bodies. */
66
+ readonly detail: Record<string, unknown> | null;
67
+ readonly at: Date;
68
+ }
69
+ /** Shape a use case passes to the repository; id + timestamp are assigned there. */
70
+ interface NewAuditEvent {
71
+ readonly messageId: string | null;
72
+ readonly eventType: AuditEventType;
73
+ readonly actor: string;
74
+ readonly detail?: Record<string, unknown> | null;
75
+ }
76
+
77
+ /**
78
+ * Persistence ports (TDR §6). Use cases depend on these interfaces; concrete
79
+ * Drizzle/Postgres implementations are injected at the edge (Dependency
80
+ * Inversion). Ports are deliberately narrow (Interface Segregation): a
81
+ * send-only consumer never has to depend on suppression-management methods.
82
+ */
83
+ /**
84
+ * Fields required to create a new outbox row. Timestamps are assigned by the
85
+ * implementation. `id` is stored when the caller supplies it; otherwise the
86
+ * implementation generates one.
87
+ */
88
+ interface NewMessage {
89
+ readonly id?: string;
90
+ readonly idempotencyKey: string;
91
+ readonly recipientHmac: string;
92
+ readonly recipientSealed: Sealed;
93
+ readonly bodySealed: Sealed;
94
+ readonly subject: string;
95
+ readonly templateId: string | null;
96
+ readonly templateVersion: number | null;
97
+ readonly provider: string;
98
+ readonly metadata: Record<string, unknown>;
99
+ readonly state: LifecycleState;
100
+ readonly scheduledFor: Date | null;
101
+ readonly nextAttemptAt: Date;
102
+ }
103
+ interface ListMessagesQuery {
104
+ readonly state?: LifecycleState;
105
+ readonly recipientHmac?: string;
106
+ readonly provider?: string;
107
+ readonly createdAfter?: Date;
108
+ readonly createdBefore?: Date;
109
+ readonly limit?: number;
110
+ readonly offset?: number;
111
+ }
112
+ /** Patch applied during a state transition; impl bumps `updatedAt`. */
113
+ interface MessageStatePatch {
114
+ readonly state: LifecycleState;
115
+ readonly attempts?: number;
116
+ readonly nextAttemptAt?: Date;
117
+ readonly providerMessageId?: string | null;
118
+ readonly lastError?: string | null;
119
+ }
120
+ /**
121
+ * `updatedAt` written by this generation of `claimBatchForSending`.
122
+ * Dispatch uses it so a stale worker cannot overwrite a newer row.
123
+ */
124
+ interface SendingClaim {
125
+ readonly updatedAt: Date;
126
+ }
127
+ /** Audit written with a new outbox row. The repository assigns `messageId`. */
128
+ interface EnqueueAuditWrite {
129
+ readonly eventType: "enqueued" | "suppressed";
130
+ readonly actor: string;
131
+ readonly detail?: Record<string, unknown> | null;
132
+ }
133
+ interface EnqueueWriteResult {
134
+ readonly message: Message;
135
+ readonly deduplicated: boolean;
136
+ }
137
+ interface OutboxRepository {
138
+ insert(msg: NewMessage): Promise<Message>;
139
+ /**
140
+ * Insert the outbox row and its enqueue audit as one write.
141
+ * When this is omitted, enqueue inserts and then appends the audit as two
142
+ * steps. `deduplicated` is true when the idempotency unique index already
143
+ * holds the key and the existing row is returned.
144
+ */
145
+ insertWithEnqueueAudit?(msg: NewMessage, audit: EnqueueAuditWrite): Promise<EnqueueWriteResult>;
146
+ findById(id: string): Promise<Message | null>;
147
+ findByIdempotencyKey(key: string): Promise<Message | null>;
148
+ /** Correlate an inbound webhook back to its outbox row. */
149
+ findByProviderMessageId(providerMessageId: string): Promise<Message | null>;
150
+ list(query: ListMessagesQuery): Promise<Message[]>;
151
+ /** Count rows grouped by lifecycle state (admin observability). */
152
+ countByState(): Promise<Record<LifecycleState, number>>;
153
+ /**
154
+ * Atomically claim a batch of ready messages for sending and mark them
155
+ * `sending`, so concurrent send workers never grab the same row. Postgres
156
+ * impl uses `FOR UPDATE SKIP LOCKED`.
157
+ *
158
+ * Eligible rows are EITHER:
159
+ * - `queued` with `next_attempt_at <= now` and no future `scheduled_for`, OR
160
+ * - `sending` last updated before `reclaimBefore` — i.e. abandoned by a
161
+ * worker that crashed mid-dispatch (lease expiry). This makes dispatch
162
+ * crash-safe: a stuck row is retried rather than lost forever.
163
+ */
164
+ claimBatchForSending(limit: number, now: Date, reclaimBefore: Date): Promise<Message[]>;
165
+ /** Apply a validated state transition + persist the patch. */
166
+ updateState(id: string, patch: MessageStatePatch): Promise<void>;
167
+ /**
168
+ * Dispatch-only transition out of `sending`. Writes only when the row is
169
+ * still `sending` and `updatedAt` is still this claim's timestamp.
170
+ * Returns false when zero rows match. Optional so existing repository
171
+ * implementations keep typechecking; the shipped adapters implement it.
172
+ */
173
+ updateStateWhileSending?(id: string, patch: MessageStatePatch, claim: SendingClaim): Promise<boolean>;
174
+ /**
175
+ * Rows eligible for a retention select: state is one of `TERMINAL_STATES`,
176
+ * `updatedAt` is strictly before `olderThan`, and the body seal is not
177
+ * already `redacted`. The caller passes the cutoff it computed for the
178
+ * cycle. The purge write repeats this predicate.
179
+ */
180
+ claimTerminalForPurge(olderThan: Date, limit: number): Promise<Message[]>;
181
+ /**
182
+ * Wipe PII columns by id only (keep the row, metadata, and HMAC). Returns
183
+ * the number of rows written. This does not re-check state, age, or an
184
+ * existing tombstone. Retention does not call it.
185
+ */
186
+ redactBatch(ids: readonly string[]): Promise<number>;
187
+ /**
188
+ * Hard-delete rows by id only. Returns the number of rows removed. This
189
+ * does not re-check eligibility. Retention does not call it.
190
+ */
191
+ deleteBatch(ids: readonly string[]): Promise<number>;
192
+ /**
193
+ * Redact PII only for ids that still match the `claimTerminalForPurge`
194
+ * predicate against `olderThan`: terminal state, `updatedAt` strictly
195
+ * before that cutoff, and a body seal whose `alg` is not `redacted`.
196
+ * `olderThan` is the cutoff the caller already computed; do not read the
197
+ * clock again. Writes only the recipient and body seals to
198
+ * `{ alg: "redacted", ciphertext: "" }` and refreshes `updatedAt`. Returns
199
+ * the matched count (0 for an empty id list). Optional so existing
200
+ * repositories keep typechecking. Retention calls this and throws before
201
+ * it writes when the method is missing.
202
+ */
203
+ redactBatchIfEligible?(ids: readonly string[], olderThan: Date): Promise<number>;
204
+ /**
205
+ * Delete only ids that match the same predicate as `redactBatchIfEligible`.
206
+ * Returns the matched count (0 for an empty id list). Retention calls this
207
+ * and throws before it writes when the method is missing.
208
+ */
209
+ deleteBatchIfEligible?(ids: readonly string[], olderThan: Date): Promise<number>;
210
+ }
211
+ interface SuppressionRepository {
212
+ isSuppressed(recipientHmac: string): Promise<boolean>;
213
+ get(recipientHmac: string): Promise<SuppressionEntry | null>;
214
+ add(entry: {
215
+ recipientHmac: string;
216
+ reason: SuppressionReason;
217
+ createdBy: string;
218
+ note?: string;
219
+ }): Promise<SuppressionEntry>;
220
+ remove(recipientHmac: string): Promise<boolean>;
221
+ list(limit: number, offset: number): Promise<SuppressionEntry[]>;
222
+ }
223
+ interface AuditRepository {
224
+ append(event: NewAuditEvent): Promise<AuditEvent>;
225
+ listForMessage(messageId: string): Promise<AuditEvent[]>;
226
+ /**
227
+ * Delete audit rows older than the cutoff, in batches. Returns count.
228
+ * `pauseMs`, when positive, is the wait after a full batch. Implementations
229
+ * may ignore it.
230
+ */
231
+ purgeOlderThan(cutoff: Date, batchSize: number, pauseMs?: number): Promise<number>;
232
+ }
233
+ interface NewApiKey {
234
+ readonly label: string;
235
+ readonly keyHash: string;
236
+ readonly scopes: readonly ApiScope[];
237
+ readonly expiresAt: Date | null;
238
+ }
239
+ interface ApiKeyRepository {
240
+ insert(key: NewApiKey): Promise<ApiKey>;
241
+ findByHash(keyHash: string): Promise<ApiKey | null>;
242
+ findById(id: string): Promise<ApiKey | null>;
243
+ list(): Promise<ApiKey[]>;
244
+ revoke(id: string, at: Date): Promise<boolean>;
245
+ touchLastUsed(id: string, at: Date): Promise<void>;
246
+ }
247
+ /** How a stored webhook row was settled. */
248
+ type WebhookDisposition = "pending" | "applied" | "rejected";
249
+ /**
250
+ * Optional insert metadata. See `WebhookEventRepository.record`.
251
+ * Adapters that persist disposition default to `pending` when this is
252
+ * omitted or `disposition` is absent.
253
+ */
254
+ interface WebhookRecordMeta {
255
+ readonly disposition?: WebhookDisposition;
256
+ }
257
+ /** One stored webhook row. `messageId` is the correlated outbox id when known. */
258
+ interface StoredWebhookEvent {
259
+ readonly id: string;
260
+ readonly disposition: WebhookDisposition;
261
+ readonly receivedAt: Date;
262
+ readonly messageId: string | null;
263
+ readonly event: WebhookEvent;
264
+ }
265
+ /**
266
+ * Identity lookup. Any disposition is a hit. Return one matching row, or null.
267
+ *
268
+ * - `providerEvent`: (provider, providerEventId).
269
+ * - `providerMessage`: (provider, providerMessageId, type, occurredAt).
270
+ * Compare instants. A null `occurredAt` matches only a stored null timestamp.
271
+ * - `settledWithoutEventId`: a stored row whose providerEventId is null and
272
+ * whose (provider, providerMessageId, type) matches, ignoring occurredAt.
273
+ * The use case calls this only when the incoming event has no provider
274
+ * event id, so a new id is stored even if an older row of that type exists.
275
+ */
276
+ type WebhookIdentityQuery = {
277
+ readonly match: "providerEvent";
278
+ readonly provider: string;
279
+ readonly providerEventId: string;
280
+ } | {
281
+ readonly match: "providerMessage";
282
+ readonly provider: string;
283
+ readonly providerMessageId: string;
284
+ readonly type: WebhookEvent["type"];
285
+ readonly occurredAt: Date | null;
286
+ } | {
287
+ readonly match: "settledWithoutEventId";
288
+ readonly provider: string;
289
+ readonly providerMessageId: string;
290
+ readonly type: WebhookEvent["type"];
291
+ };
292
+ /**
293
+ * Raw verified webhook events, kept for traceability until the retention cutoff.
294
+ * The shipped Drizzle and in-memory adapters implement the optional methods.
295
+ * A custom repository may omit them; the use case then skips dedupe and
296
+ * pending apply, and retention skips webhook deletion. Transition, suppression,
297
+ * and audit still run. Suppression uses the outbox HMAC, not a stored address.
298
+ */
299
+ interface WebhookEventRepository {
300
+ /**
301
+ * Persist a verified event. `meta.disposition` defaults to `pending` when
302
+ * the adapter stores disposition and the argument is omitted.
303
+ */
304
+ record(event: WebhookEvent, meta?: WebhookRecordMeta): Promise<void>;
305
+ /** Dedupe lookup. Absent means the use case skips identity dedupe. */
306
+ findByIdentity?(query: WebhookIdentityQuery): Promise<StoredWebhookEvent | null>;
307
+ /**
308
+ * Pending rows for this provider message id. The use case sorts by
309
+ * `receivedAt` ascending. Absent means pending apply is skipped.
310
+ */
311
+ listPendingByProviderMessageId?(providerMessageId: string): Promise<readonly StoredWebhookEvent[]>;
312
+ /** Set disposition on an existing row after its effect is decided. */
313
+ setDisposition?(id: string, disposition: WebhookDisposition): Promise<void>;
314
+ /**
315
+ * Delete every row whose `receivedAt` is strictly before `olderThan`.
316
+ * Disposition is not a filter. Absent means retention skips this delete
317
+ * and still redacts or deletes eligible outbox rows.
318
+ */
319
+ deleteOlderThan?(olderThan: Date): Promise<number>;
320
+ }
321
+
322
+ export { type AuditRepository as A, type EnqueueAuditWrite as E, type ListMessagesQuery as L, type MessageStatePatch as M, type NewApiKey as N, type OutboxRepository as O, type SuppressionRepository as S, type WebhookEventRepository as W, type ApiKeyRepository as a, API_SCOPES as b, type ApiKey as c, type ApiScope as d, type AuditEvent as e, type AuditEventType as f, type EnqueueWriteResult as g, type NewAuditEvent as h, type NewMessage as i, SUPPRESSION_REASONS as j, type SendingClaim as k, type StoredWebhookEvent as l, type SuppressionEntry as m, type SuppressionReason as n, type WebhookDisposition as o, type WebhookIdentityQuery as p, type WebhookRecordMeta as q, hasScope as r, isKeyActive as s };
@@ -1,4 +1,4 @@
1
- import { D as DispatchableMessage, W as WebhookEvent } from './webhook-kp6CiXk-.js';
1
+ import { D as DispatchableMessage, W as WebhookEvent } from './webhook-B158Vi6p.cjs';
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 {