Management contracts
Shared endpoint lifecycle, sender reads, and custom storage interfaces.
good-webhooks/management defines the endpoint management contract, and createManagement builds one over your own storage.
import { createManagement } from 'good-webhooks/management'
import type {
EndpointManagement,
EndpointSource,
EndpointResolution,
ManagementScope,
ManagementOptions,
ManagementRepository,
EndpointLimit,
SecretCipher,
StoredEndpoint,
StoredEndpointPatch,
ManagedEndpoint,
CreateManagedEndpoint,
UpdateManagedEndpoint,
ManagedEndpointWithSecret,
} from 'good-webhooks/management'Most applications use a ready provider: PostgreSQL or Better Auth. The endpoints guide covers the lifecycle; custom senders covers building on these contracts.
EndpointManagement
interface EndpointManagement {
readonly source: EndpointSource
create(scope: ManagementScope, input: CreateManagedEndpoint): Promise<ManagedEndpointWithSecret>
list(scope: ManagementScope): Promise<ManagedEndpoint[]>
get(scope: ManagementScope, id: string): Promise<ManagedEndpoint>
update(scope: ManagementScope, id: string, patch: UpdateManagedEndpoint): Promise<ManagedEndpoint>
pause(scope: ManagementScope, id: string): Promise<ManagedEndpoint>
resume(scope: ManagementScope, id: string): Promise<ManagedEndpoint>
remove(scope: ManagementScope, id: string): Promise<ManagedEndpoint>
rotateSecret(
scope: ManagementScope,
id: string,
options?: { graceMs?: number },
): Promise<ManagedEndpointWithSecret>
sendTestEvent(scope: ManagementScope, id: string): Promise<TestEventResult>
removeScope(scope: ManagementScope): Promise<void>
reencrypt(scope: ManagementScope): Promise<number>
}import { createPostgresManagement } from 'good-webhooks/management/postgres'
import { Pool } from 'pg'
const management = createPostgresManagement({
database: new Pool({ connectionString: process.env.DATABASE_URL }),
eventTypes: ['invoice.paid'],
encryptionKey: process.env.WEBHOOK_ENCRYPTION_KEY!,
})
const scope = { type: 'organization', id: 'org_123' }
const { endpoint, secret } = await management.create(scope, {
url: 'https://receiver.example/webhooks',
eventTypes: ['invoice.paid'],
})
await management.pause(scope, endpoint.id)The library builds every EndpointManagement. To change one method, spread a provider into a wrapper; see the compatibility policy.
All direct calls are trusted server operations. They do not authorize the caller. The first argument is ManagementScope: null for application scope or { type, id } for a named scope. See scopes.
| Method | Returns |
|---|---|
create(scope, input) | Promise<ManagedEndpointWithSecret> |
list(scope) | Promise<ManagedEndpoint[]> |
get(scope, id) | Promise<ManagedEndpoint> |
update(scope, id, patch) | Promise<ManagedEndpoint> |
pause(scope, id) | Promise<ManagedEndpoint> |
resume(scope, id) | Promise<ManagedEndpoint> |
remove(scope, id) | Promise<ManagedEndpoint> |
rotateSecret(scope, id, options?) | Promise<ManagedEndpointWithSecret> |
sendTestEvent(scope, id) | Promise<TestEventResult> |
removeScope(scope) | Promise<void> |
reencrypt(scope) | Promise<number> |
source | EndpointSource |
create: creates an active endpoint and returns{ endpoint, secret }.list: returns every nondeleted endpoint in the scope.get: returns an endpoint, including its deleted state.update: returns the endpoint and changes only the supplied fields.headersreplaces the whole header set.pause: changes the status to'paused'withpauseReason: 'owner'.resume: validates the current URL, changes status to'active', and clearspauseReason. Also resumes automatic pauses.remove: sets status to'deleted', clears signing secrets and headers, and returns the endpoint. Removing an already deleted record is idempotent.rotateSecret: changes the signing secret.options.graceMsdefaults to 86,400,000 and accepts 0 through 86,400,000.sendTestEvent: signs and sends one test event to an active or paused endpoint. Deleted endpoints throwINVALID_STATE.removeScope: deletes the scope's currently registered endpoints.reencrypt: rewrites live signing-secret and header ciphertext with the current storage encryption key and returns the count.source: trusted sender reads. See EndpointSource.
Test events
sendTestEvent sends { id, type: 'good-webhooks.test', occurredAt, data: { endpointId } } with a new id each time, signed like a delivery: with the current secret, plus the previous one during a rotation overlap. It sends the endpoint's headers too. The destination is checked the same way, and redirects are not followed. It waits at most 10 seconds and keeps the first 4 KiB of the response. It writes nothing, retries nothing, and leaves automatic pauses alone. The request leaves from the calling process.
interface TestEventResult {
eventId: string
ok: boolean // a 2xx response with no transport error
responseStatus: number | null
responseBody: string
durationMs: number
error: string | null // same values as Attempt.error
}A receiver failure is a result with ok: false, never a thrown error. An unsafe destination at send time is error: 'unsafe_url'.
Inputs and limits
CreateManagedEndpoint has url, optional description, eventTypes, and optional headers. UpdateManagedEndpoint makes those fields optional, accepts description: null to clear the description, and accepts headers: null or {} to remove every header.
| Value | Limit |
|---|---|
Scope type | 1 through 64 characters |
Scope id | 1 through 200 characters |
| Endpoint ID | 1 through 255 characters |
| URL | At most 2,048 characters |
| Description | At most 2,000 characters |
eventTypes | 1 through 100 event names |
headers | See below |
| Endpoints | At most 1,000 per scope |
graceMs | 0 through 86,400,000 |
- Scope
type, scopeid, and endpoint ID: each must be nonblank, with no null bytes. - URL: must pass the configured destination validation, otherwise
UNSAFE_URL. - Description: no null bytes.
eventTypes: configured event names only. Duplicates are collapsed.headers: see endpoint headers.- Endpoints: the limit counts nondeleted endpoints.
maxEndpointscan set fewer. graceMs: an integer. Default 86,400,000.
Endpoint headers
headers adds request headers to every attempt and test event, for example a key an API gateway checks. Validation runs before any storage call and throws INVALID_INPUT:
| Rule | Limit |
|---|---|
| Count | 20 |
| Name | 1 to 100 characters, a token |
| Value | Visible ASCII, space, tab |
| Total | 2 KiB as JSON |
| Reserved | See below |
Names are RFC 9110 tokens, and two names that differ only in letter case are rejected. A value is a nonempty string of visible ASCII, spaces, and tabs. The total is the UTF-8 byte length of the headers as JSON, so escaped quotes and backslashes count their encoded size. Reserved names, whatever their letter case, are those starting with webhook-, plus content-type, user-agent, and the hop-by-hop names the transport sets: host, content-length, connection, transfer-encoding, upgrade, expect, proxy-authorization, proxy-connection, trailer, and te. Management stores the set as one encrypted JSON value, or nothing when it is empty.
Results
ManagedEndpoint is the shared Endpoint shape: id, url, nullable description, eventTypes, status, pauseReason, headers, createdAt, and updatedAt. pauseReason is 'owner' for a manual pause, 'failing' or 'gone' for an automatic pause, and null when the endpoint isn't paused or was paused before schema version 5. It is optional in the type so wrappers and test doubles that build one keep compiling. headers is optional in the type for the same reason; createManagement always returns it, {} when there are none. Headers come back to the owner who set them, while the signing secret stays write-once. Timestamps are Date values. Ordinary results contain neither plaintext signing secrets nor ciphertext. Only create and rotateSecret return the new secret.
Errors
INVALID_INPUT: an argument breaks a limit above, or names an event outside the configured list.UNSAFE_URL: the URL fails destination validation.NOT_FOUND: no endpoint with this ID in the scope, or the scope's owner no longer exists.INVALID_STATE: the endpoint is deleted, a signing-secret overlap is active, or the record keeps changing.ENDPOINT_LIMIT:createin a scope that already has its endpoint limit.
EndpointSource
interface EndpointSource {
matchRecipients(scope: ManagementScope, eventType: string): Promise<readonly string[]>
resolveEndpoint(scope: ManagementScope, id: string): Promise<EndpointResolution>
pause?(scope: ManagementScope, id: string, input: AutomaticPauseInput): Promise<boolean>
}
type EndpointResolution =
| {
status: 'active'
url: string
secrets: readonly string[]
revision?: string
headers?: Record<string, string>
}
| { status: 'paused' | 'deleted' }
interface AutomaticPauseInput {
reason: 'failing' | 'gone'
revision?: string
}import { createDelivery } from 'good-webhooks/delivery'
import type { EndpointSource } from 'good-webhooks/management'
import { Pool } from 'pg'
import { z } from 'zod'
// A fixed, single-endpoint source. Real sources read your endpoint storage.
const source: EndpointSource = {
async matchRecipients() {
return ['endpoint-1']
},
async resolveEndpoint() {
return {
status: 'active',
url: 'https://receiver.example/webhooks',
secrets: [process.env.WEBHOOK_SECRET!],
}
},
}
const delivery = createDelivery({
database: new Pool({ connectionString: process.env.DATABASE_URL }),
events: { 'invoice.paid': z.object({ invoiceId: z.string() }) },
source,
// This source has no pause(), so its worker runs without automatic pauses.
endpointHealth: false,
})The sender calls matchRecipients once at publication and resolveEndpoint before every attempt. The source is not an API for untrusted callers.
matchRecipients: returns the complete set of matching endpoint IDs, including paused endpoints. Lookup failures reject.- A source must not convert an outage into an empty result.
resolveEndpoint: returns current state. Deleted or missing records return'deleted'.- Active results contain the current URL and usable Standard Webhooks signing secrets.
- After
leaseMs / 2, or when the worker shuts down, the worker stops waiting for the call. It does not cancel the call.
pause: optional. Required by a worker with automatic pauses on.- It pauses an active endpoint for the worker and resolves
true. - It resolves
falsewithout changing anything when the endpoint isn't active or no longer hasrevision.
- It pauses an active endpoint for the worker and resolves
revision is optional and opaque. It must change whenever the endpoint changes, including on resume, so the worker can tell that earlier failures no longer describe it. Without it, a resumed endpoint that fails again is paused at once, and only a success starts a new period. The built-in sources report the record's revision.
headers is optional. A source may return endpoint headers as a plain object of string values, and the worker sends them on the attempt. The signature headers always win. A value that is not a plain object of strings, or that uses a reserved name, defers the delivery like a failed lookup, without using up an attempt. The built-in sources return the decrypted headers only when an endpoint has some.
EndpointSource grows only by optional methods and optional resolution fields, and new inputs arrive in a trailing options object, so a source written today keeps compiling.
The built-in source returns the new signing secret first and the previous secret only while the overlap remains active. It rejects an unknown event name with INVALID_INPUT. Lookup and decryption failures reject.
createManagement
createManagement(options: ManagementOptions): EndpointManagementimport { createManagement } from 'good-webhooks/management'
import { createPostgresManagementRepository } from 'good-webhooks/management/postgres'
import { Pool } from 'pg'
import { cipher } from './cipher.js' // Your SecretCipher, for example backed by a KMS.
export const management = createManagement({
repository: createPostgresManagementRepository(
new Pool({ connectionString: process.env.DATABASE_URL }),
),
cipher,
eventTypes: ['invoice.paid', 'invoice.voided'],
})Creates the shared endpoint lifecycle over custom persistence and encryption.
repository: requiredManagementRepository.cipher: requiredSecretCipher.eventTypes: required nonempty array of event names. No payload validators are required.- Each name matches
^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,119}$and does not start withgood-webhooks..
- Each name matches
allowLocalhost: optional boolean, defaultfalse. Allows development HTTP loopback URLs.validateUrl(url): optional async host check after portable URL validation. Runs on create, URL update, and resume, not on each send.- Reject a URL with
new WebhookError('UNSAFE_URL', message). Other errors reject the call unchanged.
- Reject a URL with
scopeExists(scope): optional async ownership check. Returnsfalsefor a missing owner and rejects on lookup failure.maxEndpoints(scope): optionalEndpointLimit, default 1,000. Returns, or resolves to, the scope's endpoint limit from 0 to 1,000.- Other values throw
INVALID_CONFIGon create. - The 1,000 bound is fixed for 1.x.
- Other values throw
Invalid options throw INVALID_CONFIG. Portable URL validation requires HTTPS and rejects credentials, fragments, and private or reserved IP literals. Loopback hosts, including localhost, need allowLocalhost, which also permits HTTP for them.
ManagementRepository
interface ManagementRepository {
list(scope: ManagementScope): Promise<StoredEndpoint[]>
get(scope: ManagementScope, id: string): Promise<StoredEndpoint | null>
create(
scope: ManagementScope,
endpoint: Omit<StoredEndpoint, 'id'>,
options: { limit: number },
): Promise<StoredEndpoint>
update(
scope: ManagementScope,
id: string,
revision: number,
patch: StoredEndpointPatch,
): Promise<StoredEndpoint | null>
}list: returns every live record in the scope, newest first, without truncation. Live meansstatusis not'deleted'.get: returns the record, including a deleted one, ornull.create: atomically inserts the complete record,encryptedHeadersincluded, and generates itsid.- Generate IDs of 1 to 255 characters, not all whitespace, with no null byte. Management rejects other IDs with
INVALID_INPUT, soget,update, and delivery fail for them. options.limitis 0 to 1,000. When the scope already hasoptions.limitnondeleted records,createinserts nothing and rejects withENDPOINT_LIMIT.
- Generate IDs of 1 to 255 characters, not all whitespace, with no null byte. Management rejects other IDs with
update: atomically guards on scope, ID, and revision, increments the revision, and applies the patch. A revision conflict returnsnull.
Repository errors propagate. createPostgresManagementRepository is the built-in implementation.
StoredEndpoint adds revision, encryptedSecret, nullable previousEncryptedSecret, nullable previousSecretExpiresAt, and nullable encryptedHeaders to the endpoint shape. encryptedHeaders holds endpoint headers as one encrypted JSON string, or null when there are none. create and a headers update write it, remove clears it, and reencrypt rewrites it. It has no plaintext counterpart on the stored record. Store it and return it unchanged, and never drop it. Store pauseReason too: create records and pause, resume, and remove patches include it. A repository that passes records straight to an ORM needs a column for each field. Fields added later are optional, a repository stores every field it receives, and a field missing from a stored row reads as its default. New methods are optional. revision is a number here; EndpointResolution carries its string form. StoredEndpointPatch is a partial stored record without id, createdAt, or revision. Stored records must never be sent to clients.
SecretCipher
interface SecretCipher {
encrypt(value: string): Promise<string>
decrypt(value: string): Promise<string>
}The cipher encrypts receiver-facing signing secrets and the endpoint header JSON at rest. A cipher that supports storage encryption key rotation writes with the current key and reads the retained keys until re-encryption finishes.