Modules / Outbound Webhooks / Documentation

Outbound Webhooks documentation

The README, architecture and security documents shipped in v1.0.0 of the package, published so you can judge the API before you buy. Markdown version.

Get Outbound Webhooks · $49Source, tests and examples · v1.0.0 · one-time

Outbound Webhooks (@softreuse/webhook-sender) v1.0.0

Send webhooks to your customers the way Stripe and GitHub do. Your customers register endpoints; you call send(); the kit signs, delivers, retries, protects your network, disables dead endpoints, rotates secrets and keeps a delivery log your customers can see. About 1,450 lines of TypeScript with zero runtime dependencies.

  • Node >= 20 · TypeScript strict · ESM · PostgreSQL store included (any DB via the SenderStore interface)
  • Signatures follow Standard Webhooks, so your customers can verify with an existing library in their language, or with the verifyWebhook helper included here
  • Includes a ready-made management API for your customers' "Webhooks" settings page

Contents of this package

src/                      the library
  sender.ts               endpoints, send (fan-out, outbox), worker, retries, health, rotation, replay
  api/handler.ts          JSON API for your customers' dashboard
  signing.ts              Standard Webhooks sign / verifyWebhook
  ssrf.ts, transport.ts   private-network protection at URL and connect time
  cipher.ts               AES-256-GCM encryption of endpoint secrets at rest
  schedule.ts, stores/    retry schedule; postgres.ts, memory.ts
migrations/001_outbound_webhooks.sql
tests/                    122 tests: signing (incl. the Standard Webhooks test vector), SSRF, transport over real HTTP,
                          sender, management API, store contract (Memory + Postgres)
examples/
  saas-demo/              runnable offline demo (`npm run demo`)
  next-app-router/        sender setup, dashboard API route, transactional emit, cron worker, customer-side receiver
docs/ARCHITECTURE.md      how it works and why
docs/SECURITY.md          threat model and deployment checklist
CHANGELOG.md · LICENSE.md

1. See it work (30 seconds)

npm install
npm run demo

A real HTTP server plays your customer. The demo registers an endpoint, sends events while the customer is down (retried), filters by event type, ignores a duplicate, rotates the secret with zero downtime, and stops at once when the customer answers 410 Gone. The customer verifies every signature.

Run the tests: npm test. With DATABASE_URL=postgres://... npm test the Postgres store tests run too (they create and drop their own tables).

2. Install into your project

Option A — copy the source (recommended). Copy src/ to e.g. src/lib/webhook-sender/ and migrations/001_outbound_webhooks.sql into your migrations.

Option B — local package. npm run build, then npm install ../path/to/this/folder. Import from @softreuse/webhook-sender.

3. Quick start (Next.js + Postgres)

  1. Run migrations/001_outbound_webhooks.sql. Generate a key for secrets at rest: openssl rand -base64 32 → WEBHOOK_SECRETS_KEY.
  2. Create the sender (examples/next-app-router/webhooks.ts):
export const webhooks = createWebhookSender({
  store: new PostgresStore(pool),
  secretCipher: aesGcmCipher(process.env.WEBHOOK_SECRETS_KEY!),
  onEndpointDisabled: async (endpoint, reason) => notifyCustomer(endpoint.tenantId, reason),
});
export const webhooksApi = createManagementApi(webhooks, { basePath: "/api/webhooks" });
  1. Expose the dashboard API behind your auth (examples/next-app-router/api-route.ts):
const orgId = await currentOrgId(request);
return webhooksApi.handle(request, { tenantId: orgId });
  1. Emit events, ideally in the same transaction as the change (examples/next-app-router/emit.ts):
await webhooks.send(
  { tenantId: orgId, type: "invoice.paid", data: { id: invoiceId }, id: `invoice.paid:${invoiceId}` },
  { store: webhookStore.using(client) }, // client = your transaction
);
  1. Run the worker every minute (examples/next-app-router/cron-route.ts): await webhooks.processDue({ limit: 50 }).
  2. Give your customers examples/next-app-router/customer-receiver.ts (or any Standard Webhooks library) for their side.

4. What happens to a delivery

Situation Result
2xx succeeded; the endpoint's failure streak resets
410 Gone endpoint disabled at once, onEndpointDisabled called, delivery failed
Other status, timeout, network error retried: immediately, then 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 14 h, 20 h, 24 h (±20 % jitter)
Retry-After longer than the next step honoured, capped at maxRetryAfterMs (1 h)
3xx a failure: redirects are never followed ("update the URL" in the log)
Destination resolves to a private address failed, not retried
Endpoint failing continuously for 5 days disabled, onEndpointDisabled called
Schedule exhausted (~3 days) failed; replay any time
Worker killed mid-request lease expires, another worker takes it; the stale one can't overwrite the result

Each request carries webhook-id (the event id, stable across retries: receivers deduplicate on it), webhook-timestamp and webhook-signature. The body is {"type","timestamp","data"}.

5. API

webhooks.endpoints.create(tenantId, { url, description?, eventTypes? })   // → view + secret (once)
webhooks.endpoints.get / list / update / delete / enable / disable
webhooks.endpoints.getSecret(tenantId, id)
webhooks.endpoints.rotateSecret(tenantId, id)       // old secret keeps signing for rotationOverlapMs (24 h)

webhooks.send({ tenantId, type, data, id?, endpointIds? }, { store? })   // durable on return; idempotent on id
webhooks.processDue({ limit = 25, concurrency = 8 })                     // the worker

webhooks.deliveries.list({ tenantId, endpointId?, messageId?, status?, limit? })
webhooks.deliveries.get(tenantId, id)               // with attemptLog: status, duration, error, first bytes of the body
webhooks.deliveries.replay(tenantId, id)
webhooks.deliveries.replayFailed(tenantId, endpointId, { since })

webhooks.purge({ olderThan })                       // daily: drop finished events and their logs

eventTypes: null = everything, ["invoice.*"] = a prefix, ["invoice.paid", "customer.created"] = exact types.

Management API routes (all confined to the tenant you pass): GET/POST /endpoints, GET/PATCH/DELETE /endpoints/:id, GET /endpoints/:id/secret, POST /endpoints/:id/rotate-secret, POST /endpoints/:id/test, POST /endpoints/:id/replay-failed, GET /deliveries, GET /deliveries/:id, POST /deliveries/:id/replay. Errors: 400 validation, 404 not found or another tenant's.

6. Configuration

Option Default Meaning
store required PostgresStore, MemoryStore or your own SenderStore
secretCipher required aesGcmCipher(key or [new, old]), or plaintextSecrets as a deliberate choice
transport nodeTransport() fetchTransport() for runtimes without node:http (see SECURITY.md)
allowHttp false Accept http:// endpoint URLs
allowPrivateNetworks false Accept private/internal destinations. Local development only
schedule STANDARD_SCHEDULE Retry delays after the first attempt
timeoutMs 15000 Total deadline per request
leaseMs timeoutMs + 30000 Lease per claimed delivery
disableAfterMs 5 days Disable endpoints failing this long; 0 = never
rotationOverlapMs 24 h Dual-signing window after a rotation
maxPayloadBytes 64 KiB Larger payloads are rejected: send ids, let receivers fetch
maxRetryAfterMs 1 h Cap on honoured Retry-After
onEndpointDisabled — Notify the customer; errors in it are logged, never thrown
logger, now, random console, clock, Math.random Injectables

7. Troubleshooting

Symptom Cause / fix
url must use https / public hostname Secure defaults. For local testing only: allowHttp and allowPrivateNetworks (and the same on nodeTransport).
Deliveries stay pending Nothing calls processDue(). Schedule the cron route or run a worker loop.
Customer says signatures fail They must verify the raw body before parsing, and use the secret for that endpoint. During a rotation, both secrets sign.
Endpoint got disabled It answered 410 or failed for disableAfterMs. Fix it, enable, then replayFailed({ since }).
lease_lost warnings A delivery took longer than leaseMs. Raise it, or lower timeoutMs.
could not decrypt stored secret The WEBHOOK_SECRETS_KEY changed. Pass [newKey, oldKey] while rotating keys.

Requirements and dependencies

Node 20+ (tested on 20, 22, 24 and 26). PostgreSQL 12+ for PostgresStore. Zero runtime dependencies. Development only: typescript, vitest, tsx, pg.

Licence

Commercial, see LICENSE.md. Use it in unlimited projects you or your company own; don't redistribute it as a standalone product.


Architecture

The problem

The day a customer asks "can you send us a webhook when an invoice is paid?", you take on a small distributed system: a queue, a retry policy, signatures, a settings page, a delivery log, and an HTTP client that will be pointed at addresses chosen by strangers. Hosted services sell exactly this. This kit is the same building blocks as code you own, on the Postgres you already run.

Data model

endpoints   (tenant, url, event filter, encrypted secret[s], status, failing_since)
messages    (tenant, id, type, payload)               one per event; (tenant, id) makes send() idempotent
deliveries  (message × endpoint, status, attempts, next_attempt_at, lease)
attempts    (delivery, status code, duration, error, first bytes of body)   the customer-facing log

A message fans out into one delivery per subscribed, enabled endpoint, at send time. Each delivery retries on its own schedule, so one slow customer endpoint never delays another.

Lifecycle

send() ──▶ messages + deliveries (one statement) ──▶ processDue() claims due deliveries (SKIP LOCKED, lease)
                                                         │
                                         sign (current + previous secret) ──▶ transport (SSRF-guarded)
                                                         │
                  2xx ─▶ succeeded     410 ─▶ disable endpoint     blocked ─▶ failed
                  else ─▶ schedule next attempt (or failed when exhausted; disable after N days failing)

Durable first, and optionally in your transaction

send() only writes. It returns once the message and its deliveries are stored, in a single SQL statement, so there is never a message without its deliveries. Pass { store: postgresStore.using(tx) } and that write joins your transaction: the event exists if and only if the business change commits. This is the transactional outbox pattern, and it removes the classic bug of "order saved, webhook lost" (or "webhook sent, order rolled back").

Leases and tokens

Workers claim with FOR UPDATE SKIP LOCKED, set locked_until and a claim token, and increment attempts. A worker killed mid-request can't release anything; when its lease expires another worker takes the delivery. When the slow original finishes, its token no longer matches and its write is discarded (attempt included, in the same statement). An attempt counter beyond the schedule stops a delivery that keeps killing its worker.

The retry schedule

The default is the Standard Webhooks recommendation: immediately, then 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 14 h, 20 h and 24 h, about three days, with ±20 % jitter so that a recovering customer isn't hit by every retry at the same second. Retry-After is honoured when it asks for more time, up to a cap, so a hostile endpoint can't park deliveries for a year.

Endpoint health

Every attempt updates the endpoint's failing_since (start of the current failure streak, cleared by any success). An endpoint failing continuously for disableAfterMs (5 days) is disabled and onEndpointDisabled fires, so you can email the customer. 410 Gone disables at once, as the spec asks. Disabling stops new deliveries from being created and makes queued ones fail without a request. After a fix: enable, then replayFailed({ since }).

Signatures and rotation

Signatures follow Standard Webhooks: HMAC-SHA256 over id.timestamp.body, whsec_ secrets of 24 random bytes, v1, prefixed base64 signatures, several signatures space-separated. A rotation keeps the old secret signing alongside the new one for rotationOverlapMs, so the customer can deploy the new secret whenever they like within that window. Because the format is a published spec, your customers can use the existing Standard Webhooks verification libraries for many languages.

Secrets at rest

Secrets must be shown to customers, so they can't be hashed. aesGcmCipher encrypts each with AES-256-GCM and a random IV; a database dump alone does not reveal them. The option is required, so storing plaintext is a visible decision (plaintextSecrets), not an accident.

SSRF: two layers

Customers choose the URL; your worker makes the request from inside your network. Layer one, validateEndpointUrl, runs on create, update and before every attempt: https only, no credentials, no private or reserved IP literals, no internal-looking names. Layer two is in nodeTransport: the address check runs inside DNS resolution, on the addresses actually connected to. A hostname that was public when saved and later resolves to 169.254.169.254 (DNS rebinding) is refused at connect time. Redirects are never followed, since a redirect is a second, unchecked destination.

Choices and alternatives

  • No ordering guarantee. Deliveries retry independently; a later event can arrive before an earlier one that is retrying. Receivers should use the payload's timestamp or fetch current state. Strict per-endpoint ordering would let one failing event block all others for days.
  • At-least-once. A request that succeeded but whose response was lost is retried. webhook-id is stable across retries so receivers deduplicate.
  • Postgres, not a broker. Throughput is roughly workers × concurrency ÷ receiver latency, with one indexed claim query per batch. That suits typical SaaS volumes; for Kafka-scale fan-out, implement SenderStore on a queue. Measure with your own receivers before relying on a number.
  • Payload cap of 64 KiB. Large payloads slow every retry and every customer. Send ids and let receivers fetch.
  • Fan-out at send time. An endpoint created after an event doesn't receive it. That matches what customers expect from Stripe and GitHub.

Security notes

Reviewed against the Softreuse Product Standard. This documents what the module defends against, what it does not, and what you must do in your deployment.

Threat model

Threat Mitigation in the kit
SSRF: a customer registers http://169.254.169.254/ or an internal service https only by default; private, loopback, link-local, CGNAT, reserved, multicast, documentation, NAT64/6to4/Teredo-embedded and IPv4-mapped addresses refused, as literals and after DNS resolution. Internal-looking names (localhost, *.internal, single-label) refused. Checked on save and before every attempt. Tested.
DNS rebinding (public on save, private at delivery) nodeTransport checks the addresses returned by DNS inside the connection's own lookup, so the checked address is the connected one. Tested with a rebinding resolver against a real server.
Redirect to an internal address Redirects are never followed; a 3xx is a failed attempt. Tested.
Forged webhooks reaching your customers Standard Webhooks HMAC-SHA256 signatures with per-endpoint 192-bit secrets. Matches the published test vector.
Replay of a captured webhook webhook-timestamp is signed; verifyWebhook enforces a tolerance (300 s default) and receivers deduplicate on webhook-id.
Timing attacks on verification crypto.subtle.verify (constant-time), every secret × signature pair checked without early exit.
Stolen database dump reveals secrets aesGcmCipher (AES-256-GCM, random IV, key rotation via a key list). Storing plaintext requires choosing plaintextSecrets. Tested.
Secret leaks via a customer's logs Rotation with a dual-signing overlap, so customers can rotate without downtime.
Cross-tenant access Every read and write is keyed by tenant; another tenant's endpoint or delivery is "not found". The management API takes the tenant from your auth, never the request. Tested.
Slow or hostile receivers tying up workers Total per-request deadline (15 s), response body read capped (2 KiB), bounded concurrency, Retry-After capped (1 h), endpoints disabled after 5 days of failure or on 410.
Payload bloat 64 KiB default limit at send().
SQL injection All values bound; the table prefix is validated. Hostile payload text round-trips in a test.
Leaking data via your logs Logs carry ids, tenant, host, status and attempt numbers. Never payloads, secrets or URL paths (which sometimes embed tokens). Tested.

What it does NOT do

  • No authentication of your dashboard. The management API trusts the tenantId you pass. Authenticate and authorise first.
  • No egress firewall. The kit's checks are application-level. In production also run workers where they cannot reach internal services (private subnet without routes to them, or an egress proxy such as Stripe's smokescreen). Required if you use fetchTransport, which cannot see resolved addresses.
  • No mutual TLS or IP allow-listing for receivers. If customers want a fixed source IP, send from a NAT gateway with a static address and publish it.
  • No ordering, no exactly-once. See ARCHITECTURE.md.
  • No payload encryption. Bodies are in plaintext over TLS and in the messages table. Don't put secrets in event data; send ids.
  • Response bodies in the attempt log are the receiver's text (first 2 KiB). Show them to that tenant only; the API does.

Your deployment checklist

  1. Generate WEBHOOK_SECRETS_KEY with openssl rand -base64 32, keep it in your secrets manager, never in the database.
  2. Never set allowHttp / allowPrivateNetworks in production. Grep for them in CI if you like.
  3. Run workers on a network that cannot reach internal services; with fetchTransport, an egress proxy is mandatory.
  4. Mount the management API behind your auth and pass the tenant from the session.
  5. Schedule processDue() every minute (or a worker loop) and purge() daily.
  6. Implement onEndpointDisabled to notify the customer, and alert on webhook_sender.outcome_not_recorded.
  7. Document for your customers: verify the raw body, use webhook-id to deduplicate, answer 2xx fast and process asynchronously, return 410 to unsubscribe.
  8. Restrict the four tables to your application's database role.

Dependencies

Zero runtime dependencies. Development dependencies (typescript, vitest, pg, tsx) are not shipped. npm audit --omit=dev reports nothing for this package.

Reporting a vulnerability

Email support@softreuse.com with details. We acknowledge within 3 business days and ship fixes as patch releases to all customers.

Get Outbound Webhooks · $49Source, tests and examples · v1.0.0 · one-time