@ordinatio/webhooks
v1.1.0
Published
Webhook delivery for any product: retry schedule and disable rules, HMAC signing, an SSRF-safe sender with a private-address blocklist, cron-secret check, plain-words descriptions, the message envelope, and the delivery engine behind store ports with an i
Readme
@ordinatio/webhooks
Webhook delivery for any product: the pure rules, and (1.1.0) the engine that runs a pass behind store ports. No database, no framework and no brand: the product that sends passes in its own header names and User-Agent.
afterFailedAttempt,shouldDisable,isFatalStatusand the retry/lease constants.signWebhook/verifyWebhookSignature:t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<body>">, a 5-minute window, 60 seconds of future skew allowed, constant-time compare.sendWebhook: https only (443 or 8443), no credentials, the host is checked before connecting and again by our own DNS lookup (every answer must be public, so no DNS rebinding), redirects never followed, body never read, fresh Agent per call, 10 s limit.checkWebhookUrlfor the save-time check.isBlockedIPv4/isBlockedIPv6(also at@ordinatio/webhooks/ip-blocklist): CIDR based, covers mapped, NAT64, 6to4, carrier-grade NAT and documentation ranges; an address it cannot parse counts as blocked.checkCronAuth: fails closed with no secret or one under 32 characters.describeDelivery/describeWebhookState: plain-words descriptions of deliveries; pass{ signatureHeader }to name your header in the advice.buildEnvelope,clip,iso: the shared message wrapper{ id, type, createdAt, description, ids, data }(this key order) and the whole-character text cut.
The engine (1.1.0)
createWebhookEngine(config) answers { runPass, scanWebhook, sendDelivery }. A pass: read the locked-team list ONCE; kill the locked teams' waiting deliveries and move their cursors forward; scan each enabled webhook (a forward page after its cursor, older than 60 s, plus a 5-minute re-read; one pending delivery per line, dead "backlog" past the cap; the cursor moves only AFTER the rows exist); claim due deliveries fairly across webhooks and send them with a fresh signature per attempt; clean up. A phase that throws never stops the next; logs carry ids and error names only.
You supply, through config: a DeliveryStore, a WebhookRegistry, an EventSource (see ports), and hooks for your event names, body, secret opening, headers, locked teams and notices. Every store operation is ONE conditional statement (no transaction crosses a port). createMemoryWebhookStores() is a complete in-memory implementation.
A minimal setup
import { createWebhookEngine } from '@ordinatio/webhooks';
const engine = createWebhookEngine({
deliveries, registry, events, // your stores (or createMemoryWebhookStores() to try it)
actionsForEvents, eventForAction, // your event names <-> your feed's action names
hasTarget: (event, line) => true, // false: nothing to describe for this line, never sent
buildBody: async ({ deliveryId, event, organizationId, line }) => JSON.stringify({ id: deliveryId, type: event }),
openSecret: (webhookState) => 'the signing secret' /* or null when it cannot be opened */,
headersFor: ({ event, deliveryId, secret, body, nowSeconds }) => ({ 'X-Event': event /* + your signature header via signWebhook */ }),
userAgent: 'MyProduct-Webhooks/1',
lockedOrganizationIds: async (now) => [], // teams to leave out (a billing lock); a throw is counted and the pass goes on with none
});
// Call this from a scheduler (about once a minute). Two overlapping calls are safe: claims are leases.
const report = await engine.runPass(); // or runPass({ onlyOrganizationId }) for a by-hand run of one teamScope = { onlyOrganizationId?, excludeOrganizationIds }: every list, kill and claim is narrowed by it, so a one-team run touches nothing else. EventSource.readForward returns the matching lines strictly AFTER the cursor (time, then id) and older than settleBefore, oldest first, at most take (200); readOverlap returns the window just before the cursor, newest first, never before notBefore. The engine passes the lease ids it makes with newId, which must therefore be unique (the default is randomUUID). A line whose buildBody throws PermanentBodyError becomes a dead body_failed row so one bad record cannot block a webhook; any other error fails the scan and is retried on the next pass (nothing is lost to a database blip). No foreign key from a delivery to its webhook is assumed: the contract kit creates deliveries for webhooks that were never stored.
Proving your own store: @ordinatio/webhooks/testing
defineWebhookStoreContract({ describe, it, expect }, { name, globalClean: 'run' | 'skip', makeStores }) registers the checks every store must pass (skip-duplicate create, atomic claim that re-checks due/epoch/scope, lease-guarded finishes, bodies blanked on every terminal move, tenancy-safe cancels, compare-and-set cursor, a disable that exactly one racing caller wins, ...). clean is global across teams, so a store shared with real data opts out with globalClean: 'skip'. memoryStoresUnderTest() is a worked example of makeStores. The package's own tests run this kit against dozens of deliberately wrong stores and require every one to be caught.
