@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.
- package/AGENTS.md +268 -0
- package/LICENSE +21 -0
- package/README.md +117 -0
- package/dist/adapters/drizzle/index.cjs +405 -0
- package/dist/adapters/drizzle/index.cjs.map +1 -0
- package/dist/adapters/drizzle/index.d.cts +1765 -0
- package/dist/adapters/drizzle/index.d.ts +1765 -0
- package/dist/adapters/drizzle/index.js +387 -0
- package/dist/adapters/drizzle/index.js.map +1 -0
- package/dist/adapters/index.cjs +584 -0
- package/dist/adapters/index.cjs.map +1 -0
- package/dist/adapters/index.d.cts +232 -0
- package/dist/adapters/index.d.ts +232 -0
- package/dist/adapters/index.js +565 -0
- package/dist/adapters/index.js.map +1 -0
- package/dist/fake-BY6t7UXb.d.cts +30 -0
- package/dist/fake-en-oOdg0.d.ts +30 -0
- package/dist/http/index.cjs +224 -0
- package/dist/http/index.cjs.map +1 -0
- package/dist/http/index.d.cts +49 -0
- package/dist/http/index.d.ts +49 -0
- package/dist/http/index.js +221 -0
- package/dist/http/index.js.map +1 -0
- package/dist/index-CVUvaJms.d.ts +179 -0
- package/dist/index-Dmt-aLH2.d.cts +179 -0
- package/dist/index.cjs +1387 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +153 -0
- package/dist/index.d.ts +153 -0
- package/dist/index.js +1331 -0
- package/dist/index.js.map +1 -0
- package/dist/outpost-client-yUijE00q.d.cts +271 -0
- package/dist/outpost-client-ymTJISpu.d.ts +271 -0
- package/dist/repositories-Bck6wJNS.d.ts +180 -0
- package/dist/repositories-DhUe8f2R.d.cts +180 -0
- package/dist/services-CQINhAGo.d.cts +90 -0
- package/dist/services-CfTEsetF.d.ts +90 -0
- package/dist/template-CREUq7bB.d.ts +260 -0
- package/dist/template-DxI_p2Ny.d.cts +260 -0
- package/dist/testing/index.cjs +321 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.cts +97 -0
- package/dist/testing/index.d.ts +97 -0
- package/dist/testing/index.js +312 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/webhook-kp6CiXk-.d.cts +149 -0
- package/dist/webhook-kp6CiXk-.d.ts +149 -0
- package/dist/workers/index.cjs +430 -0
- package/dist/workers/index.cjs.map +1 -0
- package/dist/workers/index.d.cts +5 -0
- package/dist/workers/index.d.ts +5 -0
- package/dist/workers/index.js +427 -0
- package/dist/workers/index.js.map +1 -0
- package/package.json +114 -0
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { S as Sealed, b as MessageBody } from './webhook-kp6CiXk-.cjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Encryption ports (TDR §5.4).
|
|
5
|
+
*
|
|
6
|
+
* `Encryptor` is split into seal (write) and open (read) so the asymmetric,
|
|
7
|
+
* least-privilege model is expressible in the type system: the ingestion API
|
|
8
|
+
* is wired with a seal-only encryptor (public key), while the send worker holds
|
|
9
|
+
* the open-capable one (private key). Compromising the web API therefore can
|
|
10
|
+
* never read plaintext bodies back.
|
|
11
|
+
*/
|
|
12
|
+
interface Encryptor {
|
|
13
|
+
/** Algorithm tag stamped onto produced `Sealed` values. */
|
|
14
|
+
readonly alg: string;
|
|
15
|
+
/** Encrypt plaintext for storage at rest. */
|
|
16
|
+
seal(plaintext: string): Promise<Sealed>;
|
|
17
|
+
/**
|
|
18
|
+
* Decrypt a sealed value. Seal-only encryptors (public-key ingestion side)
|
|
19
|
+
* reject this with an error — by construction they cannot read.
|
|
20
|
+
*/
|
|
21
|
+
open(sealed: Sealed): Promise<string>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Deterministic keyed HMAC of a recipient address. Used as the searchable
|
|
25
|
+
* column for suppression matching and idempotency-by-recipient when the
|
|
26
|
+
* plaintext recipient is encrypted (TDR §5.4 condition 3). Deterministic so the
|
|
27
|
+
* same address always maps to the same digest; keyed so the digest cannot be
|
|
28
|
+
* brute-forced from a leaked dump without the key.
|
|
29
|
+
*/
|
|
30
|
+
interface RecipientHasher {
|
|
31
|
+
hash(address: string): string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Retry policy: exponential backoff with full jitter (TDR §3.4).
|
|
36
|
+
*
|
|
37
|
+
* Pure function of (attempt number, config) → delay. Jitter is injected as a
|
|
38
|
+
* 0..1 random sample so the policy stays deterministic and testable (the
|
|
39
|
+
* worker passes a real random; tests pass a fixed value).
|
|
40
|
+
*/
|
|
41
|
+
interface RetryConfig {
|
|
42
|
+
/** Max dispatch attempts before a message is dead-lettered. */
|
|
43
|
+
readonly maxAttempts: number;
|
|
44
|
+
/** Base backoff in ms (first retry waits ~this, before jitter). */
|
|
45
|
+
readonly baseDelayMs: number;
|
|
46
|
+
/** Cap on the backoff in ms. */
|
|
47
|
+
readonly maxDelayMs: number;
|
|
48
|
+
}
|
|
49
|
+
declare const DEFAULT_RETRY: RetryConfig;
|
|
50
|
+
/** True once attempts have reached the budget — message goes to the DLQ. */
|
|
51
|
+
declare function isExhausted(attempts: number, config: RetryConfig): boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Backoff for the NEXT attempt after `attempts` failed tries.
|
|
54
|
+
* delay = min(maxDelay, base * 2^(attempts-1)) then full-jitter: random in
|
|
55
|
+
* [0, delay]. `jitter` is a sample in [0,1).
|
|
56
|
+
*/
|
|
57
|
+
declare function backoffMs(attempts: number, config: RetryConfig, jitter: number): number;
|
|
58
|
+
/** Convenience: the Date of the next attempt from `now`. */
|
|
59
|
+
declare function nextAttemptAt(attempts: number, config: RetryConfig, jitter: number, now: Date): Date;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Outbound sanitization (TDR §3.2 step 2, §5.3).
|
|
63
|
+
*
|
|
64
|
+
* These are conservative, dependency-free guards focused on the email-specific
|
|
65
|
+
* attack surface: header injection (CRLF) and oversize payloads. For rich HTML
|
|
66
|
+
* sanitization against XSS you SHOULD plug a hardened sanitizer (e.g.
|
|
67
|
+
* `sanitize-html` / DOMPurify) via `createOutpost({ sanitizeHtml })`; the
|
|
68
|
+
* built-in `stripDangerousHtml` below is a last-resort fallback, not a
|
|
69
|
+
* substitute for a real sanitizer.
|
|
70
|
+
*/
|
|
71
|
+
/** Default ceilings; override via config. */
|
|
72
|
+
interface SanitizeLimits {
|
|
73
|
+
readonly maxSubjectBytes: number;
|
|
74
|
+
readonly maxBodyBytes: number;
|
|
75
|
+
readonly maxRecipientBytes: number;
|
|
76
|
+
readonly maxHeaderValueBytes: number;
|
|
77
|
+
}
|
|
78
|
+
declare const DEFAULT_SANITIZE_LIMITS: SanitizeLimits;
|
|
79
|
+
/**
|
|
80
|
+
* Reject control characters in any value used as an email header (To, Subject,
|
|
81
|
+
* custom headers). This is THE header-injection defense — without it an attacker
|
|
82
|
+
* can inject a CR/LF + "Bcc:" and turn one message into many, or use a NUL to
|
|
83
|
+
* truncate. Implemented as a char-code scan (not a regex) so the intent is
|
|
84
|
+
* unambiguous: reject every C0 control char (0x00–0x1F, which includes CR, LF,
|
|
85
|
+
* NUL and TAB) and DEL (0x7F), while ALLOWING ordinary printable characters
|
|
86
|
+
* including the space (0x20). An earlier regex form also matched the space,
|
|
87
|
+
* which wrongly rejected normal multi-word subjects.
|
|
88
|
+
*/
|
|
89
|
+
declare function assertNoHeaderInjection(field: string, value: string): void;
|
|
90
|
+
declare function sanitizeSubject(subject: string, limits?: SanitizeLimits): string;
|
|
91
|
+
declare function sanitizeRecipient(to: string, limits?: SanitizeLimits): string;
|
|
92
|
+
declare function sanitizeHeaders(headers: Record<string, string>, limits?: SanitizeLimits): Record<string, string>;
|
|
93
|
+
declare function assertBodyWithinLimits(body: {
|
|
94
|
+
html?: string;
|
|
95
|
+
text?: string;
|
|
96
|
+
}, limits?: SanitizeLimits): void;
|
|
97
|
+
/**
|
|
98
|
+
* Last-resort HTML hardening: strip <script>/<style>/<iframe>/<object> blocks,
|
|
99
|
+
* `on*=` event handlers, and `javascript:` URLs. NOT a full sanitizer — prefer
|
|
100
|
+
* a real one via config. Returns cleaned HTML.
|
|
101
|
+
*/
|
|
102
|
+
declare function stripDangerousHtml(html: string): string;
|
|
103
|
+
/** Validate an attachment's MIME type and size (TDR §3.2). */
|
|
104
|
+
interface AttachmentSpec {
|
|
105
|
+
readonly filename: string;
|
|
106
|
+
readonly contentType: string;
|
|
107
|
+
readonly sizeBytes: number;
|
|
108
|
+
}
|
|
109
|
+
interface AttachmentPolicy {
|
|
110
|
+
readonly allowedMimeTypes: readonly string[];
|
|
111
|
+
readonly maxSizeBytes: number;
|
|
112
|
+
}
|
|
113
|
+
declare const DEFAULT_ATTACHMENT_POLICY: AttachmentPolicy;
|
|
114
|
+
declare function validateAttachment(att: AttachmentSpec, policy?: AttachmentPolicy): void;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Recipient domain validation (TDR §3.2 step 3, §3.10, decision #4).
|
|
118
|
+
*
|
|
119
|
+
* Two checks, in order of cost:
|
|
120
|
+
* 1. Syntax — always on. RFC-5322-ish address shape.
|
|
121
|
+
* 2. MX records — optional, cached. Confirms the domain can receive mail.
|
|
122
|
+
*
|
|
123
|
+
* Outpost deliberately does NOT probe whether an individual mailbox exists:
|
|
124
|
+
* it is unreliable and damages sender reputation (decision #4).
|
|
125
|
+
*/
|
|
126
|
+
interface DomainValidationConfig {
|
|
127
|
+
readonly syntax: boolean;
|
|
128
|
+
readonly mx: boolean;
|
|
129
|
+
readonly mailboxProbe: false;
|
|
130
|
+
/** TTL for the MX-result cache, ms. */
|
|
131
|
+
readonly mxCacheTtlMs?: number;
|
|
132
|
+
}
|
|
133
|
+
declare const DEFAULT_DOMAIN_VALIDATION: DomainValidationConfig;
|
|
134
|
+
/**
|
|
135
|
+
* Pluggable MX resolver so the core stays free of `node:dns`. The default
|
|
136
|
+
* resolver (provided in adapters) uses `dns/promises`. Returns the MX hosts.
|
|
137
|
+
*/
|
|
138
|
+
interface MxResolver {
|
|
139
|
+
resolveMx(domain: string): Promise<string[]>;
|
|
140
|
+
}
|
|
141
|
+
declare function extractDomain(address: string): string;
|
|
142
|
+
declare function validateSyntax(address: string): string;
|
|
143
|
+
/** Small in-process TTL cache for MX results to avoid hammering DNS. */
|
|
144
|
+
declare class MxCache {
|
|
145
|
+
private readonly ttlMs;
|
|
146
|
+
private readonly entries;
|
|
147
|
+
constructor(ttlMs: number);
|
|
148
|
+
get(domain: string, nowMs: number): string[] | undefined;
|
|
149
|
+
set(domain: string, hosts: string[], nowMs: number): void;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Full recipient validation. `syntax` is enforced synchronously; `mx`, when
|
|
153
|
+
* enabled, resolves (cached) and throws if the domain has no usable MX (and no
|
|
154
|
+
* fallback A record — many small domains accept mail on the A record).
|
|
155
|
+
*/
|
|
156
|
+
declare function validateRecipient(address: string, config: DomainValidationConfig, deps: {
|
|
157
|
+
mxResolver?: MxResolver;
|
|
158
|
+
mxCache?: MxCache;
|
|
159
|
+
nowMs: number;
|
|
160
|
+
}): Promise<void>;
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Retention policy domain types (TDR §3.9, §5.5).
|
|
164
|
+
*
|
|
165
|
+
* Operational data (the outbox payload) and audit data have independent TTLs.
|
|
166
|
+
* The default action on purge is REDACTION, not deletion: the PII payload is
|
|
167
|
+
* wiped while the audit row (metadata + HMAC) survives. This satisfies data
|
|
168
|
+
* minimization without destroying the audit trail.
|
|
169
|
+
*/
|
|
170
|
+
interface RetentionPolicy {
|
|
171
|
+
/** Age (days) after which a terminal outbox row's PII may be purged. */
|
|
172
|
+
readonly operationalTtlDays: number;
|
|
173
|
+
/** Age (days) after which audit events may be deleted. */
|
|
174
|
+
readonly auditTtlDays: number;
|
|
175
|
+
/** When true (default) purge redacts PII; when false it deletes the row. */
|
|
176
|
+
readonly redactOnPurge: boolean;
|
|
177
|
+
/**
|
|
178
|
+
* Grace window (hours) after a message reaches a terminal state during which
|
|
179
|
+
* it is NOT purged, so late webhooks (delivery/bounce) can still arrive.
|
|
180
|
+
* Purging earlier would break bounce/complaint handling.
|
|
181
|
+
*/
|
|
182
|
+
readonly webhookWindowHours: number;
|
|
183
|
+
/** Rows deleted/redacted per batch, to avoid long table locks. */
|
|
184
|
+
readonly batchSize: number;
|
|
185
|
+
}
|
|
186
|
+
declare const DEFAULT_RETENTION: RetentionPolicy;
|
|
187
|
+
/**
|
|
188
|
+
* The cutoff before which a terminal message becomes eligible for purge:
|
|
189
|
+
* it must be older than the operational TTL AND past the webhook window.
|
|
190
|
+
* Returns the latest (most conservative) of the two cutoffs.
|
|
191
|
+
*/
|
|
192
|
+
declare function purgeCutoff(policy: RetentionPolicy, now: Date): Date;
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Layered rate-limit budgets (TDR §3.2 step 4). Each is a token-bucket-style
|
|
196
|
+
* "max events per window". The in-memory limiter and any external limiter share
|
|
197
|
+
* this shape via the `RateLimiter` port.
|
|
198
|
+
*/
|
|
199
|
+
interface RateLimitConfig {
|
|
200
|
+
/** Global ceiling across all providers/recipients. */
|
|
201
|
+
readonly global?: RateBudget;
|
|
202
|
+
/** Per-provider ceiling, keyed by provider name. */
|
|
203
|
+
readonly perProvider?: RateBudget;
|
|
204
|
+
/** Per recipient-domain ceiling. */
|
|
205
|
+
readonly perRecipientDomain?: RateBudget;
|
|
206
|
+
}
|
|
207
|
+
interface RateBudget {
|
|
208
|
+
readonly max: number;
|
|
209
|
+
readonly windowMs: number;
|
|
210
|
+
}
|
|
211
|
+
/** Fully-resolved internal config — every field defaulted, no optionals. */
|
|
212
|
+
interface ResolvedConfig {
|
|
213
|
+
readonly retry: RetryConfig;
|
|
214
|
+
readonly retention: RetentionPolicy;
|
|
215
|
+
readonly sanitize: SanitizeLimits;
|
|
216
|
+
readonly attachments: AttachmentPolicy;
|
|
217
|
+
readonly domainValidation: DomainValidationConfig;
|
|
218
|
+
readonly rateLimits: RateLimitConfig;
|
|
219
|
+
/** Max rows the send worker claims per poll. */
|
|
220
|
+
readonly sendBatchSize: number;
|
|
221
|
+
/**
|
|
222
|
+
* Lease window for `sending` rows, ms. A row left in `sending` longer than
|
|
223
|
+
* this is treated as abandoned (its worker crashed mid-dispatch) and is
|
|
224
|
+
* reclaimed by the next poll. Keep comfortably larger than a real dispatch.
|
|
225
|
+
*/
|
|
226
|
+
readonly staleSendingLeaseMs: number;
|
|
227
|
+
}
|
|
228
|
+
interface ConfigOverrides {
|
|
229
|
+
retry?: Partial<RetryConfig>;
|
|
230
|
+
retention?: Partial<RetentionPolicy>;
|
|
231
|
+
sanitize?: Partial<SanitizeLimits>;
|
|
232
|
+
attachments?: Partial<AttachmentPolicy>;
|
|
233
|
+
domainValidation?: Partial<Omit<DomainValidationConfig, "mailboxProbe">>;
|
|
234
|
+
rateLimits?: RateLimitConfig;
|
|
235
|
+
sendBatchSize?: number;
|
|
236
|
+
staleSendingLeaseMs?: number;
|
|
237
|
+
}
|
|
238
|
+
declare function resolveConfig(overrides?: ConfigOverrides): ResolvedConfig;
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Template port (TDR §3.7). Resolves a template id+version and a bag of
|
|
242
|
+
* variables into a concrete subject + body. Implementations MUST escape
|
|
243
|
+
* user-supplied variables to prevent injection into HTML.
|
|
244
|
+
*
|
|
245
|
+
* Phase 1 ships a simple in-memory renderer; versioning + an admin editor are
|
|
246
|
+
* Phase 2, but the port is defined now so the API shape is stable.
|
|
247
|
+
*/
|
|
248
|
+
interface RenderedTemplate {
|
|
249
|
+
readonly subject: string;
|
|
250
|
+
readonly body: MessageBody;
|
|
251
|
+
}
|
|
252
|
+
interface TemplateRenderer {
|
|
253
|
+
render(input: {
|
|
254
|
+
id: string;
|
|
255
|
+
version?: number;
|
|
256
|
+
vars: Record<string, unknown>;
|
|
257
|
+
}): Promise<RenderedTemplate>;
|
|
258
|
+
}
|
|
259
|
+
|
|
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 };
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
|
|
5
|
+
// src/testing/in-memory-repositories.ts
|
|
6
|
+
|
|
7
|
+
// src/domain/lifecycle.ts
|
|
8
|
+
var TERMINAL_STATES = [
|
|
9
|
+
"delivered",
|
|
10
|
+
"bounced",
|
|
11
|
+
"complained",
|
|
12
|
+
"failed",
|
|
13
|
+
"suppressed"
|
|
14
|
+
];
|
|
15
|
+
new Set(TERMINAL_STATES);
|
|
16
|
+
|
|
17
|
+
// src/testing/in-memory-repositories.ts
|
|
18
|
+
var REDACTED = { alg: "redacted", ciphertext: "" };
|
|
19
|
+
var InMemoryOutboxRepository = class {
|
|
20
|
+
/** Optional injected clock so retention/lifecycle is deterministic in tests. */
|
|
21
|
+
constructor(clock = () => /* @__PURE__ */ new Date()) {
|
|
22
|
+
this.clock = clock;
|
|
23
|
+
}
|
|
24
|
+
messages = /* @__PURE__ */ new Map();
|
|
25
|
+
async insert(msg) {
|
|
26
|
+
const now = this.clock();
|
|
27
|
+
const message = {
|
|
28
|
+
id: crypto.randomUUID(),
|
|
29
|
+
idempotencyKey: msg.idempotencyKey,
|
|
30
|
+
state: msg.state,
|
|
31
|
+
recipientHmac: msg.recipientHmac,
|
|
32
|
+
recipientSealed: msg.recipientSealed,
|
|
33
|
+
bodySealed: msg.bodySealed,
|
|
34
|
+
subject: msg.subject,
|
|
35
|
+
templateId: msg.templateId,
|
|
36
|
+
templateVersion: msg.templateVersion,
|
|
37
|
+
provider: msg.provider,
|
|
38
|
+
metadata: msg.metadata,
|
|
39
|
+
attempts: 0,
|
|
40
|
+
nextAttemptAt: msg.nextAttemptAt,
|
|
41
|
+
scheduledFor: msg.scheduledFor,
|
|
42
|
+
providerMessageId: null,
|
|
43
|
+
lastError: null,
|
|
44
|
+
createdAt: now,
|
|
45
|
+
updatedAt: now
|
|
46
|
+
};
|
|
47
|
+
this.messages.set(message.id, message);
|
|
48
|
+
return { ...message };
|
|
49
|
+
}
|
|
50
|
+
async findById(id) {
|
|
51
|
+
const m = this.messages.get(id);
|
|
52
|
+
return m ? { ...m } : null;
|
|
53
|
+
}
|
|
54
|
+
async findByIdempotencyKey(key) {
|
|
55
|
+
for (const m of this.messages.values()) if (m.idempotencyKey === key) return { ...m };
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
async findByProviderMessageId(id) {
|
|
59
|
+
for (const m of this.messages.values()) if (m.providerMessageId === id) return { ...m };
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
async list(query) {
|
|
63
|
+
let all = [...this.messages.values()];
|
|
64
|
+
if (query.state) all = all.filter((m) => m.state === query.state);
|
|
65
|
+
if (query.recipientHmac) all = all.filter((m) => m.recipientHmac === query.recipientHmac);
|
|
66
|
+
if (query.provider) all = all.filter((m) => m.provider === query.provider);
|
|
67
|
+
if (query.createdAfter) all = all.filter((m) => m.createdAt >= query.createdAfter);
|
|
68
|
+
if (query.createdBefore) all = all.filter((m) => m.createdAt < query.createdBefore);
|
|
69
|
+
all.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
|
|
70
|
+
const offset = query.offset ?? 0;
|
|
71
|
+
return all.slice(offset, offset + (query.limit ?? 50)).map((m) => ({ ...m }));
|
|
72
|
+
}
|
|
73
|
+
async claimBatchForSending(limit, now, reclaimBefore) {
|
|
74
|
+
const claimed = [];
|
|
75
|
+
const eligible = [...this.messages.values()].filter(
|
|
76
|
+
(m) => m.state === "queued" && m.nextAttemptAt <= now && (m.scheduledFor === null || m.scheduledFor <= now) || m.state === "sending" && m.updatedAt < reclaimBefore
|
|
77
|
+
).sort((a, b) => a.nextAttemptAt.getTime() - b.nextAttemptAt.getTime()).slice(0, limit);
|
|
78
|
+
for (const m of eligible) {
|
|
79
|
+
m.state = "sending";
|
|
80
|
+
m.updatedAt = now;
|
|
81
|
+
claimed.push({ ...m });
|
|
82
|
+
}
|
|
83
|
+
return claimed;
|
|
84
|
+
}
|
|
85
|
+
async updateState(id, patch) {
|
|
86
|
+
const m = this.messages.get(id);
|
|
87
|
+
if (!m) return;
|
|
88
|
+
m.state = patch.state;
|
|
89
|
+
if (patch.attempts !== void 0) m.attempts = patch.attempts;
|
|
90
|
+
if (patch.nextAttemptAt !== void 0) m.nextAttemptAt = patch.nextAttemptAt;
|
|
91
|
+
if (patch.providerMessageId !== void 0) m.providerMessageId = patch.providerMessageId;
|
|
92
|
+
if (patch.lastError !== void 0) m.lastError = patch.lastError;
|
|
93
|
+
m.updatedAt = this.clock();
|
|
94
|
+
}
|
|
95
|
+
async claimTerminalForPurge(olderThan, limit) {
|
|
96
|
+
const terminal = new Set(TERMINAL_STATES);
|
|
97
|
+
return [...this.messages.values()].filter(
|
|
98
|
+
(m) => terminal.has(m.state) && m.updatedAt < olderThan && m.bodySealed.alg !== "redacted"
|
|
99
|
+
).sort((a, b) => a.updatedAt.getTime() - b.updatedAt.getTime()).slice(0, limit).map((m) => ({ ...m }));
|
|
100
|
+
}
|
|
101
|
+
async redactBatch(ids) {
|
|
102
|
+
let n = 0;
|
|
103
|
+
for (const id of ids) {
|
|
104
|
+
const m = this.messages.get(id);
|
|
105
|
+
if (m) {
|
|
106
|
+
m.recipientSealed = REDACTED;
|
|
107
|
+
m.bodySealed = REDACTED;
|
|
108
|
+
m.updatedAt = this.clock();
|
|
109
|
+
n++;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return n;
|
|
113
|
+
}
|
|
114
|
+
async deleteBatch(ids) {
|
|
115
|
+
let n = 0;
|
|
116
|
+
for (const id of ids) if (this.messages.delete(id)) n++;
|
|
117
|
+
return n;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
var InMemorySuppressionRepository = class {
|
|
121
|
+
entries = /* @__PURE__ */ new Map();
|
|
122
|
+
async isSuppressed(recipientHmac) {
|
|
123
|
+
return this.entries.has(recipientHmac);
|
|
124
|
+
}
|
|
125
|
+
async get(recipientHmac) {
|
|
126
|
+
return this.entries.get(recipientHmac) ?? null;
|
|
127
|
+
}
|
|
128
|
+
async add(entry) {
|
|
129
|
+
const existing = this.entries.get(entry.recipientHmac);
|
|
130
|
+
if (existing) return existing;
|
|
131
|
+
const created = { ...entry, createdAt: /* @__PURE__ */ new Date() };
|
|
132
|
+
this.entries.set(entry.recipientHmac, created);
|
|
133
|
+
return created;
|
|
134
|
+
}
|
|
135
|
+
async remove(recipientHmac) {
|
|
136
|
+
return this.entries.delete(recipientHmac);
|
|
137
|
+
}
|
|
138
|
+
async list(limit, offset) {
|
|
139
|
+
return [...this.entries.values()].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()).slice(offset, offset + limit);
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
var InMemoryAuditRepository = class {
|
|
143
|
+
constructor(clock = () => /* @__PURE__ */ new Date()) {
|
|
144
|
+
this.clock = clock;
|
|
145
|
+
}
|
|
146
|
+
events = [];
|
|
147
|
+
async append(event) {
|
|
148
|
+
const created = {
|
|
149
|
+
id: crypto.randomUUID(),
|
|
150
|
+
messageId: event.messageId,
|
|
151
|
+
eventType: event.eventType,
|
|
152
|
+
actor: event.actor,
|
|
153
|
+
detail: event.detail ?? null,
|
|
154
|
+
at: this.clock()
|
|
155
|
+
};
|
|
156
|
+
this.events.push(created);
|
|
157
|
+
return created;
|
|
158
|
+
}
|
|
159
|
+
async listForMessage(messageId) {
|
|
160
|
+
return this.events.filter((e) => e.messageId === messageId);
|
|
161
|
+
}
|
|
162
|
+
async purgeOlderThan(cutoff, _batchSize) {
|
|
163
|
+
const before = this.events.length;
|
|
164
|
+
for (let i = this.events.length - 1; i >= 0; i--) {
|
|
165
|
+
if (this.events[i].at < cutoff) this.events.splice(i, 1);
|
|
166
|
+
}
|
|
167
|
+
return before - this.events.length;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
var InMemoryApiKeyRepository = class {
|
|
171
|
+
keys = /* @__PURE__ */ new Map();
|
|
172
|
+
async insert(key) {
|
|
173
|
+
const created = {
|
|
174
|
+
id: crypto.randomUUID(),
|
|
175
|
+
label: key.label,
|
|
176
|
+
keyHash: key.keyHash,
|
|
177
|
+
scopes: key.scopes,
|
|
178
|
+
expiresAt: key.expiresAt,
|
|
179
|
+
revokedAt: null,
|
|
180
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
181
|
+
lastUsedAt: null
|
|
182
|
+
};
|
|
183
|
+
this.keys.set(created.id, created);
|
|
184
|
+
return created;
|
|
185
|
+
}
|
|
186
|
+
async findByHash(keyHash) {
|
|
187
|
+
for (const k of this.keys.values()) if (k.keyHash === keyHash) return { ...k };
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
async findById(id) {
|
|
191
|
+
const k = this.keys.get(id);
|
|
192
|
+
return k ? { ...k } : null;
|
|
193
|
+
}
|
|
194
|
+
async list() {
|
|
195
|
+
return [...this.keys.values()];
|
|
196
|
+
}
|
|
197
|
+
async revoke(id, at) {
|
|
198
|
+
const k = this.keys.get(id);
|
|
199
|
+
if (!k || k.revokedAt) return false;
|
|
200
|
+
k.revokedAt = at;
|
|
201
|
+
return true;
|
|
202
|
+
}
|
|
203
|
+
async touchLastUsed(id, at) {
|
|
204
|
+
const k = this.keys.get(id);
|
|
205
|
+
if (k) k.lastUsedAt = at;
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
var InMemoryWebhookEventRepository = class {
|
|
209
|
+
events = [];
|
|
210
|
+
async record(event) {
|
|
211
|
+
this.events.push(event);
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
// src/domain/errors.ts
|
|
216
|
+
var OutpostError = class extends Error {
|
|
217
|
+
code;
|
|
218
|
+
constructor(code, message, options) {
|
|
219
|
+
super(message, options);
|
|
220
|
+
this.name = new.target.name;
|
|
221
|
+
this.code = code;
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
var WebhookVerificationError = class extends OutpostError {
|
|
225
|
+
constructor(message = "Webhook signature verification failed") {
|
|
226
|
+
super("webhook_unverified", message);
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
var ProviderError = class _ProviderError extends OutpostError {
|
|
230
|
+
errorClass;
|
|
231
|
+
providerCode;
|
|
232
|
+
constructor(errorClass, message, options) {
|
|
233
|
+
super(`provider_${errorClass}`, message, options);
|
|
234
|
+
this.errorClass = errorClass;
|
|
235
|
+
this.providerCode = options?.providerCode;
|
|
236
|
+
}
|
|
237
|
+
static transient(message, options) {
|
|
238
|
+
return new _ProviderError("transient", message, options);
|
|
239
|
+
}
|
|
240
|
+
static permanent(message, options) {
|
|
241
|
+
return new _ProviderError("permanent", message, options);
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
// src/adapters/providers/fake.ts
|
|
246
|
+
var FakeEmailProvider = class {
|
|
247
|
+
name;
|
|
248
|
+
sent = [];
|
|
249
|
+
failures = [];
|
|
250
|
+
counter = 0;
|
|
251
|
+
constructor(name = "fake") {
|
|
252
|
+
this.name = name;
|
|
253
|
+
}
|
|
254
|
+
failNext(kind = "transient") {
|
|
255
|
+
this.failures.push(kind);
|
|
256
|
+
}
|
|
257
|
+
async send(msg) {
|
|
258
|
+
const failure = this.failures.shift();
|
|
259
|
+
if (failure === "transient") throw ProviderError.transient("fake transient failure");
|
|
260
|
+
if (failure === "permanent") throw ProviderError.permanent("fake permanent failure");
|
|
261
|
+
const providerMessageId = `fake-${++this.counter}`;
|
|
262
|
+
this.sent.push({ providerMessageId, message: msg });
|
|
263
|
+
return { providerMessageId, acceptedAt: /* @__PURE__ */ new Date(0) };
|
|
264
|
+
}
|
|
265
|
+
async verifyWebhook(req) {
|
|
266
|
+
let parsed;
|
|
267
|
+
try {
|
|
268
|
+
parsed = JSON.parse(req.rawBody);
|
|
269
|
+
} catch {
|
|
270
|
+
throw new WebhookVerificationError("fake webhook body is not valid JSON");
|
|
271
|
+
}
|
|
272
|
+
if (!parsed?.type || !parsed?.providerMessageId) {
|
|
273
|
+
throw new WebhookVerificationError("fake webhook missing type/providerMessageId");
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
provider: this.name,
|
|
277
|
+
type: parsed.type,
|
|
278
|
+
providerMessageId: String(parsed.providerMessageId),
|
|
279
|
+
recipient: parsed.recipient,
|
|
280
|
+
isHardBounce: parsed.isHardBounce,
|
|
281
|
+
raw: parsed
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
// src/testing/index.ts
|
|
287
|
+
var FakeClock = class {
|
|
288
|
+
constructor(current = /* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z")) {
|
|
289
|
+
this.current = current;
|
|
290
|
+
}
|
|
291
|
+
now() {
|
|
292
|
+
return new Date(this.current);
|
|
293
|
+
}
|
|
294
|
+
set(date) {
|
|
295
|
+
this.current = date;
|
|
296
|
+
}
|
|
297
|
+
advance(ms) {
|
|
298
|
+
this.current = new Date(this.current.getTime() + ms);
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
function inMemoryRepositories(clock) {
|
|
302
|
+
const now = clock ? () => clock.now() : void 0;
|
|
303
|
+
return {
|
|
304
|
+
outbox: new InMemoryOutboxRepository(now),
|
|
305
|
+
suppressions: new InMemorySuppressionRepository(),
|
|
306
|
+
audit: new InMemoryAuditRepository(now),
|
|
307
|
+
apiKeys: new InMemoryApiKeyRepository(),
|
|
308
|
+
webhookEvents: new InMemoryWebhookEventRepository()
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
exports.FakeClock = FakeClock;
|
|
313
|
+
exports.FakeEmailProvider = FakeEmailProvider;
|
|
314
|
+
exports.InMemoryApiKeyRepository = InMemoryApiKeyRepository;
|
|
315
|
+
exports.InMemoryAuditRepository = InMemoryAuditRepository;
|
|
316
|
+
exports.InMemoryOutboxRepository = InMemoryOutboxRepository;
|
|
317
|
+
exports.InMemorySuppressionRepository = InMemorySuppressionRepository;
|
|
318
|
+
exports.InMemoryWebhookEventRepository = InMemoryWebhookEventRepository;
|
|
319
|
+
exports.inMemoryRepositories = inMemoryRepositories;
|
|
320
|
+
//# sourceMappingURL=index.cjs.map
|
|
321
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/domain/lifecycle.ts","../../src/testing/in-memory-repositories.ts","../../src/domain/errors.ts","../../src/adapters/providers/fake.ts","../../src/testing/index.ts"],"names":["randomUUID"],"mappings":";;;;;;;AA+CO,IAAM,eAAA,GAAkB;AAAA,EAC7B,WAAA;AAAA,EACA,SAAA;AAAA,EACA,YAAA;AAAA,EACA,QAAA;AAAA,EACA;AACF,CAAA;AAEqB,IAAI,GAAA,CAAoB,eAAe;;;ACpC5D,IAAM,QAAA,GAAmB,EAAE,GAAA,EAAK,UAAA,EAAY,YAAY,EAAA,EAAG;AAOpD,IAAM,2BAAN,MAA2D;AAAA;AAAA,EAIhE,WAAA,CAA6B,KAAA,GAAoB,sBAAM,IAAI,MAAK,EAAG;AAAtC,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAAA,EAAuC;AAAA,EAH3D,QAAA,uBAAe,GAAA,EAAqB;AAAA,EAK7C,MAAM,OAAO,GAAA,EAAmC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AAI,IAAA,EAAkB;AACpB,IAAA,IAAA,CAAK,OAAA,GAAU,IAAA;AAAA,EACjB;AAAA,EACA,QAAQ,EAAA,EAAkB;AACxB,IAAA,IAAA,CAAK,UAAU,IAAI,IAAA,CAAK,KAAK,OAAA,CAAQ,OAAA,KAAY,EAAE,CAAA;AAAA,EACrD;AACF;AAaO,SAAS,qBAAqB,KAAA,EAAe;AAClD,EAAA,MAAM,GAAA,GAAM,KAAA,GAAQ,MAAM,KAAA,CAAM,KAAI,GAAI,MAAA;AACxC,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ,IAAI,wBAAA,CAAyB,GAAG,CAAA;AAAA,IACxC,YAAA,EAAc,IAAI,6BAAA,EAA8B;AAAA,IAChD,KAAA,EAAO,IAAI,uBAAA,CAAwB,GAAG,CAAA;AAAA,IACtC,OAAA,EAAS,IAAI,wBAAA,EAAyB;AAAA,IACtC,aAAA,EAAe,IAAI,8BAAA;AAA+B,GACpD;AACF","file":"index.cjs","sourcesContent":["/**\n * Message lifecycle states and the transition rules between them.\n *\n * This module is PURE: no I/O, no framework, no provider. It encodes the\n * state machine described in the TDR §3.3. Everything outward (use cases,\n * repositories, workers) leans on these rules rather than re-deriving them.\n *\n * ┌─────────────┐\n * enqueue ─────▶│ queued │\n * └──────┬──────┘\n * │ claimed by send worker\n * ▼\n * ┌─────────────┐ suppressed recipient\n * │ sending │────────────────────────▶ suppressed\n * └──────┬──────┘\n * │ provider accepted\n * ▼\n * ┌─────────────┐\n * │ sent │ (accepted, not yet confirmed)\n * └──────┬──────┘\n * │ webhook\n * ┌──────────────┼───────────────┬────────────┐\n * ▼ ▼ ▼ ▼\n * delivered bounced complained failed\n *\n * Transient dispatch error → back to `queued` with backoff (retry).\n * Permanent error / retries exhausted → `failed` (terminal, DLQ).\n */\n\nexport const LIFECYCLE_STATES = [\n \"queued\",\n \"sending\",\n \"sent\",\n \"delivered\",\n \"bounced\",\n \"complained\",\n \"failed\",\n \"suppressed\",\n] as const;\n\nexport type LifecycleState = (typeof LIFECYCLE_STATES)[number];\n\n/**\n * Terminal states never transition again. The retention worker only ever acts\n * on rows in a terminal state (and only after the webhook window has closed),\n * which is what makes it safe to run concurrently with the send worker.\n */\nexport const TERMINAL_STATES = [\n \"delivered\",\n \"bounced\",\n \"complained\",\n \"failed\",\n \"suppressed\",\n] as const satisfies readonly LifecycleState[];\n\nconst TERMINAL_SET = new Set<LifecycleState>(TERMINAL_STATES);\n\nexport function isTerminal(state: LifecycleState): boolean {\n return TERMINAL_SET.has(state);\n}\n\n/**\n * Allowed transitions. A transition not present here is a domain invariant\n * violation and must be rejected by the use case (never silently applied).\n */\nconst ALLOWED_TRANSITIONS: Record<LifecycleState, readonly LifecycleState[]> = {\n queued: [\"sending\", \"suppressed\", \"failed\"],\n // `sending` can fall back to `queued` on a transient error (retry).\n sending: [\"sent\", \"queued\", \"failed\", \"suppressed\"],\n sent: [\"delivered\", \"bounced\", \"complained\", \"failed\"],\n delivered: [],\n bounced: [],\n complained: [],\n failed: [\"queued\"], // DLQ replay re-enqueues a failed message\n suppressed: [],\n};\n\nexport function canTransition(from: LifecycleState, to: LifecycleState): boolean {\n return ALLOWED_TRANSITIONS[from].includes(to);\n}\n\n/**\n * Which lifecycle states must feed the suppression list when reached.\n * Hard bounces and complaints damage sender reputation if re-sent, so the\n * recipient is suppressed automatically (TDR §3.6).\n */\nexport function shouldSuppressOn(state: LifecycleState): boolean {\n return state === \"bounced\" || state === \"complained\";\n}\n","import { randomUUID } from \"node:crypto\";\nimport type {\n OutboxRepository,\n SuppressionRepository,\n AuditRepository,\n ApiKeyRepository,\n WebhookEventRepository,\n NewMessage,\n MessageStatePatch,\n ListMessagesQuery,\n NewApiKey,\n} from \"../ports/repositories.js\";\nimport type { Message, Sealed } from \"../domain/message.js\";\nimport type { SuppressionEntry, SuppressionReason } from \"../domain/suppression.js\";\nimport type { ApiKey } from \"../domain/api-key.js\";\nimport type { AuditEvent, NewAuditEvent } from \"../domain/audit.js\";\nimport type { WebhookEvent } from \"../domain/webhook.js\";\nimport { TERMINAL_STATES } from \"../domain/lifecycle.js\";\n\nconst REDACTED: Sealed = { alg: \"redacted\", ciphertext: \"\" };\n\n/**\n * In-memory repositories mirroring the Drizzle adapter's semantics, for tests,\n * CI, and local prototyping with NO database. They are NOT concurrency-safe\n * across processes and hold everything in RAM — never use them in production.\n */\nexport class InMemoryOutboxRepository implements OutboxRepository {\n readonly messages = new Map<string, Message>();\n\n /** Optional injected clock so retention/lifecycle is deterministic in tests. */\n constructor(private readonly clock: () => Date = () => new Date()) {}\n\n async insert(msg: NewMessage): Promise<Message> {\n const now = this.clock();\n const message: Message = {\n id: randomUUID(),\n idempotencyKey: msg.idempotencyKey,\n state: msg.state,\n recipientHmac: msg.recipientHmac,\n recipientSealed: msg.recipientSealed,\n bodySealed: msg.bodySealed,\n subject: msg.subject,\n templateId: msg.templateId,\n templateVersion: msg.templateVersion,\n provider: msg.provider,\n metadata: msg.metadata,\n attempts: 0,\n nextAttemptAt: msg.nextAttemptAt,\n scheduledFor: msg.scheduledFor,\n providerMessageId: null,\n lastError: null,\n createdAt: now,\n updatedAt: now,\n };\n this.messages.set(message.id, message);\n return { ...message };\n }\n\n async findById(id: string): Promise<Message | null> {\n const m = this.messages.get(id);\n return m ? { ...m } : null;\n }\n\n async findByIdempotencyKey(key: string): Promise<Message | null> {\n for (const m of this.messages.values()) if (m.idempotencyKey === key) return { ...m };\n return null;\n }\n\n async findByProviderMessageId(id: string): Promise<Message | null> {\n for (const m of this.messages.values()) if (m.providerMessageId === id) return { ...m };\n return null;\n }\n\n async list(query: ListMessagesQuery): Promise<Message[]> {\n let all = [...this.messages.values()];\n if (query.state) all = all.filter((m) => m.state === query.state);\n if (query.recipientHmac) all = all.filter((m) => m.recipientHmac === query.recipientHmac);\n if (query.provider) all = all.filter((m) => m.provider === query.provider);\n if (query.createdAfter) all = all.filter((m) => m.createdAt >= query.createdAfter!);\n if (query.createdBefore) all = all.filter((m) => m.createdAt < query.createdBefore!);\n all.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n const offset = query.offset ?? 0;\n return all.slice(offset, offset + (query.limit ?? 50)).map((m) => ({ ...m }));\n }\n\n async claimBatchForSending(limit: number, now: Date, reclaimBefore: Date): Promise<Message[]> {\n const claimed: Message[] = [];\n const eligible = [...this.messages.values()]\n .filter(\n (m) =>\n (m.state === \"queued\" &&\n m.nextAttemptAt <= now &&\n (m.scheduledFor === null || m.scheduledFor <= now)) ||\n (m.state === \"sending\" && m.updatedAt < reclaimBefore),\n )\n .sort((a, b) => a.nextAttemptAt.getTime() - b.nextAttemptAt.getTime())\n .slice(0, limit);\n for (const m of eligible) {\n m.state = \"sending\";\n m.updatedAt = now;\n claimed.push({ ...m });\n }\n return claimed;\n }\n\n async updateState(id: string, patch: MessageStatePatch): Promise<void> {\n const m = this.messages.get(id);\n if (!m) return;\n m.state = patch.state;\n if (patch.attempts !== undefined) m.attempts = patch.attempts;\n if (patch.nextAttemptAt !== undefined) m.nextAttemptAt = patch.nextAttemptAt;\n if (patch.providerMessageId !== undefined) m.providerMessageId = patch.providerMessageId;\n if (patch.lastError !== undefined) m.lastError = patch.lastError;\n m.updatedAt = this.clock();\n }\n\n async claimTerminalForPurge(olderThan: Date, limit: number): Promise<Message[]> {\n const terminal = new Set<string>(TERMINAL_STATES);\n return [...this.messages.values()]\n .filter(\n (m) => terminal.has(m.state) && m.updatedAt < olderThan && m.bodySealed.alg !== \"redacted\",\n )\n .sort((a, b) => a.updatedAt.getTime() - b.updatedAt.getTime())\n .slice(0, limit)\n .map((m) => ({ ...m }));\n }\n\n async redactBatch(ids: readonly string[]): Promise<number> {\n let n = 0;\n for (const id of ids) {\n const m = this.messages.get(id);\n if (m) {\n m.recipientSealed = REDACTED;\n m.bodySealed = REDACTED;\n m.updatedAt = this.clock();\n n++;\n }\n }\n return n;\n }\n\n async deleteBatch(ids: readonly string[]): Promise<number> {\n let n = 0;\n for (const id of ids) if (this.messages.delete(id)) n++;\n return n;\n }\n}\n\nexport class InMemorySuppressionRepository implements SuppressionRepository {\n readonly entries = new Map<string, SuppressionEntry>();\n\n async isSuppressed(recipientHmac: string): Promise<boolean> {\n return this.entries.has(recipientHmac);\n }\n async get(recipientHmac: string): Promise<SuppressionEntry | null> {\n return this.entries.get(recipientHmac) ?? null;\n }\n async add(entry: {\n recipientHmac: string;\n reason: SuppressionReason;\n createdBy: string;\n note?: string;\n }): Promise<SuppressionEntry> {\n const existing = this.entries.get(entry.recipientHmac);\n if (existing) return existing;\n const created: SuppressionEntry = { ...entry, createdAt: new Date() };\n this.entries.set(entry.recipientHmac, created);\n return created;\n }\n async remove(recipientHmac: string): Promise<boolean> {\n return this.entries.delete(recipientHmac);\n }\n async list(limit: number, offset: number): Promise<SuppressionEntry[]> {\n return [...this.entries.values()]\n .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())\n .slice(offset, offset + limit);\n }\n}\n\nexport class InMemoryAuditRepository implements AuditRepository {\n readonly events: AuditEvent[] = [];\n\n constructor(private readonly clock: () => Date = () => new Date()) {}\n\n async append(event: NewAuditEvent): Promise<AuditEvent> {\n const created: AuditEvent = {\n id: randomUUID(),\n messageId: event.messageId,\n eventType: event.eventType,\n actor: event.actor,\n detail: event.detail ?? null,\n at: this.clock(),\n };\n this.events.push(created);\n return created;\n }\n async listForMessage(messageId: string): Promise<AuditEvent[]> {\n return this.events.filter((e) => e.messageId === messageId);\n }\n async purgeOlderThan(cutoff: Date, _batchSize: number): Promise<number> {\n const before = this.events.length;\n for (let i = this.events.length - 1; i >= 0; i--) {\n if (this.events[i]!.at < cutoff) this.events.splice(i, 1);\n }\n return before - this.events.length;\n }\n}\n\nexport class InMemoryApiKeyRepository implements ApiKeyRepository {\n readonly keys = new Map<string, ApiKey>();\n\n async insert(key: NewApiKey): Promise<ApiKey> {\n const created: ApiKey = {\n id: randomUUID(),\n label: key.label,\n keyHash: key.keyHash,\n scopes: key.scopes,\n expiresAt: key.expiresAt,\n revokedAt: null,\n createdAt: new Date(),\n lastUsedAt: null,\n };\n this.keys.set(created.id, created);\n return created;\n }\n async findByHash(keyHash: string): Promise<ApiKey | null> {\n for (const k of this.keys.values()) if (k.keyHash === keyHash) return { ...k };\n return null;\n }\n async findById(id: string): Promise<ApiKey | null> {\n const k = this.keys.get(id);\n return k ? { ...k } : null;\n }\n async list(): Promise<ApiKey[]> {\n return [...this.keys.values()];\n }\n async revoke(id: string, at: Date): Promise<boolean> {\n const k = this.keys.get(id);\n if (!k || k.revokedAt) return false;\n k.revokedAt = at;\n return true;\n }\n async touchLastUsed(id: string, at: Date): Promise<void> {\n const k = this.keys.get(id);\n if (k) k.lastUsedAt = at;\n }\n}\n\nexport class InMemoryWebhookEventRepository implements WebhookEventRepository {\n readonly events: WebhookEvent[] = [];\n async record(event: WebhookEvent): Promise<void> {\n this.events.push(event);\n }\n}\n","/**\n * Domain error taxonomy.\n *\n * Errors are classified so the dispatch pipeline can decide retry vs. fail\n * without inspecting provider-specific error shapes (TDR §3.4). Adapters map\n * their native errors onto these classes; the core never sees raw SDK errors.\n */\n\nexport type ErrorClass = \"transient\" | \"permanent\";\n\n/** Base class for all errors Outpost raises. Carries a stable machine `code`. */\nexport class OutpostError extends Error {\n readonly code: string;\n constructor(code: string, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = new.target.name;\n this.code = code;\n }\n}\n\n/** A request failed authentication (missing/expired/revoked key). → HTTP 401. */\nexport class UnauthorizedError extends OutpostError {\n constructor(message = \"Missing, expired, or revoked API key\") {\n super(\"unauthorized\", message);\n }\n}\n\n/** A valid key lacked the required scope. → HTTP 403. */\nexport class ForbiddenError extends OutpostError {\n constructor(message = \"API key lacks the required scope\") {\n super(\"forbidden\", message);\n }\n}\n\n/** Caller input failed validation/sanitization. Never retried. → HTTP 400. */\nexport class ValidationError extends OutpostError {\n readonly details?: unknown;\n constructor(message: string, details?: unknown) {\n super(\"validation_failed\", message);\n this.details = details;\n }\n}\n\n/** A referenced resource does not exist. → HTTP 404. */\nexport class NotFoundError extends OutpostError {\n constructor(message = \"Resource not found\") {\n super(\"not_found\", message);\n }\n}\n\n/** A lifecycle transition violated the state machine. Programming/state bug. */\nexport class InvalidStateTransitionError extends OutpostError {\n constructor(from: string, to: string) {\n super(\"invalid_transition\", `Cannot transition message from \"${from}\" to \"${to}\"`);\n }\n}\n\n/** Webhook signature verification failed. → HTTP 401, logged. */\nexport class WebhookVerificationError extends OutpostError {\n constructor(message = \"Webhook signature verification failed\") {\n super(\"webhook_unverified\", message);\n }\n}\n\n/**\n * Raised by `EmailProvider` implementations. The `errorClass` drives retry:\n * `transient` errors go back to the queue with backoff; `permanent` errors go\n * straight to `failed` and the Dead Letter Queue.\n */\nexport class ProviderError extends OutpostError {\n readonly errorClass: ErrorClass;\n readonly providerCode?: string;\n constructor(\n errorClass: ErrorClass,\n message: string,\n options?: { providerCode?: string; cause?: unknown },\n ) {\n super(`provider_${errorClass}`, message, options);\n this.errorClass = errorClass;\n this.providerCode = options?.providerCode;\n }\n\n static transient(message: string, options?: { providerCode?: string; cause?: unknown }) {\n return new ProviderError(\"transient\", message, options);\n }\n\n static permanent(message: string, options?: { providerCode?: string; cause?: unknown }) {\n return new ProviderError(\"permanent\", message, options);\n }\n}\n\n/** Returns true when an unknown thrown value should be treated as retryable. */\nexport function isTransient(err: unknown): boolean {\n return err instanceof ProviderError && err.errorClass === \"transient\";\n}\n","import type { EmailProvider, ProviderReceipt, RawWebhook } from \"../../ports/email-provider.js\";\nimport type { DispatchableMessage } from \"../../domain/message.js\";\nimport type { WebhookEvent, WebhookEventType } from \"../../domain/webhook.js\";\nimport { ProviderError, WebhookVerificationError } from \"../../domain/errors.js\";\n\nexport interface SentRecord {\n readonly providerMessageId: string;\n readonly message: DispatchableMessage;\n}\n\n/**\n * In-memory fake provider for tests and CI (TDR §3.8). Substitutable for any\n * real provider (Liskov): same interface, same error contract.\n *\n * - Records every accepted send in `sent` for assertions.\n * - `failNext(\"transient\"|\"permanent\")` queues a one-shot failure to exercise\n * the retry / dead-letter paths.\n * - `verifyWebhook` accepts an UNSIGNED JSON body of shape\n * `{ type, providerMessageId, recipient?, isHardBounce? }` — convenient for\n * driving lifecycle transitions in tests. Never use this provider in prod.\n */\nexport class FakeEmailProvider implements EmailProvider {\n readonly name: string;\n readonly sent: SentRecord[] = [];\n private failures: Array<\"transient\" | \"permanent\"> = [];\n private counter = 0;\n\n constructor(name = \"fake\") {\n this.name = name;\n }\n\n failNext(kind: \"transient\" | \"permanent\" = \"transient\"): void {\n this.failures.push(kind);\n }\n\n async send(msg: DispatchableMessage): Promise<ProviderReceipt> {\n const failure = this.failures.shift();\n if (failure === \"transient\") throw ProviderError.transient(\"fake transient failure\");\n if (failure === \"permanent\") throw ProviderError.permanent(\"fake permanent failure\");\n\n const providerMessageId = `fake-${++this.counter}`;\n this.sent.push({ providerMessageId, message: msg });\n return { providerMessageId, acceptedAt: new Date(0) };\n }\n\n async verifyWebhook(req: RawWebhook): Promise<WebhookEvent> {\n let parsed: any;\n try {\n parsed = JSON.parse(req.rawBody);\n } catch {\n throw new WebhookVerificationError(\"fake webhook body is not valid JSON\");\n }\n if (!parsed?.type || !parsed?.providerMessageId) {\n throw new WebhookVerificationError(\"fake webhook missing type/providerMessageId\");\n }\n return {\n provider: this.name,\n type: parsed.type as WebhookEventType,\n providerMessageId: String(parsed.providerMessageId),\n recipient: parsed.recipient,\n isHardBounce: parsed.isHardBounce,\n raw: parsed,\n };\n }\n}\n","/**\n * Testing utilities — exported at `@tgoliveira/outpost/testing`.\n *\n * In-memory repositories + a deterministic fake clock, and re-export of the\n * fake provider. Build a fully in-process Outpost with NO Postgres and NO real\n * email for unit/integration tests and CI (TDR §3.8).\n */\nimport type { Clock } from \"../ports/services.js\";\nimport {\n InMemoryOutboxRepository,\n InMemorySuppressionRepository,\n InMemoryAuditRepository,\n InMemoryApiKeyRepository,\n InMemoryWebhookEventRepository,\n} from \"./in-memory-repositories.js\";\n\nexport * from \"./in-memory-repositories.js\";\nexport { FakeEmailProvider } from \"../adapters/providers/fake.js\";\n\n/** A controllable clock for deterministic tests. */\nexport class FakeClock implements Clock {\n constructor(private current: Date = new Date(\"2026-01-01T00:00:00.000Z\")) {}\n now(): Date {\n return new Date(this.current);\n }\n set(date: Date): void {\n this.current = date;\n }\n advance(ms: number): void {\n this.current = new Date(this.current.getTime() + ms);\n }\n}\n\n/**\n * Convenience: a complete in-memory repository bundle for `createOutpost`.\n *\n * import { createOutpost } from \"@tgoliveira/outpost\";\n * import { inMemoryRepositories, FakeEmailProvider } from \"@tgoliveira/outpost/testing\";\n * const outpost = createOutpost({\n * repositories: inMemoryRepositories(),\n * providers: [new FakeEmailProvider()],\n * recipientHmacKey: \"test-key-at-least-16-bytes-long\",\n * });\n */\nexport function inMemoryRepositories(clock?: Clock) {\n const now = clock ? () => clock.now() : undefined;\n return {\n outbox: new InMemoryOutboxRepository(now),\n suppressions: new InMemorySuppressionRepository(),\n audit: new InMemoryAuditRepository(now),\n apiKeys: new InMemoryApiKeyRepository(),\n webhookEvents: new InMemoryWebhookEventRepository(),\n };\n}\n"]}
|