// DECLARED EVENTS (docs/contributing/architecture.md, "What an author writes, and how": the events row) — the webhook a // vendor sends for a write, as data the kernel executes. A pack declares which write sends which event type, the // event's envelope, the scheme that signs it and where the World's endpoints are kept; the kernel renders, signs, // delivers (through the World's application route and egress rule) and records each delivery. The one thing a pack // may write is how its vendor renders an event's `data` (`semantics/events.ts`), when it is not the written object. // // Imports stay free of side effects: the delivery's transport (Node's http, the World's egress policy) is loaded when a // delivery is made, never when a browser client imports the kernel. import { createHash, createHmac } from 'node:crypto'; import { resolve } from 'node:path'; import { applyTwinWrite, applyTwinWriteAtomic, twinResources } from './serve.ts'; import { equalSecrets as same, jwks, jwtSignClaims, jwtVerify, jwtVerifySignature, ksuidFrom, signWith, verifyWith } from './signing.ts'; import { deliveryTraceHeaders } from './trace-context.ts'; import { attemptDelivery } from './event-delivery.ts'; import { getActiveWorldStore, withWorldStore, type WorldStore } from './world-store.ts'; import { worldPaths } from './storage.ts'; import { worldNow } from './world-clock.ts'; import { recordFault, serviceLedger, webhookFault } from './scenario-consume.ts'; import { durationMs } from './placements.ts'; /** How the vendor signs a delivery. */ export type EventScheme = /** One header carrying the destination's secret as it is, no signature over the body (Cloudflare Notifications' * `cf-webhook-auth`, the secret a webhook destination was made with). */ | { kind: 'secret'; header: string } /** A message id, a timestamp and a signature header (the Standard Webhooks shape): `-id`, * `-timestamp` (seconds) and `-signature: v1,` over `${id}.${timestamp}.${body}`, * keyed by the base64 part of the secret after `secretPrefix`, or by the secret's own UTF-8 bytes (`secretKey: 'utf8'`: * Polar's, whose SDK base64-encodes the secret as it is before verifying). */ | { kind: 'webhook-id'; prefix: string; secretPrefix?: string; secretKey?: 'base64' | 'utf8' } /** One header of a timestamp and its signatures: `
: t=,v1=` over `${t}.${body}`, * keyed by the secret as it is; `version` names the signature's key when the vendor's is not `v1` (ElevenLabs' * `ElevenLabs-Signature: t=…,v0=…`). */ | { kind: 'timestamp-v1'; header: string; version?: string } /** One HMAC header over the body (`X-Hub-Signature-256: sha256=`, GitHub's), or over `${timestamp}.${body}` when * the vendor sends its timestamp in `timestampHeader`; `signed` names what is signed otherwise (`{t}` the timestamp * as the header carries it, `{t.s}` and `{t.ms}` in seconds and milliseconds, `{body}` the body, `{method}` and * `{url}` the request's: Slack's `v0:{t}:{body}`, HubSpot v3's `{method}{url}{body}{t}` with `timestampUnit: 'ms'`), * and `algorithm` the hash (SHA-256 unless named: GitHub's older `X-Hub-Signature` is SHA-1). */ | { kind: 'hmac'; header: string; encoding: 'hex' | 'base64'; prefix?: string; timestampHeader?: string; timestampUnit?: 's' | 'ms'; signed?: string; algorithm?: 'sha1' | 'sha256' } /** An Ed25519 signature (Discord's interactions: `X-Signature-Ed25519` in hex over `{t}{body}`, the seconds in * `X-Signature-Timestamp`), by the private key (PEM) held at the endpoint's field `key` (a dotted path, through its * joins: an application's key pair); `signed` as `hmac`'s, `{t}{body}` unless named. */ | { kind: 'ed25519'; key: string; header: string; timestampHeader: string; signed?: string; encoding?: 'hex' | 'base64' } /** An RS256 JWT in a header (`Authorization: Bearer `, Pub/Sub push's OIDC token), by the private key (PEM) at the * endpoint's field `key`, carrying the key's `kid`: `iat` and `exp` (`expiresIn` seconds after, an hour unless named) * on the receiver's clock, and the declared `claims`, each `$endpoint.`, `$url` (the delivery's URL) or written * as it is (one left undefined is not sent). */ | { kind: 'oidc-jwt'; key: string; claims: Record; header?: string; prefix?: string; expiresIn?: number; kidPrefix?: string } /** An RSA (SHA-256) signature over a canonical string by the private key (PEM) at the endpoint's field `key`, with the * URL of the certificate that verifies it (`certUrl`, `$endpoint.` or written as it is), as SNS signs. `signed` * is a template as `hmac`'s (`{body.}` a field of the JSON body), or `fields`: each named body field present, * as `\n\n` (SNS's string to sign). `at` places the signature, the certificate URL and the timestamp * (`timestamp.unit`: ISO 8601 unless named) in headers or, `body`, in fields of the JSON body, the timestamp set * before the string is made. */ | { kind: 'rsa-x509'; key: string; certUrl: string; signed: string | { fields: ReadonlyArray }; at: 'header' | 'body'; signature: string; certUrlAt: string; timestamp?: { at: string; unit?: 'iso' | 's' | 'ms' }; encoding?: 'base64' | 'hex' } /** One header of a plain hash (not an HMAC) of the secret and the body (HubSpot's v1 `X-HubSpot-Signature`: the SHA-256 * of the app's client secret followed by the request body); `signed` names the input, `{secret}` and `{body}`; * `base64-unpadded` is base64 with its trailing `=` removed (E2B's `e2b-signature`) */ | { kind: 'hash'; header: string; signed: string; encoding: 'hex' | 'base64' | 'base64-unpadded'; algorithm?: 'sha256' }; /** Where the World's endpoints of one kind are kept (a door the vendor's dashboard stands in for writes them): their * stored type and the fields holding the URL, the signing secret, the event types an endpoint takes (all when absent, * `*` and `.*` patterns) and whether it is disabled (`disabled` true), not enabled (`enabled` false) or not live * (`status`). A field may be a dotted path into the row (`config.url`). `url` is needed by an HTTP delivery alone, and * `secret` by a shared-secret scheme alone (an endpoint without one is live without it). */ export type EndpointsDecl = { storedAs: string; url?: string; secret?: string; filter?: string; disabled?: string; enabled?: string; /** When the vendor turns an endpoint off for failing (Polar after ten failures in a row, Clerk and Resend after five * days of failing, Slack under a 5% success rate): after `failures` consecutive failed attempts, when its failures * have run for `failingFor` of World time, or when fewer than `successRate.below` (0 to 1) of its last * `successRate.of` attempts succeeded; the kernel then writes `set` (top-level field → value) on the endpoint's row, * the vendor's own disabled state, which `disabled`, `enabled` or `status` reads. */ disable?: { failures?: number; failingFor?: string; successRate?: { below: number; of: number }; set: Record }; /** An endpoint that is live only while a field holds one value (Stripe's `status: 'enabled'`). */ status?: { field: string; live: string }; /** Which events an endpoint takes by whom they are about: one whose `field` is true takes only events whose * envelope value `value` is set (Stripe's Connect endpoint, `connect: true`, takes connected accounts' events, those * with an `$account`), and any other only events where it is not. */ scope?: { field: string; value: string }; /** Endpoint fields that must equal an event's values (field → `$value`, or a literal): a repository's hook takes only * its repository's events (GitHub's `{ repository: '$repository' }`), an organization's its organization's. A list * field takes the event when it holds the value. Several matches: the endpoint takes the event when any holds (a * GitHub App's installation: its own events, its account's when it covers all the account's repositories, a listed * repository's). */ match?: Record | ReadonlyArray>; /** Related rows an endpoint's fields read through (`app.hook_url`): each join's name, the stored type it names and the * endpoint's field holding its id (a GitHub installation's URL, secret and events are its App's). */ joins?: Record; /** The event types this kind of endpoint takes (every type when absent), or those it does not (`skip`): two kinds over * the same rows, one taking a type under a `match` the other has no need of (a Slack app is sent `app_mention` only * when a message mentions it, and every `message` its subscription names). */ types?: ReadonlyArray; skip?: ReadonlyArray; }; /** Whether an endpoint takes an event by its `match`: every field of one match (any, when several) equal to the event's * value, or, a list, holding it. */ function matches(row: Record, match: EndpointsDecl['match'], filled: Record): boolean { if (match === undefined) return true; const one = (m: Record): boolean => Object.entries(m).every(([field, value]) => { const want = value.startsWith('$') ? filled[value] : value; const have = at(row, field); // a list value takes a row whose field is one of it (the apps a Slack message mentions) if (Array.isArray(want)) return want.some((w) => String(w) === String(have)); return Array.isArray(have) ? have.some((h) => String(h) === String(want)) : have === want || (have !== undefined && want !== undefined && String(have) === String(want)); }); return Array.isArray(match) ? match.some(one) : one(match as Record); } /** How a delivery reaches its receiver: * - `http` (the default): a POST to the endpoint's URL, through the World's application route and egress rule; * - `socket`: a frame into each open session of the vendor's socket (sockets.ts) bound to the endpoint, a session whose * `state[session]` (`endpoint` unless named) holds the endpoint's id (Discord's Gateway, Slack's Socket Mode). The * frame is `frame`, a template as the envelope is with `$event` the rendered event and `$seq` the delivery's sequence * number (increasing in the twin, never reused), the event itself when absent; a session that resumes after the * last sequence number it saw is sent every later frame of its endpoint again (`SocketSession.resume`). An attempt * no bound session is open for fails; * - `twin`: a request to another vendor's operation, as the app would call it and routed to that vendor's twin in the * World (Gmail publishing to Pub/Sub, S3 to SQS or SNS): `url` with `{endpoint.}` filled from the endpoint, * `body` a template with `$event`, `$event.text` and `$event.base64` (the rendered event, its JSON text, that text * in base64) and `$endpoint.`, `headers` as the delivery's further headers. The receiving twin owns its * retries, acknowledgements and signing: such a delivery declares no scheme (`[]`) and, usually, `retry: 'none'`. */ export type DeliveryTransportDecl = | 'http' | { socket: string; session?: string; frame?: unknown } | { twin: { method?: string; url: string; body?: unknown; headers?: Record } }; /** The vendor's retry schedule: the delays after each failed attempt (`['1h', '2h', '4h']`: four attempts in all); * `none`, a single attempt (GitHub's); or exponential backoff within a window where the vendor publishes the window * and not the delays (Vercel within 24 hours, Discord within 10 minutes), which `undocumented` marks: the delays double * from `first` (a minute, or an eighth of a shorter window) while their sum stays within the window, and each packet * records that its schedule is not the vendor's published one. */ export type RetryDecl = ReadonlyArray | 'none' | { backoff: 'exponential'; within: string; undocumented: true; first?: string }; /** The events a pack's writes send. */ export type EventsDecl = { /** how each delivery is signed; several schemes each add their headers (GitHub's SHA-256 and SHA-1 signatures); `[]` * signs nothing (a delivery into another twin, which signs its own) */ scheme: EventScheme | ReadonlyArray; /** how a delivery reaches its receiver: HTTP to the endpoint's URL unless named */ transport?: DeliveryTransportDecl; /** further headers each delivery carries, templates as the envelope's are, plus `$endpoint.` for the endpoint * it goes to (GitHub's `X-GitHub-Event`, `X-GitHub-Delivery` and `X-GitHub-Hook-ID`), and the attempt's own: * `$attempt` (1 for the first), `$retry` (the retry's number, absent on the first attempt) and `$retryReason` (why * the attempt before failed: `http_timeout`, `http_error` or `connection_failed`; Slack's `x-slack-retry-num` and * `x-slack-retry-reason`). A header whose value is absent is not sent. */ headers?: Record; /** How long an attempt waits for its answer (`3s`, a duration as a scenario's): one not answered in time fails as * `http_timeout`. Absent, the transport's own limit. */ timeout?: string; /** When the body is rendered: once at the write (the default), or at each attempt (Linear's `webhookTimestamp`, * HubSpot's attempt number, Resend loading the object as it is then): the pack's render is called again with the * write and its `attempt`, and the envelope is filled again, with `$attempt` and `$time.attempt.ms`, `.s` and `.iso` * (the receiver's clock) beside the write's values. */ renderAt?: 'write' | 'attempt'; /** Events for one endpoint sent together as one request whose body is their array (HubSpot's up to 100), in the order * they were made, at most `max` a request: each event waits `within` (World time) and its first attempt gathers * every event for the endpoint not yet sent; without `within`, those queued when the first is attempted. */ batch?: { max: number; within?: string }; /** A write's kernel operation (`user.create`) → the vendor's event type (`user.created`), or several (a Slack message * sends `message` and `app_mention`; `values` withholds one the write does not warrant); a write not named sends none. */ types: Record>; /** The event types the vendor enumerates, when it names every write's event by its resource: an operation that is * one of them sends it, and `.create|update|delete` sends `.created|updated|deleted` when that is * one of them (a vendor whose spec lists its event types: Stripe's). `types` is read first. */ known?: ReadonlyArray; /** The vendor's own resource each event is also kept as (its Events API: Stripe's `GET /v1/events`), the envelope as * its fields under the event's id, whether or not an endpoint takes it. */ store?: string; /** The stored event's field the kernel keeps as the number of its deliveries not yet answered 2xx (Stripe's * `pending_webhooks`): the endpoints it goes to at the write, one fewer at each delivery's first acceptance. */ pending?: string; /** The event as the vendor sends it, a template: a string `$type`, `$data`, `$id`, `$time.ms`, `$time.s`, `$time.iso`, * `$request.client_ip` or `$request.user_agent` is replaced by that value; everything else is sent as written. */ envelope: unknown; /** Where the World's endpoints are kept: one kind, or several (GitHub's repository and organization hooks). */ endpoints: EndpointsDecl | ReadonlyArray; /** The bookkeeping type each delivery is kept as (`_webhook_message`), otherwise `_world_event_delivery`. * Queuing and each transport attempt's outcome are separate retained facts. */ record?: string; /** The vendor's retry schedule (`RetryDecl`), durations as a scenario's are (`90s`, `5m`, `12h`, `3d`). Absent, a * delivery is attempted once. Each attempt is signed when it is sent; one that is not answered 2xx, or not answered, * is failed. A failed or finished delivery can be sent again by hand under its own id (`redeliverEvent`: GitHub's * redelivery). */ retry?: RetryDecl; }; /** A retry declaration's delays in milliseconds, and whether they are the vendor's published ones. */ export function retrySchedule(retry: RetryDecl | undefined): { delays: number[]; undocumented: boolean } { if (retry === undefined || retry === 'none') return { delays: [], undocumented: false }; if (Array.isArray(retry)) return { delays: (retry as ReadonlyArray).map(durationMs), undocumented: false }; const { within, first } = retry as Exclude | 'none'>; const window = durationMs(within); const delays: number[] = []; let next = first !== undefined ? durationMs(first) : Math.min(60_000, window / 8), total = 0; while (next > 0 && total + next <= window) { delays.push(next); total += next; next *= 2; } return { delays, undocumented: true }; } /** An event's further envelope values (`$`-named) the pack computes for a write, from the vendor's own state (the * connected account it is about, the API version it is rendered in): the pack's `semantics/events.ts` `values`. A * value left undefined drops its key from the envelope; `$send: false` keeps the event (stored) but sends it to no * endpoint (an account the vendor no longer reports to). */ export type EventValues = (ctx: C, write: EventWrite, type: string) => Record; /** The write an event reports, as the kernel's write hook sees it. */ export type EventWrite = { operation: string; storedType: string; body: Record; root?: string; occurredAt: string; request?: Request; /** The attempt the event is rendered for, when the vendor renders it at each attempt (`renderAt: 'attempt'`). */ attempt?: number }; /** How the vendor renders an event's `data` for a write, when it is not the written object as its operation answered * it: the pack's `semantics/events.ts`, under the handler contract's read-only context, for each type the write sends * (a Slack message renders as `message` and as `app_mention`). */ export type EventRender = (ctx: C, write: EventWrite, type: string) => Record; /** A packet as one attempt sends it, signed at that attempt. Its transport outcome and acceptance are separate retained * facts. */ export type EventDelivery = { url: string; body: string; headers: Record }; /** The transport a delivery is made over; the World's by default, a test's own when given. */ export type EventTransport = (url: string, body: string, headers: Record) => Promise; /** A `webhook-id` scheme's key: the base64 part of the secret, after its prefix when it carries one. */ const webhookKey = (scheme: { secretPrefix?: string; secretKey?: 'base64' | 'utf8' }, secret: string): Buffer => scheme.secretKey === 'utf8' ? Buffer.from(secret, 'utf8') : Buffer.from(scheme.secretPrefix && secret.startsWith(scheme.secretPrefix) ? secret.slice(scheme.secretPrefix.length) : secret, 'base64'); /** What an attempt is signed with beyond the secret: the request's method (POST unless named), the instant in * milliseconds (the receiver's clock; `seconds` when absent) and the endpoint (joined) whose fields hold an asymmetric * scheme's private key, claims and certificate URL. */ export type SignContext = { method?: string; ms?: number; endpoint?: Record }; /** A signing template's values: `{t}` (the timestamp in the unit its header carries), `{t.s}`, `{t.ms}`, `{t.iso}`, * `{body}`, `{method}`, `{url}`. */ const signedValues = (seconds: number, ms: number, unit: 's' | 'ms' | undefined, body: string, url: string, method: string): Record => ({ t: unit === 'ms' ? String(ms) : String(seconds), 't.s': String(seconds), 't.ms': String(ms), 't.iso': new Date(ms).toISOString(), body, method, url }); /** A signing template filled in one pass (nothing put in is read again): its values, and `{body.}` a field of the * JSON body; any other `{…}` is kept as written. */ function fillSigned(template: string, values: Record, body: string): string { let json: unknown, parsed = false; return template.replace(/\{(body\.[^}]+|[A-Za-z.]+)\}/g, (whole, name: string) => { if (!name.startsWith('body.')) return values[name] ?? whole; if (!parsed) { parsed = true; try { json = JSON.parse(body); } catch { json = undefined; } } const v = json && typeof json === 'object' ? at(json as Record, name.slice('body.'.length)) : undefined; return v === undefined || v === null ? '' : typeof v === 'string' ? v : JSON.stringify(v); }); } /** A canonical string of named JSON body fields: each present as `\n\n`, in the order named. */ function canonicalFields(fields: ReadonlyArray, body: string): string { const json = JSON.parse(body) as Record; return fields.flatMap((f) => { const v = json[f]; return v === undefined || v === null ? [] : [`${f}\n${typeof v === 'string' ? v : JSON.stringify(v)}\n`]; }).join(''); } /** A JSON object body with top-level fields set (a field already there keeps its place). */ function setFields(body: string, fields: Record): string { const json = JSON.parse(body) as unknown; if (!json || typeof json !== 'object' || Array.isArray(json)) throw new Error('A signature placed in the body needs a JSON object body.'); return JSON.stringify({ ...(json as Record), ...fields }); } /** A declared value for one delivery: `$endpoint.`, `$url`, or as written. */ const declaredValue = (template: unknown, endpoint: Record | undefined, url: string): unknown => typeof template !== 'string' ? template : template === '$url' ? url : template.startsWith('$endpoint.') ? (endpoint ? at(endpoint, template.slice('$endpoint.'.length)) : undefined) : template; /** An asymmetric scheme's private key (PEM), held at the endpoint's field `key`. */ function endpointKey(scheme: { kind: string; key: string }, endpoint: Record | undefined): string { const pem = endpoint ? at(endpoint, scheme.key) : undefined; if (typeof pem !== 'string' || !pem.includes('PRIVATE KEY')) throw new Error(`A ${scheme.kind} delivery's endpoint holds no private key at ${scheme.key}; it cannot be signed.`); return pem; } /** One scheme applied to one attempt: the headers it adds, and the body as sent (changed only by a signature placed in * the body). */ function signPart(scheme: EventScheme, secret: string, body: string, seconds: number, url: string, messageId: string | undefined, ctx: SignContext): { headers: Record; body: string } { const ms = ctx.ms ?? seconds * 1000, method = ctx.method ?? 'POST'; if (scheme.kind === 'webhook-id') { // Svix's `msg_` and a KSUID (its ids' form) const id = messageId ?? `msg_${ksuidFrom(seconds, 0, `${url}|${seconds}|0|${body}`)}`; const p = scheme.prefix.toLowerCase(); const signature = createHmac('sha256', webhookKey(scheme, secret)).update(`${id}.${seconds}.${body}`, 'utf8').digest('base64'); return { body, headers: { [`${p}-id`]: id, [`${p}-timestamp`]: String(seconds), [`${p}-signature`]: `v1,${signature}` } }; } if (scheme.kind === 'timestamp-v1') { const signature = createHmac('sha256', secret).update(`${seconds}.${body}`, 'utf8').digest('hex'); return { body, headers: { [scheme.header.toLowerCase()]: `t=${seconds},${scheme.version ?? 'v1'}=${signature}` } }; } if (scheme.kind === 'secret') return { body, headers: { [scheme.header.toLowerCase()]: secret } }; if (scheme.kind === 'hash') return { body, headers: { [scheme.header.toLowerCase()]: hashOf(scheme, secret, body) } }; if (scheme.kind === 'ed25519') { const signed = fillSigned(scheme.signed ?? '{t}{body}', signedValues(seconds, ms, 's', body, url, method), body); return { body, headers: { [scheme.header.toLowerCase()]: signWith(endpointKey(scheme, ctx.endpoint), signed, scheme.encoding ?? 'hex'), [scheme.timestampHeader.toLowerCase()]: String(seconds) } }; } if (scheme.kind === 'oidc-jwt') { const claims: Record = { iat: seconds, exp: seconds + (scheme.expiresIn ?? 3600) }; for (const [name, template] of Object.entries(scheme.claims)) { const value = declaredValue(template, ctx.endpoint, url); if (value !== undefined) claims[name] = value; } const token = jwtSignClaims(claims, { alg: 'RS256', privatePem: endpointKey(scheme, ctx.endpoint) }, scheme.kidPrefix !== undefined ? { kidPrefix: scheme.kidPrefix } : {}); return { body, headers: { [(scheme.header ?? 'authorization').toLowerCase()]: `${scheme.prefix ?? 'Bearer '}${token}` } }; } if (scheme.kind === 'rsa-x509') { const certUrl = String(declaredValue(scheme.certUrl, ctx.endpoint, url) ?? ''); const stamp = scheme.timestamp === undefined ? undefined : scheme.timestamp.unit === 's' ? String(seconds) : scheme.timestamp.unit === 'ms' ? String(ms) : new Date(ms).toISOString(); const sent = scheme.at === 'body' && scheme.timestamp ? setFields(body, { [scheme.timestamp.at]: stamp }) : body; const base = typeof scheme.signed === 'string' ? fillSigned(scheme.signed, signedValues(seconds, ms, 's', sent, url, method), sent) : canonicalFields(scheme.signed.fields, sent); const signature = signWith(endpointKey(scheme, ctx.endpoint), base, scheme.encoding ?? 'base64'); if (scheme.at === 'body') return { headers: {}, body: setFields(sent, { [scheme.signature]: signature, [scheme.certUrlAt]: certUrl }) }; return { body, headers: { [scheme.signature.toLowerCase()]: signature, [scheme.certUrlAt.toLowerCase()]: certUrl, ...(scheme.timestamp ? { [scheme.timestamp.at.toLowerCase()]: stamp! } : {}) } }; } const values = signedValues(seconds, ms, scheme.timestampUnit, body, url, method); const mac = createHmac(scheme.algorithm ?? 'sha256', secret).update(hmacBase(scheme, values, body), 'utf8').digest(scheme.encoding); return { body, headers: { [scheme.header.toLowerCase()]: `${scheme.prefix ?? ''}${mac}`, ...(scheme.timestampHeader ? { [scheme.timestampHeader.toLowerCase()]: values.t! } : {}) } }; } /** A `hash` scheme's value: the digest of its `signed` template with the secret and the body put in. */ const hashOf = (scheme: { signed: string; encoding: 'hex' | 'base64' | 'base64-unpadded'; algorithm?: 'sha256' }, secret: string, body: string): string => { const digest = createHash(scheme.algorithm ?? 'sha256').update(scheme.signed.replaceAll('{secret}', secret).replaceAll('{body}', body), 'utf8'); return scheme.encoding === 'base64-unpadded' ? digest.digest('base64').replace(/=+$/, '') : digest.digest(scheme.encoding); }; /** What an `hmac` scheme signs: its `signed` template, else `${t}.${body}` with a timestamp header, else the body. */ const hmacBase = (scheme: { timestampHeader?: string; signed?: string }, values: Record, body: string): string => scheme.signed !== undefined ? fillSigned(scheme.signed, values, body) : scheme.timestampHeader ? `${values.t}.${body}` : body; /** Every scheme's headers for one delivery, merged. */ export function signEventAll(schemes: EventScheme | ReadonlyArray, secret: string, body: string, seconds: number, url: string, messageId?: string, ctx: SignContext = {}): Record { return signPacket(schemes, secret, body, seconds, url, messageId, ctx).headers; } /** Every scheme applied to one attempt in its declared order: the headers merged, and the body as it is sent (a scheme * that places its signature in the body changes it, and a later scheme signs the changed body). */ export function signPacket(schemes: EventScheme | ReadonlyArray, secret: string, body: string, seconds: number, url: string, messageId?: string, ctx: SignContext = {}): { headers: Record; body: string } { let sent = body; const headers: Record = {}; for (const scheme of (Array.isArray(schemes) ? schemes : [schemes]) as ReadonlyArray) { const part = signPart(scheme, secret, sent, seconds, url, messageId, ctx); Object.assign(headers, part.headers); sent = part.body; } return { headers, body: sent }; } /** Reserve occurrences under the same cross-process lock that appends actions. This private retained row is never a * vendor resource. Deleted event/delivery rows, concurrent renders and restarts cannot give its ordinals back. */ async function reserveEventOrdinals(service: string, root: string | undefined, occurredAt: string, count: number): Promise { const { value } = await applyTwinWriteAtomic(service, (resources) => { const counter = resources.find((r) => r.type === '_world_event_sequence' && r.id === 'sequence'); const last = counter === undefined ? 0 : (counter as Record).last_ordinal; if (typeof last !== 'number' || !Number.isSafeInteger(last) || last < 0 || !Number.isSafeInteger(count) || count < 1 || !Number.isSafeInteger(last + count)) { throw new Error('Invalid retained declared-event sequence; occurrence ids cannot be reused.'); } return { kind: 'write', value: last + 1, write: { operation: 'world_event_sequence.reserve', subjectType: '_world_event_sequence', subjectId: 'sequence', fields: { last_ordinal: last + count }, input: { clock: true }, occurredAt, actor: { kind: 'system' }, } }; }, root); return value; } /** A delivery's signature checked as its receiver checks it (a Standard Webhooks verifier, a timestamp-v1 verifier, a plain * HMAC header, an Ed25519, OIDC or RSA verifier): true when one of its signatures is the one the secret makes (constant * time), or, for an asymmetric scheme, verifies under `secret` read as the public key or certificate (PEM), and its * timestamp, when the scheme sends one, is within `tolerance` seconds of `now`. `method` and `url` are the request's, * for a scheme that signs them. */ export function verifyEvent(scheme: EventScheme, secret: string, body: string, headers: Record, opts: { tolerance?: number; now?: number; method?: string; url?: string } = {}): boolean { const h = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v])); // a check given the time holds the timestamp to five minutes unless it says otherwise (Standard Webhooks' default) const fresh = (seconds: number): boolean => opts.now === undefined || Math.abs(opts.now - seconds) <= (opts.tolerance ?? 300); const url = opts.url ?? '', method = opts.method ?? 'POST'; if (secret === '') return false; if (scheme.kind === 'webhook-id') { const p = scheme.prefix.toLowerCase(); const id = h[`${p}-id`]; const seconds = Number(h[`${p}-timestamp`]); const given = h[`${p}-signature`]; if (!id || !given || !Number.isFinite(seconds) || !fresh(seconds)) return false; const expected = createHmac('sha256', webhookKey(scheme, secret)).update(`${id}.${seconds}.${body}`, 'utf8').digest('base64'); return given.split(' ').some((part) => part.startsWith('v1,') && same(part.slice('v1,'.length), expected)); } if (scheme.kind === 'timestamp-v1') { const parts = (h[scheme.header.toLowerCase()] ?? '').split(',').map((p) => p.split('=') as [string, string]); const seconds = Number(parts.find(([k]) => k === 't')?.[1]); if (!Number.isFinite(seconds) || !fresh(seconds)) return false; const expected = createHmac('sha256', secret).update(`${seconds}.${body}`, 'utf8').digest('hex'); return parts.some(([k, v]) => k === (scheme.version ?? 'v1') && v !== undefined && same(v, expected)); } if (scheme.kind === 'secret') { const given = h[scheme.header.toLowerCase()]; return given !== undefined && same(given, secret); } if (scheme.kind === 'hash') { const given = h[scheme.header.toLowerCase()]; return given !== undefined && same(given, hashOf(scheme, secret, body)); } if (scheme.kind === 'ed25519') { const seconds = Number(h[scheme.timestampHeader.toLowerCase()]); const given = h[scheme.header.toLowerCase()]; if (!given || !Number.isFinite(seconds) || !fresh(seconds)) return false; const signed = fillSigned(scheme.signed ?? '{t}{body}', signedValues(seconds, seconds * 1000, 's', body, url, method), body); return verifyWith(secret, signed, given, { encoding: scheme.encoding ?? 'hex' }); } if (scheme.kind === 'oidc-jwt') { const given = h[(scheme.header ?? 'authorization').toLowerCase()] ?? '', prefix = scheme.prefix ?? 'Bearer '; if (!given.startsWith(prefix)) return false; const token = given.slice(prefix.length), key = jwks(secret, scheme.kidPrefix); return opts.now === undefined ? jwtVerifySignature(token, key).valid : jwtVerify(token, key, { now: opts.now }).valid; } if (scheme.kind === 'rsa-x509') { let given: string | undefined, stamp: string | undefined, signedBody = body; if (scheme.at === 'body') { let json: Record; try { json = JSON.parse(body) as Record; } catch { return false; } given = typeof json[scheme.signature] === 'string' ? json[scheme.signature] as string : undefined; stamp = scheme.timestamp && json[scheme.timestamp.at] !== undefined ? String(json[scheme.timestamp.at]) : undefined; // the body as it was signed: without the signature and certificate URL placed in it after const rest = { ...json }; delete rest[scheme.signature]; delete rest[scheme.certUrlAt]; signedBody = JSON.stringify(rest); } else { given = h[scheme.signature.toLowerCase()]; stamp = scheme.timestamp ? h[scheme.timestamp.at.toLowerCase()] : undefined; } if (!given || (scheme.timestamp && stamp === undefined)) return false; const ms = stamp === undefined ? 0 : scheme.timestamp?.unit === 's' ? Number(stamp) * 1000 : scheme.timestamp?.unit === 'ms' ? Number(stamp) : Date.parse(stamp); if (stamp !== undefined && (!Number.isFinite(ms) || !fresh(Math.floor(ms / 1000)))) return false; const base = typeof scheme.signed === 'string' ? fillSigned(scheme.signed, signedValues(Math.floor(ms / 1000), ms, 's', signedBody, url, method), signedBody) : canonicalFields(scheme.signed.fields, signedBody); return verifyWith(secret, base, given, { encoding: scheme.encoding ?? 'base64' }); } const raw = scheme.timestampHeader ? Number(h[scheme.timestampHeader.toLowerCase()]) : undefined; const seconds = raw === undefined ? undefined : scheme.timestampUnit === 'ms' ? Math.floor(raw / 1000) : raw; if (seconds !== undefined && (!Number.isFinite(seconds) || !fresh(seconds))) return false; const values = signedValues(seconds ?? 0, raw === undefined ? 0 : scheme.timestampUnit === 'ms' ? raw : raw * 1000, scheme.timestampUnit, body, url, method); const expected = `${scheme.prefix ?? ''}${createHmac(scheme.algorithm ?? 'sha256', secret).update(hmacBase(scheme, values, body), 'utf8').digest(scheme.encoding)}`; return same(h[scheme.header.toLowerCase()] ?? '', expected); } /** The envelope template filled for one event, and for one endpoint when it names `$endpoint.` (left out when * there is none: the event as kept). A `...` key spreads its filled value into the object. */ export function fillEnvelope(template: unknown, values: Record, endpoint?: Record): unknown { if (typeof template === 'string') { if (template.startsWith('$endpoint.')) return endpoint ? at(endpoint, template.slice('$endpoint.'.length)) ?? undefined : undefined; return template.startsWith('$') && template in values ? values[template] : template; } if (Array.isArray(template)) return template.map((item) => fillEnvelope(item, values, endpoint)); // a key whose value is a `$` value left undefined is not sent (an event about no connected account has no `account`) if (template && typeof template === 'object') { const out: Record = {}; for (const [key, value] of Object.entries(template)) { const filled = fillEnvelope(value, values, endpoint); if (key === '...') { if (filled && typeof filled === 'object' && !Array.isArray(filled)) Object.assign(out, filled); continue; } if (filled !== undefined) out[key] = filled; } return out; } return template; } /** Whether an envelope template names an endpoint's fields (so each delivery's body is its own). */ const perEndpoint = (template: unknown): boolean => JSON.stringify(template ?? null).includes('"$endpoint.'); /** A row's field by a dotted path (`config.url`). */ function at(row: Record, path: string): unknown { let v: unknown = row; for (const key of path.split('.')) v = v && typeof v === 'object' ? (v as Record)[key] : undefined; return v; } /** An endpoint's row with its joined rows under their names (`app.hook_url` reads the installation's App). */ function joined(all: ReadonlyArray>, kind: EndpointsDecl, r: Record): Record { if (!kind.joins) return r; const out: Record = { ...r, id: r.id }; for (const [name, j] of Object.entries(kind.joins)) out[name] = all.find((x) => x.type === j.storedAs && x.deleted !== true && String(x.id) === String(at(r, j.by))); return out; } /** Whether an endpoint (joined) is live and can be sent to: not disabled, enabled, its status live, a URL (when the * delivery is made over HTTP) and its secret (when it declares one). */ const live = (kind: EndpointsDecl, r: Record, needsUrl = true): boolean => (kind.disabled === undefined || at(r, kind.disabled) !== true) && (kind.enabled === undefined || at(r, kind.enabled) !== false) && (kind.status === undefined || at(r, kind.status.field) === kind.status.live) && (!needsUrl || (kind.url !== undefined && typeof at(r, kind.url) === 'string')) && (kind.secret === undefined || typeof at(r, kind.secret) === 'string'); /** A delivery's endpoint (joined) as it is now, when it is still live. */ export function liveEndpoint(all: ReadonlyArray>, kind: EndpointsDecl, id: string, needsUrl = true): Record | undefined { const row = all.find((r) => r.type === kind.storedAs && r.deleted !== true && String(r.id) === id); const endpoint = row && joined(all, kind, row); return endpoint && live(kind, endpoint, needsUrl) ? endpoint : undefined; } /** The secret a delivery's attempt is signed with: its endpoint's as it is now (empty when its kind declares none), when * the endpoint is still live. */ export function endpointSecret(all: ReadonlyArray>, kind: EndpointsDecl, id: string, needsUrl = true): string | undefined { const endpoint = liveEndpoint(all, kind, id, needsUrl); return endpoint === undefined ? undefined : kind.secret === undefined ? '' : String(at(endpoint, kind.secret)); } /** A URL template filled from an endpoint: `{endpoint.}`. */ const fillUrl = (template: string, endpoint: Record): string => template.replace(/\{endpoint\.([^}]+)\}/g, (_whole, path: string) => { const v = at(endpoint, path); return v === undefined || v === null ? '' : String(v); }); /** The names of the attempt's own values, which a header or an envelope rendered at each attempt is filled with then. */ const ATTEMPT_VALUES: ReadonlySet = new Set(['$attempt', '$retry', '$retryReason', '$time.attempt.ms', '$time.attempt.s', '$time.attempt.iso']); /** A delivery's further headers: each a `$` value, an endpoint's `$endpoint.`, or written as it is; one naming an * attempt's own value is left for the attempt (`attemptHeaders`). */ function headersFor(templates: Record, values: Record, endpoint: Record): Record { const out: Record = {}; for (const [name, template] of Object.entries(templates)) { if (ATTEMPT_VALUES.has(template)) continue; const value = template.startsWith('$endpoint.') ? at(endpoint, template.slice('$endpoint.'.length)) : template.startsWith('$') ? values[template] : template; if (value !== undefined && value !== null) out[name.toLowerCase()] = String(value); } return out; } const knownSets = new WeakMap, Set>(); /** The event types a write's operation sends: `types`, else the vendor's enumerated types (`known`). */ export function eventTypesOf(decl: Pick, operation: string): string[] { const named = decl.types[operation]; if (named !== undefined) return typeof named === 'string' ? [named] : [...named]; const one = eventTypeOf(decl, operation); return one === undefined ? [] : [one]; } /** The event type a write's operation sends, if any: its first under `types`, else the vendor's enumerated types * (`known`). */ export function eventTypeOf(decl: Pick, operation: string): string | undefined { const given = decl.types[operation]; const named = typeof given === 'string' || given === undefined ? given : given[0]; if (named !== undefined || !decl.known) return named; let known = knownSets.get(decl.known); if (!known) knownSets.set(decl.known, known = new Set(decl.known)); if (known.has(operation)) return operation; const verb = /^(.+)\.(create|update|delete)$/.exec(operation); return verb && known.has(`${verb[1]}.${verb[2]}d`) ? `${verb[1]}.${verb[2]}d` : undefined; } /** Whether an endpoint's list of event types takes a type: every type when the list is empty, `*` or `.*` * its patterns, else the type itself. */ export function takesEvent(list: unknown, type: string): boolean { if (!Array.isArray(list) || list.length === 0) return true; return list.some((p) => { const s = String(p); return s === '*' || s === type || (s.endsWith('.*') && type.startsWith(s.slice(0, -1))); }); } /** The request that made the write, as an event's attributes name it: the client's address (the first hop a proxy * names) and its user agent. */ function requestValues(request: Request | undefined): Record { const forwarded = request?.headers.get('x-forwarded-for')?.split(',')[0]?.trim(); return { '$request.client_ip': forwarded ?? request?.headers.get('x-real-ip') ?? '', '$request.user_agent': request?.headers.get('user-agent') ?? '', }; } /** The World's transport: its application route (the app's own hostnames reach it inside the World) and its egress * rule (a refused destination is dropped as an unreachable endpoint is), never awaited by the write that sent it (deliverEvents schedules it after the answer). Loaded at * the first delivery, so importing the kernel stays free of Node's http. */ const worldTransport: EventTransport = async (url, body, headers) => { const [{ appDestination, appFetch }, { worldEgressRefusal }] = await Promise.all([ import('../app-route.cjs') as Promise<{ appDestination: (value: string) => unknown; appFetch: (url: string, init: RequestInit) => Promise }>, import('../network-policy.cjs') as Promise<{ worldEgressRefusal: (value: string, env?: NodeJS.ProcessEnv, method?: string) => unknown }>, ]); if (!appDestination(url) && worldEgressRefusal(url, process.env, 'POST') !== null) return 0; try { return ((await appFetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body })) as { status: number }).status; } catch { return 0; } }; const pendingDeliveries = new WeakMap>>>(); function forgetDeliveries(store: WorldStore, root: string, deliveries: Iterable>): void { const roots = pendingDeliveries.get(store), pending = roots?.get(root); if (!pending) return; for (const delivery of deliveries) pending.delete(delivery); if (!pending.size) roots!.delete(root); if (!roots!.size) pendingDeliveries.delete(store); } /** Await already-scheduled first dispatches and consume their retained persistence failures. */ export async function settleEventDeliveries(root: string): Promise { const store = getActiveWorldStore(), path = resolve(root); const deliveries = [...(pendingDeliveries.get(store)?.get(path) ?? [])]; const outcomes = await Promise.allSettled(deliveries); forgetDeliveries(store, path, deliveries); const failures = outcomes.flatMap((outcome) => outcome.status === 'rejected' ? [outcome.reason] : []); if (failures.length) throw new AggregateError(failures, 'Declared-event dispatch failed'); } /** Who watches signed packets before dispatch (a walk reading each as its receiver would). This is not evidence of * transport or acceptance. Set and restored by the walk, as its World store is; unset, nothing watches. */ export type DeliveryObserver = (delivery: EventDelivery & { service: string }) => void; let deliveryObserver: DeliveryObserver | undefined; export function setDeliveryObserver(observer: DeliveryObserver | undefined): DeliveryObserver | undefined { const previous = deliveryObserver; deliveryObserver = observer; return previous; } /** What the application's server answered a message the vendor waits on (its status, its headers by lower-cased name, * its body), or why it did not answer: `missed` when the World let no request out to it or it could not be reached * (`unreachable`), or it did not answer in time (`timeout`). */ export type ApplicationAnswer = { status: number; headers: Record; body: string; missed?: 'timeout' | 'unreachable' }; /** Who answers a vendor's requests to the application before the World's application route does, given to a * pack's fetch (`PackFetchOptions.application`) and belonging to that fetch alone: an answer it gives is the * application's; `'unreachable'` is a question nobody answers (a walk's life, a sealed World, takes no other); undefined * is a question it does not take, which goes on as any other does: the application route, the World's egress rule, the * network. A walk's stand-in answers every question (its life's answers, else unreachable); a hosted World's router * answers only what it can answer truthfully (WorldDoors.askInWorld) and leaves the rest. `bodyError` models a * disconnect after the response headers; a caller needing the complete body receives no complete answer, while an * event dispatch acknowledges the response status without reading its body. */ export type ApplicationStandIn = (url: string, init: RequestInit) => Promise<{ status: number; headers?: Record; body: string; bodyError?: string } | 'unreachable' | undefined>; /** A message the vendor sends the application's server and decides by its answer (Stripe's real-time authorization * request, answered within its window): over the same transport, waited on for at most `within` milliseconds, the * fetch's stand-in first when it was given one (its window the same). */ export async function askApplication(url: string, init: RequestInit, within: number, standIn?: ApplicationStandIn): Promise { if (standIn) { let timer: ReturnType | undefined; const late = new Promise<'late'>((done) => { timer = setTimeout(() => done('late'), within); }); const stood = await Promise.race([standIn(url, init), late]).finally(() => clearTimeout(timer)); if (stood === 'late') return { status: 0, headers: {}, body: '', missed: 'timeout' }; if (stood === 'unreachable') return { status: 0, headers: {}, body: '', missed: 'unreachable' }; if (stood !== undefined && stood.bodyError !== undefined) return { status: 0, headers: {}, body: '', missed: 'unreachable' }; if (stood !== undefined) return { status: stood.status, headers: Object.fromEntries(Object.entries(stood.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v])), body: stood.body }; } const [{ appDestination, appFetch }, { worldEgressRefusal }] = await Promise.all([ import('../app-route.cjs') as Promise<{ appDestination: (value: string) => unknown; appFetch: (url: string, init: RequestInit) => Promise<{ status: number; headers: Headers; text(): Promise }> }>, import('../network-policy.cjs') as Promise<{ worldEgressRefusal: (value: string, env?: NodeJS.ProcessEnv, method?: string) => unknown }>, ]); if (!appDestination(url) && worldEgressRefusal(url, process.env, init.method ?? 'GET') !== null) return { status: 0, headers: {}, body: '', missed: 'unreachable' }; const headers = new Headers(init.headers); for (const [k, v] of Object.entries(deliveryTraceHeaders())) if (!headers.has(k)) headers.set(k, v); try { const res = await appFetch(url, { ...init, headers, signal: AbortSignal.timeout(within) }); return { status: res.status, headers: Object.fromEntries(res.headers), body: await res.text() }; } catch (e) { return { status: 0, headers: {}, body: '', missed: e instanceof Error && (e.name === 'TimeoutError' || e.name === 'AbortError') ? 'timeout' : 'unreachable' }; } } /** Every event a write sends, rendered, stored when the vendor keeps its events, signed, delivered to each endpoint * that takes it, and recorded. */ export async function deliverEvents( service: string, decl: EventsDecl, write: EventWrite, data: (type: string) => Promise>, transport: EventTransport = worldTransport, values?: (type: string) => Promise>, application?: ApplicationStandIn, vendor?: string, ): Promise { if (write.storedType === decl.store) return; const dispatch: EventTransport = application ? async (url, body, headers) => { const answer = await application(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body }); return answer === undefined ? transport(url, body, headers) : answer === 'unreachable' ? 0 : answer.status; } : transport; for (const type of eventTypesOf(decl, write.operation)) await deliverEventType(service, decl, write, data, dispatch, values, type, vendor); } /** One event type a write sends: to the live endpoints that take it, stored when the vendor keeps its events. */ async function deliverEventType( service: string, decl: EventsDecl, write: EventWrite, data: (type: string) => Promise>, transport: EventTransport, values: ((type: string) => Promise>) | undefined, type: string, vendor: string | undefined, ): Promise { const all = twinResources(service, write.root) as unknown as Array>; const kinds = Array.isArray(decl.endpoints) ? decl.endpoints : [decl.endpoints as EndpointsDecl]; const via = decl.transport ?? 'http'; const takers = kinds.filter((kind) => (!kind.types || kind.types.includes(type)) && !kind.skip?.includes(type)).flatMap((kind) => all .filter((r) => r.type === kind.storedAs && r.deleted !== true) .map((r) => joined(all, kind, r)) .filter((r) => live(kind, r, via === 'http')) .filter((r) => kind.filter === undefined || takesEvent(at(r, kind.filter), type)) .map((row) => ({ row, kind }))); if (takers.length === 0 && decl.store === undefined) return; const millis = Date.parse(write.occurredAt) || 0; const seconds = Math.floor(millis / 1000); const eventData = await data(type); const extra = values ? await values(type) : {}; // Reserve one event and at most one delivery per live endpoint before assigning identities. Unused ordinals are // harmless gaps; a failed render/store never gives them back. This is not an atomic originating-write outbox. const ordinal = await reserveEventOrdinals(service, write.root, write.occurredAt, 1 + takers.length); // Fresh/forked Worlds can reserve the same ordinal at a pinned clock. Keep // content binding as well as the lineage's occurrence ordinal, so different // event payloads cannot reuse a receiver's event/webhook id across those Worlds. const eventContent = createHash('sha256').update(JSON.stringify({ operation: write.operation, type, data: eventData, envelope: decl.envelope, values: extra, request: requestValues(write.request), }), 'utf8').digest('hex'); const filled: Record = { $type: type, $data: eventData, $id: `evt_${ksuidFrom(seconds, ordinal, `world-events:v1:${service}:${type}:${ordinal}:${eventContent}`)}`, '$time.ms': millis, '$time.s': seconds, '$time.iso': write.occurredAt, ...requestValues(write.request), ...extra, }; const envelope = fillEnvelope(decl.envelope, filled); const endpoints = extra.$send === false ? [] : takers .filter(({ row, kind }) => kind.scope === undefined || (at(row, kind.scope.field) === true) === (filled[kind.scope.value] !== undefined)) .filter(({ row, kind }) => matches(row, kind.match, filled)); if (decl.store !== undefined) { // kept with the deliveries it waits on, as many as the endpoints it goes to (`pending`) const fields = decl.pending !== undefined ? { ...(envelope as Record), [decl.pending]: endpoints.length } : envelope as Record; await applyTwinWrite(service, { operation: `${decl.store}.record`, subjectType: decl.store, subjectId: String(filled.$id), fields, occurredAt: write.occurredAt, actor: { kind: 'system' } }, write.root); } if (endpoints.length === 0) return; const shared = JSON.stringify(envelope); const each = perEndpoint(decl.envelope); const schedule = retrySchedule(decl.retry); const record = decl.record ?? '_world_event_delivery'; // the headers an attempt fills itself (its number, the retry's reason), kept as declared const attemptHeaders = Object.fromEntries(Object.entries(decl.headers ?? {}).filter(([, template]) => ATTEMPT_VALUES.has(template)).map(([name, template]) => [name.toLowerCase(), template])); const batchWithin = decl.batch?.within !== undefined ? durationMs(decl.batch.within) : 0; const recorded: Array<{ type: string; id: string }> = []; let held = false; for (const [i, { row, kind }] of endpoints.entries()) { const body = each ? JSON.stringify(fillEnvelope(decl.envelope, filled, row)) : shared; // where the delivery goes, and how: the endpoint's URL; another vendor's operation, its request's body and headers // filled from the endpoint now and from the event at each attempt; a socket's frame, likewise const url = via === 'http' ? String(at(row, kind.url!)) : 'twin' in via ? fillUrl(via.twin.url, row) : `socket:${via.socket}`; const carried = via === 'http' ? 'http' : 'twin' in via ? { twin: { method: via.twin.method ?? 'POST', body: fillEnvelope(via.twin.body ?? '$event', filled, row) ?? null, headers: headersFor(via.twin.headers ?? {}, filled, row) } } : { socket: via.socket, session: via.session ?? 'endpoint', frame: fillEnvelope(via.frame ?? '$event', filled, row) ?? null }; const seq = ordinal + 1 + i; const deliveryContent = createHash('sha256').update(url, 'utf8').update('\0').update(body, 'utf8').digest('hex'); const identity = `world-events:v1:${service}:${seq}:${deliveryContent}`; // kept with the write, by an id of the delivery itself (two made at once never take the same one), with what each // attempt signs anew: the scheme, the endpoint its secret is read from, and the message id every attempt carries. // `headers` are the declared further headers; the signature's are an attempt's own. const id = `${record.slice(1)}_v1_${seq}`; const packet = { url, body, headers: decl.headers ? headersFor(decl.headers, filled, row) : {}, event_type: type, sent_at: millis, delivery_protocol: 2, event_id: String(filled.$id), message_id: `msg_${ksuidFrom(seconds, seq, identity)}`, scheme: decl.scheme, retry_ms: schedule.delays, endpoint_type: kind.storedAs, endpoint_id: String(row.id), endpoint: kind, vendor: vendor ?? null, delivery_state: 'queued', due_at: millis, attempt_count: 0, current_attempt: null, transport_status: null, finished_at: null, accepted_at: null, seq, transport: carried, attempt_headers: attemptHeaders, timeout_ms: decl.timeout !== undefined ? durationMs(decl.timeout) : null, ...(schedule.undocumented ? { retry_undocumented: true } : {}), // the stored event whose count of deliveries not yet accepted this one's first acceptance lowers ...(decl.store !== undefined && decl.pending !== undefined ? { pending: { store: decl.store, field: decl.pending } } : {}), // rendered again at each attempt: the envelope, the write's values and the write itself are kept to render it from ...(decl.renderAt === 'attempt' ? { render: { envelope: decl.envelope ?? null, values: filled, write: { operation: write.operation, storedType: write.storedType, body: write.body, occurredAt: write.occurredAt } } } : {}), ...(decl.batch ? { batch_max: Math.max(1, Math.floor(decl.batch.max)) } : {}), }; await applyTwinWrite(service, { operation: `${record.slice(1)}.record`, subjectType: record, subjectId: id, fields: packet, occurredAt: write.occurredAt, actor: { kind: 'system' } }, write.root); // a webhook fault the World's scenario placed (architecture, "Scenarios"): the first attempt held until the World's // clock reaches its delay, or the event sent twice; a drop lands on the attempts themselves (event-delivery.ts) const ledger = vendor ? serviceLedger({ vendor, service, root: write.root, at: write.occurredAt, recording: true }) : undefined; const fault = ledger ? webhookFault(ledger, type, ['webhook-delay', 'webhook-duplicate']) : undefined; if (fault?.kind === 'webhook-delay') { await recordFault(ledger!, fault, { event: type, delivery: id }); await applyTwinWrite(service, { operation: `${record.slice(1)}.record`, subjectType: record, subjectId: id, fields: { delivery_state: 'held', due_at: millis + durationMs(fault.by!) }, occurredAt: write.occurredAt, actor: { kind: 'system' } }, write.root); held = true; continue; } // a batched event waits for the others its window gathers, in World time; the first attempt made gathers them if (batchWithin > 0) { await applyTwinWrite(service, { operation: `${record.slice(1)}.record`, subjectType: record, subjectId: id, fields: { delivery_state: 'held', due_at: millis + batchWithin }, occurredAt: write.occurredAt, actor: { kind: 'system' } }, write.root); held = true; continue; } recorded.push({ type: record, id }); if (fault?.kind === 'webhook-duplicate') { await recordFault(ledger!, fault, { event: type, delivery: id }); const twin = `${id}_duplicate`; await applyTwinWrite(service, { operation: `${record.slice(1)}.record`, subjectType: record, subjectId: twin, fields: packet, occurredAt: write.occurredAt, actor: { kind: 'system' } }, write.root); recorded.push({ type: record, id: twin }); } } // sent after the write's answer, as a vendor sends it: the caller never waits on its receiver, and a receiver that is // slow or down fails no request // the write's trace is read now, inside its request, and carried on each delivery (W3C trace continuation) const trace = deliveryTraceHeaders(); // A timer must retain the request's store/root even if another World becomes // active before it runs. Transport completion writes to the same retained state. const store = getActiveWorldStore(), deliveryRoot = worldPaths(service, write.root).root; if (held) heldListeners.get(deliveryRoot)?.(); dispatchRecorded(service, store, deliveryRoot, recorded, transport, trace); } /** Each recorded packet's next attempt made after the write's answer, keeping its request's store and root; one that * failed and is held for its next attempt tells who sets the timer a running clock needs. */ function dispatchRecorded(service: string, store: WorldStore, deliveryRoot: string, recorded: ReadonlyArray<{ type: string; id: string }>, transport: EventTransport, trace: Record): void { const roots = pendingDeliveries.get(store) ?? new Map>>(); pendingDeliveries.set(store, roots); const pending = roots.get(deliveryRoot) ?? new Set>(); roots.set(deliveryRoot, pending); const observed: EventTransport = (url, body, headers) => { deliveryObserver?.({ url, body, headers, service }); return transport(url, body, headers); }; for (const packet of recorded) { let finish!: () => void; let fail!: (reason: unknown) => void; const dispatched = new Promise((done, reject) => { finish = done; fail = reject; }); // Live writes return before dispatch; an explicit settlement reports persistence failures. void dispatched.catch(() => {}); pending.add(dispatched); setTimeout(async () => { try { const held = await withWorldStore(store, () => attemptDelivery(service, packet.type, packet.id, deliveryRoot, observed, trace)); finish(); forgetDeliveries(store, deliveryRoot, [dispatched]); if (held) heldListeners.get(deliveryRoot)?.(); } catch (error) { // Keep the rejection until explicit settlement consumes it. The queued/sending claim remains for // native recovery; this must not fail the already-committed vendor write or cause a blind resend. fail(error); } }, 0); } } const heldListeners = new Map void>(); /** Who hears that a twin held a packet for a later attempt (its pack's fetch, which sets the timer a running clock * needs). */ export function onHeldDelivery(service: string, root: string | undefined, listener: () => void): void { heldListeners.set(worldPaths(service, root).root, listener); } /** How a pack renders an event's `data` again at an attempt (`renderAt: 'attempt'`): its render, called with the write * as it was kept and the attempt's number. */ export type AttemptRender = (write: EventWrite, type: string) => Promise>; const attemptRenderers = new Map(); /** Who renders a twin's events again at each attempt (its pack's fetch, over the pack's render). */ export function onAttemptRender(service: string, root: string | undefined, render: AttemptRender): void { attemptRenderers.set(worldPaths(service, root).root, render); } /** The render a twin's attempts call, if its pack's fetch gave one; without it an attempt fills the envelope again with * the write's own `data`. */ export const attemptRenderer = (deliveryRoot: string): AttemptRender | undefined => attemptRenderers.get(deliveryRoot); /** Send a delivery again by hand under its own delivery and message ids (GitHub's redelivery, which a pack's door * calls): one that is not queued, held, being sent or gathered into a batch is queued for one more attempt, signed * then and made after this answers, and not retried after. Answers whether it was queued. */ export async function redeliverEvent(service: string, root: string | undefined, deliveryId: string, record = '_world_event_delivery', transport: EventTransport = worldTransport): Promise { const at = worldNow(); const { value } = await applyTwinWriteAtomic(service, (resources) => { const row = resources.find((r) => r.type === record && r.id === deliveryId); if (!row || row.deleted === true || ['queued', 'held', 'sending', 'batched'].includes(String(row.delivery_state))) return { kind: 'skip', value: false }; return { kind: 'write', value: true, write: { operation: `${record.slice(1)}.redeliver`, subjectType: record, subjectId: deliveryId, fields: { delivery_state: 'queued', due_at: Date.parse(at), redelivery: true, redelivered: Number(row.redelivered ?? 0) + 1 }, occurredAt: at, actor: { kind: 'system' as const }, } }; }, root); if (value) dispatchRecorded(service, getActiveWorldStore(), worldPaths(service, root).root, [{ type: record, id: deliveryId }], transport, deliveryTraceHeaders()); return value; } /** Make every held attempt the World's clock has reached, in the order it fell due, and wait until each is made; a * failed one held again for an attempt the clock has also reached is made in turn. Answer the instant the next held * attempt falls due, if any (ADR 0036 §4: the mover of the clock waits on it). */ export async function releaseHeldDeliveries(service: string, root: string | undefined, record = '_world_event_delivery', transport: EventTransport = worldTransport): Promise { const deliveryRoot = worldPaths(service, root).root; const held = () => twinResources(service, root).filter((r) => r.type === record && r.deleted !== true && r.delivery_state === 'held').sort((a, b) => Number(a.due_at) - Number(b.due_at)); for (;;) { const now = Date.parse(worldNow()); const due = held().filter((r) => Number(r.due_at) <= now); if (due.length === 0) break; for (const r of due) await applyTwinWrite(service, { operation: `${record.slice(1)}.release`, subjectType: record, subjectId: r.id, fields: { delivery_state: 'queued' }, occurredAt: worldNow(), actor: { kind: 'system' } }, root); dispatchRecorded(service, getActiveWorldStore(), deliveryRoot, due.map((r) => ({ type: record, id: r.id })), transport, {}); await settleEventDeliveries(deliveryRoot); } const next = held()[0]; return next ? new Date(Number(next.due_at)).toISOString() : null; }