@playstack/webhooks
Verified inbound webhook receipt plus direct, durable, and Relaypath-backed outbound dispatch.
Reference: @playstack/webhooks@0.1.0-beta.5 · TypeScript
Pro. Covered by the Playstack Pro License. Registry access is required; check preview availability before installing. See package access.
@playstack/webhooks verifies exact request bytes, claims a provider event once, and inserts its normalized event into an application queue in the same transaction. It also exposes a small outbound dispatch contract for observational event routes. It does not provide event-store replay or provider business logic.
Install
After confirming preview access, install the package at your application's shared Playstack version:
npm install --save-exact @playstack/webhooks@0.1.0-beta.5Check the peer requirements below before choosing a runtime or provider.
Compose
import { createWebhooks, githubWebhookProvider, stripeWebhookProvider } from '@playstack/webhooks'
import { prismaWebhookPersistence } from '@playstack/webhooks/prisma'
const webhooks = createWebhooks({
providers: [stripeWebhookProvider({ secret, crypto, clock }), githubWebhookProvider({ secret: githubSecret, crypto, clock })],
persistence: prismaWebhookPersistence(prisma),
queue: applicationWebhookOutbox,
})
const result = await webhooks.receive(provider, {
headers: request.headers,
body: request.rawBody,
})Bridge contracts
| Contract | Boundary |
|---|---|
WebhookProvider | Verifies and parses exact raw bytes into a normalized provider event. |
WebhookPersistence | Transactionally claims the provider and event ID once. |
WebhookQueue | Inserts the verified event using the same transaction kind. |
WebhookHmacVerifier | Narrow SHA-256 verification contract compatible with @playstack/crypto. |
The built-in Stripe and GitHub providers reject duplicate or ambiguous signature headers and malformed fields, including extra = separators. They verify and parse the same captured request bytes. Custom providers can retain the normalized payload and raw request as escape hatches. Unknown event types belong to application handlers and do not fail receipt.
@playstack/webhooks/prisma supplies a non-ejectable, security-critical receipt artifact and a structurally typed persistence adapter. Queue storage remains application-owned because it must share the application's transactional outbox.
See the Stripe and GitHub integration guides for provider-specific composition.
Send outbound webhooks
Use createOutboundWebhookHandler() to map an accepted Playstack event to one or more configured endpoints. Endpoint URLs, authorization headers, and signing keys stay in live application configuration rather than domain events or queued payloads.
| Dispatcher | Use |
|---|---|
@playstack/webhooks/direct | One-shot HTTPS delivery for development or small application hooks, with optional exact-body signing. |
@playstack/webhooks/durable | Self-hosted delivery engine with injected atomic persistence, ordered endpoint leases, bounded retry, and history queries. |
@playstack/webhooks/relaypath | Relaypath-managed signing, retries, fan-out, endpoint health, and delivery history. |
The direct adapter rejects redirects and does not persist, retry, or record delivery. The durable adapter claims at most one ordered record per endpoint and classifies permanent versus retryable failures. Relaypath receives the source event ID as its idempotency key and only a managed endpoint ID—not the direct URL or secret headers.
The current direct contract projects a bounded Retry-After into a validated
absolute WebhooksError.retryAt; provider bodies and arbitrary headers are not
exposed. Durable retries add bounded local jitter without shortening that provider
deadline. maxAttempts defaults to 10 durable claims, including crash recovery;
maxAgeMs defaults to 24 hours from admission. Persistence must atomically
increment the claim count and fence ordinary completions with an unexpired lease.
No new send starts at/after expiry or beyond the budget. In-flight sends can still
finish later, and the default leased-retry policy can duplicate delivery after
uncertain remote acknowledgments.
Verify signed response receipts
For a provider-specific acceptance receipt, use
createDirectWebhookReceiptSender from @playstack/webhooks/direct. Its separate
sendReceipt method returns facts accepted by your required verifyResponse
callback. The verifier receives the exact body and canonical URL, successful
status, bounded copied headers and an abort signal. Your verifier owns signature,
tenant/delivery/request binding and time policy; 2xx alone does not prove acceptance.
The Node transport opts into receipt fields with
responseHeaders: ['x-receipt', 'x-request-id']. It rejects duplicate selected raw
headers and oversized/control-containing values, excludes known credential fields
and discards response bodies. Default transports retain status/retry metadata.
All send-time failures on the receipt path are redacted, non-retryable
outbound_receipt_unconfirmed; missing or lost receipts never permit resubmission.
Keep your existing durable submission authority. Acknowledge its begin commit and
bind the final body/destination to the admitted intent before HTTP. The
beforeSubmission callback is a repeatable recheck, called before fetch and again
after native DNS; it must not consume one-use permission. Verify observationally,
then persist the returned facts under the same receipt/fencing rules. Lost commit
acknowledgments or receipt-write failure preserve the no-replay barrier. This API
adds no journal, retry engine, built-in signed-receipt format or private-network
transport. Deployment TLS and application/provider acceptance remain required.
Quarantine uncertain submissions
deliveryPolicy: 'quarantine-uncertain' selects a conservative alternative for
new admissions. The stored policy cannot be weakened by a restarted worker or
duplicate endpoint/event admission. After target resolution, a root-committed,
one-use submission marker must be acknowledged before the dispatcher is invoked.
False/unknown commitment or a deadline reached during that wait prevents dispatch.
Lookup failures before commitment may retry within the original budgets; every
dispatcher error afterward quarantines, including preflight or retryable errors.
Marked deliveries never receive another send grant. Lease expiry quarantines
them without incrementing attempts. Quarantine holds endpoint FIFO until the
existing authorized recovery confirm or retain operation commits its required
evidence/journal; these actions preserve the permanent marker and fence late
sender updates. A same-token factual success can finish before that review even
after lease expiry. Evidence-qualified retry refuses marked deliveries forever,
including after retention or payload compaction. process().quarantined counts
quarantines performed directly by the worker, not sweep-only cleanup.
Adopt the updated outbound artifact, required deliveryPolicy, nullable
submissionCommittedAt and custom/native persistence methods together; existing
rows require a reviewed explicit policy migration. This grants at most one worker
dispatcher invocation, not exactly-once effects or control over an SDK's internal
retries. Qualify a bounded non-retrying transport, sender lifecycle and truthful
operator evidence. A marker can exist even when no request escaped; the profile
deliberately does not infer safe replay from arbitrary dispatcher failures.
PrismaOutboundWebhookPersistence from @playstack/webhooks/durable/prisma
provides namespaced, immutable event-bound PostgreSQL outbound storage. Select and
migrate the optional webhooks.outbound.prisma artifact. It serializes endpoint
FIFO, fences completion by unexpired database-clock leases and supplies bounded,
scope/filter-bound history cursors. compactTerminal({ completedBefore, limit, endpointId? }) removes payloads from eligible terminal rows in atomic bounded
batches, retaining immutable binding digests and identifiers for replay refusal.
Compacted history uses the payload-free OutboundWebhookCompactedDelivery
variant; replay never restores payloads or sends again. Apply the current reviewed
artifact migration before activating compaction. Retained metadata/gates are not
complete erasure or bounded metadata retention. Optional shared admission and
authorized recovery are described below; neither makes an uncertain send safe to
repeat. The inbound Prisma receipt adapter is not outbound delivery storage. An
injected test store or a passing transport test does not qualify production Slack
or Discord notifications; supply and verify actual persistence and provider
composition before enabling them.
An audience confirmation can therefore notify Slack or Discord by routing audiences.subscription.confirmed to a formatter and dispatcher without coupling the Audiences package to either service.
Slack and Discord profiles
Root exports createSlackIncomingWebhookDispatcher and
createDiscordWebhookDispatcher take immutable { endpoints, fetch, formatText }
configuration. endpoints maps opaque IDs to server-owned secret URLs; per-send
URL/header overrides are rejected. The host formatter explicitly projects only
permitted text, such as aggregate counts or opaque IDs. Slack uses an escaped
literal profile (up to 4,000 UTF-16 units before/after escaping); Discord limits
content to 2,000 units, suppresses mentions and forces wait=true.
Use native createNodeWebhookFetch with exact provider host/443 policy. These
profiles accept only HTTP 200 and propagate bounded Retry-After deadlines to
durable retries. Missing/invalid 429 metadata refuses rather than guessing an
early retry. The generic transport discards bodies and supplies no provider
message receipt or body acknowledgment.
For Discord body-only retry metadata, explicitly inject
createNodeDiscordWebhookFetch from @playstack/webhooks/node. It accepts only
canonical Discord HTTPS webhook URLs and reads at most 4 KiB of uncompressed
429 JSON under the whole-operation deadline. It validates retry_after and
global-limit hints without exposing response bodies or bucket identifiers.
Competing valid deadlines use the later minimum; malformed or incomplete
metadata refuses rather than falling back to an earlier retry. Slack and the
generic transport retain their body-discard behavior. Qualify live provider and
runtime behavior before activation; none of these profiles guarantees exactly-once delivery.
Shared route and global admission
createCoordinatedWebhookDispatcher from @playstack/webhooks/coordination
wraps a dispatcher with shared route/global permits and persistent 429
cooldowns. Compose PrismaOutboundWebhookCoordination from
@playstack/webhooks/coordination/prisma and explicitly migrate
webhooks.coordination.prisma. Use trusted opaque group IDs shared by every
participating worker; map actual provider credentials/resources and egress
identity, not just application list or tenant boundaries.
Admission acquires short database locks, not a transaction spanning provider I/O.
Native Direct and pinned Node transports recheck the permit before submission;
custom transports must honor context.beforeSubmission. Cooldowns survive
restarts only after their write commits. A crash or uncertain database write
after observing a provider deadline requires an operational pause and reviewed
reconciliation; permit expiry cannot reconstruct a lost deadline. Configure
bounded database timeouts and a lease longer than the qualified send deadline.
This coordinates participating senders, not unrelated clients or discovered
provider quotas, and does not recall an already submitted request.
Authorized inspection and recovery
PrismaOutboundWebhookRecovery from @playstack/webhooks/recovery/prisma
supplies masked inspection, history and revision-bound reconciliation. Select
webhooks.outbound.prisma and webhooks.outbound-recovery.prisma, and supply
transaction-bound operator authorization, independent evidence verification and
safe Audit/Events recording. No recovery HTTP controller is installed for you.
retain parks an unknown outcome without asserting non-delivery; confirm
requires verified delivered evidence. Neither sends or resets the original
attempt/age budget. Optional retry additionally requires current destination
authorization, independent non-delivery evidence and fencing of every prior
sender. The package supplies no Slack/Discord evidence source establishing those
conditions: keep administrative resends unavailable without a qualified one.
Timeouts, absent receipts and operator assertions are not non-delivery evidence.
Retained journals, identifiers and tombstones need a separate reviewed lifecycle;
compaction and reconciliation are not complete erasure.
Editable settings and durable routing
WebhookIntegrationSettings from @playstack/webhooks/settings and
PrismaWebhookIntegrationSettingsPersistence from
@playstack/webhooks/settings/prisma provide encrypted Slack/Discord settings,
masked reads, scoped event routing and expected-revision rotation/enable/disable/
revocation. Explicitly compose and migrate webhooks.settings.prisma; durable
dispatch also needs webhooks.outbound.prisma. Supply native Crypto and mandatory
operator/worker authority and safe Audit callbacks joining the original transaction.
Opaque IDs are not credentials; expose no secret-resolution endpoint to browsers.
route(listId, fullEvent, workerPrincipal) retains the original fan-out and full
event digest, including empty fan-out. Replays cannot expand to newly enabled or
replaced destinations. Private resolution requires that receipt and current
authority/state/revision. The root createWebhookIntegrationTargetResolver
composes this with native provider dispatchers, an explicit approved text formatter,
trusted event-to-list projection and injected pinned transport. Select exactly one
of static targets or dynamic targetResolver in the durable engine.
Lookup is bounded and repeated before dispatch. Config changes invalidate old queued revisions; a snapshot already resolved may still send to its old URL, never the replacement. Route receipts commit separately from outbound enqueue: recover the same event through a durable source outbox. Retained IDs/digests/tombstones are not complete erasure or anonymous data. Operator recovery and live provider qualification remain separate work. Webhook failure must remain independent of consent signup/mail.
Optional @playstack/webhooks/settings/nest provides
WebhookIntegrationSettingsModule.forRoot with mandatory operator guard, trusted
principal, exact Origin/session-bound CSRF and native mutation-rate admission.
Strict path/body scope, masked responses and fixed errors do not replace host
authentication; no browser secret-resolution route is exposed.
Native admitTestSend requires explicit bounded admission and an original-handle
Events/outbox enqueue. Authority/current revision, quota, routing receipt, outbox
intent and safe Audit commit together. Tests use fixed server text and a five-minute
profile, not a caller-supplied URL/payload. HTTP accepted is not delivered. Workers
recover the original event/key and reauthorize before sending; repeat requests are
new rate-admitted intents. Complete erasure, administrative recovery and deployed
provider qualification remain separate gates.
Customer-provided outbound URLs
HTTPS and redirect rejection alone are not an SSRF boundary. For Node public-endpoint delivery, inject createNodeWebhookFetch from @playstack/webhooks/node into createDirectWebhookDispatcher from @playstack/webhooks/direct. Configure the dispatcher's timeout; direct transport use must supply a deadline signal.
The transport validates all DNS answers, rejects non-public/special-use addresses, pins an approved address to the TLS lookup and preserves hostname/certificate verification. It resolves each attempt afresh, uses no shared agent/proxy, rejects redirects and defaults to port 443. Optional allowedHosts/allowedPorts never bypass address validation. Request bodies default to 1 MiB, response headers are capped at 16 KiB and response bodies are discarded.
Keep your infrastructure egress controls and deployment DNS/TLS tests in place; the transport's address checks complement them rather than replace them. Private-network or proxied delivery needs an explicitly owned transport.
API entry points and requirements
Reference snapshot: @playstack/webhooks@0.1.0-beta.5. Import only the entry point your runtime needs. Paths below are relative to the installed package; use Go to Definition in your editor to inspect exact parameters, return types and overloads. Do not import the declaration-file paths directly.
| Public entry point | Declaration file |
|---|---|
@playstack/webhooks | ./dist/index.d.ts |
@playstack/webhooks/errors | ./dist/errors.d.ts |
@playstack/webhooks/prisma | ./dist/prisma.d.ts |
@playstack/webhooks/direct | ./dist/direct.d.ts |
@playstack/webhooks/node | ./dist/node.d.ts |
@playstack/webhooks/durable | ./dist/durable.d.ts |
@playstack/webhooks/durable/prisma | ./dist/outbound-prisma.d.ts |
@playstack/webhooks/coordination | ./dist/coordination.d.ts |
@playstack/webhooks/coordination/prisma | ./dist/coordination-prisma.d.ts |
@playstack/webhooks/recovery | ./dist/recovery.d.ts |
@playstack/webhooks/recovery/prisma | ./dist/recovery-prisma.d.ts |
@playstack/webhooks/settings | ./dist/settings.d.ts |
@playstack/webhooks/settings/prisma | ./dist/settings-prisma.d.ts |
@playstack/webhooks/settings/nest | ./dist/settings-nest.d.ts |
@playstack/webhooks/relaypath | ./dist/relaypath.d.ts |
@playstack/webhooks/testing | ./dist/testing.d.ts |
@playstack/webhooks/package.json | No TypeScript declaration (asset or metadata export). |
Node.js engine requirement: >=20. This is not a claim that every entry point works in browsers or Workers.
Peer dependencies
Keep existing framework versions that satisfy these ranges. Install optional peers only when using the corresponding adapter. The package manager resolves ordinary dependencies separately.
| Peer | Compatible range | When needed |
|---|---|---|
@nestjs/common | ^10.0.0 || ^11.0.0 || ^12.0.0 | Optional; only for the entry points that use it. |
rxjs | ^7.0.0 | Optional; only for the entry points that use it. |
For a complete first program, start with Getting started. For API lookup and partial-example conventions, see Reading the reference. Provider failures, lifecycle requirements and application responsibilities remain described in the guide above; types alone do not establish production safety.