@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,221 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
|
|
3
|
+
// src/domain/api-key.ts
|
|
4
|
+
function isKeyActive(key, now) {
|
|
5
|
+
if (key.revokedAt !== null) return false;
|
|
6
|
+
if (key.expiresAt !== null && key.expiresAt.getTime() <= now.getTime()) return false;
|
|
7
|
+
return true;
|
|
8
|
+
}
|
|
9
|
+
function hasScope(scopes, required) {
|
|
10
|
+
return scopes.includes("admin") || scopes.includes(required);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// src/domain/errors.ts
|
|
14
|
+
var OutpostError = class extends Error {
|
|
15
|
+
code;
|
|
16
|
+
constructor(code, message, options) {
|
|
17
|
+
super(message, options);
|
|
18
|
+
this.name = new.target.name;
|
|
19
|
+
this.code = code;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
var UnauthorizedError = class extends OutpostError {
|
|
23
|
+
constructor(message = "Missing, expired, or revoked API key") {
|
|
24
|
+
super("unauthorized", message);
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
var ForbiddenError = class extends OutpostError {
|
|
28
|
+
constructor(message = "API key lacks the required scope") {
|
|
29
|
+
super("forbidden", message);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
var ValidationError = class extends OutpostError {
|
|
33
|
+
details;
|
|
34
|
+
constructor(message, details) {
|
|
35
|
+
super("validation_failed", message);
|
|
36
|
+
this.details = details;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
var NotFoundError = class extends OutpostError {
|
|
40
|
+
constructor(message = "Resource not found") {
|
|
41
|
+
super("not_found", message);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
var WebhookVerificationError = class extends OutpostError {
|
|
45
|
+
constructor(message = "Webhook signature verification failed") {
|
|
46
|
+
super("webhook_unverified", message);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
function hashApiKey(secret) {
|
|
50
|
+
return createHash("sha256").update(secret, "utf8").digest("hex");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/application/authenticate.ts
|
|
54
|
+
var Authenticate = class {
|
|
55
|
+
constructor(deps) {
|
|
56
|
+
this.deps = deps;
|
|
57
|
+
}
|
|
58
|
+
/** Resolve a bearer secret to an AuthContext or throw UnauthorizedError. */
|
|
59
|
+
async resolve(presentedSecret) {
|
|
60
|
+
if (!presentedSecret) throw new UnauthorizedError();
|
|
61
|
+
const keyHash = hashApiKey(presentedSecret);
|
|
62
|
+
const key = await this.deps.apiKeys.findByHash(keyHash);
|
|
63
|
+
if (!key) throw new UnauthorizedError();
|
|
64
|
+
if (!isKeyActive(key, this.deps.clock.now())) throw new UnauthorizedError();
|
|
65
|
+
void this.deps.apiKeys.touchLastUsed(key.id, this.deps.clock.now());
|
|
66
|
+
return { keyId: key.id, scopes: key.scopes };
|
|
67
|
+
}
|
|
68
|
+
/** Resolve then assert the context carries the required scope. */
|
|
69
|
+
async authorize(presentedSecret, required) {
|
|
70
|
+
const ctx = await this.resolve(presentedSecret);
|
|
71
|
+
if (!hasScope(ctx.scopes, required)) throw new ForbiddenError();
|
|
72
|
+
return ctx;
|
|
73
|
+
}
|
|
74
|
+
/** Assert a scope on an already-resolved context. */
|
|
75
|
+
static requireScope(ctx, required) {
|
|
76
|
+
if (!hasScope(ctx.scopes, required)) throw new ForbiddenError();
|
|
77
|
+
}
|
|
78
|
+
/** Helper to extract a bearer/x-outpost-key value from headers. */
|
|
79
|
+
static extractKey(headers) {
|
|
80
|
+
const auth = headerValue(headers, "authorization");
|
|
81
|
+
if (auth && /^bearer\s+/i.test(auth)) return auth.replace(/^bearer\s+/i, "").trim();
|
|
82
|
+
return headerValue(headers, "x-outpost-key");
|
|
83
|
+
}
|
|
84
|
+
// Exposed for tests / admin tooling.
|
|
85
|
+
async findKey(presentedSecret) {
|
|
86
|
+
return this.deps.apiKeys.findByHash(hashApiKey(presentedSecret));
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
function headerValue(headers, name) {
|
|
90
|
+
const raw = headers[name] ?? headers[name.toLowerCase()];
|
|
91
|
+
if (Array.isArray(raw)) return raw[0] ?? null;
|
|
92
|
+
return raw ?? null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// src/http/handlers.ts
|
|
96
|
+
var OutpostRouter = class {
|
|
97
|
+
constructor(outpost) {
|
|
98
|
+
this.outpost = outpost;
|
|
99
|
+
}
|
|
100
|
+
/** POST /api/outpost/messages — enqueue. Scope: messages:send. */
|
|
101
|
+
enqueue = (req) => this.guarded(req, "messages:send", async (body, ctx) => {
|
|
102
|
+
const result = await this.outpost.send(body, { actor: `key:${ctx.keyId}` });
|
|
103
|
+
return json(result, result.deduplicated ? 200 : 202);
|
|
104
|
+
});
|
|
105
|
+
/** GET /api/outpost/messages — list. Scope: messages:read. */
|
|
106
|
+
list = (req) => this.authed(req, "messages:read", async () => {
|
|
107
|
+
const url = new URL(req.url);
|
|
108
|
+
const q = url.searchParams;
|
|
109
|
+
const messages = await this.outpost.list({
|
|
110
|
+
state: q.get("state") ?? void 0,
|
|
111
|
+
recipientHmac: q.get("recipientHmac") ?? void 0,
|
|
112
|
+
provider: q.get("provider") ?? void 0,
|
|
113
|
+
limit: q.get("limit") ? Number(q.get("limit")) : void 0,
|
|
114
|
+
offset: q.get("offset") ? Number(q.get("offset")) : void 0
|
|
115
|
+
});
|
|
116
|
+
return json({ messages });
|
|
117
|
+
});
|
|
118
|
+
/** GET /api/outpost/messages/:id — fetch one. Scope: messages:read. */
|
|
119
|
+
get = (req, id) => this.authed(req, "messages:read", async () => json(await this.outpost.get(id)));
|
|
120
|
+
/** POST /api/outpost/messages/:id/replay — DLQ replay. Scope: messages:replay. */
|
|
121
|
+
replay = (req, id) => this.authed(
|
|
122
|
+
req,
|
|
123
|
+
"messages:replay",
|
|
124
|
+
async (ctx) => json(await this.outpost.replay(id, { actor: `key:${ctx.keyId}` }))
|
|
125
|
+
);
|
|
126
|
+
/** GET /api/outpost/suppressions/:hash — check. Scope: suppressions:read. */
|
|
127
|
+
getSuppression = (req, hash) => this.authed(req, "suppressions:read", async () => {
|
|
128
|
+
const entry = await this.outpost.suppression.getByHmac(hash);
|
|
129
|
+
if (!entry) throw new NotFoundError("Not suppressed");
|
|
130
|
+
return json(entry);
|
|
131
|
+
});
|
|
132
|
+
/** POST /api/outpost/suppressions — add. Scope: suppressions:write. */
|
|
133
|
+
suppress = (req) => this.guarded(req, "suppressions:write", async (body, ctx) => {
|
|
134
|
+
if (!body?.address) throw new ValidationError("address is required");
|
|
135
|
+
const entry = await this.outpost.suppress(body.address, body.reason ?? "manual", {
|
|
136
|
+
note: body.note,
|
|
137
|
+
actor: `key:${ctx.keyId}`
|
|
138
|
+
});
|
|
139
|
+
return json(entry, 201);
|
|
140
|
+
});
|
|
141
|
+
/** DELETE /api/outpost/suppressions/:hash — remove. Scope: suppressions:write. */
|
|
142
|
+
unsuppress = (req, hash) => this.authed(req, "suppressions:write", async (ctx) => {
|
|
143
|
+
const removed = await this.outpost.suppression.unsuppressByHmac(hash, `key:${ctx.keyId}`);
|
|
144
|
+
return json({ removed });
|
|
145
|
+
});
|
|
146
|
+
/**
|
|
147
|
+
* POST /api/outpost/webhooks/:provider — provider webhook sink.
|
|
148
|
+
* NOT API-key authenticated; verified by the provider's signature scheme.
|
|
149
|
+
*/
|
|
150
|
+
webhook = async (req, provider) => {
|
|
151
|
+
try {
|
|
152
|
+
const rawBody = await req.text();
|
|
153
|
+
const result = await this.outpost.webhook(provider, {
|
|
154
|
+
headers: headersToRecord(req.headers),
|
|
155
|
+
rawBody
|
|
156
|
+
});
|
|
157
|
+
return json(result);
|
|
158
|
+
} catch (err) {
|
|
159
|
+
return errorResponse(err);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
// --- internals -----------------------------------------------------------
|
|
163
|
+
/** Auth + scope, no body parsing. Passes the AuthContext to the handler. */
|
|
164
|
+
async authed(req, scope, handler) {
|
|
165
|
+
try {
|
|
166
|
+
const ctx = await this.authorize(req, scope);
|
|
167
|
+
return await handler(ctx);
|
|
168
|
+
} catch (err) {
|
|
169
|
+
return errorResponse(err);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** Auth + scope + JSON body parsing. */
|
|
173
|
+
async guarded(req, scope, handler) {
|
|
174
|
+
try {
|
|
175
|
+
const ctx = await this.authorize(req, scope);
|
|
176
|
+
const body = await parseJson(req);
|
|
177
|
+
return await handler(body, ctx);
|
|
178
|
+
} catch (err) {
|
|
179
|
+
return errorResponse(err);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
authorize(req, scope) {
|
|
183
|
+
const key = Authenticate.extractKey(headersToRecord(req.headers));
|
|
184
|
+
return this.outpost.auth.authorize(key, scope);
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
function json(body, status = 200) {
|
|
188
|
+
return new Response(JSON.stringify(body), {
|
|
189
|
+
status,
|
|
190
|
+
headers: { "content-type": "application/json" }
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
async function parseJson(req) {
|
|
194
|
+
try {
|
|
195
|
+
return await req.json();
|
|
196
|
+
} catch {
|
|
197
|
+
throw new ValidationError("Request body is not valid JSON");
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function headersToRecord(headers) {
|
|
201
|
+
const out = {};
|
|
202
|
+
headers.forEach((v, k) => {
|
|
203
|
+
out[k] = v;
|
|
204
|
+
});
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
function errorResponse(err) {
|
|
208
|
+
if (err instanceof UnauthorizedError) return json({ error: err.code, message: err.message }, 401);
|
|
209
|
+
if (err instanceof ForbiddenError) return json({ error: err.code, message: err.message }, 403);
|
|
210
|
+
if (err instanceof ValidationError)
|
|
211
|
+
return json({ error: err.code, message: err.message, details: err.details }, 400);
|
|
212
|
+
if (err instanceof NotFoundError) return json({ error: err.code, message: err.message }, 404);
|
|
213
|
+
if (err instanceof WebhookVerificationError)
|
|
214
|
+
return json({ error: err.code, message: err.message }, 401);
|
|
215
|
+
if (err instanceof OutpostError) return json({ error: err.code, message: err.message }, 400);
|
|
216
|
+
return json({ error: "internal_error", message: "Unexpected error" }, 500);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export { OutpostRouter, errorResponse };
|
|
220
|
+
//# sourceMappingURL=index.js.map
|
|
221
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/domain/api-key.ts","../../src/domain/errors.ts","../../src/application/manage-api-key.ts","../../src/application/authenticate.ts","../../src/http/handlers.ts"],"names":[],"mappings":";;;AAmCO,SAAS,WAAA,CAAY,KAA8C,GAAA,EAAoB;AAC5F,EAAA,IAAI,GAAA,CAAI,SAAA,KAAc,IAAA,EAAM,OAAO,KAAA;AACnC,EAAA,IAAI,GAAA,CAAI,SAAA,KAAc,IAAA,IAAQ,GAAA,CAAI,SAAA,CAAU,SAAQ,IAAK,GAAA,CAAI,OAAA,EAAQ,EAAG,OAAO,KAAA;AAC/E,EAAA,OAAO,IAAA;AACT;AAGO,SAAS,QAAA,CAAS,QAA6B,QAAA,EAA6B;AACjF,EAAA,OAAO,OAAO,QAAA,CAAS,OAAO,CAAA,IAAK,MAAA,CAAO,SAAS,QAAQ,CAAA;AAC7D;;;ACjCO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,IAAA;AAAA,EACT,WAAA,CAAY,IAAA,EAAc,OAAA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AA,OAAO,IAAA,CAAK,EAAE,KAAA,EAAO,GAAA,CAAI,IAAA,EAAM,OAAA,EAAS,GAAA,CAAI,OAAA,EAAS,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAG,GAAG,CAAA;AAClF,EAAA,IAAI,GAAA,YAAe,aAAA,EAAe,OAAO,IAAA,CAAK,EAAE,KAAA,EAAO,GAAA,CAAI,IAAA,EAAM,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAG,GAAG,CAAA;AAC5F,EAAA,IAAI,GAAA,YAAe,wBAAA;AACjB,IAAA,OAAO,IAAA,CAAK,EAAE,KAAA,EAAO,GAAA,CAAI,MAAM,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAG,GAAG,CAAA;AAC5D,EAAA,IAAI,GAAA,YAAe,YAAA,EAAc,OAAO,IAAA,CAAK,EAAE,KAAA,EAAO,GAAA,CAAI,IAAA,EAAM,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAG,GAAG,CAAA;AAC3F,EAAA,OAAO,KAAK,EAAE,KAAA,EAAO,kBAAkB,OAAA,EAAS,kBAAA,IAAsB,GAAG,CAAA;AAC3E","file":"index.js","sourcesContent":["/**\n * API key domain types and scope model (TDR §5.1).\n *\n * Keys are opaque high-entropy secrets. Only a hash is ever stored; the\n * plaintext is shown once at creation. A key carries a label, optional expiry,\n * and a revoked flag — both enforced on every request. Scopes implement\n * least-privilege (a send-only key cannot manage suppressions).\n */\n\nexport const API_SCOPES = [\n \"messages:send\",\n \"messages:read\",\n \"messages:replay\",\n \"suppressions:read\",\n \"suppressions:write\",\n \"keys:manage\",\n \"admin\", // implies all of the above\n] as const;\n\nexport type ApiScope = (typeof API_SCOPES)[number];\n\nexport interface ApiKey {\n readonly id: string;\n /** Human label shown in the admin panel. */\n readonly label: string;\n /** Hash of the secret (never the secret itself). */\n readonly keyHash: string;\n readonly scopes: readonly ApiScope[];\n readonly expiresAt: Date | null;\n revokedAt: Date | null;\n readonly createdAt: Date;\n lastUsedAt: Date | null;\n}\n\n/** A key is usable iff it is not revoked and not past its expiry. */\nexport function isKeyActive(key: Pick<ApiKey, \"revokedAt\" | \"expiresAt\">, now: Date): boolean {\n if (key.revokedAt !== null) return false;\n if (key.expiresAt !== null && key.expiresAt.getTime() <= now.getTime()) return false;\n return true;\n}\n\n/** True when the key's scopes satisfy the required scope (admin implies all). */\nexport function hasScope(scopes: readonly ApiScope[], required: ApiScope): boolean {\n return scopes.includes(\"admin\") || scopes.includes(required);\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 { createHash, randomBytes } from \"node:crypto\";\nimport type { CoreDeps } from \"./context.js\";\nimport type { ApiKey, ApiScope } from \"../domain/api-key.js\";\n\n/**\n * Hash an API key secret for storage. Keys are high-entropy random tokens\n * (not user passwords), so a fast one-way SHA-256 is appropriate and lets us\n * look the hash up directly. A slow password hash (bcrypt/argon2) buys nothing\n * against a 256-bit random secret and would break O(1) lookup.\n */\nexport function hashApiKey(secret: string): string {\n return createHash(\"sha256\").update(secret, \"utf8\").digest(\"hex\");\n}\n\n/** Generate an opaque, high-entropy key with a recognizable prefix. */\nexport function generateApiKeySecret(): string {\n return `opk_${randomBytes(32).toString(\"base64url\")}`;\n}\n\nexport interface CreatedApiKey {\n readonly id: string;\n readonly label: string;\n readonly scopes: readonly ApiScope[];\n readonly expiresAt: Date | null;\n /** The plaintext secret — shown ONCE, never stored, never recoverable. */\n readonly secret: string;\n}\n\n/**\n * ManageApiKey — admin-side key lifecycle (TDR §5.1, §3.12).\n *\n * Only the hash is stored. The plaintext is returned exactly once at creation.\n * Revocation takes effect immediately (no caching of key state beyond the\n * documented short window in the Authenticate use case).\n */\nexport class ManageApiKey {\n constructor(private readonly deps: CoreDeps) {}\n\n async create(input: {\n label: string;\n scopes: readonly ApiScope[];\n expiresAt?: Date | null;\n }): Promise<CreatedApiKey> {\n const secret = generateApiKeySecret();\n const key = await this.deps.apiKeys.insert({\n label: input.label,\n keyHash: hashApiKey(secret),\n scopes: input.scopes,\n expiresAt: input.expiresAt ?? null,\n });\n await this.deps.audit.append({\n messageId: null,\n eventType: \"key_created\",\n actor: \"admin\",\n detail: { keyId: key.id, label: key.label, scopes: key.scopes },\n });\n return {\n id: key.id,\n label: key.label,\n scopes: key.scopes,\n expiresAt: key.expiresAt,\n secret,\n };\n }\n\n async revoke(id: string): Promise<boolean> {\n const ok = await this.deps.apiKeys.revoke(id, this.deps.clock.now());\n if (ok) {\n await this.deps.audit.append({\n messageId: null,\n eventType: \"key_revoked\",\n actor: \"admin\",\n detail: { keyId: id },\n });\n }\n return ok;\n }\n\n /** Lists keys WITHOUT secrets (only hashes are stored anyway). */\n async list(): Promise<ApiKey[]> {\n return this.deps.apiKeys.list();\n }\n}\n","import type { CoreDeps } from \"./context.js\";\nimport type { ApiKey, ApiScope } from \"../domain/api-key.js\";\nimport { isKeyActive, hasScope } from \"../domain/api-key.js\";\nimport { UnauthorizedError, ForbiddenError } from \"../domain/errors.js\";\nimport { hashApiKey } from \"./manage-api-key.js\";\n\nexport interface AuthContext {\n readonly keyId: string;\n readonly scopes: readonly ApiScope[];\n}\n\n/**\n * Authenticate — validates an API key on every request (TDR §5.1).\n *\n * - Hashes the presented secret and looks up the stored hash.\n * - Rejects missing / unknown / expired / revoked keys with 401.\n * - Enforces the required scope (least privilege) with 403.\n * - Touches `last_used_at` for observability.\n *\n * Revocation/expiry are enforced on every call (no long-lived caching), so\n * they take effect immediately as the TDR requires.\n */\nexport class Authenticate {\n constructor(private readonly deps: CoreDeps) {}\n\n /** Resolve a bearer secret to an AuthContext or throw UnauthorizedError. */\n async resolve(presentedSecret: string | null | undefined): Promise<AuthContext> {\n if (!presentedSecret) throw new UnauthorizedError();\n const keyHash = hashApiKey(presentedSecret);\n const key = await this.deps.apiKeys.findByHash(keyHash);\n if (!key) throw new UnauthorizedError();\n if (!isKeyActive(key, this.deps.clock.now())) throw new UnauthorizedError();\n\n // Fire-and-forget last-used update; never block the request on it.\n void this.deps.apiKeys.touchLastUsed(key.id, this.deps.clock.now());\n\n return { keyId: key.id, scopes: key.scopes };\n }\n\n /** Resolve then assert the context carries the required scope. */\n async authorize(presentedSecret: string | null | undefined, required: ApiScope): Promise<AuthContext> {\n const ctx = await this.resolve(presentedSecret);\n if (!hasScope(ctx.scopes, required)) throw new ForbiddenError();\n return ctx;\n }\n\n /** Assert a scope on an already-resolved context. */\n static requireScope(ctx: AuthContext, required: ApiScope): void {\n if (!hasScope(ctx.scopes, required)) throw new ForbiddenError();\n }\n\n /** Helper to extract a bearer/x-outpost-key value from headers. */\n static extractKey(headers: Record<string, string | string[] | undefined>): string | null {\n const auth = headerValue(headers, \"authorization\");\n if (auth && /^bearer\\s+/i.test(auth)) return auth.replace(/^bearer\\s+/i, \"\").trim();\n return headerValue(headers, \"x-outpost-key\");\n }\n\n // Exposed for tests / admin tooling.\n async findKey(presentedSecret: string): Promise<ApiKey | null> {\n return this.deps.apiKeys.findByHash(hashApiKey(presentedSecret));\n }\n}\n\nfunction headerValue(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | null {\n const raw = headers[name] ?? headers[name.toLowerCase()];\n if (Array.isArray(raw)) return raw[0] ?? null;\n return raw ?? null;\n}\n","import type { Outpost } from \"../client/outpost-client.js\";\nimport type { ApiScope } from \"../domain/api-key.js\";\nimport type { AuthContext } from \"../application/authenticate.js\";\nimport { Authenticate } from \"../application/authenticate.js\";\nimport {\n OutpostError,\n UnauthorizedError,\n ForbiddenError,\n ValidationError,\n NotFoundError,\n WebhookVerificationError,\n} from \"../domain/errors.js\";\n\n/**\n * HTTP layer (TDR §4) — exported at `@tgoliveira/outpost/next`.\n *\n * Built on the Web Fetch `Request`/`Response`, so it drops straight into the\n * Next.js App Router (route handlers), Remix, Hono, or any Fetch-based runtime.\n * Each handler authenticates with an API key and enforces a least-privilege\n * scope; the webhook sink is signature-verified instead (TDR §5.1, §5.2).\n *\n * Wiring example (Next.js App Router) is in docs/nextjs.md.\n */\nexport class OutpostRouter {\n constructor(private readonly outpost: Outpost) {}\n\n /** POST /api/outpost/messages — enqueue. Scope: messages:send. */\n enqueue = (req: Request): Promise<Response> =>\n this.guarded(req, \"messages:send\", async (body, ctx) => {\n const result = await this.outpost.send(body, { actor: `key:${ctx.keyId}` });\n return json(result, result.deduplicated ? 200 : 202);\n });\n\n /** GET /api/outpost/messages — list. Scope: messages:read. */\n list = (req: Request): Promise<Response> =>\n this.authed(req, \"messages:read\", async () => {\n const url = new URL(req.url);\n const q = url.searchParams;\n const messages = await this.outpost.list({\n state: (q.get(\"state\") as any) ?? undefined,\n recipientHmac: q.get(\"recipientHmac\") ?? undefined,\n provider: q.get(\"provider\") ?? undefined,\n limit: q.get(\"limit\") ? Number(q.get(\"limit\")) : undefined,\n offset: q.get(\"offset\") ? Number(q.get(\"offset\")) : undefined,\n });\n return json({ messages });\n });\n\n /** GET /api/outpost/messages/:id — fetch one. Scope: messages:read. */\n get = (req: Request, id: string): Promise<Response> =>\n this.authed(req, \"messages:read\", async () => json(await this.outpost.get(id)));\n\n /** POST /api/outpost/messages/:id/replay — DLQ replay. Scope: messages:replay. */\n replay = (req: Request, id: string): Promise<Response> =>\n this.authed(req, \"messages:replay\", async (ctx) =>\n json(await this.outpost.replay(id, { actor: `key:${ctx.keyId}` })),\n );\n\n /** GET /api/outpost/suppressions/:hash — check. Scope: suppressions:read. */\n getSuppression = (req: Request, hash: string): Promise<Response> =>\n this.authed(req, \"suppressions:read\", async () => {\n const entry = await this.outpost.suppression.getByHmac(hash);\n if (!entry) throw new NotFoundError(\"Not suppressed\");\n return json(entry);\n });\n\n /** POST /api/outpost/suppressions — add. Scope: suppressions:write. */\n suppress = (req: Request): Promise<Response> =>\n this.guarded(req, \"suppressions:write\", async (body, ctx) => {\n if (!body?.address) throw new ValidationError(\"address is required\");\n const entry = await this.outpost.suppress(body.address, body.reason ?? \"manual\", {\n note: body.note,\n actor: `key:${ctx.keyId}`,\n });\n return json(entry, 201);\n });\n\n /** DELETE /api/outpost/suppressions/:hash — remove. Scope: suppressions:write. */\n unsuppress = (req: Request, hash: string): Promise<Response> =>\n this.authed(req, \"suppressions:write\", async (ctx) => {\n const removed = await this.outpost.suppression.unsuppressByHmac(hash, `key:${ctx.keyId}`);\n return json({ removed });\n });\n\n /**\n * POST /api/outpost/webhooks/:provider — provider webhook sink.\n * NOT API-key authenticated; verified by the provider's signature scheme.\n */\n webhook = async (req: Request, provider: string): Promise<Response> => {\n try {\n const rawBody = await req.text();\n const result = await this.outpost.webhook(provider, {\n headers: headersToRecord(req.headers),\n rawBody,\n });\n return json(result);\n } catch (err) {\n return errorResponse(err);\n }\n };\n\n // --- internals -----------------------------------------------------------\n\n /** Auth + scope, no body parsing. Passes the AuthContext to the handler. */\n private async authed(\n req: Request,\n scope: ApiScope,\n handler: (ctx: AuthContext) => Promise<Response>,\n ): Promise<Response> {\n try {\n const ctx = await this.authorize(req, scope);\n return await handler(ctx);\n } catch (err) {\n return errorResponse(err);\n }\n }\n\n /** Auth + scope + JSON body parsing. */\n private async guarded(\n req: Request,\n scope: ApiScope,\n handler: (body: any, ctx: AuthContext) => Promise<Response>,\n ): Promise<Response> {\n try {\n const ctx = await this.authorize(req, scope);\n const body = await parseJson(req);\n return await handler(body, ctx);\n } catch (err) {\n return errorResponse(err);\n }\n }\n\n private authorize(req: Request, scope: ApiScope): Promise<AuthContext> {\n const key = Authenticate.extractKey(headersToRecord(req.headers));\n return this.outpost.auth.authorize(key, scope);\n }\n}\n\n// --- helpers ---------------------------------------------------------------\n\nfunction json(body: unknown, status = 200): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n}\n\nasync function parseJson(req: Request): Promise<any> {\n try {\n return await req.json();\n } catch {\n throw new ValidationError(\"Request body is not valid JSON\");\n }\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n headers.forEach((v, k) => {\n out[k] = v;\n });\n return out;\n}\n\n/** Map domain errors onto HTTP status codes (TDR §4, §5). */\nexport function errorResponse(err: unknown): Response {\n if (err instanceof UnauthorizedError) return json({ error: err.code, message: err.message }, 401);\n if (err instanceof ForbiddenError) return json({ error: err.code, message: err.message }, 403);\n if (err instanceof ValidationError)\n return json({ error: err.code, message: err.message, details: err.details }, 400);\n if (err instanceof NotFoundError) return json({ error: err.code, message: err.message }, 404);\n if (err instanceof WebhookVerificationError)\n return json({ error: err.code, message: err.message }, 401);\n if (err instanceof OutpostError) return json({ error: err.code, message: err.message }, 400);\n return json({ error: \"internal_error\", message: \"Unexpected error\" }, 500);\n}\n"]}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { O as OutboxRepository, S as SuppressionRepository, A as AuditRepository, a as ApiKeyRepository, W as WebhookEventRepository } from './repositories-Bck6wJNS.js';
|
|
2
|
+
import { E as EmailProvider, a as RateLimiter, C as Clock, I as IdGenerator, L as Logger, T as Telemetry } from './services-CfTEsetF.js';
|
|
3
|
+
import { k as ResolvedConfig, E as Encryptor, i as RecipientHasher, T as TemplateRenderer, M as MxResolver } from './template-CREUq7bB.js';
|
|
4
|
+
import { M as Message } from './webhook-kp6CiXk-.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The dependency container the use cases receive (composed at the edge by
|
|
8
|
+
* `createOutpost`). This is the seam where Clean Architecture's Dependency
|
|
9
|
+
* Inversion is realized: use cases only ever touch these interfaces.
|
|
10
|
+
*
|
|
11
|
+
* Note the deliberate split between `sealEncryptor` and `openEncryptor`:
|
|
12
|
+
* the ingestion side is wired with a seal-only encryptor (public key) and the
|
|
13
|
+
* send worker with an open-capable one (private key). In a single-process
|
|
14
|
+
* deployment they may be the same symmetric instance; in the asymmetric
|
|
15
|
+
* least-privilege deployment they are different (TDR §5.4).
|
|
16
|
+
*/
|
|
17
|
+
interface CoreDeps {
|
|
18
|
+
readonly config: ResolvedConfig;
|
|
19
|
+
readonly outbox: OutboxRepository;
|
|
20
|
+
readonly suppressions: SuppressionRepository;
|
|
21
|
+
readonly audit: AuditRepository;
|
|
22
|
+
readonly apiKeys: ApiKeyRepository;
|
|
23
|
+
readonly webhookEvents: WebhookEventRepository;
|
|
24
|
+
readonly providers: ReadonlyMap<string, EmailProvider>;
|
|
25
|
+
/** Provider name used when an enqueue does not specify one. */
|
|
26
|
+
readonly defaultProvider: string;
|
|
27
|
+
/** Write-side encryptor (public key in the asymmetric model). */
|
|
28
|
+
readonly sealEncryptor: Encryptor;
|
|
29
|
+
/** Read-side encryptor (private key). Only the send worker needs this. */
|
|
30
|
+
readonly openEncryptor: Encryptor;
|
|
31
|
+
readonly recipientHasher: RecipientHasher;
|
|
32
|
+
readonly rateLimiter: RateLimiter;
|
|
33
|
+
readonly clock: Clock;
|
|
34
|
+
readonly ids: IdGenerator;
|
|
35
|
+
readonly logger: Logger;
|
|
36
|
+
readonly telemetry: Telemetry;
|
|
37
|
+
readonly templates?: TemplateRenderer;
|
|
38
|
+
readonly mxResolver?: MxResolver;
|
|
39
|
+
/** Pluggable strong HTML sanitizer; falls back to the built-in stripper. */
|
|
40
|
+
readonly sanitizeHtml?: (html: string) => string;
|
|
41
|
+
/** Random sample in [0,1) for retry jitter. Injected for testability. */
|
|
42
|
+
readonly random: () => number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
type DispatchOutcome = {
|
|
46
|
+
kind: "sent";
|
|
47
|
+
providerMessageId: string;
|
|
48
|
+
} | {
|
|
49
|
+
kind: "retry";
|
|
50
|
+
nextAttemptAt: Date;
|
|
51
|
+
} | {
|
|
52
|
+
kind: "rate_limited";
|
|
53
|
+
nextAttemptAt: Date;
|
|
54
|
+
} | {
|
|
55
|
+
kind: "failed";
|
|
56
|
+
reason: string;
|
|
57
|
+
} | {
|
|
58
|
+
kind: "skipped";
|
|
59
|
+
reason: string;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* DispatchMessage — processes ONE message already claimed (state `sending`) by
|
|
63
|
+
* the send worker. Implements the outbound pipeline (TDR §3.2):
|
|
64
|
+
*
|
|
65
|
+
* 1. Idempotency / state guard (no double-send under concurrency)
|
|
66
|
+
* 2. Decrypt PII (READ-side encryptor, only here)
|
|
67
|
+
* 3. Re-sanitize decrypted data (defense in depth)
|
|
68
|
+
* 4. Domain validation (syntax + cached MX)
|
|
69
|
+
* 5. Rate limiting (global / provider / domain)
|
|
70
|
+
* 6. Dispatch (provider.send)
|
|
71
|
+
* 7. State transition + audit
|
|
72
|
+
*
|
|
73
|
+
* Decryption happens as late as possible — immediately before dispatch — so
|
|
74
|
+
* plaintext never lives in the queue (TDR §5.4).
|
|
75
|
+
*/
|
|
76
|
+
declare class DispatchMessage {
|
|
77
|
+
private readonly deps;
|
|
78
|
+
private readonly mxCache;
|
|
79
|
+
constructor(deps: CoreDeps);
|
|
80
|
+
execute(message: Message): Promise<DispatchOutcome>;
|
|
81
|
+
/** Classify the error and either retry-with-backoff or dead-letter. */
|
|
82
|
+
private handleError;
|
|
83
|
+
/** Move to `failed` (terminal) and record in the Dead Letter Queue. */
|
|
84
|
+
private fail;
|
|
85
|
+
/** Re-queue without counting a failed attempt; short, jittered backoff. */
|
|
86
|
+
private requeueRateLimited;
|
|
87
|
+
private checkRateLimits;
|
|
88
|
+
/** List-Unsubscribe and other always-on headers (TDR §3.11). */
|
|
89
|
+
private buildHeaders;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
interface SendTickReport {
|
|
93
|
+
readonly claimed: number;
|
|
94
|
+
readonly outcomes: DispatchOutcome[];
|
|
95
|
+
}
|
|
96
|
+
interface SendWorkerOptions {
|
|
97
|
+
/** Poll interval for the long-running loop, ms. Default 1000. */
|
|
98
|
+
readonly intervalMs?: number;
|
|
99
|
+
/** Max messages claimed per tick. Defaults to config.sendBatchSize. */
|
|
100
|
+
readonly batchSize?: number;
|
|
101
|
+
/** Max concurrent dispatches within a tick. Default 10. */
|
|
102
|
+
readonly concurrency?: number;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* SendWorker — the polling outbound processor (TDR §3.2, decision #2).
|
|
106
|
+
*
|
|
107
|
+
* Polls the outbox (NEVER a dual-written queue), atomically claims a batch with
|
|
108
|
+
* `FOR UPDATE SKIP LOCKED`, and runs each message through `DispatchMessage`.
|
|
109
|
+
* Safe to run as multiple concurrent instances — the claim guarantees no two
|
|
110
|
+
* workers process the same row.
|
|
111
|
+
*
|
|
112
|
+
* Two ways to run it:
|
|
113
|
+
* - `start()` / `stop()` — long-running process (setInterval-style loop).
|
|
114
|
+
* - `tick()` — one cycle; call it from a cron job or Next.js route handler
|
|
115
|
+
* (e.g. a Vercel Cron hitting `/api/cron/outpost-send`).
|
|
116
|
+
*/
|
|
117
|
+
declare class SendWorker {
|
|
118
|
+
private readonly deps;
|
|
119
|
+
private readonly options;
|
|
120
|
+
private readonly dispatch;
|
|
121
|
+
private running;
|
|
122
|
+
private timer;
|
|
123
|
+
constructor(deps: CoreDeps, options?: SendWorkerOptions);
|
|
124
|
+
/** Process one batch. Returns what happened (for logging/metrics/tests). */
|
|
125
|
+
tick(): Promise<SendTickReport>;
|
|
126
|
+
/** Start the long-running poll loop. Idempotent. */
|
|
127
|
+
start(): void;
|
|
128
|
+
/** Stop the loop. In-flight dispatches complete; no new tick starts. */
|
|
129
|
+
stop(): void;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
interface PurgeReport {
|
|
133
|
+
/** Outbox rows whose PII was redacted (or deleted if redactOnPurge=false). */
|
|
134
|
+
readonly operationalProcessed: number;
|
|
135
|
+
/** Audit rows deleted. */
|
|
136
|
+
readonly auditDeleted: number;
|
|
137
|
+
readonly redacted: boolean;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* PurgeRetention — the executor of the data-minimization policy (TDR §3.9, §5.5).
|
|
141
|
+
*
|
|
142
|
+
* Safety properties baked in here:
|
|
143
|
+
* - Acts ONLY on terminal rows older than the operational TTL AND past the
|
|
144
|
+
* webhook window (`purgeCutoff`). Never touches `sent`/non-terminal rows,
|
|
145
|
+
* so it can run concurrently with the send worker.
|
|
146
|
+
* - Default action is REDACTION (wipe PII, keep audit metadata), not deletion.
|
|
147
|
+
* - Works in batches with pauses to avoid long-held table locks.
|
|
148
|
+
* - Logs counts per cycle so operators can detect "stopped cleaning" and
|
|
149
|
+
* "cleaning too much".
|
|
150
|
+
*/
|
|
151
|
+
declare class PurgeRetention {
|
|
152
|
+
private readonly deps;
|
|
153
|
+
constructor(deps: CoreDeps);
|
|
154
|
+
execute(): Promise<PurgeReport>;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
interface RetentionWorkerOptions {
|
|
158
|
+
/** Loop interval, ms. Default 1 hour. Retention is not latency-sensitive. */
|
|
159
|
+
readonly intervalMs?: number;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* RetentionWorker — periodically enforces the retention/purge policy
|
|
163
|
+
* (TDR §3.9). Like the send worker it offers both a long-running `start()`
|
|
164
|
+
* loop and a single `tick()` for cron/route-handler deployments. It only ever
|
|
165
|
+
* touches terminal, aged rows, so it is safe to run alongside the send worker.
|
|
166
|
+
*/
|
|
167
|
+
declare class RetentionWorker {
|
|
168
|
+
private readonly deps;
|
|
169
|
+
private readonly options;
|
|
170
|
+
private readonly purge;
|
|
171
|
+
private running;
|
|
172
|
+
private timer;
|
|
173
|
+
constructor(deps: CoreDeps, options?: RetentionWorkerOptions);
|
|
174
|
+
tick(): Promise<PurgeReport>;
|
|
175
|
+
start(): void;
|
|
176
|
+
stop(): void;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export { type CoreDeps as C, DispatchMessage as D, type PurgeReport as P, RetentionWorker as R, SendWorker as S, type DispatchOutcome as a, PurgeRetention as b, type RetentionWorkerOptions as c, type SendTickReport as d, type SendWorkerOptions as e };
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { O as OutboxRepository, S as SuppressionRepository, A as AuditRepository, a as ApiKeyRepository, W as WebhookEventRepository } from './repositories-DhUe8f2R.cjs';
|
|
2
|
+
import { E as EmailProvider, a as RateLimiter, C as Clock, I as IdGenerator, L as Logger, T as Telemetry } from './services-CQINhAGo.cjs';
|
|
3
|
+
import { k as ResolvedConfig, E as Encryptor, i as RecipientHasher, T as TemplateRenderer, M as MxResolver } from './template-DxI_p2Ny.cjs';
|
|
4
|
+
import { M as Message } from './webhook-kp6CiXk-.cjs';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The dependency container the use cases receive (composed at the edge by
|
|
8
|
+
* `createOutpost`). This is the seam where Clean Architecture's Dependency
|
|
9
|
+
* Inversion is realized: use cases only ever touch these interfaces.
|
|
10
|
+
*
|
|
11
|
+
* Note the deliberate split between `sealEncryptor` and `openEncryptor`:
|
|
12
|
+
* the ingestion side is wired with a seal-only encryptor (public key) and the
|
|
13
|
+
* send worker with an open-capable one (private key). In a single-process
|
|
14
|
+
* deployment they may be the same symmetric instance; in the asymmetric
|
|
15
|
+
* least-privilege deployment they are different (TDR §5.4).
|
|
16
|
+
*/
|
|
17
|
+
interface CoreDeps {
|
|
18
|
+
readonly config: ResolvedConfig;
|
|
19
|
+
readonly outbox: OutboxRepository;
|
|
20
|
+
readonly suppressions: SuppressionRepository;
|
|
21
|
+
readonly audit: AuditRepository;
|
|
22
|
+
readonly apiKeys: ApiKeyRepository;
|
|
23
|
+
readonly webhookEvents: WebhookEventRepository;
|
|
24
|
+
readonly providers: ReadonlyMap<string, EmailProvider>;
|
|
25
|
+
/** Provider name used when an enqueue does not specify one. */
|
|
26
|
+
readonly defaultProvider: string;
|
|
27
|
+
/** Write-side encryptor (public key in the asymmetric model). */
|
|
28
|
+
readonly sealEncryptor: Encryptor;
|
|
29
|
+
/** Read-side encryptor (private key). Only the send worker needs this. */
|
|
30
|
+
readonly openEncryptor: Encryptor;
|
|
31
|
+
readonly recipientHasher: RecipientHasher;
|
|
32
|
+
readonly rateLimiter: RateLimiter;
|
|
33
|
+
readonly clock: Clock;
|
|
34
|
+
readonly ids: IdGenerator;
|
|
35
|
+
readonly logger: Logger;
|
|
36
|
+
readonly telemetry: Telemetry;
|
|
37
|
+
readonly templates?: TemplateRenderer;
|
|
38
|
+
readonly mxResolver?: MxResolver;
|
|
39
|
+
/** Pluggable strong HTML sanitizer; falls back to the built-in stripper. */
|
|
40
|
+
readonly sanitizeHtml?: (html: string) => string;
|
|
41
|
+
/** Random sample in [0,1) for retry jitter. Injected for testability. */
|
|
42
|
+
readonly random: () => number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
type DispatchOutcome = {
|
|
46
|
+
kind: "sent";
|
|
47
|
+
providerMessageId: string;
|
|
48
|
+
} | {
|
|
49
|
+
kind: "retry";
|
|
50
|
+
nextAttemptAt: Date;
|
|
51
|
+
} | {
|
|
52
|
+
kind: "rate_limited";
|
|
53
|
+
nextAttemptAt: Date;
|
|
54
|
+
} | {
|
|
55
|
+
kind: "failed";
|
|
56
|
+
reason: string;
|
|
57
|
+
} | {
|
|
58
|
+
kind: "skipped";
|
|
59
|
+
reason: string;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* DispatchMessage — processes ONE message already claimed (state `sending`) by
|
|
63
|
+
* the send worker. Implements the outbound pipeline (TDR §3.2):
|
|
64
|
+
*
|
|
65
|
+
* 1. Idempotency / state guard (no double-send under concurrency)
|
|
66
|
+
* 2. Decrypt PII (READ-side encryptor, only here)
|
|
67
|
+
* 3. Re-sanitize decrypted data (defense in depth)
|
|
68
|
+
* 4. Domain validation (syntax + cached MX)
|
|
69
|
+
* 5. Rate limiting (global / provider / domain)
|
|
70
|
+
* 6. Dispatch (provider.send)
|
|
71
|
+
* 7. State transition + audit
|
|
72
|
+
*
|
|
73
|
+
* Decryption happens as late as possible — immediately before dispatch — so
|
|
74
|
+
* plaintext never lives in the queue (TDR §5.4).
|
|
75
|
+
*/
|
|
76
|
+
declare class DispatchMessage {
|
|
77
|
+
private readonly deps;
|
|
78
|
+
private readonly mxCache;
|
|
79
|
+
constructor(deps: CoreDeps);
|
|
80
|
+
execute(message: Message): Promise<DispatchOutcome>;
|
|
81
|
+
/** Classify the error and either retry-with-backoff or dead-letter. */
|
|
82
|
+
private handleError;
|
|
83
|
+
/** Move to `failed` (terminal) and record in the Dead Letter Queue. */
|
|
84
|
+
private fail;
|
|
85
|
+
/** Re-queue without counting a failed attempt; short, jittered backoff. */
|
|
86
|
+
private requeueRateLimited;
|
|
87
|
+
private checkRateLimits;
|
|
88
|
+
/** List-Unsubscribe and other always-on headers (TDR §3.11). */
|
|
89
|
+
private buildHeaders;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
interface SendTickReport {
|
|
93
|
+
readonly claimed: number;
|
|
94
|
+
readonly outcomes: DispatchOutcome[];
|
|
95
|
+
}
|
|
96
|
+
interface SendWorkerOptions {
|
|
97
|
+
/** Poll interval for the long-running loop, ms. Default 1000. */
|
|
98
|
+
readonly intervalMs?: number;
|
|
99
|
+
/** Max messages claimed per tick. Defaults to config.sendBatchSize. */
|
|
100
|
+
readonly batchSize?: number;
|
|
101
|
+
/** Max concurrent dispatches within a tick. Default 10. */
|
|
102
|
+
readonly concurrency?: number;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* SendWorker — the polling outbound processor (TDR §3.2, decision #2).
|
|
106
|
+
*
|
|
107
|
+
* Polls the outbox (NEVER a dual-written queue), atomically claims a batch with
|
|
108
|
+
* `FOR UPDATE SKIP LOCKED`, and runs each message through `DispatchMessage`.
|
|
109
|
+
* Safe to run as multiple concurrent instances — the claim guarantees no two
|
|
110
|
+
* workers process the same row.
|
|
111
|
+
*
|
|
112
|
+
* Two ways to run it:
|
|
113
|
+
* - `start()` / `stop()` — long-running process (setInterval-style loop).
|
|
114
|
+
* - `tick()` — one cycle; call it from a cron job or Next.js route handler
|
|
115
|
+
* (e.g. a Vercel Cron hitting `/api/cron/outpost-send`).
|
|
116
|
+
*/
|
|
117
|
+
declare class SendWorker {
|
|
118
|
+
private readonly deps;
|
|
119
|
+
private readonly options;
|
|
120
|
+
private readonly dispatch;
|
|
121
|
+
private running;
|
|
122
|
+
private timer;
|
|
123
|
+
constructor(deps: CoreDeps, options?: SendWorkerOptions);
|
|
124
|
+
/** Process one batch. Returns what happened (for logging/metrics/tests). */
|
|
125
|
+
tick(): Promise<SendTickReport>;
|
|
126
|
+
/** Start the long-running poll loop. Idempotent. */
|
|
127
|
+
start(): void;
|
|
128
|
+
/** Stop the loop. In-flight dispatches complete; no new tick starts. */
|
|
129
|
+
stop(): void;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
interface PurgeReport {
|
|
133
|
+
/** Outbox rows whose PII was redacted (or deleted if redactOnPurge=false). */
|
|
134
|
+
readonly operationalProcessed: number;
|
|
135
|
+
/** Audit rows deleted. */
|
|
136
|
+
readonly auditDeleted: number;
|
|
137
|
+
readonly redacted: boolean;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* PurgeRetention — the executor of the data-minimization policy (TDR §3.9, §5.5).
|
|
141
|
+
*
|
|
142
|
+
* Safety properties baked in here:
|
|
143
|
+
* - Acts ONLY on terminal rows older than the operational TTL AND past the
|
|
144
|
+
* webhook window (`purgeCutoff`). Never touches `sent`/non-terminal rows,
|
|
145
|
+
* so it can run concurrently with the send worker.
|
|
146
|
+
* - Default action is REDACTION (wipe PII, keep audit metadata), not deletion.
|
|
147
|
+
* - Works in batches with pauses to avoid long-held table locks.
|
|
148
|
+
* - Logs counts per cycle so operators can detect "stopped cleaning" and
|
|
149
|
+
* "cleaning too much".
|
|
150
|
+
*/
|
|
151
|
+
declare class PurgeRetention {
|
|
152
|
+
private readonly deps;
|
|
153
|
+
constructor(deps: CoreDeps);
|
|
154
|
+
execute(): Promise<PurgeReport>;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
interface RetentionWorkerOptions {
|
|
158
|
+
/** Loop interval, ms. Default 1 hour. Retention is not latency-sensitive. */
|
|
159
|
+
readonly intervalMs?: number;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* RetentionWorker — periodically enforces the retention/purge policy
|
|
163
|
+
* (TDR §3.9). Like the send worker it offers both a long-running `start()`
|
|
164
|
+
* loop and a single `tick()` for cron/route-handler deployments. It only ever
|
|
165
|
+
* touches terminal, aged rows, so it is safe to run alongside the send worker.
|
|
166
|
+
*/
|
|
167
|
+
declare class RetentionWorker {
|
|
168
|
+
private readonly deps;
|
|
169
|
+
private readonly options;
|
|
170
|
+
private readonly purge;
|
|
171
|
+
private running;
|
|
172
|
+
private timer;
|
|
173
|
+
constructor(deps: CoreDeps, options?: RetentionWorkerOptions);
|
|
174
|
+
tick(): Promise<PurgeReport>;
|
|
175
|
+
start(): void;
|
|
176
|
+
stop(): void;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export { type CoreDeps as C, DispatchMessage as D, type PurgeReport as P, RetentionWorker as R, SendWorker as S, type DispatchOutcome as a, PurgeRetention as b, type RetentionWorkerOptions as c, type SendTickReport as d, type SendWorkerOptions as e };
|