@tgoliveira/outpost 1.2.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +172 -18
- package/README.md +17 -12
- package/dist/adapters/drizzle/index.cjs +194 -15
- package/dist/adapters/drizzle/index.cjs.map +1 -1
- package/dist/adapters/drizzle/index.d.cts +124 -7
- package/dist/adapters/drizzle/index.d.ts +124 -7
- package/dist/adapters/drizzle/index.js +194 -15
- package/dist/adapters/drizzle/index.js.map +1 -1
- package/dist/adapters/index.cjs +148 -38
- package/dist/adapters/index.cjs.map +1 -1
- package/dist/adapters/index.d.cts +21 -13
- package/dist/adapters/index.d.ts +21 -13
- package/dist/adapters/index.js +149 -39
- package/dist/adapters/index.js.map +1 -1
- package/dist/admin/index.cjs +10 -3
- package/dist/admin/index.cjs.map +1 -1
- package/dist/admin/index.d.cts +7 -7
- package/dist/admin/index.d.ts +7 -7
- package/dist/admin/index.js +10 -3
- package/dist/admin/index.js.map +1 -1
- package/dist/{fake-BY6t7UXb.d.cts → fake-B6OIEdod.d.ts} +6 -4
- package/dist/{fake-en-oOdg0.d.ts → fake-CpQc9p0N.d.cts} +6 -4
- package/dist/http/index.cjs.map +1 -1
- package/dist/http/index.d.cts +6 -6
- package/dist/http/index.d.ts +6 -6
- package/dist/http/index.js.map +1 -1
- package/dist/{index-c6caPsUG.d.ts → index-B4F7euCt.d.cts} +53 -21
- package/dist/{index-BO0GiZmP.d.cts → index-Cn1YsmGe.d.ts} +53 -21
- package/dist/index.cjs +509 -146
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -15
- package/dist/index.d.ts +17 -15
- package/dist/index.js +509 -148
- package/dist/index.js.map +1 -1
- package/dist/modules/ui/index.cjs +38 -21
- package/dist/modules/ui/index.cjs.map +1 -1
- package/dist/modules/ui/index.js +38 -21
- package/dist/modules/ui/index.js.map +1 -1
- package/dist/modules/ui/pages/admin/admin-config-page.cjs +39 -20
- package/dist/modules/ui/pages/admin/admin-config-page.cjs.map +1 -1
- package/dist/modules/ui/pages/admin/admin-config-page.d.cts +23 -1
- package/dist/modules/ui/pages/admin/admin-config-page.d.ts +23 -1
- package/dist/modules/ui/pages/admin/admin-config-page.js +38 -20
- package/dist/modules/ui/pages/admin/admin-config-page.js.map +1 -1
- package/dist/modules/ui/pages/admin/admin-panel-page.cjs +1 -1
- package/dist/modules/ui/pages/admin/admin-panel-page.js +1 -1
- package/dist/modules/ui/pages/index.cjs +38 -21
- package/dist/modules/ui/pages/index.cjs.map +1 -1
- package/dist/modules/ui/pages/index.js +38 -21
- package/dist/modules/ui/pages/index.js.map +1 -1
- package/dist/{outpost-client-BItbgqIo.d.ts → outpost-client-BX3SsOFb.d.ts} +50 -21
- package/dist/{outpost-client-BlVf4gjo.d.cts → outpost-client-DhQgZY16.d.cts} +50 -21
- package/dist/react/index.cjs +38 -21
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.js +38 -21
- package/dist/react/index.js.map +1 -1
- package/dist/repositories-DJYu4nGV.d.ts +322 -0
- package/dist/repositories-sMN6RHZJ.d.cts +322 -0
- package/dist/{services-CfTEsetF.d.ts → services-DZwZjDn_.d.cts} +9 -3
- package/dist/{services-CQINhAGo.d.cts → services-PoM2bxjP.d.ts} +9 -3
- package/dist/{template-DxI_p2Ny.d.cts → template-Dl1_ciRo.d.ts} +24 -4
- package/dist/{template-CREUq7bB.d.ts → template-Dny_7Ymi.d.cts} +24 -4
- package/dist/testing/index.cjs +200 -15
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +26 -7
- package/dist/testing/index.d.ts +26 -7
- package/dist/testing/index.js +200 -15
- package/dist/testing/index.js.map +1 -1
- package/dist/{webhook-kp6CiXk-.d.cts → webhook-B158Vi6p.d.cts} +20 -4
- package/dist/{webhook-kp6CiXk-.d.ts → webhook-B158Vi6p.d.ts} +20 -4
- package/dist/workers/index.cjs +471 -85
- package/dist/workers/index.cjs.map +1 -1
- package/dist/workers/index.d.cts +5 -5
- package/dist/workers/index.d.ts +5 -5
- package/dist/workers/index.js +471 -85
- package/dist/workers/index.js.map +1 -1
- package/package.json +6 -3
- package/dist/repositories-CHIOFGn3.d.cts +0 -182
- package/dist/repositories-WyhvxzyY.d.ts +0 -182
package/dist/http/index.js.map
CHANGED
|
@@ -1 +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,EAAiB,OAAA,EAA+B;AACxE,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AACvB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF,CAAA;AAGO,IAAM,iBAAA,GAAN,cAAgC,YAAA,CAAa;AAAA,EAClD,WAAA,CAAY,UAAU,sCAAA,EAAwC;AAC5D,IAAA,KAAA,CAAM,gBAAgB,OAAO,CAAA;AAAA,EAC/B;AACF,CAAA;AAGO,IAAM,cAAA,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AAO,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"]}
|
|
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;;;AC/BO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,IAAA;AAAA,EACT,WAAA,CAAY,IAAA,EAAc,OAAA,EAAiB,OAAA,EAA+B;AACxE,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AACvB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF,CAAA;AAGO,IAAM,iBAAA,GAAN,cAAgC,YAAA,CAAa;AAAA,EAClD,WAAA,CAAY,UAAU,sCAAA,EAAwC;AAC5D,IAAA,KAAA,CAAM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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\nimport { classifyProviderFailure } from \"./provider-failure.js\";\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. Classification uses the stored\n * pair, not one field alone: `errorClass === \"transient\"` with\n * `code === \"provider_transient\"`, or `errorClass === \"permanent\"` with\n * `code === \"provider_permanent\"`.\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/** True only when `errorClass === \"transient\"` and `code === \"provider_transient\"`. */\nexport function isTransient(err: unknown): boolean {\n return classifyProviderFailure(err) === \"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"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { O as OutboxRepository, S as SuppressionRepository, A as AuditRepository, a as ApiKeyRepository, W as WebhookEventRepository } from './repositories-
|
|
2
|
-
import { E as EmailProvider, a as RateLimiter, C as Clock, I as IdGenerator, L as Logger, T as Telemetry } from './services-
|
|
3
|
-
import { k as ResolvedConfig, E as Encryptor, i as RecipientHasher, T as TemplateRenderer, M as MxResolver } from './template-
|
|
4
|
-
import { M as Message } from './webhook-
|
|
1
|
+
import { O as OutboxRepository, S as SuppressionRepository, A as AuditRepository, a as ApiKeyRepository, W as WebhookEventRepository } from './repositories-sMN6RHZJ.cjs';
|
|
2
|
+
import { E as EmailProvider, a as RateLimiter, C as Clock, I as IdGenerator, L as Logger, T as Telemetry } from './services-DZwZjDn_.cjs';
|
|
3
|
+
import { k as ResolvedConfig, E as Encryptor, i as RecipientHasher, T as TemplateRenderer, M as MxResolver } from './template-Dny_7Ymi.cjs';
|
|
4
|
+
import { M as Message } from './webhook-B158Vi6p.cjs';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* The dependency container the use cases receive (composed at the edge by
|
|
@@ -62,30 +62,48 @@ type DispatchOutcome = {
|
|
|
62
62
|
* DispatchMessage — processes ONE message already claimed (state `sending`) by
|
|
63
63
|
* the send worker. Implements the outbound pipeline (TDR §3.2):
|
|
64
64
|
*
|
|
65
|
-
* 1.
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
65
|
+
* 1. Claim fence (still `sending` at the claimed `updatedAt`)
|
|
66
|
+
* then `dispatch_started`. A failed append does not stop the send.
|
|
67
|
+
* 2. Suppression check (stored HMAC, before decrypt)
|
|
68
|
+
* 3. Decrypt PII (READ-side encryptor, only here)
|
|
69
|
+
* 4. Recipient, subject, size (HTML sanitization already ran at enqueue)
|
|
70
|
+
* 5. Domain validation (syntax + cached MX)
|
|
71
|
+
* 6. Rate limiting (global / provider / domain)
|
|
72
|
+
* 7. Dispatch (provider.send)
|
|
73
|
+
* 8. State transition + audit
|
|
72
74
|
*
|
|
75
|
+
* Suppression is checked on the stored HMAC before decrypt. A listed
|
|
76
|
+
* recipient moves `sending` → `suppressed` and is never opened or sent.
|
|
73
77
|
* Decryption happens as late as possible — immediately before dispatch — so
|
|
74
78
|
* plaintext never lives in the queue (TDR §5.4).
|
|
75
79
|
*/
|
|
76
80
|
declare class DispatchMessage {
|
|
77
81
|
private readonly deps;
|
|
78
82
|
private readonly mxCache;
|
|
83
|
+
private readonly webhooks;
|
|
79
84
|
constructor(deps: CoreDeps);
|
|
80
85
|
execute(message: Message): Promise<DispatchOutcome>;
|
|
81
|
-
/**
|
|
86
|
+
/**
|
|
87
|
+
* Recipient was listed after enqueue. `sending` → `suppressed` on the
|
|
88
|
+
* stored HMAC. Do not decrypt, call the provider, or add a suppression row.
|
|
89
|
+
* A lost claim does not audit. An audit failure leaves the row suppressed.
|
|
90
|
+
*/
|
|
91
|
+
private suppressListed;
|
|
92
|
+
/** Classify a provider or pipeline error and either retry or dead-letter. */
|
|
82
93
|
private handleError;
|
|
83
94
|
/** Move to `failed` (terminal) and record in the Dead Letter Queue. */
|
|
84
95
|
private fail;
|
|
85
96
|
/** Re-queue without counting a failed attempt; short, jittered backoff. */
|
|
86
97
|
private requeueRateLimited;
|
|
98
|
+
/**
|
|
99
|
+
* Fence write. `false` means the claim no longer owns the row, or the driver
|
|
100
|
+
* threw. Neither path is a provider retry. When the provider may already
|
|
101
|
+
* have accepted, the log says so and the caller leaves the row alone.
|
|
102
|
+
*/
|
|
103
|
+
private commitWhileSending;
|
|
104
|
+
private logWrite;
|
|
87
105
|
private checkRateLimits;
|
|
88
|
-
/**
|
|
106
|
+
/** No headers are added. List-Unsubscribe is not set. */
|
|
89
107
|
private buildHeaders;
|
|
90
108
|
}
|
|
91
109
|
|
|
@@ -106,8 +124,9 @@ interface SendWorkerOptions {
|
|
|
106
124
|
*
|
|
107
125
|
* Polls the outbox (NEVER a dual-written queue), atomically claims a batch with
|
|
108
126
|
* `FOR UPDATE SKIP LOCKED`, and runs each message through `DispatchMessage`.
|
|
109
|
-
*
|
|
110
|
-
*
|
|
127
|
+
* Concurrent claims skip locked rows. A `sending` row past the lease can be
|
|
128
|
+
* claimed again, so the provider can be called twice. The stale claim's later
|
|
129
|
+
* write does not change the row.
|
|
111
130
|
*
|
|
112
131
|
* Two ways to run it:
|
|
113
132
|
* - `start()` / `stop()` — long-running process (setInterval-style loop).
|
|
@@ -140,11 +159,14 @@ interface PurgeReport {
|
|
|
140
159
|
* PurgeRetention — the executor of the data-minimization policy (TDR §3.9, §5.5).
|
|
141
160
|
*
|
|
142
161
|
* Safety properties baked in here:
|
|
143
|
-
* -
|
|
144
|
-
* webhook window (`purgeCutoff`).
|
|
145
|
-
*
|
|
162
|
+
* - Selects terminal rows older than the operational TTL and past the
|
|
163
|
+
* webhook window (`purgeCutoff`). The purge write repeats that predicate
|
|
164
|
+
* against the cutoff computed for this cycle.
|
|
165
|
+
* - Calls `redactBatchIfEligible` or `deleteBatchIfEligible`. A repository
|
|
166
|
+
* that does not implement both throws here, before any id-only write.
|
|
146
167
|
* - Default action is REDACTION (wipe PII, keep audit metadata), not deletion.
|
|
147
|
-
|
|
168
|
+
* - Works in batches. After a full batch it waits `batchPauseMs` before the
|
|
169
|
+
* next claim. A short batch does not wait.
|
|
148
170
|
* - Logs counts per cycle so operators can detect "stopped cleaning" and
|
|
149
171
|
* "cleaning too much".
|
|
150
172
|
*/
|
|
@@ -161,8 +183,15 @@ interface RetentionWorkerOptions {
|
|
|
161
183
|
/**
|
|
162
184
|
* RetentionWorker — periodically enforces the retention/purge policy
|
|
163
185
|
* (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
|
|
165
|
-
*
|
|
186
|
+
* loop and a single `tick()` for cron/route-handler deployments. It redacts or
|
|
187
|
+
* deletes terminal, aged outbox rows, and deletes webhook rows older than the
|
|
188
|
+
* same cutoff, so it is safe to run alongside the send worker.
|
|
189
|
+
*
|
|
190
|
+
* Loop lifecycle (`start` / `stop`) is serialized on this class only. A tick
|
|
191
|
+
* already in flight is not cancelled by `stop()`, and a later `start()` does
|
|
192
|
+
* not run a second tick while that work is pending. The next interval is always
|
|
193
|
+
* armed with `setTimeout`, including `intervalMs` 0, so the loop yields.
|
|
194
|
+
* `SendWorker` does not inherit this guarantee.
|
|
166
195
|
*/
|
|
167
196
|
declare class RetentionWorker {
|
|
168
197
|
private readonly deps;
|
|
@@ -170,10 +199,13 @@ declare class RetentionWorker {
|
|
|
170
199
|
private readonly purge;
|
|
171
200
|
private running;
|
|
172
201
|
private timer;
|
|
202
|
+
private inFlight;
|
|
173
203
|
constructor(deps: CoreDeps, options?: RetentionWorkerOptions);
|
|
174
204
|
tick(): Promise<PurgeReport>;
|
|
175
205
|
start(): void;
|
|
176
206
|
stop(): void;
|
|
207
|
+
private intervalMs;
|
|
208
|
+
private runLoopTick;
|
|
177
209
|
}
|
|
178
210
|
|
|
179
211
|
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 };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { O as OutboxRepository, S as SuppressionRepository, A as AuditRepository, a as ApiKeyRepository, W as WebhookEventRepository } from './repositories-
|
|
2
|
-
import { E as EmailProvider, a as RateLimiter, C as Clock, I as IdGenerator, L as Logger, T as Telemetry } from './services-
|
|
3
|
-
import { k as ResolvedConfig, E as Encryptor, i as RecipientHasher, T as TemplateRenderer, M as MxResolver } from './template-
|
|
4
|
-
import { M as Message } from './webhook-
|
|
1
|
+
import { O as OutboxRepository, S as SuppressionRepository, A as AuditRepository, a as ApiKeyRepository, W as WebhookEventRepository } from './repositories-DJYu4nGV.js';
|
|
2
|
+
import { E as EmailProvider, a as RateLimiter, C as Clock, I as IdGenerator, L as Logger, T as Telemetry } from './services-PoM2bxjP.js';
|
|
3
|
+
import { k as ResolvedConfig, E as Encryptor, i as RecipientHasher, T as TemplateRenderer, M as MxResolver } from './template-Dl1_ciRo.js';
|
|
4
|
+
import { M as Message } from './webhook-B158Vi6p.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* The dependency container the use cases receive (composed at the edge by
|
|
@@ -62,30 +62,48 @@ type DispatchOutcome = {
|
|
|
62
62
|
* DispatchMessage — processes ONE message already claimed (state `sending`) by
|
|
63
63
|
* the send worker. Implements the outbound pipeline (TDR §3.2):
|
|
64
64
|
*
|
|
65
|
-
* 1.
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
65
|
+
* 1. Claim fence (still `sending` at the claimed `updatedAt`)
|
|
66
|
+
* then `dispatch_started`. A failed append does not stop the send.
|
|
67
|
+
* 2. Suppression check (stored HMAC, before decrypt)
|
|
68
|
+
* 3. Decrypt PII (READ-side encryptor, only here)
|
|
69
|
+
* 4. Recipient, subject, size (HTML sanitization already ran at enqueue)
|
|
70
|
+
* 5. Domain validation (syntax + cached MX)
|
|
71
|
+
* 6. Rate limiting (global / provider / domain)
|
|
72
|
+
* 7. Dispatch (provider.send)
|
|
73
|
+
* 8. State transition + audit
|
|
72
74
|
*
|
|
75
|
+
* Suppression is checked on the stored HMAC before decrypt. A listed
|
|
76
|
+
* recipient moves `sending` → `suppressed` and is never opened or sent.
|
|
73
77
|
* Decryption happens as late as possible — immediately before dispatch — so
|
|
74
78
|
* plaintext never lives in the queue (TDR §5.4).
|
|
75
79
|
*/
|
|
76
80
|
declare class DispatchMessage {
|
|
77
81
|
private readonly deps;
|
|
78
82
|
private readonly mxCache;
|
|
83
|
+
private readonly webhooks;
|
|
79
84
|
constructor(deps: CoreDeps);
|
|
80
85
|
execute(message: Message): Promise<DispatchOutcome>;
|
|
81
|
-
/**
|
|
86
|
+
/**
|
|
87
|
+
* Recipient was listed after enqueue. `sending` → `suppressed` on the
|
|
88
|
+
* stored HMAC. Do not decrypt, call the provider, or add a suppression row.
|
|
89
|
+
* A lost claim does not audit. An audit failure leaves the row suppressed.
|
|
90
|
+
*/
|
|
91
|
+
private suppressListed;
|
|
92
|
+
/** Classify a provider or pipeline error and either retry or dead-letter. */
|
|
82
93
|
private handleError;
|
|
83
94
|
/** Move to `failed` (terminal) and record in the Dead Letter Queue. */
|
|
84
95
|
private fail;
|
|
85
96
|
/** Re-queue without counting a failed attempt; short, jittered backoff. */
|
|
86
97
|
private requeueRateLimited;
|
|
98
|
+
/**
|
|
99
|
+
* Fence write. `false` means the claim no longer owns the row, or the driver
|
|
100
|
+
* threw. Neither path is a provider retry. When the provider may already
|
|
101
|
+
* have accepted, the log says so and the caller leaves the row alone.
|
|
102
|
+
*/
|
|
103
|
+
private commitWhileSending;
|
|
104
|
+
private logWrite;
|
|
87
105
|
private checkRateLimits;
|
|
88
|
-
/**
|
|
106
|
+
/** No headers are added. List-Unsubscribe is not set. */
|
|
89
107
|
private buildHeaders;
|
|
90
108
|
}
|
|
91
109
|
|
|
@@ -106,8 +124,9 @@ interface SendWorkerOptions {
|
|
|
106
124
|
*
|
|
107
125
|
* Polls the outbox (NEVER a dual-written queue), atomically claims a batch with
|
|
108
126
|
* `FOR UPDATE SKIP LOCKED`, and runs each message through `DispatchMessage`.
|
|
109
|
-
*
|
|
110
|
-
*
|
|
127
|
+
* Concurrent claims skip locked rows. A `sending` row past the lease can be
|
|
128
|
+
* claimed again, so the provider can be called twice. The stale claim's later
|
|
129
|
+
* write does not change the row.
|
|
111
130
|
*
|
|
112
131
|
* Two ways to run it:
|
|
113
132
|
* - `start()` / `stop()` — long-running process (setInterval-style loop).
|
|
@@ -140,11 +159,14 @@ interface PurgeReport {
|
|
|
140
159
|
* PurgeRetention — the executor of the data-minimization policy (TDR §3.9, §5.5).
|
|
141
160
|
*
|
|
142
161
|
* Safety properties baked in here:
|
|
143
|
-
* -
|
|
144
|
-
* webhook window (`purgeCutoff`).
|
|
145
|
-
*
|
|
162
|
+
* - Selects terminal rows older than the operational TTL and past the
|
|
163
|
+
* webhook window (`purgeCutoff`). The purge write repeats that predicate
|
|
164
|
+
* against the cutoff computed for this cycle.
|
|
165
|
+
* - Calls `redactBatchIfEligible` or `deleteBatchIfEligible`. A repository
|
|
166
|
+
* that does not implement both throws here, before any id-only write.
|
|
146
167
|
* - Default action is REDACTION (wipe PII, keep audit metadata), not deletion.
|
|
147
|
-
|
|
168
|
+
* - Works in batches. After a full batch it waits `batchPauseMs` before the
|
|
169
|
+
* next claim. A short batch does not wait.
|
|
148
170
|
* - Logs counts per cycle so operators can detect "stopped cleaning" and
|
|
149
171
|
* "cleaning too much".
|
|
150
172
|
*/
|
|
@@ -161,8 +183,15 @@ interface RetentionWorkerOptions {
|
|
|
161
183
|
/**
|
|
162
184
|
* RetentionWorker — periodically enforces the retention/purge policy
|
|
163
185
|
* (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
|
|
165
|
-
*
|
|
186
|
+
* loop and a single `tick()` for cron/route-handler deployments. It redacts or
|
|
187
|
+
* deletes terminal, aged outbox rows, and deletes webhook rows older than the
|
|
188
|
+
* same cutoff, so it is safe to run alongside the send worker.
|
|
189
|
+
*
|
|
190
|
+
* Loop lifecycle (`start` / `stop`) is serialized on this class only. A tick
|
|
191
|
+
* already in flight is not cancelled by `stop()`, and a later `start()` does
|
|
192
|
+
* not run a second tick while that work is pending. The next interval is always
|
|
193
|
+
* armed with `setTimeout`, including `intervalMs` 0, so the loop yields.
|
|
194
|
+
* `SendWorker` does not inherit this guarantee.
|
|
166
195
|
*/
|
|
167
196
|
declare class RetentionWorker {
|
|
168
197
|
private readonly deps;
|
|
@@ -170,10 +199,13 @@ declare class RetentionWorker {
|
|
|
170
199
|
private readonly purge;
|
|
171
200
|
private running;
|
|
172
201
|
private timer;
|
|
202
|
+
private inFlight;
|
|
173
203
|
constructor(deps: CoreDeps, options?: RetentionWorkerOptions);
|
|
174
204
|
tick(): Promise<PurgeReport>;
|
|
175
205
|
start(): void;
|
|
176
206
|
stop(): void;
|
|
207
|
+
private intervalMs;
|
|
208
|
+
private runLoopTick;
|
|
177
209
|
}
|
|
178
210
|
|
|
179
211
|
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 };
|