@tgoliveira/outpost 1.2.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/AGENTS.md +172 -18
  2. package/README.md +17 -12
  3. package/dist/adapters/drizzle/index.cjs +194 -15
  4. package/dist/adapters/drizzle/index.cjs.map +1 -1
  5. package/dist/adapters/drizzle/index.d.cts +124 -7
  6. package/dist/adapters/drizzle/index.d.ts +124 -7
  7. package/dist/adapters/drizzle/index.js +194 -15
  8. package/dist/adapters/drizzle/index.js.map +1 -1
  9. package/dist/adapters/index.cjs +148 -38
  10. package/dist/adapters/index.cjs.map +1 -1
  11. package/dist/adapters/index.d.cts +21 -13
  12. package/dist/adapters/index.d.ts +21 -13
  13. package/dist/adapters/index.js +149 -39
  14. package/dist/adapters/index.js.map +1 -1
  15. package/dist/admin/index.cjs +10 -3
  16. package/dist/admin/index.cjs.map +1 -1
  17. package/dist/admin/index.d.cts +7 -7
  18. package/dist/admin/index.d.ts +7 -7
  19. package/dist/admin/index.js +10 -3
  20. package/dist/admin/index.js.map +1 -1
  21. package/dist/{fake-BY6t7UXb.d.cts → fake-B6OIEdod.d.ts} +6 -4
  22. package/dist/{fake-en-oOdg0.d.ts → fake-CpQc9p0N.d.cts} +6 -4
  23. package/dist/http/index.cjs.map +1 -1
  24. package/dist/http/index.d.cts +6 -6
  25. package/dist/http/index.d.ts +6 -6
  26. package/dist/http/index.js.map +1 -1
  27. package/dist/{index-c6caPsUG.d.ts → index-B4F7euCt.d.cts} +53 -21
  28. package/dist/{index-BO0GiZmP.d.cts → index-Cn1YsmGe.d.ts} +53 -21
  29. package/dist/index.cjs +509 -146
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +17 -15
  32. package/dist/index.d.ts +17 -15
  33. package/dist/index.js +509 -148
  34. package/dist/index.js.map +1 -1
  35. package/dist/modules/ui/index.cjs +38 -21
  36. package/dist/modules/ui/index.cjs.map +1 -1
  37. package/dist/modules/ui/index.js +38 -21
  38. package/dist/modules/ui/index.js.map +1 -1
  39. package/dist/modules/ui/pages/admin/admin-config-page.cjs +39 -20
  40. package/dist/modules/ui/pages/admin/admin-config-page.cjs.map +1 -1
  41. package/dist/modules/ui/pages/admin/admin-config-page.d.cts +23 -1
  42. package/dist/modules/ui/pages/admin/admin-config-page.d.ts +23 -1
  43. package/dist/modules/ui/pages/admin/admin-config-page.js +38 -20
  44. package/dist/modules/ui/pages/admin/admin-config-page.js.map +1 -1
  45. package/dist/modules/ui/pages/admin/admin-panel-page.cjs +1 -1
  46. package/dist/modules/ui/pages/admin/admin-panel-page.js +1 -1
  47. package/dist/modules/ui/pages/index.cjs +38 -21
  48. package/dist/modules/ui/pages/index.cjs.map +1 -1
  49. package/dist/modules/ui/pages/index.js +38 -21
  50. package/dist/modules/ui/pages/index.js.map +1 -1
  51. package/dist/{outpost-client-BItbgqIo.d.ts → outpost-client-BX3SsOFb.d.ts} +50 -21
  52. package/dist/{outpost-client-BlVf4gjo.d.cts → outpost-client-DhQgZY16.d.cts} +50 -21
  53. package/dist/react/index.cjs +38 -21
  54. package/dist/react/index.cjs.map +1 -1
  55. package/dist/react/index.js +38 -21
  56. package/dist/react/index.js.map +1 -1
  57. package/dist/repositories-DJYu4nGV.d.ts +322 -0
  58. package/dist/repositories-sMN6RHZJ.d.cts +322 -0
  59. package/dist/{services-CfTEsetF.d.ts → services-DZwZjDn_.d.cts} +9 -3
  60. package/dist/{services-CQINhAGo.d.cts → services-PoM2bxjP.d.ts} +9 -3
  61. package/dist/{template-DxI_p2Ny.d.cts → template-Dl1_ciRo.d.ts} +24 -4
  62. package/dist/{template-CREUq7bB.d.ts → template-Dny_7Ymi.d.cts} +24 -4
  63. package/dist/testing/index.cjs +200 -15
  64. package/dist/testing/index.cjs.map +1 -1
  65. package/dist/testing/index.d.cts +26 -7
  66. package/dist/testing/index.d.ts +26 -7
  67. package/dist/testing/index.js +200 -15
  68. package/dist/testing/index.js.map +1 -1
  69. package/dist/{webhook-kp6CiXk-.d.cts → webhook-B158Vi6p.d.cts} +20 -4
  70. package/dist/{webhook-kp6CiXk-.d.ts → webhook-B158Vi6p.d.ts} +20 -4
  71. package/dist/workers/index.cjs +471 -85
  72. package/dist/workers/index.cjs.map +1 -1
  73. package/dist/workers/index.d.cts +5 -5
  74. package/dist/workers/index.d.ts +5 -5
  75. package/dist/workers/index.js +471 -85
  76. package/dist/workers/index.js.map +1 -1
  77. package/package.json +6 -3
  78. package/dist/repositories-CHIOFGn3.d.cts +0 -182
  79. package/dist/repositories-WyhvxzyY.d.ts +0 -182
package/AGENTS.md CHANGED
@@ -10,7 +10,7 @@
10
10
  Outpost is a **transactional outbox with a pluggable transport layer**. Email is
11
11
  the only transport in v1. It is **not** an email client and **not** a marketing
12
12
  platform. Its job is to guarantee a message is **persisted before it is sent**,
13
- **deduplicated** (at-most-once), **auditable**, **lifecycle-tracked** via provider
13
+ **deduplicated on the idempotency key**, **auditable**, **lifecycle-tracked** via provider
14
14
  webhooks, **reputation-safe** (suppression list), and **provider-agnostic**
15
15
  (swap Resend ↔ SMTP ↔ SES without touching your code).
16
16
 
@@ -24,7 +24,7 @@ resets, invoices) and you need an audit trail + delivery tracking.
24
24
  your app ──outpost.send()──▶ [outbox table] (persisted FIRST, state=queued)
25
25
  │
26
26
  SendWorker polls & claims (FOR UPDATE SKIP LOCKED)
27
- │ decrypt → sanitize → validate → rate-limit
27
+ │ suppression (stored HMAC) → decrypt → sanitize → validate → rate-limit
28
28
  ▼
29
29
  EmailProvider.send() → state=sent
30
30
  │
@@ -39,8 +39,8 @@ Three rules that explain almost every design choice:
39
39
  sent synchronously. A separate worker sends it later by polling. (No queue is
40
40
  written at ingestion — that would risk a dual-write inconsistency.)
41
41
  2. **The DB is the source of truth.** State lives in Postgres. Workers are
42
- stateless loops over it. You can run many workers; row claiming prevents
43
- double-send.
42
+ stateless loops over it. You can run many workers. Row claiming keeps one
43
+ worker on a live row. A stale lease can still call the provider again.
44
44
  3. **PII is encrypted at rest and matched by HMAC.** The recipient and body are
45
45
  sealed; suppression/idempotency-by-recipient use a keyed HMAC of the address,
46
46
  never plaintext.
@@ -65,6 +65,10 @@ Requires Node ≥ 18.17 (uses global `fetch` and the Web `Request`/`Response`).
65
65
  | `@tgoliveira/outpost/adapters` | Providers (Resend/SMTP/Fake), encryptors, HMAC hasher, rate limiters, logger, telemetry, template renderer |
66
66
  | `@tgoliveira/outpost/drizzle` | `outpostSchema`, `DrizzleOutboxRepository` & friends, `OutpostDb` type |
67
67
  | `@tgoliveira/outpost/next` | `OutpostRouter` — Fetch-based HTTP handlers for the Next.js App Router |
68
+ | `@tgoliveira/outpost/admin` | Admin route handlers and services |
69
+ | `@tgoliveira/outpost/react` | Admin UI pages |
70
+ | `@tgoliveira/outpost/react/client` | Client entry for the admin UI |
71
+ | `@tgoliveira/outpost/styles.css` | Admin UI stylesheet |
68
72
  | `@tgoliveira/outpost/workers` | `SendWorker`, `RetentionWorker` |
69
73
  | `@tgoliveira/outpost/testing` | In-memory repos, `FakeEmailProvider`, `FakeClock`, `inMemoryRepositories()` |
70
74
 
@@ -212,31 +216,97 @@ See `docs/security.md`. Quick reference:
212
216
  - Bring-your-own KMS: pass `{ sealEncryptor, openEncryptor }` implementing the
213
217
  `Encryptor` port.
214
218
 
219
+ ## Upgrading from 1.x
220
+
221
+ 2.0 keeps the same entry points. Before you deploy it over a 1.2.2 database,
222
+ apply the webhook migration and check the integrator behavior below. The
223
+ detailed release notes stay in `CHANGELOG.md`.
224
+
225
+ ### Database
226
+
227
+ Generate a new migration from `outpostSchema` and apply it before this version
228
+ writes webhook rows. In the git repository, that change is
229
+ `drizzle/0002_webhook_event_identity.sql`. It adds nullable
230
+ `provider_event_id`, `verified_at`, and `disposition` on
231
+ `outpost_webhook_events`, and a non-unique index
232
+ `outpost_webhook_provider_event_id_idx` on `(provider, provider_event_id)`.
233
+ It does not rewrite outbox rows, seals, or suppression HMACs. See
234
+ [docs/database.md](./docs/database.md#upgrading-an-existing-database).
235
+
236
+ Envelopes stored without a `bound` field, including `alg: "plain"`, still
237
+ open. New AES-GCM and hybrid envelopes are authenticated to the message id
238
+ and the column (`recipient` or `body`).
239
+
240
+ ### Behavior that affects integrators
241
+
242
+ - Install `drizzle-orm` when you use `@tgoliveira/outpost/drizzle`. It is an
243
+ optional peer. The adapters entry does not import it. A TypeScript consumer
244
+ needs `@types/node` because published types use `Buffer`.
245
+ - A custom `OutboxRepository` must implement `updateStateWhileSending`.
246
+ Dispatch throws before it calls the provider when that method is missing.
247
+ The shipped Drizzle and in-memory repositories implement it.
248
+ `staleSendingLeaseMs` still defaults to `300000`.
249
+ - A custom outbox used for retention must implement `redactBatchIfEligible`
250
+ and `deleteBatchIfEligible`. Purge throws before it writes when either is
251
+ missing. `redactBatch` and `deleteBatch` remain id-only, and retention does
252
+ not call them.
253
+ - A custom webhook repository without `deleteOlderThan` keeps its webhook
254
+ rows. The outbox purge still runs. With the shipped repository, webhook
255
+ rows of every disposition whose `receivedAt` is strictly before the cutoff
256
+ are deleted. New webhook rows store a null recipient.
257
+ - `list` caps `limit` at 100. The default stays 50. A non-finite or
258
+ non-positive value uses that default.
259
+ - A message view omits the body and the recipient address. Subject, metadata,
260
+ and last error stay in the clear.
261
+ - Replay and requeue clear the provider message id. `queued` does not move
262
+ to `failed`.
263
+ - A verified lifecycle webhook whose timestamp is more than five minutes from
264
+ the clock is rejected and not stored. A repeated provider event does not
265
+ change state or append the lifecycle audit twice.
266
+ - Signed Resend events `email.sent`, `email.clicked`, and
267
+ `email.delivery_delayed` return HTTP 200 with `note: "ignored"`. They do
268
+ not change state or store a webhook row. A bad signature is still 401.
269
+ - A permanent provider failure (`errorClass: "permanent"` and
270
+ `code: "provider_permanent"`) is dead-lettered on the first dispatch. A
271
+ transient pair (`provider_transient`) still retries. Class identity across
272
+ package entries is not required.
273
+ - SMTP with `auth` requires `secure: true`. Mailpit without `auth` can omit
274
+ TLS. `transportOptions` cannot replace `host`, `port`, `secure`, or `auth`,
275
+ and cannot set `tls.rejectUnauthorized` to false or pass a truthy `url` or
276
+ `service`.
277
+ - Admin config POST refuses a key marked secret and does not store it.
278
+ - The shipped rate limiter does not consume a token from a scope that still
279
+ had budget when another configured scope refuses the send.
280
+
215
281
  ## Hard rules / gotchas (read before you ship)
216
282
 
217
283
  - **`idempotencyKey` is required and is your dedupe key.** Derive it from the
218
284
  business event (`order-1234-receipt`), not a random UUID, or retries duplicate.
219
285
  - **`send()` does not send.** It enqueues. A worker must be running (loop or
220
286
  cron) or nothing leaves the building.
221
- - **SMTP has no webhooks.** With the SMTP/Mailpit provider, lifecycle stops at
222
- `sent` — no `delivered`/`bounced`/`complained`. Use Resend/SES/SendGrid for
223
- delivery tracking.
287
+ - **SMTP has no webhooks.** An accepted message stops at `sent`. A permanent
288
+ SMTP rejection moves the row to `failed` and does not add a suppression.
289
+ There is no `delivered`, `bounced`, or `complained` from SMTP. Use
290
+ Resend/SES/SendGrid for delivery tracking.
224
291
  - **`recipientHmacKey` is mandatory and must be stable.** Changing it orphans
225
292
  every existing suppression entry and breaks recipient lookups. Keep it in a
226
293
  secret manager, never in the DB.
227
294
  - **Encryption at rest is NOT end-to-end.** The provider receives readable
228
295
  content. Outpost protects the DB/backups, not the wire to the provider.
229
- - **The retention worker redacts by default**, it does not delete: PII columns
230
- are wiped, the audit row survives. It only touches terminal rows past the
231
- webhook window.
232
- - **Delivery semantics.** Idempotency guards prevent duplicate *enqueues* and
233
- duplicate *dispatch under concurrency*. To survive a worker crashing
234
- mid-dispatch, a row stuck in `sending` past a lease (default 5 min,
235
- `staleSendingLeaseMs`) is reclaimed and retried — this is at-least-once at the
236
- edge. To keep it effectively at-most-once, Outpost passes the message id as the
237
- provider's idempotency key (e.g. Resend's `Idempotency-Key`), so a reclaim
238
- cannot double-send through a provider that honors it. Plain SMTP has no such
239
- key — tune the lease accordingly.
296
+ - **The retention worker redacts outbox PII by default**, it does not delete
297
+ those rows: PII columns are wiped, the audit row survives. Outbox redaction
298
+ is limited to terminal rows past the webhook window. Webhook rows of every
299
+ disposition older than that same cutoff are deleted. A new webhook row does
300
+ not store the recipient address.
301
+ - **Delivery semantics.** Enqueue is deduped on `idempotencyKey`. The
302
+ suppression check on the stored HMAC sits before decrypt. A dispatch
303
+ write leaves `sending` only while the row's `updatedAt` is still the one
304
+ returned by that claim. A worker whose claim is stale does not change the
305
+ row, including when an audit write fails after the row is already `sent`.
306
+ A `sending` row past the lease (`createOutpost({ staleSendingLeaseMs })`,
307
+ default `300000`) can be claimed again, and the provider can be called again.
308
+ Resend is given the message id as `Idempotency-Key`. SMTP has no such key, so
309
+ a lost lease can deliver twice. Keep the lease longer than a real dispatch.
240
310
  - **Never use `FakeEmailProvider` or `inMemoryRepositories()` in production** —
241
311
  they hold everything in RAM and verify nothing.
242
312
  - **API keys are shown once.** Only a hash is stored; there is no "reveal key".
@@ -258,6 +328,86 @@ pass it in `providers: [...]`. Nothing in the core changes.
258
328
  To **swap storage**: implement the repository ports
259
329
  (`src/ports/repositories.ts`). The Drizzle adapter is one implementation.
260
330
 
331
+ ## Developing Outpost (agents working in this repo)
332
+
333
+ The sections above tell an application how to **use** Outpost. This section is
334
+ for agents **changing** this repository. One primary Grok Build conversation is
335
+ the engineering orchestrator. Do not add an orchestration framework, a custom
336
+ task engine, or a second documentation tree.
337
+
338
+ ### Context
339
+
340
+ - Product shape and ADRs: `docs/architecture.md`, `docs/adr/`, `docs/tdr.md`.
341
+ Code and tests are the current behavior. ADRs and the design record are the
342
+ intended behavior. When they disagree, say so and escalate. Do not treat a
343
+ proposal as an approved requirement.
344
+ - Open work and lessons: `docs/backlog.md`, `docs/engineering-memory.md`.
345
+ - Detailed discovery evidence stays outside this repo, under the local
346
+ discovery workspace. Do not copy credentials, raw logs, or exploit detail
347
+ into git.
348
+
349
+ ### Commands
350
+
351
+ CI and the discovery baseline use Node 20. The machine default may differ.
352
+ Run `npm run validate` with Node 20 (`fnm exec --using=20 -- npm run validate`
353
+ when fnm is installed). `npm test` is the source-graph suite. `npm run lint`
354
+ is `tsc --noEmit`. A change that can ship must also be checked on the built
355
+ package (`npm run build`, then a local `npm pack` install). See
356
+ `.agents/skills/artifact-validation/SKILL.md`. Do not publish.
357
+
358
+ ### Delegation
359
+
360
+ Simple, local edits stay in the primary conversation. For cross-cutting,
361
+ security, provider, or release-sensitive work, delegate to the project
362
+ subagents in `.cursor/agents/`. Specialists:
363
+
364
+ | Agent | Use |
365
+ |---|---|
366
+ | `architect` | Read-only design and invariant analysis |
367
+ | `core-engineer` | Domain, application, and worker behavior |
368
+ | `security-engineer` | Read-only review, or an explicitly assigned security change |
369
+ | `integration-engineer` | Providers, webhooks, HTTP, Next.js, admin UI |
370
+ | `platform-engineer` | Package, CI proposal, release process. Do not dispatch publish |
371
+ | `quality-engineer` | Tests and coverage. Does not rewrite the implementation it is checking |
372
+ | `technical-reviewer` | Read-only review of a finished change |
373
+
374
+ Give each subagent the task, the allowed paths, and the acceptance check.
375
+ Do not give two agents write access to the same files. Parallelize only
376
+ independent paths. Use a separate isolated copy only when concurrent edits
377
+ would otherwise collide. `model: inherit` means the parent model. It is not
378
+ proof of which model ran. Use Grok 4.7. If a delegation would select another
379
+ model, stop and report that.
380
+
381
+ Skills in `.agents/skills/` are procedures, not permissions. `implement-task`
382
+ is the default workflow for a product change. Load a skill by name when its
383
+ description matches. Do not auto-load every skill for a one-file edit.
384
+
385
+ Documentation stays with the change. The orchestrator makes sure it happens
386
+ and assigns the files. The agent that implements the change updates the docs
387
+ that change made false. The `technical-reviewer` audits those claims and their
388
+ links and reports gaps before the task is done. Consult the `architect` when
389
+ the change touches a contract or an ADR. A pull request maps each approved
390
+ acceptance criterion to the scenario, the command, and the observed result,
391
+ and states the limits of that evidence.
392
+
393
+ ### Human approval
394
+
395
+ Ask the human before architectural changes, new security or privacy behavior,
396
+ public API or package-export changes, dependency changes, CI or release
397
+ changes, and any commit, push, pull request, or publish. Branch creation
398
+ follows `docs/contributing.md`. Commits and pull requests happen only when
399
+ asked.
400
+
401
+ ### Learning
402
+
403
+ After a verified surprise (a test that passed in source and failed in `dist/`,
404
+ a doc that contradicts code), add a short lesson to `docs/engineering-memory.md`
405
+ when the human agrees. Do not record session ids, host paths, or secrets there.
406
+
407
+ `.cursor/` and `.agents/` are not in the npm `files` list. `AGENTS.md` is
408
+ published. Keep consumer instructions accurate and keep private evidence out
409
+ of this file.
410
+
261
411
  ## Contributing to this repo (agents & humans)
262
412
 
263
413
  If you are **changing Outpost itself** (not integrating it), read these before
@@ -273,6 +423,10 @@ you branch:
273
423
  `## [Unreleased]`
274
424
  - [docs/repo-settings.md](./docs/repo-settings.md) — GitHub branch protection
275
425
  and `npmjs` environment
426
+ - [docs/backlog.md](./docs/backlog.md) — open product work. Current behavior is not a promise to change it
427
+ - [docs/engineering-memory.md](./docs/engineering-memory.md) — verified lessons
428
+ - [.cursor/agents/](./.cursor/agents/) — project subagents
429
+ - [.agents/skills/](./.agents/skills/) — task skills
276
430
  - [.cursor/rules/](./.cursor/rules/) — Cursor guardrails when present
277
431
 
278
432
  Hard rules: branch from `main` with `feature/`/`fix/`/`docs/`/`chore/` prefixes;
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Outpost
2
2
 
3
3
  **A transactional outbox with pluggable transport for Next.js.**
4
- Durable, at-most-once, fully auditable transactional email — with the sending
4
+ Durable, fully auditable transactional email — with the sending
5
5
  provider as a swappable detail.
6
6
 
7
7
  [![provenance](https://img.shields.io/badge/npm-provenance-blue)](https://docs.npmjs.com/generating-provenance-statements)
@@ -17,8 +17,9 @@ await outpost.send({
17
17
  ```
18
18
 
19
19
  Outpost is **not an email client**. Libraries already send email. Outpost
20
- guarantees a message is **never lost, delivered at-most-once, fully auditable,
21
- and provider-independent**. It persists every message before dispatch, processes
20
+ guarantees a message is **never lost, fully auditable, and
21
+ provider-independent**. Enqueue is deduplicated on the idempotency key. A lost
22
+ send lease can still call the provider again, and SMTP has no idempotency key. It persists every message before dispatch, processes
22
23
  it through a controlled pipeline (sanitization, rate limiting, domain
23
24
  validation, encryption-at-rest), tracks its lifecycle via provider webhooks,
24
25
  enforces a suppression list, and redacts/retains data per policy.
@@ -28,23 +29,23 @@ enforces a suppression list, and redacts/retains data per policy.
28
29
 
29
30
  ## Why
30
31
 
31
- A naive `await resend.send(...)` in a request handler can: send twice on retry,
32
- lose the message if the process dies, keep mailing addresses that hard-bounced
33
- (burning your sender reputation), and leave no audit trail. Outpost fixes all
34
- four by making the **database the source of truth** and the **send a separate,
35
- idempotent, observable step**.
32
+ A naive `await resend.send(...)` in a request handler can lose the message if
33
+ the process dies, keep mailing an address after a hard bounce, and leave no
34
+ audit trail. Outpost persists the row first and keeps an audit trail. Enqueue
35
+ dedupe stops a repeated idempotency key. A lost send lease can still call the
36
+ provider again.
36
37
 
37
38
  ## Features (v1)
38
39
 
39
40
  - ✅ **Durable outbox** — persist-before-dispatch; survives crashes.
40
- - ✅ **At-most-once** — idempotency key required at ingestion, re-checked at dispatch.
41
+ - ✅ **Deduplicated enqueue** — idempotency key required. A lost send lease can still call the provider again. SMTP has no idempotency key.
41
42
  - ✅ **Pluggable transport** — Resend, generic SMTP/Mailpit, in-memory fake; one `EmailProvider` interface.
42
- - ✅ **Lifecycle tracking** — `queued → sending → sent → delivered | bounced | complained | failed` via verified webhooks.
43
+ - ✅ **Lifecycle tracking** — verified webhooks can move `sent` to `delivered`, `bounced`, or `complained`. A permanent provider error moves the row to `failed` with no webhook.
43
44
  - ✅ **Suppression list** — hard bounces & complaints auto-suppress; matched by keyed HMAC.
44
45
  - ✅ **Retry + Dead Letter Queue** — exponential backoff with jitter; inspect & replay failures.
45
46
  - ✅ **Encryption at rest** — optional AES-256-GCM (symmetric) or RSA-hybrid (asymmetric, least-privilege split). Keys live in KMS, not the DB.
46
- - ✅ **Append-only audit trail + OpenTelemetry** — on by default.
47
- - ✅ **Configurable retention** — redact PII, keep audit; batched, terminal-rows-only.
47
+ - ✅ **Append-only audit trail** — on. OpenTelemetry stays off unless a telemetry adapter is passed.
48
+ - ✅ **Configurable retention** — redact terminal outbox PII, keep audit; delete aged webhook rows.
48
49
  - ✅ **Authenticated API** — opaque keys with scopes, expiry, and immediate revocation.
49
50
  - ✅ **Clean Architecture + SOLID** — testable core, swappable everything.
50
51
 
@@ -85,9 +86,13 @@ export const outpost = createOutpost({
85
86
  ```
86
87
 
87
88
  1. Generate & run the DB migration → [docs/database.md](./docs/database.md).
89
+ An existing 1.x database also needs the webhook identity migration in
90
+ [Upgrading an existing database](./docs/database.md#upgrading-an-existing-database).
88
91
  2. Wire the HTTP routes → [docs/nextjs.md](./docs/nextjs.md).
89
92
  3. Run the send worker → [docs/workers.md](./docs/workers.md).
90
93
 
94
+ Upgrading from 1.x: [AGENTS.md — Upgrading from 1.x](./AGENTS.md#upgrading-from-1x).
95
+
91
96
  ## Documentation
92
97
 
93
98
  | Doc | What's in it |
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var pgCore = require('drizzle-orm/pg-core');
4
+ var crypto = require('crypto');
4
5
  var drizzleOrm = require('drizzle-orm');
5
6
 
6
7
  // src/adapters/drizzle/schema.ts
@@ -84,10 +85,23 @@ var webhookEvents = pgCore.pgTable(
84
85
  isHardBounce: pgCore.boolean("is_hard_bounce"),
85
86
  occurredAt: pgCore.timestamp("occurred_at", { withTimezone: true }),
86
87
  raw: pgCore.jsonb("raw").notNull(),
87
- receivedAt: pgCore.timestamp("received_at", { withTimezone: true }).notNull().defaultNow()
88
+ receivedAt: pgCore.timestamp("received_at", { withTimezone: true }).notNull().defaultNow(),
89
+ /** Provider event id. Null on rows written before the column existed. */
90
+ providerEventId: pgCore.text("provider_event_id"),
91
+ /** Signature time from the adapter, when it supplied one. */
92
+ verifiedAt: pgCore.timestamp("verified_at", { withTimezone: true }),
93
+ /**
94
+ * `pending`, `applied`, `rejected`, or other text. Null on legacy rows,
95
+ * and a null is not `pending`.
96
+ */
97
+ disposition: pgCore.text("disposition")
88
98
  },
89
99
  (t) => ({
90
- providerMessageIdIdx: pgCore.index("outpost_webhook_provider_message_id_idx").on(t.providerMessageId)
100
+ providerMessageIdIdx: pgCore.index("outpost_webhook_provider_message_id_idx").on(t.providerMessageId),
101
+ providerEventIdIdx: pgCore.index("outpost_webhook_provider_event_id_idx").on(
102
+ t.provider,
103
+ t.providerEventId
104
+ )
91
105
  })
92
106
  );
93
107
  var apiKeys = pgCore.pgTable(
@@ -123,6 +137,29 @@ var outpostSchema = {
123
137
  suppressionReasonEnum
124
138
  };
125
139
 
140
+ // src/domain/lifecycle.ts
141
+ var TERMINAL_STATES = [
142
+ "delivered",
143
+ "bounced",
144
+ "complained",
145
+ "failed",
146
+ "suppressed"
147
+ ];
148
+ new Set(TERMINAL_STATES);
149
+
150
+ // src/domain/retention.ts
151
+ function normalizeBatchPauseMs(ms) {
152
+ if (!Number.isFinite(ms) || ms <= 0) return 0;
153
+ return ms;
154
+ }
155
+ function waitForBatchPause(ms) {
156
+ const pause = normalizeBatchPauseMs(ms);
157
+ if (pause === 0) return Promise.resolve();
158
+ return new Promise((resolve) => {
159
+ setTimeout(resolve, pause);
160
+ });
161
+ }
162
+
126
163
  // src/adapters/drizzle/mappers.ts
127
164
  function rowToMessage(r) {
128
165
  return {
@@ -180,12 +217,27 @@ function rowToAuditEvent(r) {
180
217
 
181
218
  // src/adapters/drizzle/repositories.ts
182
219
  var REDACTED = { alg: "redacted", ciphertext: "" };
220
+ var IDEMPOTENCY_CONSTRAINT = "outpost_outbox_idempotency_key_uq";
221
+ function isOutboxIdempotencyConflict(error) {
222
+ return matchesIdempotencyConstraint(error) || matchesIdempotencyConstraint(causeOf(error));
223
+ }
224
+ function causeOf(error) {
225
+ if (typeof error !== "object" || error === null || !("cause" in error)) return void 0;
226
+ return error.cause;
227
+ }
228
+ function matchesIdempotencyConstraint(error) {
229
+ if (typeof error !== "object" || error === null) return false;
230
+ const candidate = error;
231
+ const constraint = candidate.constraint ?? candidate.constraint_name;
232
+ return candidate.code === "23505" && constraint === IDEMPOTENCY_CONSTRAINT;
233
+ }
183
234
  var DrizzleOutboxRepository = class {
184
235
  constructor(db) {
185
236
  this.db = db;
186
237
  }
187
238
  async insert(msg) {
188
239
  const [row] = await this.db.insert(outbox).values({
240
+ ...msg.id ? { id: msg.id } : {},
189
241
  idempotencyKey: msg.idempotencyKey,
190
242
  state: msg.state,
191
243
  recipientHmac: msg.recipientHmac,
@@ -201,6 +253,42 @@ var DrizzleOutboxRepository = class {
201
253
  }).returning();
202
254
  return rowToMessage(row);
203
255
  }
256
+ async insertWithEnqueueAudit(msg, audit) {
257
+ try {
258
+ const message = await this.db.transaction(async (tx) => {
259
+ const [row] = await tx.insert(outbox).values({
260
+ ...msg.id ? { id: msg.id } : {},
261
+ idempotencyKey: msg.idempotencyKey,
262
+ state: msg.state,
263
+ recipientHmac: msg.recipientHmac,
264
+ recipientSealed: msg.recipientSealed,
265
+ bodySealed: msg.bodySealed,
266
+ subject: msg.subject,
267
+ templateId: msg.templateId,
268
+ templateVersion: msg.templateVersion,
269
+ provider: msg.provider,
270
+ metadata: msg.metadata,
271
+ scheduledFor: msg.scheduledFor,
272
+ nextAttemptAt: msg.nextAttemptAt
273
+ }).returning();
274
+ const inserted = rowToMessage(row);
275
+ await tx.insert(auditEvents).values({
276
+ messageId: inserted.id,
277
+ eventType: audit.eventType,
278
+ actor: audit.actor,
279
+ detail: audit.detail ?? null
280
+ });
281
+ return inserted;
282
+ });
283
+ return { message, deduplicated: false };
284
+ } catch (error) {
285
+ if (isOutboxIdempotencyConflict(error)) {
286
+ const existing = await this.findByIdempotencyKey(msg.idempotencyKey);
287
+ if (existing) return { message: existing, deduplicated: true };
288
+ }
289
+ throw error;
290
+ }
291
+ }
204
292
  async findById(id) {
205
293
  const [row] = await this.db.select().from(outbox).where(drizzleOrm.eq(outbox.id, id)).limit(1);
206
294
  return row ? rowToMessage(row) : null;
@@ -261,26 +349,28 @@ var DrizzleOutboxRepository = class {
261
349
  if (rows.length === 0) return [];
262
350
  const ids = rows.map((r) => r.id);
263
351
  await tx.update(outbox).set({ state: "sending", updatedAt: now }).where(drizzleOrm.inArray(outbox.id, ids));
264
- return rows.map((r) => rowToMessage({ ...r, state: "sending" }));
352
+ return rows.map((r) => rowToMessage({ ...r, state: "sending", updatedAt: now }));
265
353
  });
266
354
  }
267
355
  async updateState(id, patch) {
356
+ await this.db.update(outbox).set(this.statePatch(patch)).where(drizzleOrm.eq(outbox.id, id));
357
+ }
358
+ async updateStateWhileSending(id, patch, claim) {
359
+ const rows = await this.db.update(outbox).set(this.statePatch(patch)).where(
360
+ drizzleOrm.and(drizzleOrm.eq(outbox.id, id), drizzleOrm.eq(outbox.state, "sending"), drizzleOrm.eq(outbox.updatedAt, claim.updatedAt))
361
+ ).returning({ id: outbox.id });
362
+ return rows.length > 0;
363
+ }
364
+ statePatch(patch) {
268
365
  const set = { state: patch.state, updatedAt: /* @__PURE__ */ new Date() };
269
366
  if (patch.attempts !== void 0) set.attempts = patch.attempts;
270
367
  if (patch.nextAttemptAt !== void 0) set.nextAttemptAt = patch.nextAttemptAt;
271
368
  if (patch.providerMessageId !== void 0) set.providerMessageId = patch.providerMessageId;
272
369
  if (patch.lastError !== void 0) set.lastError = patch.lastError;
273
- await this.db.update(outbox).set(set).where(drizzleOrm.eq(outbox.id, id));
370
+ return set;
274
371
  }
275
372
  async claimTerminalForPurge(olderThan, limit) {
276
- const rows = await this.db.select().from(outbox).where(
277
- drizzleOrm.and(
278
- drizzleOrm.inArray(outbox.state, ["delivered", "bounced", "complained", "failed", "suppressed"]),
279
- drizzleOrm.lt(outbox.updatedAt, olderThan),
280
- // Skip rows already redacted (idempotent purge).
281
- drizzleOrm.sql`${outbox.bodySealed}->>'alg' <> 'redacted'`
282
- )
283
- ).orderBy(drizzleOrm.asc(outbox.updatedAt)).limit(limit);
373
+ const rows = await this.db.select().from(outbox).where(this.terminalAgedWhere(olderThan)).orderBy(drizzleOrm.asc(outbox.updatedAt)).limit(limit);
284
374
  return rows.map(rowToMessage);
285
375
  }
286
376
  async redactBatch(ids) {
@@ -293,6 +383,27 @@ var DrizzleOutboxRepository = class {
293
383
  const rows = await this.db.delete(outbox).where(drizzleOrm.inArray(outbox.id, [...ids])).returning({ id: outbox.id });
294
384
  return rows.length;
295
385
  }
386
+ async redactBatchIfEligible(ids, olderThan) {
387
+ if (ids.length === 0) return 0;
388
+ const rows = await this.db.update(outbox).set({ recipientSealed: REDACTED, bodySealed: REDACTED, updatedAt: /* @__PURE__ */ new Date() }).where(drizzleOrm.and(drizzleOrm.inArray(outbox.id, [...ids]), this.terminalAgedWhere(olderThan))).returning({ id: outbox.id });
389
+ return rows.length;
390
+ }
391
+ async deleteBatchIfEligible(ids, olderThan) {
392
+ if (ids.length === 0) return 0;
393
+ const rows = await this.db.delete(outbox).where(drizzleOrm.and(drizzleOrm.inArray(outbox.id, [...ids]), this.terminalAgedWhere(olderThan))).returning({ id: outbox.id });
394
+ return rows.length;
395
+ }
396
+ /**
397
+ * Select predicate for a retention cycle. `olderThan` is the cutoff the
398
+ * caller already computed; this does not read the clock.
399
+ */
400
+ terminalAgedWhere(olderThan) {
401
+ return drizzleOrm.and(
402
+ drizzleOrm.inArray(outbox.state, [...TERMINAL_STATES]),
403
+ drizzleOrm.lt(outbox.updatedAt, olderThan),
404
+ drizzleOrm.sql`${outbox.bodySealed}->>'alg' <> 'redacted'`
405
+ );
406
+ }
296
407
  };
297
408
  var DrizzleSuppressionRepository = class {
298
409
  constructor(db) {
@@ -341,7 +452,7 @@ var DrizzleAuditRepository = class {
341
452
  const rows = await this.db.select().from(auditEvents).where(drizzleOrm.eq(auditEvents.messageId, messageId)).orderBy(drizzleOrm.asc(auditEvents.at));
342
453
  return rows.map(rowToAuditEvent);
343
454
  }
344
- async purgeOlderThan(cutoff, batchSize) {
455
+ async purgeOlderThan(cutoff, batchSize, pauseMs = 0) {
345
456
  let total = 0;
346
457
  for (; ; ) {
347
458
  const ids = await this.db.select({ id: auditEvents.id }).from(auditEvents).where(drizzleOrm.lt(auditEvents.at, cutoff)).limit(batchSize);
@@ -354,6 +465,7 @@ var DrizzleAuditRepository = class {
354
465
  );
355
466
  total += ids.length;
356
467
  if (ids.length < batchSize) break;
468
+ await waitForBatchPause(pauseMs);
357
469
  }
358
470
  return total;
359
471
  }
@@ -395,18 +507,85 @@ var DrizzleWebhookEventRepository = class {
395
507
  constructor(db) {
396
508
  this.db = db;
397
509
  }
398
- async record(event) {
510
+ async record(event, meta) {
399
511
  await this.db.insert(webhookEvents).values({
512
+ id: crypto.randomUUID(),
400
513
  provider: event.provider,
401
514
  type: event.type,
402
515
  providerMessageId: event.providerMessageId,
403
- recipient: event.recipient ?? null,
516
+ recipient: null,
404
517
  isHardBounce: event.isHardBounce ?? null,
405
518
  occurredAt: event.occurredAt ?? null,
519
+ providerEventId: event.providerEventId ?? null,
520
+ verifiedAt: event.verifiedAt ?? null,
521
+ disposition: meta?.disposition ?? "pending",
406
522
  raw: event.raw
407
523
  });
408
524
  }
525
+ async findByIdentity(query) {
526
+ const [row] = await this.db.select().from(webhookEvents).where(identityWhere(query)).orderBy(drizzleOrm.asc(webhookEvents.receivedAt), drizzleOrm.asc(webhookEvents.id)).limit(1);
527
+ return row ? rowToStoredWebhook(row) : null;
528
+ }
529
+ async listPendingByProviderMessageId(providerMessageId) {
530
+ const rows = await this.db.select().from(webhookEvents).where(
531
+ drizzleOrm.and(
532
+ drizzleOrm.eq(webhookEvents.providerMessageId, providerMessageId),
533
+ drizzleOrm.eq(webhookEvents.disposition, "pending")
534
+ )
535
+ ).orderBy(drizzleOrm.asc(webhookEvents.receivedAt), drizzleOrm.asc(webhookEvents.id));
536
+ return rows.map(rowToStoredWebhook);
537
+ }
538
+ async setDisposition(id, disposition) {
539
+ await this.db.update(webhookEvents).set({ disposition }).where(drizzleOrm.eq(webhookEvents.id, id));
540
+ }
541
+ async deleteOlderThan(olderThan) {
542
+ const rows = await this.db.delete(webhookEvents).where(drizzleOrm.lt(webhookEvents.receivedAt, olderThan)).returning({ id: webhookEvents.id });
543
+ return rows.length;
544
+ }
409
545
  };
546
+ function identityWhere(query) {
547
+ switch (query.match) {
548
+ case "providerEvent":
549
+ return drizzleOrm.and(
550
+ drizzleOrm.eq(webhookEvents.provider, query.provider),
551
+ drizzleOrm.eq(webhookEvents.providerEventId, query.providerEventId)
552
+ );
553
+ case "providerMessage":
554
+ return drizzleOrm.and(
555
+ drizzleOrm.eq(webhookEvents.provider, query.provider),
556
+ drizzleOrm.eq(webhookEvents.providerMessageId, query.providerMessageId),
557
+ drizzleOrm.eq(webhookEvents.type, query.type),
558
+ query.occurredAt === null ? drizzleOrm.isNull(webhookEvents.occurredAt) : drizzleOrm.eq(webhookEvents.occurredAt, query.occurredAt)
559
+ );
560
+ case "settledWithoutEventId":
561
+ return drizzleOrm.and(
562
+ drizzleOrm.isNull(webhookEvents.providerEventId),
563
+ drizzleOrm.eq(webhookEvents.provider, query.provider),
564
+ drizzleOrm.eq(webhookEvents.providerMessageId, query.providerMessageId),
565
+ drizzleOrm.eq(webhookEvents.type, query.type)
566
+ );
567
+ }
568
+ }
569
+ function rowToStoredWebhook(row) {
570
+ return {
571
+ id: row.id,
572
+ // Legacy rows have a null disposition. Keep that at runtime so it is not pending.
573
+ disposition: row.disposition,
574
+ receivedAt: row.receivedAt,
575
+ messageId: null,
576
+ event: {
577
+ provider: row.provider,
578
+ type: row.type,
579
+ providerMessageId: row.providerMessageId,
580
+ ...row.recipient !== null ? { recipient: row.recipient } : {},
581
+ ...row.isHardBounce !== null ? { isHardBounce: row.isHardBounce } : {},
582
+ ...row.occurredAt !== null ? { occurredAt: row.occurredAt } : {},
583
+ ...row.providerEventId !== null ? { providerEventId: row.providerEventId } : {},
584
+ ...row.verifiedAt !== null ? { verifiedAt: row.verifiedAt } : {},
585
+ raw: row.raw
586
+ }
587
+ };
588
+ }
410
589
  var DrizzleConfigOverrideRepository = class {
411
590
  constructor(db) {
412
591
  this.db = db;