@tgoliveira/outpost 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/AGENTS.md +268 -0
  2. package/LICENSE +21 -0
  3. package/README.md +117 -0
  4. package/dist/adapters/drizzle/index.cjs +405 -0
  5. package/dist/adapters/drizzle/index.cjs.map +1 -0
  6. package/dist/adapters/drizzle/index.d.cts +1765 -0
  7. package/dist/adapters/drizzle/index.d.ts +1765 -0
  8. package/dist/adapters/drizzle/index.js +387 -0
  9. package/dist/adapters/drizzle/index.js.map +1 -0
  10. package/dist/adapters/index.cjs +584 -0
  11. package/dist/adapters/index.cjs.map +1 -0
  12. package/dist/adapters/index.d.cts +232 -0
  13. package/dist/adapters/index.d.ts +232 -0
  14. package/dist/adapters/index.js +565 -0
  15. package/dist/adapters/index.js.map +1 -0
  16. package/dist/fake-BY6t7UXb.d.cts +30 -0
  17. package/dist/fake-en-oOdg0.d.ts +30 -0
  18. package/dist/http/index.cjs +224 -0
  19. package/dist/http/index.cjs.map +1 -0
  20. package/dist/http/index.d.cts +49 -0
  21. package/dist/http/index.d.ts +49 -0
  22. package/dist/http/index.js +221 -0
  23. package/dist/http/index.js.map +1 -0
  24. package/dist/index-CVUvaJms.d.ts +179 -0
  25. package/dist/index-Dmt-aLH2.d.cts +179 -0
  26. package/dist/index.cjs +1387 -0
  27. package/dist/index.cjs.map +1 -0
  28. package/dist/index.d.cts +153 -0
  29. package/dist/index.d.ts +153 -0
  30. package/dist/index.js +1331 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/outpost-client-yUijE00q.d.cts +271 -0
  33. package/dist/outpost-client-ymTJISpu.d.ts +271 -0
  34. package/dist/repositories-Bck6wJNS.d.ts +180 -0
  35. package/dist/repositories-DhUe8f2R.d.cts +180 -0
  36. package/dist/services-CQINhAGo.d.cts +90 -0
  37. package/dist/services-CfTEsetF.d.ts +90 -0
  38. package/dist/template-CREUq7bB.d.ts +260 -0
  39. package/dist/template-DxI_p2Ny.d.cts +260 -0
  40. package/dist/testing/index.cjs +321 -0
  41. package/dist/testing/index.cjs.map +1 -0
  42. package/dist/testing/index.d.cts +97 -0
  43. package/dist/testing/index.d.ts +97 -0
  44. package/dist/testing/index.js +312 -0
  45. package/dist/testing/index.js.map +1 -0
  46. package/dist/webhook-kp6CiXk-.d.cts +149 -0
  47. package/dist/webhook-kp6CiXk-.d.ts +149 -0
  48. package/dist/workers/index.cjs +430 -0
  49. package/dist/workers/index.cjs.map +1 -0
  50. package/dist/workers/index.d.cts +5 -0
  51. package/dist/workers/index.d.ts +5 -0
  52. package/dist/workers/index.js +427 -0
  53. package/dist/workers/index.js.map +1 -0
  54. package/package.json +114 -0
@@ -0,0 +1,271 @@
1
+ import { C as CoreDeps, S as SendWorker, R as RetentionWorker } from './index-CVUvaJms.js';
2
+ import { M as Message, W as WebhookEvent } from './webhook-kp6CiXk-.js';
3
+ import { R as RawWebhook } from './services-CfTEsetF.js';
4
+ import { j as SuppressionEntry, k as SuppressionReason, d as ApiScope, c as ApiKey, L as ListMessagesQuery } from './repositories-Bck6wJNS.js';
5
+
6
+ /**
7
+ * Input accepted by `outpost.send(...)` and `POST /messages` (TDR §4.3).
8
+ * Either `template` OR (`subject` + `html`/`text`) must be supplied.
9
+ */
10
+ interface EnqueueInput {
11
+ /** Required. Dedupes re-enqueues (TDR §3.1, decision #3). */
12
+ readonly idempotencyKey: string;
13
+ readonly to: string;
14
+ readonly template?: {
15
+ id: string;
16
+ version?: number;
17
+ vars: Record<string, unknown>;
18
+ };
19
+ readonly subject?: string;
20
+ readonly html?: string;
21
+ readonly text?: string;
22
+ /** Override the default provider for this message. */
23
+ readonly provider?: string;
24
+ /** Clear, queryable metadata. Never put PII here. */
25
+ readonly metadata?: Record<string, unknown>;
26
+ /** Phase 2 scheduling; if set, the worker won't claim it until then. */
27
+ readonly scheduledFor?: Date;
28
+ }
29
+ interface EnqueueResult {
30
+ readonly id: string;
31
+ readonly state: Message["state"];
32
+ readonly idempotencyKey: string;
33
+ /** True when an existing message was returned (idempotent replay). */
34
+ readonly deduplicated: boolean;
35
+ }
36
+ /**
37
+ * EnqueueMessage — persist-before-dispatch ingestion (TDR §3.1, decision #1).
38
+ *
39
+ * Order of operations is load-bearing:
40
+ * 1. Validate + sanitize (reject bad input synchronously, before any write).
41
+ * 2. Idempotency guard — return the existing message if the key is known.
42
+ * 3. Suppression check — suppressed recipients are recorded, never dispatched.
43
+ * 4. Seal PII (recipient + body) with the WRITE-side encryptor.
44
+ * 5. Insert as `queued`. The row exists before anything tries to send it.
45
+ * 6. Append an `enqueued` audit event.
46
+ *
47
+ * The send worker (a separate process) picks it up later by polling — the
48
+ * ingestion path NEVER publishes to a queue, avoiding the dual-write hazard
49
+ * (decision #2).
50
+ */
51
+ declare class EnqueueMessage {
52
+ private readonly deps;
53
+ constructor(deps: CoreDeps);
54
+ execute(input: EnqueueInput, actor: string): Promise<EnqueueResult>;
55
+ /** Resolve template or raw content into subject + body. */
56
+ private resolveContent;
57
+ /** Apply the configured strong sanitizer (or built-in fallback) to HTML. */
58
+ private sanitizeBody;
59
+ }
60
+
61
+ interface IngestWebhookResult {
62
+ readonly accepted: boolean;
63
+ readonly eventType: WebhookEvent["type"];
64
+ readonly messageId: string | null;
65
+ /** Why a verified event did not change state (e.g. unknown message). */
66
+ readonly note?: string;
67
+ }
68
+ /**
69
+ * IngestWebhook — the webhook worker's single responsibility (TDR §3.5).
70
+ *
71
+ * 1. Verify the signature via the named provider (NEVER trust unverified).
72
+ * 2. Record the raw event for traceability/replay.
73
+ * 3. Correlate to the outbox row by providerMessageId.
74
+ * 4. Transition the message lifecycle (validated against the state machine).
75
+ * 5. Feed the suppression list on hard bounce / complaint.
76
+ * 6. Append an audit event.
77
+ *
78
+ * Webhook endpoints are NOT API-key authenticated — the provider calls them.
79
+ * Trust is established purely by signature verification (TDR §5.2).
80
+ */
81
+ declare class IngestWebhook {
82
+ private readonly deps;
83
+ constructor(deps: CoreDeps);
84
+ execute(providerName: string, raw: RawWebhook): Promise<IngestWebhookResult>;
85
+ /** A soft bounce must not suppress; only hard bounces and complaints do. */
86
+ private isSuppressable;
87
+ private auditType;
88
+ }
89
+
90
+ /**
91
+ * ManageSuppression — view/add/remove suppression entries (TDR §3.6).
92
+ *
93
+ * All matching is by recipient HMAC, so the plaintext address is hashed with
94
+ * the same keyed HMAC used at ingestion. Adds/removes are audited.
95
+ */
96
+ declare class ManageSuppression {
97
+ private readonly deps;
98
+ constructor(deps: CoreDeps);
99
+ isSuppressed(address: string): Promise<boolean>;
100
+ /** Lookup by precomputed HMAC (the form the HTTP API exposes). */
101
+ getByHmac(recipientHmac: string): Promise<SuppressionEntry | null>;
102
+ suppress(address: string, reason: SuppressionReason, actor: string, note?: string): Promise<SuppressionEntry>;
103
+ /** Remove by HMAC (what the DELETE endpoint receives). Audited. */
104
+ unsuppressByHmac(recipientHmac: string, actor: string): Promise<boolean>;
105
+ list(limit?: number, offset?: number): Promise<SuppressionEntry[]>;
106
+ }
107
+
108
+ /**
109
+ * Hash an API key secret for storage. Keys are high-entropy random tokens
110
+ * (not user passwords), so a fast one-way SHA-256 is appropriate and lets us
111
+ * look the hash up directly. A slow password hash (bcrypt/argon2) buys nothing
112
+ * against a 256-bit random secret and would break O(1) lookup.
113
+ */
114
+ declare function hashApiKey(secret: string): string;
115
+ /** Generate an opaque, high-entropy key with a recognizable prefix. */
116
+ declare function generateApiKeySecret(): string;
117
+ interface CreatedApiKey {
118
+ readonly id: string;
119
+ readonly label: string;
120
+ readonly scopes: readonly ApiScope[];
121
+ readonly expiresAt: Date | null;
122
+ /** The plaintext secret — shown ONCE, never stored, never recoverable. */
123
+ readonly secret: string;
124
+ }
125
+ /**
126
+ * ManageApiKey — admin-side key lifecycle (TDR §5.1, §3.12).
127
+ *
128
+ * Only the hash is stored. The plaintext is returned exactly once at creation.
129
+ * Revocation takes effect immediately (no caching of key state beyond the
130
+ * documented short window in the Authenticate use case).
131
+ */
132
+ declare class ManageApiKey {
133
+ private readonly deps;
134
+ constructor(deps: CoreDeps);
135
+ create(input: {
136
+ label: string;
137
+ scopes: readonly ApiScope[];
138
+ expiresAt?: Date | null;
139
+ }): Promise<CreatedApiKey>;
140
+ revoke(id: string): Promise<boolean>;
141
+ /** Lists keys WITHOUT secrets (only hashes are stored anyway). */
142
+ list(): Promise<ApiKey[]>;
143
+ }
144
+
145
+ interface AuthContext {
146
+ readonly keyId: string;
147
+ readonly scopes: readonly ApiScope[];
148
+ }
149
+ /**
150
+ * Authenticate — validates an API key on every request (TDR §5.1).
151
+ *
152
+ * - Hashes the presented secret and looks up the stored hash.
153
+ * - Rejects missing / unknown / expired / revoked keys with 401.
154
+ * - Enforces the required scope (least privilege) with 403.
155
+ * - Touches `last_used_at` for observability.
156
+ *
157
+ * Revocation/expiry are enforced on every call (no long-lived caching), so
158
+ * they take effect immediately as the TDR requires.
159
+ */
160
+ declare class Authenticate {
161
+ private readonly deps;
162
+ constructor(deps: CoreDeps);
163
+ /** Resolve a bearer secret to an AuthContext or throw UnauthorizedError. */
164
+ resolve(presentedSecret: string | null | undefined): Promise<AuthContext>;
165
+ /** Resolve then assert the context carries the required scope. */
166
+ authorize(presentedSecret: string | null | undefined, required: ApiScope): Promise<AuthContext>;
167
+ /** Assert a scope on an already-resolved context. */
168
+ static requireScope(ctx: AuthContext, required: ApiScope): void;
169
+ /** Helper to extract a bearer/x-outpost-key value from headers. */
170
+ static extractKey(headers: Record<string, string | string[] | undefined>): string | null;
171
+ findKey(presentedSecret: string): Promise<ApiKey | null>;
172
+ }
173
+
174
+ /**
175
+ * A safe, PII-free projection of a message for read APIs and the admin panel.
176
+ * Operators see metadata and lifecycle, NOT the encrypted body/recipient.
177
+ * Body access is a separate, gated, audited operation (not exposed here).
178
+ */
179
+ interface MessageView {
180
+ readonly id: string;
181
+ readonly idempotencyKey: string;
182
+ readonly state: Message["state"];
183
+ readonly recipientHmac: string;
184
+ readonly subject: string;
185
+ readonly provider: string;
186
+ readonly templateId: string | null;
187
+ readonly templateVersion: number | null;
188
+ readonly metadata: Record<string, unknown>;
189
+ readonly attempts: number;
190
+ readonly nextAttemptAt: string;
191
+ readonly providerMessageId: string | null;
192
+ readonly lastError: string | null;
193
+ readonly createdAt: string;
194
+ readonly updatedAt: string;
195
+ }
196
+ declare function toView(m: Message): MessageView;
197
+ declare class GetMessage {
198
+ private readonly deps;
199
+ constructor(deps: CoreDeps);
200
+ execute(id: string): Promise<MessageView>;
201
+ }
202
+ declare class ListMessages {
203
+ private readonly deps;
204
+ constructor(deps: CoreDeps);
205
+ execute(query: ListMessagesQuery): Promise<MessageView[]>;
206
+ }
207
+ /**
208
+ * ReplayMessage — re-enqueue a dead-lettered (`failed`) message from the DLQ
209
+ * (TDR §3.4, §3.12). Resets the retry budget and schedules an immediate retry.
210
+ */
211
+ declare class ReplayMessage {
212
+ private readonly deps;
213
+ constructor(deps: CoreDeps);
214
+ execute(id: string, actor: string): Promise<MessageView>;
215
+ }
216
+
217
+ /**
218
+ * The high-level, typed programmatic client returned by `createOutpost`
219
+ * (TDR §4.2). Server-side use within the same app calls these methods directly;
220
+ * cross-service callers go through the HTTP handlers (which call the same use
221
+ * cases under the hood).
222
+ *
223
+ * `actor` labels who performed an action in the audit trail. The programmatic
224
+ * client defaults to `"programmatic"`; the HTTP layer passes the API key id.
225
+ */
226
+ declare class Outpost {
227
+ readonly deps: CoreDeps;
228
+ private readonly defaultActor;
229
+ readonly enqueueMessage: EnqueueMessage;
230
+ readonly ingestWebhook: IngestWebhook;
231
+ readonly suppression: ManageSuppression;
232
+ readonly keys: ManageApiKey;
233
+ readonly auth: Authenticate;
234
+ readonly send_worker: SendWorker;
235
+ readonly retention_worker: RetentionWorker;
236
+ private readonly getMessage;
237
+ private readonly listMessages;
238
+ private readonly replayMessage;
239
+ constructor(deps: CoreDeps, defaultActor?: string);
240
+ /** Enqueue a message (persist-then-queue). Idempotent on `idempotencyKey`. */
241
+ send(input: EnqueueInput, opts?: {
242
+ actor?: string;
243
+ }): Promise<EnqueueResult>;
244
+ /** Fetch a message's lifecycle + metadata (PII-free view). */
245
+ get(id: string): Promise<MessageView>;
246
+ /** List messages by state / recipient hash / date. */
247
+ list(query?: ListMessagesQuery): Promise<MessageView[]>;
248
+ /** Re-enqueue a dead-lettered (failed) message from the DLQ. */
249
+ replay(id: string, opts?: {
250
+ actor?: string;
251
+ }): Promise<MessageView>;
252
+ /** Check whether an address is on the suppression list. */
253
+ isSuppressed(address: string): Promise<boolean>;
254
+ /** Add an address to the suppression list (audited). */
255
+ suppress(address: string, reason?: SuppressionReason, opts?: {
256
+ note?: string;
257
+ actor?: string;
258
+ }): Promise<SuppressionEntry>;
259
+ /** Remove an address from the suppression list (audited). */
260
+ unsuppress(address: string, opts?: {
261
+ actor?: string;
262
+ }): Promise<boolean>;
263
+ /** Ingest a verified provider webhook (used by the HTTP webhook sink). */
264
+ webhook(provider: string, raw: RawWebhook): Promise<IngestWebhookResult>;
265
+ /** Convenience: run one send-worker cycle (cron/route-handler deployments). */
266
+ tickSend(): ReturnType<SendWorker["tick"]>;
267
+ /** Convenience: run one retention cycle. */
268
+ tickRetention(): ReturnType<RetentionWorker["tick"]>;
269
+ }
270
+
271
+ export { type AuthContext as A, type CreatedApiKey as C, type EnqueueInput as E, GetMessage as G, IngestWebhook as I, ListMessages as L, ManageApiKey as M, Outpost as O, ReplayMessage as R, Authenticate as a, EnqueueMessage as b, type EnqueueResult as c, type IngestWebhookResult as d, ManageSuppression as e, type MessageView as f, generateApiKeySecret as g, hashApiKey as h, toView as t };
@@ -0,0 +1,180 @@
1
+ import { S as Sealed, a as LifecycleState, M as Message, W as WebhookEvent } from './webhook-kp6CiXk-.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
+ /** Fields required to create a new outbox row. id/timestamps assigned by impl. */
84
+ interface NewMessage {
85
+ readonly idempotencyKey: string;
86
+ readonly recipientHmac: string;
87
+ readonly recipientSealed: Sealed;
88
+ readonly bodySealed: Sealed;
89
+ readonly subject: string;
90
+ readonly templateId: string | null;
91
+ readonly templateVersion: number | null;
92
+ readonly provider: string;
93
+ readonly metadata: Record<string, unknown>;
94
+ readonly state: LifecycleState;
95
+ readonly scheduledFor: Date | null;
96
+ readonly nextAttemptAt: Date;
97
+ }
98
+ interface ListMessagesQuery {
99
+ readonly state?: LifecycleState;
100
+ readonly recipientHmac?: string;
101
+ readonly provider?: string;
102
+ readonly createdAfter?: Date;
103
+ readonly createdBefore?: Date;
104
+ readonly limit?: number;
105
+ readonly offset?: number;
106
+ }
107
+ /** Patch applied during a state transition; impl bumps `updatedAt`. */
108
+ interface MessageStatePatch {
109
+ readonly state: LifecycleState;
110
+ readonly attempts?: number;
111
+ readonly nextAttemptAt?: Date;
112
+ readonly providerMessageId?: string | null;
113
+ readonly lastError?: string | null;
114
+ }
115
+ interface OutboxRepository {
116
+ insert(msg: NewMessage): Promise<Message>;
117
+ findById(id: string): Promise<Message | null>;
118
+ findByIdempotencyKey(key: string): Promise<Message | null>;
119
+ /** Correlate an inbound webhook back to its outbox row. */
120
+ findByProviderMessageId(providerMessageId: string): Promise<Message | null>;
121
+ list(query: ListMessagesQuery): Promise<Message[]>;
122
+ /**
123
+ * Atomically claim a batch of ready messages for sending and mark them
124
+ * `sending`, so concurrent send workers never grab the same row. Postgres
125
+ * impl uses `FOR UPDATE SKIP LOCKED`.
126
+ *
127
+ * Eligible rows are EITHER:
128
+ * - `queued` with `next_attempt_at <= now` and no future `scheduled_for`, OR
129
+ * - `sending` last updated before `reclaimBefore` — i.e. abandoned by a
130
+ * worker that crashed mid-dispatch (lease expiry). This makes dispatch
131
+ * crash-safe: a stuck row is retried rather than lost forever.
132
+ */
133
+ claimBatchForSending(limit: number, now: Date, reclaimBefore: Date): Promise<Message[]>;
134
+ /** Apply a validated state transition + persist the patch. */
135
+ updateState(id: string, patch: MessageStatePatch): Promise<void>;
136
+ /** Terminal rows older than `olderThan` and past their webhook window. */
137
+ claimTerminalForPurge(olderThan: Date, limit: number): Promise<Message[]>;
138
+ /** Wipe PII columns (keep the row + metadata + HMAC). Returns rows redacted. */
139
+ redactBatch(ids: readonly string[]): Promise<number>;
140
+ /** Hard-delete rows entirely. Returns rows deleted. */
141
+ deleteBatch(ids: readonly string[]): Promise<number>;
142
+ }
143
+ interface SuppressionRepository {
144
+ isSuppressed(recipientHmac: string): Promise<boolean>;
145
+ get(recipientHmac: string): Promise<SuppressionEntry | null>;
146
+ add(entry: {
147
+ recipientHmac: string;
148
+ reason: SuppressionReason;
149
+ createdBy: string;
150
+ note?: string;
151
+ }): Promise<SuppressionEntry>;
152
+ remove(recipientHmac: string): Promise<boolean>;
153
+ list(limit: number, offset: number): Promise<SuppressionEntry[]>;
154
+ }
155
+ interface AuditRepository {
156
+ append(event: NewAuditEvent): Promise<AuditEvent>;
157
+ listForMessage(messageId: string): Promise<AuditEvent[]>;
158
+ /** Delete audit rows older than the cutoff, in batches. Returns count. */
159
+ purgeOlderThan(cutoff: Date, batchSize: number): Promise<number>;
160
+ }
161
+ interface NewApiKey {
162
+ readonly label: string;
163
+ readonly keyHash: string;
164
+ readonly scopes: readonly ApiScope[];
165
+ readonly expiresAt: Date | null;
166
+ }
167
+ interface ApiKeyRepository {
168
+ insert(key: NewApiKey): Promise<ApiKey>;
169
+ findByHash(keyHash: string): Promise<ApiKey | null>;
170
+ findById(id: string): Promise<ApiKey | null>;
171
+ list(): Promise<ApiKey[]>;
172
+ revoke(id: string, at: Date): Promise<boolean>;
173
+ touchLastUsed(id: string, at: Date): Promise<void>;
174
+ }
175
+ /** Raw verified webhook events, retained for traceability/replay (TDR §7). */
176
+ interface WebhookEventRepository {
177
+ record(event: WebhookEvent): Promise<void>;
178
+ }
179
+
180
+ export { type AuditRepository as A, 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 NewAuditEvent as g, type NewMessage as h, SUPPRESSION_REASONS as i, type SuppressionEntry as j, type SuppressionReason as k, hasScope as l, isKeyActive as m };
@@ -0,0 +1,180 @@
1
+ import { S as Sealed, a as LifecycleState, M as Message, W as WebhookEvent } from './webhook-kp6CiXk-.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
+ /** Fields required to create a new outbox row. id/timestamps assigned by impl. */
84
+ interface NewMessage {
85
+ readonly idempotencyKey: string;
86
+ readonly recipientHmac: string;
87
+ readonly recipientSealed: Sealed;
88
+ readonly bodySealed: Sealed;
89
+ readonly subject: string;
90
+ readonly templateId: string | null;
91
+ readonly templateVersion: number | null;
92
+ readonly provider: string;
93
+ readonly metadata: Record<string, unknown>;
94
+ readonly state: LifecycleState;
95
+ readonly scheduledFor: Date | null;
96
+ readonly nextAttemptAt: Date;
97
+ }
98
+ interface ListMessagesQuery {
99
+ readonly state?: LifecycleState;
100
+ readonly recipientHmac?: string;
101
+ readonly provider?: string;
102
+ readonly createdAfter?: Date;
103
+ readonly createdBefore?: Date;
104
+ readonly limit?: number;
105
+ readonly offset?: number;
106
+ }
107
+ /** Patch applied during a state transition; impl bumps `updatedAt`. */
108
+ interface MessageStatePatch {
109
+ readonly state: LifecycleState;
110
+ readonly attempts?: number;
111
+ readonly nextAttemptAt?: Date;
112
+ readonly providerMessageId?: string | null;
113
+ readonly lastError?: string | null;
114
+ }
115
+ interface OutboxRepository {
116
+ insert(msg: NewMessage): Promise<Message>;
117
+ findById(id: string): Promise<Message | null>;
118
+ findByIdempotencyKey(key: string): Promise<Message | null>;
119
+ /** Correlate an inbound webhook back to its outbox row. */
120
+ findByProviderMessageId(providerMessageId: string): Promise<Message | null>;
121
+ list(query: ListMessagesQuery): Promise<Message[]>;
122
+ /**
123
+ * Atomically claim a batch of ready messages for sending and mark them
124
+ * `sending`, so concurrent send workers never grab the same row. Postgres
125
+ * impl uses `FOR UPDATE SKIP LOCKED`.
126
+ *
127
+ * Eligible rows are EITHER:
128
+ * - `queued` with `next_attempt_at <= now` and no future `scheduled_for`, OR
129
+ * - `sending` last updated before `reclaimBefore` — i.e. abandoned by a
130
+ * worker that crashed mid-dispatch (lease expiry). This makes dispatch
131
+ * crash-safe: a stuck row is retried rather than lost forever.
132
+ */
133
+ claimBatchForSending(limit: number, now: Date, reclaimBefore: Date): Promise<Message[]>;
134
+ /** Apply a validated state transition + persist the patch. */
135
+ updateState(id: string, patch: MessageStatePatch): Promise<void>;
136
+ /** Terminal rows older than `olderThan` and past their webhook window. */
137
+ claimTerminalForPurge(olderThan: Date, limit: number): Promise<Message[]>;
138
+ /** Wipe PII columns (keep the row + metadata + HMAC). Returns rows redacted. */
139
+ redactBatch(ids: readonly string[]): Promise<number>;
140
+ /** Hard-delete rows entirely. Returns rows deleted. */
141
+ deleteBatch(ids: readonly string[]): Promise<number>;
142
+ }
143
+ interface SuppressionRepository {
144
+ isSuppressed(recipientHmac: string): Promise<boolean>;
145
+ get(recipientHmac: string): Promise<SuppressionEntry | null>;
146
+ add(entry: {
147
+ recipientHmac: string;
148
+ reason: SuppressionReason;
149
+ createdBy: string;
150
+ note?: string;
151
+ }): Promise<SuppressionEntry>;
152
+ remove(recipientHmac: string): Promise<boolean>;
153
+ list(limit: number, offset: number): Promise<SuppressionEntry[]>;
154
+ }
155
+ interface AuditRepository {
156
+ append(event: NewAuditEvent): Promise<AuditEvent>;
157
+ listForMessage(messageId: string): Promise<AuditEvent[]>;
158
+ /** Delete audit rows older than the cutoff, in batches. Returns count. */
159
+ purgeOlderThan(cutoff: Date, batchSize: number): Promise<number>;
160
+ }
161
+ interface NewApiKey {
162
+ readonly label: string;
163
+ readonly keyHash: string;
164
+ readonly scopes: readonly ApiScope[];
165
+ readonly expiresAt: Date | null;
166
+ }
167
+ interface ApiKeyRepository {
168
+ insert(key: NewApiKey): Promise<ApiKey>;
169
+ findByHash(keyHash: string): Promise<ApiKey | null>;
170
+ findById(id: string): Promise<ApiKey | null>;
171
+ list(): Promise<ApiKey[]>;
172
+ revoke(id: string, at: Date): Promise<boolean>;
173
+ touchLastUsed(id: string, at: Date): Promise<void>;
174
+ }
175
+ /** Raw verified webhook events, retained for traceability/replay (TDR §7). */
176
+ interface WebhookEventRepository {
177
+ record(event: WebhookEvent): Promise<void>;
178
+ }
179
+
180
+ export { type AuditRepository as A, 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 NewAuditEvent as g, type NewMessage as h, SUPPRESSION_REASONS as i, type SuppressionEntry as j, type SuppressionReason as k, hasScope as l, isKeyActive as m };