@secondlayer/subgraphs 7.6.0 → 7.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@
2
2
  "version": 3,
3
3
  "sources": ["src/runtime/emitter.ts", "src/runtime/formats/index.ts", "src/runtime/formats/cloudevents.ts", "src/runtime/formats/cloudflare.ts", "src/runtime/formats/inngest.ts", "src/runtime/formats/raw.ts", "src/runtime/formats/standard-webhooks.ts", "src/runtime/formats/trigger.ts", "src/runtime/meter-socket.ts", "src/runtime/receiver-cert.ts"],
4
4
  "sourcesContent": [
5
- "import { randomUUID } from \"node:crypto\";\nimport { lookup as dnsLookup } from \"node:dns/promises\";\nimport {\n\ttype Database,\n\ttype Webhook,\n\ttype WebhookOutbox,\n\tdescribeDbUrl,\n\tgetTargetDb,\n} from \"@secondlayer/shared/db\";\nimport { getWebhookSigningSecret } from \"@secondlayer/shared/db/queries/webhooks\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { listen, targetListenerUrl } from \"@secondlayer/shared/queue/listener\";\nimport {\n\ttype WebhookTestResult,\n\twebhookTimeoutMsCeiling,\n} from \"@secondlayer/shared/schemas/webhooks\";\nimport { type Kysely, sql } from \"kysely\";\nimport { buildForFormat } from \"./formats/index.ts\";\nimport { recordDelivery } from \"./meter-socket.ts\";\nimport { refreshReceiverCerts } from \"./receiver-cert.ts\";\n\n/**\n * Webhook emitter — drains `webhook_outbox` and POSTs deliveries.\n *\n * Hot path: LISTEN on `webhooks:new_outbox` and `webhooks:changed`.\n * On notify, claim a batch with `FOR UPDATE SKIP LOCKED LIMIT 50`, dispatch\n * each row via HTTP, write a `webhook_deliveries` attempt row, then\n * either mark `status='delivered'` or schedule the next attempt.\n *\n * Backoff schedule (attempt → wait):\n * 0 → 30s, 1 → 2m, 2 → 10m, 3 → 1h, 4 → 6h, 5 → 24h, 6 → 72h.\n * After `max_retries` (default 7) attempts → `status='dead'`.\n *\n * Per-sub circuit breaker: 20 consecutive failures → sub flipped to\n * `paused` with `circuit_opened_at=NOW()`. Manual /resume drains backlog.\n *\n * Per-sub concurrency cap: in-memory semaphore, default 4 in-flight HTTP\n * requests per webhook. Sprint-4 adds SSRF allowlist.\n */\n\nconst BATCH_SIZE = 50;\nconst LIVE_SHARE = 0.9; // 90% of batch to non-replay, 10% to replay\nconst BACKOFF_SECONDS = [30, 120, 600, 3600, 21600, 86400, 259200];\nconst CIRCUIT_THRESHOLD = 20;\n/**\n * When a batch is claimed the outbox row's `next_attempt_at` is pushed\n * `LOCK_WINDOW_MS` into the future. Any crash between claim + settle\n * leaves the row re-claimable after this window expires — the SSOT for\n * double-dispatch prevention.\n *\n * Must exceed the maximum possible in-flight delivery time so a slow-but-alive\n * receiver's row is never re-claimed mid-delivery (duplicate dispatch). Derived\n * from the configurable timeout ceiling (`WEBHOOK_TIMEOUT_MS_CEILING`, default\n * 300_000ms — see `webhookTimeoutMsCeiling` in shared/schemas/webhooks.ts) so a\n * raised ceiling can never create a delivery window shorter than a webhook's\n * own timeout.\n */\nexport const MAX_WEBHOOK_TIMEOUT_MS: number = webhookTimeoutMsCeiling();\nexport const LOCK_WINDOW_MS: number = MAX_WEBHOOK_TIMEOUT_MS + 60_000; // ceiling + settle margin\n\n/** A sub's persistent delivery queue + in-flight counter. Lives for as long\n * as the sub has (or recently had) work — see `enqueueForSub`/`pumpSub`.\n * `sub` is refreshed on every enqueue so a status/concurrency change (a\n * pause, a resume, a config edit) is picked up by the next batch of rows\n * without waiting for anything to expire. */\ninterface SubQueue {\n\tsub: Webhook;\n\tqueue: WebhookOutbox[];\n\tinFlight: number;\n}\n\ninterface RunningState {\n\trunning: boolean;\n\t/** Per-webhook queue + concurrency counter — see `SubQueue`. Replaces a\n\t * bare in-flight counter so dispatch can be decoupled from the claim\n\t * transaction (see `claimAndDispatchOnce`): claiming a batch no longer\n\t * waits for a sub's HTTP calls to finish before the NEXT claim can run,\n\t * it just hands rows to that sub's queue and returns. */\n\tsubQueues: Map<string, SubQueue>;\n\tclaimInFlight: boolean;\n\t/** Set when a wake (NOTIFY) arrives while a claim cycle is already\n\t * running. The in-flight cycle checks this before releasing the lock —\n\t * see `claimAndDrain`'s \"drain-loop\" pass — so rows that land mid-drain\n\t * aren't stranded until an unrelated future wake or the safety poll. */\n\tclaimPending: boolean;\n\t/** The promise of whichever `claimAndDrain` call currently owns\n\t * `claimInFlight` (assigned by that call itself, before its first\n\t * `await`, so there is no race with a concurrent caller that just sets\n\t * `claimPending` and returns). `stopEmitter`'s clean-stop path awaits\n\t * this so shutdown doesn't race a claim pass that's mid-dispatch. */\n\tcurrentClaim: Promise<number> | null;\n\t/** Every `runOne` promise currently dispatching, added by `pumpSub` at\n\t * start and removed on settle. `stopEmitter` awaits this set (bounded)\n\t * so it never reports \"stopped\" while a delivery is still mid-flight. */\n\tinFlightRuns: Set<Promise<void>>;\n}\n\nfunction nextDelaySeconds(attempt: number): number {\n\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\treturn BACKOFF_SECONDS[Math.min(attempt, BACKOFF_SECONDS.length - 1)]!;\n}\n\n// ── SSRF guard ────────────────────────────────────────────────────────\n// Block deliveries to private/loopback/link-local ranges unless\n// SECONDLAYER_ALLOW_PRIVATE_EGRESS=true (self-host + local-dev opt-in).\n\nconst PRIVATE_V4_PATTERNS = [\n\t/^127\\./, // loopback\n\t/^10\\./, // private class A\n\t/^172\\.(1[6-9]|2\\d|3[01])\\./, // private class B\n\t/^192\\.168\\./, // private class C\n\t/^169\\.254\\./, // link-local\n\t/^0\\./, // \"this\" network\n\t/^100\\.(6[4-9]|[7-9]\\d|1[01]\\d|12[0-7])\\./, // CGNAT 100.64/10\n\t/^198\\.(1[89])\\./, // benchmarking 198.18.0.0/15\n\t/^(22[4-9]|23[0-9])\\./, // multicast 224.0.0.0/4\n\t/^(24[0-9]|25[0-5])\\./, // reserved 240.0.0.0/4 (incl. 255.255.255.255 broadcast)\n];\n\n/**\n * Classify a raw IP address literal (v4 or v6, no brackets, already lowercased\n * or not) as private/loopback/link-local/reserved. Covers v4 private ranges +\n * link-local (incl. `169.254.169.254`), `0.0.0.0`, benchmarking\n * (`198.18.0.0/15`), multicast (`224.0.0.0/4`), reserved/broadcast\n * (`240.0.0.0/4`, incl. `255.255.255.255`), IPv6 loopback (`::1`), unspecified\n * (`::`), unique-local (`fc00::/7`), link-local (`fe80::/10`), IPv6 multicast\n * (`ff00::/8`), IPv4-mapped IPv6 (`::ffff:127.0.0.1`, `::ffff:7f00:0001`), and\n * NAT64 (`64:ff9b::/96`, embedded v4 classified the same as IPv4-mapped).\n *\n * Shared by `isPrivateEgress` (literal-hostname fast-fail) and the resolved-\n * DNS-address check in `checkEgressAllowed` (rebinding mitigation).\n */\nfunction isPrivateIp(address: string): boolean {\n\tconst host = address.toLowerCase();\n\n\tif (host === \"0.0.0.0\") return true;\n\tif (host === \"::\" || host === \"::1\") return true;\n\t// Unique-local (fc00::/7) + link-local (fe80::/10) + multicast (ff00::/8)\n\tif (/^f[cd][0-9a-f]{2}:/.test(host)) return true;\n\tif (/^fe[89ab][0-9a-f]:/.test(host)) return true;\n\tif (/^ff[0-9a-f]{2}:/.test(host)) return true;\n\n\t// IPv4-mapped IPv6 — `::ffff:127.0.0.1` or `::ffff:7f00:0001`\n\tconst mapped = host.match(/^::ffff:(.+)$/);\n\tif (mapped) {\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\tconst inner = mapped[1]!;\n\t\t// Dotted form: rerun v4 checks.\n\t\tif (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(inner)) {\n\t\t\tfor (const p of PRIVATE_V4_PATTERNS) if (p.test(inner)) return true;\n\t\t}\n\t\t// Hex form: 7f00:0001 → 127.0.0.1\n\t\tconst hex = inner.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n\t\tif (hex) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst a = Number.parseInt(hex[1]!, 16);\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst b = Number.parseInt(hex[2]!, 16);\n\t\t\tconst dotted = `${(a >> 8) & 0xff}.${a & 0xff}.${(b >> 8) & 0xff}.${b & 0xff}`;\n\t\t\tfor (const p of PRIVATE_V4_PATTERNS) if (p.test(dotted)) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t// NAT64 (`64:ff9b::/96`) embeds an IPv4 address in the low 32 bits —\n\t// classify it exactly like the IPv4-mapped case above (dotted or hex).\n\tconst nat64 = host.match(/^64:ff9b::(.+)$/);\n\tif (nat64) {\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\tconst inner = nat64[1]!;\n\t\tif (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(inner)) {\n\t\t\tfor (const p of PRIVATE_V4_PATTERNS) if (p.test(inner)) return true;\n\t\t}\n\t\tconst hex = inner.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n\t\tif (hex) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst a = Number.parseInt(hex[1]!, 16);\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst b = Number.parseInt(hex[2]!, 16);\n\t\t\tconst dotted = `${(a >> 8) & 0xff}.${a & 0xff}.${(b >> 8) & 0xff}.${b & 0xff}`;\n\t\t\tfor (const p of PRIVATE_V4_PATTERNS) if (p.test(dotted)) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tfor (const p of PRIVATE_V4_PATTERNS) {\n\t\tif (p.test(host)) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Reject hostnames spelled as private IPs (cheap, synchronous, no I/O — a\n * fast-fail pre-filter). DNS-level rebinding (hostname that *resolves* to a\n * private IP at egress time) is NOT caught here — see `checkEgressAllowed`,\n * which resolves DNS and validates every returned address.\n */\nfunction isPrivateEgress(url: string): boolean {\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch {\n\t\treturn true; // malformed URL: reject\n\t}\n\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n\t\treturn true;\n\t}\n\n\t// Strip brackets from IPv6 literals.\n\tconst raw = parsed.hostname.toLowerCase();\n\tconst host =\n\t\traw.startsWith(\"[\") && raw.endsWith(\"]\") ? raw.slice(1, -1) : raw;\n\n\tif (host === \"localhost\") return true;\n\treturn isPrivateIp(host);\n}\n\n/** How often the emitter re-probes receivers' TLS certificates. */\nconst RECEIVER_CERT_INTERVAL_MS = 30 * 60_000;\n\nexport function allowPrivateEgress(): boolean {\n\treturn process.env.SECONDLAYER_ALLOW_PRIVATE_EGRESS === \"true\";\n}\n\ninterface ResolvedAddress {\n\taddress: string;\n\tfamily: number;\n}\n\ntype DnsLookupFn = (hostname: string) => Promise<ResolvedAddress[]>;\n\nasync function defaultDnsLookup(hostname: string): Promise<ResolvedAddress[]> {\n\treturn dnsLookup(hostname, { all: true });\n}\n\nlet dnsLookupImpl: DnsLookupFn = defaultDnsLookup;\n\n/**\n * Test-only seam: inject a fake DNS resolver so tests can simulate a hostname\n * resolving to a private/metadata IP without depending on real DNS or\n * network access. Pass `null` to restore the real `dns.lookup`-backed\n * resolver. Production code never calls this — only `ssrf.test.ts` does.\n */\nexport function __setDnsLookupForTest(fn: DnsLookupFn | null): void {\n\tdnsLookupImpl = fn ?? defaultDnsLookup;\n}\n\nconst ALLOW_HINT = \"(set SECONDLAYER_ALLOW_PRIVATE_EGRESS=true to allow)\";\n\n/**\n * Full egress check: literal fast-fail, then resolve DNS and reject if *any*\n * returned address (not just the first) is private/loopback/link-local —\n * a single private answer among several is enough for an attacker to abuse.\n *\n * Residual TOCTOU: this resolves-and-validates *immediately before* `fetch()`\n * but does not pin the actual connection to the validated address. True\n * pinning (resolve once, connect to that literal IP, keep the original `Host`\n * header/SNI) was attempted per plan f053 via a custom undici `Agent` with\n * `connect.lookup` passed as `fetch()`'s `dispatcher` — the standard Node\n * ecosystem pattern for this. Empirically, under Bun 1.3.10, that hook was\n * silently never invoked (confirmed with a throwaway smoke test hitting a\n * real local HTTP server: `lookupCalled` stayed `false` and the connection\n * failed even though the dispatcher was passed) — Bun's `fetch()` does not\n * implement undici's `connect.lookup` dispatcher hook, whether reached via\n * the global `fetch` or `import { fetch } from \"undici\"` (Bun overrides\n * \"undici\"'s `fetch` export with its own native implementation regardless of\n * an installed real `undici` package). Re-tested under Bun 1.4.2 (plan 043):\n * identical result — `lookupCalled` still stays `false` via both the global\n * `fetch` and `import { fetch } from \"undici\"`, so the gap remains unfixed at\n * this version too. So a second DNS answer between this check and `fetch()`'s\n * own resolution (true rebinding, not just a one-time private answer) could\n * in theory still slip through. This closes the practical rebinding gap\n * (attacker's hostname resolves private at delivery time) without adding a\n * dependency; a network-level egress allowlist/proxy is the recommended\n * defense-in-depth for the remaining TOCTOU sliver.\n */\nexport async function checkEgressAllowed(url: string): Promise<string | null> {\n\tif (isPrivateEgress(url)) {\n\t\treturn `refused private egress: literal address ${ALLOW_HINT}`;\n\t}\n\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch {\n\t\treturn `refused private egress: malformed URL ${ALLOW_HINT}`;\n\t}\n\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n\t\treturn `refused private egress: unsupported protocol ${ALLOW_HINT}`;\n\t}\n\n\tconst raw = parsed.hostname.toLowerCase();\n\tconst hostname =\n\t\traw.startsWith(\"[\") && raw.endsWith(\"]\") ? raw.slice(1, -1) : raw;\n\n\tlet resolved: ResolvedAddress[];\n\ttry {\n\t\tresolved = await dnsLookupImpl(hostname);\n\t} catch (err) {\n\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\treturn `refused private egress: DNS resolution failed (${msg}) ${ALLOW_HINT}`;\n\t}\n\tif (resolved.length === 0) {\n\t\treturn `refused private egress: DNS resolution returned no addresses ${ALLOW_HINT}`;\n\t}\n\tfor (const { address } of resolved) {\n\t\tif (isPrivateIp(address)) {\n\t\t\treturn `refused private egress: hostname resolves to private address ${address} ${ALLOW_HINT}`;\n\t\t}\n\t}\n\treturn null;\n}\n\n/** The wire result of one POST attempt (no DB side effect) — shared by the\n * emitter hot path and the `deliverTestEvent` test path. */\ninterface PostResult {\n\tok: boolean;\n\tstatusCode: number | null;\n\terror: string | null;\n\tdurationMs: number;\n\tresponseBody: string | null;\n\tresponseHeaders: Record<string, string> | null;\n}\n\n/**\n * Bound on redirect hops honored while delivering a webhook. `fetch` is\n * called with `redirect: \"manual\"` so a 3xx never auto-follows — each hop's\n * target is re-validated through `checkEgressAllowed` before it is fetched\n * (see `postToWebhook`), otherwise a `Location` header pointing at a\n * private/metadata address would bypass the egress guard entirely. Counts\n * every fetch issued (the initial request plus each redirect), so this is\n * also the max number of `fetch` calls one delivery attempt can make.\n */\nexport const MAX_REDIRECT_HOPS: number = 3;\n\n/** POST a pre-built body to a webhook URL with the SSRF guard + timeout.\n * Pure transport: returns the attempt result; the caller logs the delivery row.\n * Follows redirects manually (up to `MAX_REDIRECT_HOPS`), re-running the\n * egress guard against every hop's target — the guard only protects the\n * first request otherwise, and a webhook target can redirect to a private/\n * metadata address to read back the response after f053 pinned the guard to\n * just the original URL. */\nasync function postToWebhook(\n\turl: string,\n\tbody: string,\n\theaders: Record<string, string>,\n\ttimeoutMs: number,\n): Promise<PostResult> {\n\tconst start = performance.now();\n\tlet target = url;\n\tlet statusCode: number | null = null;\n\tlet error: string | null = null;\n\tlet ok = false;\n\tlet responseBody = \"\";\n\tlet responseHeaders: Record<string, string> | null = null;\n\ttry {\n\t\tfor (let hop = 0; ; hop++) {\n\t\t\tif (!allowPrivateEgress()) {\n\t\t\t\tconst refusal = await checkEgressAllowed(target);\n\t\t\t\tif (refusal) {\n\t\t\t\t\tlogger.warn(\"[emitter] refused private egress\", {\n\t\t\t\t\t\turl: target,\n\t\t\t\t\t\treason: refusal,\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\tstatusCode: null,\n\t\t\t\t\t\terror: refusal,\n\t\t\t\t\t\tdurationMs: Math.round(performance.now() - start),\n\t\t\t\t\t\tresponseBody: null,\n\t\t\t\t\t\tresponseHeaders: null,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hop >= MAX_REDIRECT_HOPS) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tstatusCode,\n\t\t\t\t\terror: `too many redirects (exceeded ${MAX_REDIRECT_HOPS} hops)`,\n\t\t\t\t\tdurationMs: Math.round(performance.now() - start),\n\t\t\t\t\tresponseBody: null,\n\t\t\t\t\tresponseHeaders: null,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst res = await fetch(target, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders,\n\t\t\t\tbody,\n\t\t\t\tredirect: \"manual\",\n\t\t\t\tsignal: AbortSignal.timeout(timeoutMs),\n\t\t\t});\n\t\t\tstatusCode = res.status;\n\n\t\t\tconst location = res.headers.get(\"location\");\n\t\t\tif (res.status >= 300 && res.status < 400 && location) {\n\t\t\t\ttarget = new URL(location, target).toString();\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tok = res.ok;\n\t\t\t// Collect small response preview for the delivery log (≤8KB).\n\t\t\tconst buf = await res.arrayBuffer();\n\t\t\tconst truncated = buf.byteLength > 8192 ? buf.slice(0, 8192) : buf;\n\t\t\tresponseBody = Buffer.from(truncated).toString(\"utf8\");\n\t\t\tresponseHeaders = Object.fromEntries(res.headers.entries());\n\t\t\tbreak;\n\t\t}\n\t} catch (err) {\n\t\terror = err instanceof Error ? err.message : String(err);\n\t}\n\treturn {\n\t\tok,\n\t\tstatusCode,\n\t\terror,\n\t\tdurationMs: Math.round(performance.now() - start),\n\t\tresponseBody: responseBody || null,\n\t\tresponseHeaders,\n\t};\n}\n\n/**\n * Test-only seam: exposes `postToWebhook` (otherwise module-private) so\n * redirect/egress behavior can be exercised directly against a stubbed\n * `fetch` + injected DNS lookup, without standing up the DB-backed emitter\n * loop. Production code never calls this — only tests do.\n */\nexport const __postToWebhookForTest: (\n\turl: string,\n\tbody: string,\n\theaders: Record<string, string>,\n\ttimeoutMs: number,\n) => Promise<PostResult> = postToWebhook;\n\nasync function dispatchOne(\n\tdb: Kysely<Database>,\n\toutboxRow: WebhookOutbox,\n\tsub: Webhook,\n): Promise<{\n\tok: boolean;\n\tstatusCode: number | null;\n\terror: string | null;\n\tdurationMs: number;\n}> {\n\tconst { body, headers } = buildForFormat(\n\t\toutboxRow,\n\t\tsub,\n\t\tgetWebhookSigningSecret(sub),\n\t);\n\tconst r = await postToWebhook(sub.url, body, headers, sub.timeout_ms);\n\n\tconst attempt = outboxRow.attempt + 1;\n\tawait db\n\t\t.insertInto(\"webhook_deliveries\")\n\t\t.values({\n\t\t\toutbox_id: outboxRow.id,\n\t\t\twebhook_id: outboxRow.webhook_id,\n\t\t\tattempt,\n\t\t\tstatus_code: r.statusCode,\n\t\t\tresponse_headers: r.responseHeaders,\n\t\t\tresponse_body: r.responseBody,\n\t\t\terror_message: r.error,\n\t\t\tduration_ms: r.durationMs,\n\t\t})\n\t\t.execute();\n\n\treturn {\n\t\tok: r.ok,\n\t\tstatusCode: r.statusCode,\n\t\terror: r.error,\n\t\tdurationMs: r.durationMs,\n\t};\n}\n\n/** A representative (non-persisted) outbox row for a test delivery, so\n * `buildForFormat` produces a realistic body. */\nfunction buildTestOutboxRow(sub: Webhook): WebhookOutbox {\n\tconst now = new Date();\n\treturn {\n\t\tid: randomUUID(),\n\t\twebhook_id: sub.id,\n\t\tkind: sub.kind,\n\t\tblock_height: 0,\n\t\ttx_id: null,\n\t\trow_pk: null,\n\t\tevent_type: \"chain.test.apply\",\n\t\tpayload: {\n\t\t\ttest: true,\n\t\t\tmessage: \"Secondlayer test delivery\",\n\t\t\twebhook_id: sub.id,\n\t\t\tsent_at: now.toISOString(),\n\t\t},\n\t\tdedup_key: `test:${sub.id}:${now.getTime()}`,\n\t\tattempt: 0,\n\t\tnext_attempt_at: now,\n\t\tstatus: \"pending\",\n\t\tis_replay: false,\n\t\tblock_time: null,\n\t\tdelivered_at: null,\n\t\tfailed_at: null,\n\t\tlocked_by: null,\n\t\tlocked_until: null,\n\t\tlast_error: null,\n\t\tcreated_at: now,\n\t};\n}\n\n/**\n * Build a representative webhook for `sub`'s configured format, POST it (same\n * SSRF guard + timeout + signing as a real delivery), and log a delivery row\n * with a null `outbox_id` so it appears under the webhook's deliveries\n * without being tied to a queued event. Powers `POST /:id/test`.\n */\nexport async function deliverTestEvent(\n\tdb: Kysely<Database>,\n\tsub: Webhook,\n): Promise<WebhookTestResult> {\n\tconst testRow = buildTestOutboxRow(sub);\n\tconst { body, headers } = buildForFormat(\n\t\ttestRow,\n\t\tsub,\n\t\tgetWebhookSigningSecret(sub),\n\t);\n\tconst r = await postToWebhook(sub.url, body, headers, sub.timeout_ms);\n\tconst inserted = await db\n\t\t.insertInto(\"webhook_deliveries\")\n\t\t.values({\n\t\t\toutbox_id: null,\n\t\t\twebhook_id: sub.id,\n\t\t\tattempt: 1,\n\t\t\tstatus_code: r.statusCode,\n\t\t\tresponse_headers: r.responseHeaders,\n\t\t\tresponse_body: r.responseBody,\n\t\t\terror_message: r.error,\n\t\t\tduration_ms: r.durationMs,\n\t\t})\n\t\t.returning(\"id\")\n\t\t.executeTakeFirstOrThrow();\n\treturn {\n\t\tok: r.ok,\n\t\tstatusCode: r.statusCode,\n\t\terror: r.error,\n\t\tdurationMs: r.durationMs,\n\t\tdeliveryId: inserted.id,\n\t};\n}\n\nasync function settleDelivered(\n\tdb: Kysely<Database>,\n\toutboxRow: WebhookOutbox,\n): Promise<void> {\n\tawait db.transaction().execute(async (tx) => {\n\t\tconst result = await tx\n\t\t\t.updateTable(\"webhook_outbox\")\n\t\t\t.set({\n\t\t\t\tstatus: \"delivered\",\n\t\t\t\tdelivered_at: new Date(),\n\t\t\t\tattempt: outboxRow.attempt + 1,\n\t\t\t\tlocked_by: null,\n\t\t\t\tlocked_until: null,\n\t\t\t})\n\t\t\t// Guard against a reorg that marked this row `dead` (orphaned) while\n\t\t\t// the POST was in flight — settling a delivery outcome must never\n\t\t\t// resurrect a row the reorg already decided is gone. `status='pending'`\n\t\t\t// is the only state a claimed row can settle from.\n\t\t\t.where(\"id\", \"=\", outboxRow.id)\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.executeTakeFirst();\n\t\tif (Number(result.numUpdatedRows ?? 0) === 0) {\n\t\t\tlogger.info(\"webhook.settle.orphaned\", {\n\t\t\t\toutboxId: outboxRow.id,\n\t\t\t\twebhookId: outboxRow.webhook_id,\n\t\t\t\toutcome: \"delivered\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tawait tx\n\t\t\t.updateTable(\"webhooks\")\n\t\t\t.set({\n\t\t\t\tlast_delivery_at: new Date(),\n\t\t\t\tlast_success_at: new Date(),\n\t\t\t\tcircuit_failures: 0,\n\t\t\t\tlast_error: null,\n\t\t\t\tupdated_at: new Date(),\n\t\t\t})\n\t\t\t.where(\"id\", \"=\", outboxRow.webhook_id)\n\t\t\t.execute();\n\n\t\t// Hosted-stack event meter (plan 044, step 5): counts a real delivery,\n\t\t// never a retry (this function only runs on the successful outcome) and\n\t\t// never a test delivery (`deliverTestEvent` never calls this). A no-op\n\t\t// on self-host (WEBHOOK_METER_SOCKET unset).\n\t\trecordDelivery();\n\t});\n}\n\nasync function settleFailed(\n\tdb: Kysely<Database>,\n\toutboxRow: WebhookOutbox,\n\tsub: Webhook,\n\terrText: string,\n): Promise<void> {\n\tconst attempt = outboxRow.attempt + 1;\n\tconst isDead = attempt >= sub.max_retries;\n\tconst nextAt = isDead\n\t\t? null\n\t\t: new Date(Date.now() + nextDelaySeconds(outboxRow.attempt) * 1000);\n\n\tawait db.transaction().execute(async (tx) => {\n\t\tconst result = await tx\n\t\t\t.updateTable(\"webhook_outbox\")\n\t\t\t.set({\n\t\t\t\tattempt,\n\t\t\t\tnext_attempt_at: nextAt ?? new Date(),\n\t\t\t\tstatus: isDead ? \"dead\" : \"pending\",\n\t\t\t\tfailed_at: isDead ? new Date() : null,\n\t\t\t\tlocked_by: null,\n\t\t\t\tlocked_until: null,\n\t\t\t})\n\t\t\t// Guard against a reorg that marked this row `dead` (orphaned) while\n\t\t\t// the POST was in flight — see the matching guard in `settleDelivered`.\n\t\t\t.where(\"id\", \"=\", outboxRow.id)\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.executeTakeFirst();\n\t\tif (Number(result.numUpdatedRows ?? 0) === 0) {\n\t\t\tlogger.info(\"webhook.settle.orphaned\", {\n\t\t\t\toutboxId: outboxRow.id,\n\t\t\t\twebhookId: outboxRow.webhook_id,\n\t\t\t\toutcome: \"failed\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Atomic increment — concurrent failures must not clobber each other.\n\t\t// `RETURNING circuit_failures` gives us the post-increment value to\n\t\t// decide whether this failure tripped the circuit.\n\t\tconst incResult = await sql<{ circuit_failures: number }>`\n\t\t\tUPDATE webhooks\n\t\t\tSET circuit_failures = circuit_failures + 1,\n\t\t\t\tlast_delivery_at = NOW(),\n\t\t\t\tlast_error = ${errText.slice(0, 500)},\n\t\t\t\tupdated_at = NOW()\n\t\t\tWHERE id = ${sub.id}\n\t\t\tRETURNING circuit_failures\n\t\t`.execute(tx);\n\t\tconst newFailures =\n\t\t\tincResult.rows[0]?.circuit_failures ?? sub.circuit_failures + 1;\n\t\tconst shouldTripCircuit = newFailures >= CIRCUIT_THRESHOLD;\n\n\t\tif (shouldTripCircuit) {\n\t\t\t// Transition to paused only on the first failure that crossed\n\t\t\t// the threshold — additional failures in-flight harmlessly\n\t\t\t// re-set the same fields.\n\t\t\tawait tx\n\t\t\t\t.updateTable(\"webhooks\")\n\t\t\t\t.set({\n\t\t\t\t\tstatus: \"paused\",\n\t\t\t\t\tcircuit_opened_at: new Date(),\n\t\t\t\t\tupdated_at: new Date(),\n\t\t\t\t})\n\t\t\t\t.where(\"id\", \"=\", sub.id)\n\t\t\t\t.execute();\n\t\t\tlogger.warn(\n\t\t\t\t\"Webhook circuit tripped — paused after consecutive failures\",\n\t\t\t\t{\n\t\t\t\t\twebhook: sub.name,\n\t\t\t\t\tfailures: newFailures,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t});\n}\n\n/** What woke this claim cycle — purely for the diagnostic log below; the\n * claim/dispatch logic itself doesn't branch on it. `\"drain-loop\"` marks a\n * pass this function re-ran on itself (see `claimAndDrain`) because a wake\n * arrived (or a per-lane batch cap was hit) while the previous pass was\n * still claiming. `\"changed\"` is a resume (or any webhook edit) — see the\n * `webhooks:changed` listener. */\ntype ClaimTrigger = \"notify\" | \"poll\" | \"startup\" | \"changed\" | \"drain-loop\";\n\n/**\n * The regression this closes: a NOTIFY that arrives while a claim cycle is\n * ALREADY running used to be dropped on the floor (the `claimInFlight` guard\n * below just returned 0), and nothing re-checked once that cycle finished.\n * Rows inserted mid-cycle — a normal burst of ~6 chain-webhook matches per\n * block — sat `pending` until an UNRELATED future wake happened to fire, or\n * the 2-minute safety poll.\n *\n * The holder of `claimInFlight` now keeps looping (`claimPending`, set by any\n * caller that finds the lock held) until a pass claims nothing NEW and no one\n * asked for a recheck while it ran — so a burst drains fully off one wake\n * instead of needing one wake per claim-sized chunk. Critically, this lock\n * wraps ONLY `claimAndDispatchOnce`'s DB claim query, never dispatch (see its\n * doc) — a slow or hanging receiver must never hold up the next claim.\n */\nasync function claimAndDrain(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\temitterId: string,\n\ttrigger: ClaimTrigger,\n): Promise<number> {\n\tif (state.claimInFlight) {\n\t\tstate.claimPending = true;\n\t\treturn 0;\n\t}\n\tstate.claimInFlight = true;\n\t// Assigned synchronously (before any `await` in `runClaimLoop` yields back\n\t// to the event loop) so `stopEmitter` can always await the pass that\n\t// actually owns the lock, never a concurrent caller's already-resolved\n\t// `claimPending` short-circuit above.\n\tconst drainPromise = runClaimLoop(db, state, emitterId, trigger);\n\tstate.currentClaim = drainPromise;\n\ttry {\n\t\treturn await drainPromise;\n\t} finally {\n\t\tif (state.currentClaim === drainPromise) state.currentClaim = null;\n\t}\n}\n\nasync function runClaimLoop(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\temitterId: string,\n\ttrigger: ClaimTrigger,\n): Promise<number> {\n\tlet totalClaimed = 0;\n\ttry {\n\t\tlet currentTrigger = trigger;\n\t\tfor (;;) {\n\t\t\t// Stop requested: claim no new rows. Anything already claimed by an\n\t\t\t// in-flight `claimAndDispatchOnce` call still gets handed to its\n\t\t\t// sub's queue, but `pumpSub`'s own `state.running` check means it\n\t\t\t// won't dispatch — those rows just keep their lock until the next\n\t\t\t// emitter re-claims them after LOCK_WINDOW_MS.\n\t\t\tif (!state.running) break;\n\t\t\tstate.claimPending = false;\n\t\t\tconst result = await claimAndDispatchOnce(\n\t\t\t\tdb,\n\t\t\t\tstate,\n\t\t\t\temitterId,\n\t\t\t\tcurrentTrigger,\n\t\t\t);\n\t\t\ttotalClaimed += result.claimed;\n\t\t\t// Keep going while either: a wake landed mid-pass (claimPending —\n\t\t\t// set by the guard above, from another caller), or either lane\n\t\t\t// (live/replay) came back full, meaning more may be waiting behind\n\t\t\t// it. Comparing against the LANE limits, not the combined batch\n\t\t\t// size, matters: live traffic alone is capped at `liveLimit` (90%\n\t\t\t// of BATCH_SIZE) and would never reach the full BATCH_SIZE on its\n\t\t\t// own, so that comparison never re-looped on a live-only backlog.\n\t\t\tif (!state.claimPending && !result.mayHaveMore) break;\n\t\t\tcurrentTrigger = \"drain-loop\";\n\t\t}\n\t} finally {\n\t\tstate.claimInFlight = false;\n\t}\n\treturn totalClaimed;\n}\n\ninterface ClaimResult {\n\tclaimed: number;\n\tdispatched: number;\n\treleased: number;\n\tmayHaveMore: boolean;\n}\n\n/**\n * One claim pass: SELECT a batch, mark it locked, then hand each sub's slice\n * to its persistent queue and return — WITHOUT waiting for any of it to\n * dispatch. Caller (`claimAndDrain`) owns the re-loop and the `claimInFlight`\n * lock, which now covers only this function's DB work.\n *\n * This decoupling is the fix for the emitter-wide latency regression: the\n * previous version awaited `Promise.all(subIds.map(drainForSub))` — every\n * sub's FULL dispatch — before returning, so the slowest receiver in a batch\n * (a hung connection, a multi-second response) held the process-wide claim\n * lock for as long as IT took, starving every other sub's claims (including\n * a fast sub's own fresh rows) for that whole time. Claiming is now a single\n * short transaction; delivery happens on each sub's own independent\n * queue/semaphore (`enqueueForSub`/`pumpSub`), so one sub's pace never\n * gates another's.\n *\n * Also fixes the \"stuck rows\" bug: a row claimed for a sub that turns out to\n * be `paused` (status read fresh here, after the claim) is released\n * IMMEDIATELY — `next_attempt_at` reset to now, lock cleared — instead of\n * being silently abandoned with its lock held for the full `LOCK_WINDOW_MS`.\n * The old code's `if (sub.status !== \"active\") return;` left the row\n * claimed-but-untouched: locked, `next_attempt_at` pushed far into the\n * future, never dispatched, never settled — a resumed webhook's backlog\n * then only drained once each row's stale lock happened to expire.\n */\nasync function claimAndDispatchOnce(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\temitterId: string,\n\ttrigger: ClaimTrigger,\n): Promise<ClaimResult> {\n\t// FOR UPDATE SKIP LOCKED — multiple emitters split the batch.\n\t// 90/10 live vs replay so a big replay doesn't starve live emits.\n\tconst liveLimit = Math.max(1, Math.round(BATCH_SIZE * LIVE_SHARE));\n\tconst replayLimit = BATCH_SIZE - liveLimit;\n\tconst { combined, liveCount, replayCount } = await db\n\t\t.transaction()\n\t\t.execute(async (tx) => {\n\t\t\tconst live = await sql<WebhookOutbox>`\n\t\t\t\t\tSELECT * FROM webhook_outbox\n\t\t\t\t\tWHERE status = 'pending'\n\t\t\t\t\t\tAND next_attempt_at <= NOW()\n\t\t\t\t\t\tAND is_replay = FALSE\n\t\t\t\t\tORDER BY next_attempt_at ASC\n\t\t\t\t\tFOR UPDATE SKIP LOCKED\n\t\t\t\t\tLIMIT ${sql.lit(liveLimit)}\n\t\t\t\t`.execute(tx);\n\t\t\tconst replay = await sql<WebhookOutbox>`\n\t\t\t\t\tSELECT * FROM webhook_outbox\n\t\t\t\t\tWHERE status = 'pending'\n\t\t\t\t\t\tAND next_attempt_at <= NOW()\n\t\t\t\t\t\tAND is_replay = TRUE\n\t\t\t\t\tORDER BY next_attempt_at ASC\n\t\t\t\t\tFOR UPDATE SKIP LOCKED\n\t\t\t\t\tLIMIT ${sql.lit(replayLimit)}\n\t\t\t\t`.execute(tx);\n\n\t\t\tconst rows = [...live.rows, ...replay.rows];\n\t\t\tif (rows.length === 0) {\n\t\t\t\treturn { combined: rows, liveCount: 0, replayCount: 0 };\n\t\t\t}\n\n\t\t\t// Push `next_attempt_at` forward by the lock window. This is\n\t\t\t// the only defense against double-dispatch if the emitter\n\t\t\t// process crashes mid-HTTP-call: the row won't be re-claimable\n\t\t\t// until `LOCK_WINDOW_MS` elapses, giving us a stale-lock\n\t\t\t// recovery window. `settleDelivered`/`settleFailed` overrides\n\t\t\t// this on the success/failure path (and the paused-sub release\n\t\t\t// below overrides it on the \"never got dispatched\" path).\n\t\t\tconst now = new Date();\n\t\t\tconst lockUntil = new Date(now.getTime() + LOCK_WINDOW_MS);\n\t\t\tawait tx\n\t\t\t\t.updateTable(\"webhook_outbox\")\n\t\t\t\t.set({\n\t\t\t\t\tlocked_by: emitterId,\n\t\t\t\t\tlocked_until: lockUntil,\n\t\t\t\t\tnext_attempt_at: lockUntil,\n\t\t\t\t})\n\t\t\t\t.where(\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"in\",\n\t\t\t\t\trows.map((r) => r.id),\n\t\t\t\t)\n\t\t\t\t.execute();\n\t\t\treturn {\n\t\t\t\tcombined: rows,\n\t\t\t\tliveCount: live.rows.length,\n\t\t\t\treplayCount: replay.rows.length,\n\t\t\t};\n\t\t});\n\n\tif (combined.length === 0) {\n\t\treturn { claimed: 0, dispatched: 0, released: 0, mayHaveMore: false };\n\t}\n\n\tconst bySubId = new Map<string, WebhookOutbox[]>();\n\tfor (const row of combined) {\n\t\tconst arr = bySubId.get(row.webhook_id);\n\t\tif (arr) arr.push(row);\n\t\telse bySubId.set(row.webhook_id, [row]);\n\t}\n\n\tconst subIds = Array.from(bySubId.keys());\n\tconst subs = await db\n\t\t.selectFrom(\"webhooks\")\n\t\t.selectAll()\n\t\t.where(\"id\", \"in\", subIds)\n\t\t.execute();\n\tconst subById = new Map(subs.map((s) => [s.id, s]));\n\n\tlet dispatched = 0;\n\tlet released = 0;\n\tconst releasedIds: string[] = [];\n\tfor (const subId of subIds) {\n\t\tconst sub = subById.get(subId);\n\t\t// biome-ignore lint/style/noNonNullAssertion: key came from bySubId itself\n\t\tconst rows = bySubId.get(subId)!;\n\t\tif (!sub || sub.status !== \"active\") {\n\t\t\treleased += rows.length;\n\t\t\treleasedIds.push(...rows.map((r) => r.id));\n\t\t\tcontinue;\n\t\t}\n\t\tdispatched += rows.length;\n\t\tenqueueForSub(db, state, sub, rows);\n\t}\n\n\tif (releasedIds.length > 0) {\n\t\t// Claimable again immediately: a webhook that's already resumed by the\n\t\t// time we notice the release loses nothing waiting for LOCK_WINDOW_MS\n\t\t// (up to several minutes) to expire on its own.\n\t\tawait db\n\t\t\t.updateTable(\"webhook_outbox\")\n\t\t\t.set({ next_attempt_at: new Date(), locked_by: null, locked_until: null })\n\t\t\t.where(\"id\", \"in\", releasedIds)\n\t\t\t.execute();\n\t}\n\n\t// One line per claim pass: what woke it, how much it found, how it split\n\t// between dispatched-now and released-back (paused), how stale the oldest\n\t// row was, and how loaded the in-flight pool already was — everything\n\t// needed to tell \"briefly busy\" apart from \"actually stuck\" without\n\t// reproducing it live. `in_flight`/`concurrency` sum across only the subs\n\t// THIS pass touched (a quiet sub's unrelated cap doesn't dilute the\n\t// reading).\n\tconst oldestCreatedAtMs = Math.min(\n\t\t...combined.map((r) => new Date(r.created_at).getTime()),\n\t);\n\tconst inFlight = subIds.reduce(\n\t\t(sum, id) => sum + (state.subQueues.get(id)?.inFlight ?? 0),\n\t\t0,\n\t);\n\tconst concurrency = subIds.reduce(\n\t\t(sum, id) => sum + (subById.get(id)?.concurrency || 4),\n\t\t0,\n\t);\n\tlogger.info(\"emitter claim cycle\", {\n\t\tevent: \"emitter_claim\",\n\t\ttrigger,\n\t\tclaimed: combined.length,\n\t\tdispatched,\n\t\treleased,\n\t\toldest_created_at_age_ms: Date.now() - oldestCreatedAtMs,\n\t\tin_flight: inFlight,\n\t\tconcurrency,\n\t});\n\n\treturn {\n\t\tclaimed: combined.length,\n\t\tdispatched,\n\t\treleased,\n\t\tmayHaveMore: liveCount >= liveLimit || replayCount >= replayLimit,\n\t};\n}\n\n/**\n * Hand `rows` to `sub`'s persistent queue and try to start dispatching\n * immediately. Decoupled from the claim transaction on purpose (see\n * `claimAndDispatchOnce`'s doc) — a slow or hanging sub's in-flight HTTP\n * calls must never hold up the next claim, for this sub or any other.\n *\n * `sub` is refreshed here on every call (not just on first creation) so a\n * status/concurrency change since the last batch — most importantly a\n * pause — is picked up by `pumpSub` without waiting for anything to expire.\n */\nfunction enqueueForSub(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\tsub: Webhook,\n\trows: WebhookOutbox[],\n): void {\n\tlet sq = state.subQueues.get(sub.id);\n\tif (!sq) {\n\t\tsq = { sub, queue: [], inFlight: 0 };\n\t\tstate.subQueues.set(sub.id, sq);\n\t} else {\n\t\tsq.sub = sub;\n\t}\n\tsq.queue.push(...rows);\n\tpumpSub(db, state, sub.id);\n}\n\n/**\n * Start as many workers as the sub's remaining concurrency allows, pulling\n * from its queue. Reentrant-safe without an explicit lock: every branch here\n * is synchronous (the only `await` lives in `runOne`, called but not\n * awaited), so JS's single-threaded execution means two calls — one from\n * `enqueueForSub`, one from a just-finished worker's `finally` — can never\n * interleave mid-loop; each runs to completion before the other starts.\n */\nfunction pumpSub(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\tsubId: string,\n): void {\n\tconst sq = state.subQueues.get(subId);\n\tif (!sq) return;\n\tconst cap = sq.sub.concurrency || 4;\n\twhile (\n\t\tstate.running &&\n\t\tsq.sub.status === \"active\" &&\n\t\tsq.inFlight < cap &&\n\t\tsq.queue.length > 0\n\t) {\n\t\tconst row = sq.queue.shift();\n\t\tif (!row) break;\n\t\tsq.inFlight++;\n\t\tconst runPromise = runOne(db, state, sq, row);\n\t\tstate.inFlightRuns.add(runPromise);\n\t\tvoid runPromise.finally(() => {\n\t\t\tstate.inFlightRuns.delete(runPromise);\n\t\t});\n\t}\n}\n\n/** Dispatch one claimed row end to end (POST, settle), then release its\n * in-flight slot and try to pull more work for the same sub. */\nasync function runOne(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\tsq: SubQueue,\n\trow: WebhookOutbox,\n): Promise<void> {\n\ttry {\n\t\tconst result = await dispatchOne(db, row, sq.sub);\n\t\tif (result.ok) {\n\t\t\tawait settleDelivered(db, row);\n\t\t} else {\n\t\t\tconst err = result.error ?? `HTTP ${result.statusCode ?? \"?\"}`;\n\t\t\tawait settleFailed(db, row, sq.sub, err);\n\t\t}\n\t} catch (err) {\n\t\tlogger.error(\"Emitter dispatch crashed\", {\n\t\t\toutboxId: row.id,\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\tawait settleFailed(\n\t\t\tdb,\n\t\t\trow,\n\t\t\tsq.sub,\n\t\t\terr instanceof Error ? err.message : String(err),\n\t\t);\n\t} finally {\n\t\tsq.inFlight--;\n\t\tpumpSub(db, state, sq.sub.id);\n\t}\n}\n\nexport interface StartEmitterOptions {\n\t/** Interval for the background poll (ms). Defaults to 2 minutes. */\n\tpollIntervalMs?: number;\n\t/** Retention sweep interval (ms). Defaults to 1 hour. */\n\tretentionIntervalMs?: number;\n\t/** Bound for the returned stop function's clean-shutdown drain — how long\n\t * it waits for the current claim pass + in-flight dispatches before\n\t * giving up and reporting them abandoned. Defaults to\n\t * `MAX_WEBHOOK_TIMEOUT_MS + 5_000` (a dispatch can't legitimately run\n\t * longer than the webhook timeout ceiling). `MAX_WEBHOOK_TIMEOUT_MS` is\n\t * fixed at module load from `WEBHOOK_TIMEOUT_MS_CEILING`, so this exists\n\t * mainly for tests that need a short bound without a 5-minute wait. */\n\tstopDrainDeadlineMs?: number;\n}\n\nasync function runRetention(db: Kysely<Database>): Promise<void> {\n\t// delivered outbox >7d, deliveries >30d, dead outbox >90d\n\tawait sql`\n\t\tDELETE FROM webhook_outbox\n\t\tWHERE status = 'delivered' AND delivered_at < NOW() - interval '7 days'\n\t`.execute(db);\n\tawait sql`\n\t\tDELETE FROM webhook_deliveries\n\t\tWHERE dispatched_at < NOW() - interval '30 days'\n\t`.execute(db);\n\tawait sql`\n\t\tDELETE FROM webhook_outbox\n\t\tWHERE status = 'dead' AND failed_at < NOW() - interval '90 days'\n\t`.execute(db);\n}\n\nexport async function startEmitter(\n\topts?: StartEmitterOptions,\n): Promise<() => Promise<void>> {\n\tconst emitterId = `emitter-${Math.random().toString(36).slice(2, 10)}`;\n\tconst db = getTargetDb();\n\tconst state: RunningState = {\n\t\trunning: true,\n\t\tsubQueues: new Map(),\n\t\tclaimInFlight: false,\n\t\tclaimPending: false,\n\t\tcurrentClaim: null,\n\t\tinFlightRuns: new Set(),\n\t};\n\tconst pollIntervalMs = opts?.pollIntervalMs ?? 120_000;\n\tconst retentionIntervalMs = opts?.retentionIntervalMs ?? 60 * 60_000;\n\n\tlogger.info(\"[emitter] started\", { id: emitterId });\n\n\t// LISTEN on new outbox + sub changes. Both channels fire on the TARGET DB\n\t// (webhook_outbox + webhooks are control-plane tables), so bind the\n\t// listener there — under the split it is NOT `DATABASE_URL`.\n\tconst listenUrl = targetListenerUrl();\n\tconst stopNew = await listen(\n\t\t\"webhooks:new_outbox\",\n\t\t() => {\n\t\t\tif (!state.running) return;\n\t\t\tvoid claimAndDrain(db, state, emitterId, \"notify\").catch((err) =>\n\t\t\t\tlogger.error(\"[emitter] claim failed\", {\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\t{ connectionString: listenUrl },\n\t);\n\tconst stopChanged = await listen(\n\t\t\"webhooks:changed\",\n\t\t() => {\n\t\t\tif (!state.running) return;\n\t\t\t// A resume is exactly `webhooks:changed` — its rows were already\n\t\t\t// released back to claimable (see claimAndDispatchOnce's paused-sub\n\t\t\t// branch) as soon as we noticed the pause, so a resumed webhook's\n\t\t\t// backlog drains on the SAME event that flips it active again,\n\t\t\t// instead of waiting for an unrelated future notify or the poll.\n\t\t\tvoid claimAndDrain(db, state, emitterId, \"changed\").catch((err) =>\n\t\t\t\tlogger.error(\"[emitter] claim failed\", {\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\t{ connectionString: listenUrl },\n\t);\n\t// Names both channels + the exact host/db LISTENed on (no credentials) so\n\t// a split-DB misconfiguration — the wake never reaching this process — is\n\t// visible in `docker logs` at boot, not only inferred from a delivery\n\t// latency graph later.\n\tlogger.info(\"[emitter] wake listeners connected\", {\n\t\tchannels: [\"webhooks:new_outbox\", \"webhooks:changed\"],\n\t\tdb: describeDbUrl(listenUrl),\n\t});\n\n\t// Poll every pollIntervalMs as a safety net for missed notifications +\n\t// backoff wakeups (rows whose next_attempt_at has passed).\n\tconst poll = setInterval(() => {\n\t\tif (!state.running) return;\n\t\tvoid claimAndDrain(db, state, emitterId, \"poll\").catch((err) =>\n\t\t\tlogger.error(\"[emitter] poll claim failed\", {\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t}),\n\t\t);\n\t}, pollIntervalMs);\n\n\t// Kick once on startup so any rows that arrived before we started drain.\n\tvoid claimAndDrain(db, state, emitterId, \"startup\");\n\n\t// Retention sweep — hourly by default.\n\tconst retention = setInterval(() => {\n\t\tif (!state.running) return;\n\t\tvoid runRetention(db).catch((err) =>\n\t\t\tlogger.error(\"[emitter] retention failed\", {\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t}),\n\t\t);\n\t}, retentionIntervalMs);\n\n\t// Receiver TLS expiry probe: Bun's fetch can't read peer certificates.\n\tconst receiverCerts = setInterval(() => {\n\t\tif (!state.running) return;\n\t\tvoid refreshReceiverCerts(db).catch((err) =>\n\t\t\tlogger.error(\"[emitter] receiver cert refresh failed\", {\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t}),\n\t\t);\n\t}, RECEIVER_CERT_INTERVAL_MS);\n\n\treturn async () => {\n\t\t// No new claims start (`runClaimLoop`'s own check) and no new\n\t\t// dispatches start (`pumpSub`'s own check) from this point on — the\n\t\t// two sets we're about to await can only shrink from here.\n\t\tstate.running = false;\n\t\tclearInterval(poll);\n\t\tclearInterval(retention);\n\t\tclearInterval(receiverCerts);\n\t\tawait stopNew();\n\t\tawait stopChanged();\n\n\t\tconst pendingRuns = new Set(state.inFlightRuns);\n\t\tconst drainTarget = pendingRuns.size;\n\t\t// `runOne` never rejects (it catches into `settleFailed`), but a claim\n\t\t// pass could — swallow that here rather than let it crash shutdown; the\n\t\t// call site that kicked off the claim already logs its own errors.\n\t\tconst claimSettled = (state.currentClaim ?? Promise.resolve()).catch(\n\t\t\t() => {},\n\t\t);\n\t\tconst waitAll = Promise.all([claimSettled, ...pendingRuns]);\n\t\t// A dispatch can't legitimately run longer than the webhook timeout\n\t\t// ceiling — bound the wait so a hung receiver can't hold up shutdown\n\t\t// forever. Rows still claimed/locked at the deadline keep their lock\n\t\t// and are re-claimed by the next emitter after LOCK_WINDOW_MS.\n\t\tconst deadlineMs =\n\t\t\topts?.stopDrainDeadlineMs ?? MAX_WEBHOOK_TIMEOUT_MS + 5_000;\n\t\tlet timedOut = false;\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst timeout = new Promise<void>((resolve) => {\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\ttimedOut = true;\n\t\t\t\tresolve();\n\t\t\t}, deadlineMs);\n\t\t});\n\t\tawait Promise.race([waitAll, timeout]);\n\t\tclearTimeout(timer);\n\n\t\tconst abandoned = timedOut ? state.inFlightRuns.size : 0;\n\t\tconst drained = drainTarget - abandoned;\n\t\tlogger.info(\"[emitter] stopped\", {\n\t\t\tid: emitterId,\n\t\t\tevent: \"emitter_stopped\",\n\t\t\tdrained,\n\t\t\tabandoned,\n\t\t});\n\t};\n}\n",
5
+ "import { randomUUID } from \"node:crypto\";\nimport { lookup as dnsLookup } from \"node:dns/promises\";\nimport {\n\ttype Database,\n\ttype Webhook,\n\ttype WebhookOutbox,\n\tdescribeDbUrl,\n\tgetTargetDb,\n} from \"@secondlayer/shared/db\";\nimport { finalizeReplays } from \"@secondlayer/shared/db/queries/webhook-replays\";\nimport { getWebhookSigningSecret } from \"@secondlayer/shared/db/queries/webhooks\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { listen, targetListenerUrl } from \"@secondlayer/shared/queue/listener\";\nimport {\n\ttype WebhookTestResult,\n\twebhookTimeoutMsCeiling,\n} from \"@secondlayer/shared/schemas/webhooks\";\nimport { type Kysely, sql } from \"kysely\";\nimport { buildForFormat } from \"./formats/index.ts\";\nimport { recordDelivery } from \"./meter-socket.ts\";\nimport { refreshReceiverCerts } from \"./receiver-cert.ts\";\n\n/**\n * Webhook emitter — drains `webhook_outbox` and POSTs deliveries.\n *\n * Hot path: LISTEN on `webhooks:new_outbox` and `webhooks:changed`.\n * On notify, claim a batch with `FOR UPDATE SKIP LOCKED LIMIT 50`, dispatch\n * each row via HTTP, write a `webhook_deliveries` attempt row, then\n * either mark `status='delivered'` or schedule the next attempt.\n *\n * Backoff schedule (attempt → wait):\n * 0 → 30s, 1 → 2m, 2 → 10m, 3 → 1h, 4 → 6h, 5 → 24h, 6 → 72h.\n * After `max_retries` (default 7) attempts → `status='dead'`.\n *\n * Per-sub circuit breaker: 20 consecutive failures → sub flipped to\n * `paused` with `circuit_opened_at=NOW()`. Manual /resume drains backlog.\n *\n * Per-sub concurrency cap: in-memory semaphore, default 4 in-flight HTTP\n * requests per webhook. Sprint-4 adds SSRF allowlist.\n */\n\nconst BATCH_SIZE = 50;\nconst LIVE_SHARE = 0.9; // 90% of batch to non-replay, 10% to replay\nconst BACKOFF_SECONDS = [30, 120, 600, 3600, 21600, 86400, 259200];\nconst CIRCUIT_THRESHOLD = 20;\n/**\n * When a batch is claimed the outbox row's `next_attempt_at` is pushed\n * `LOCK_WINDOW_MS` into the future. Any crash between claim + settle\n * leaves the row re-claimable after this window expires — the SSOT for\n * double-dispatch prevention.\n *\n * Must exceed the maximum possible in-flight delivery time so a slow-but-alive\n * receiver's row is never re-claimed mid-delivery (duplicate dispatch). Derived\n * from the configurable timeout ceiling (`WEBHOOK_TIMEOUT_MS_CEILING`, default\n * 300_000ms — see `webhookTimeoutMsCeiling` in shared/schemas/webhooks.ts) so a\n * raised ceiling can never create a delivery window shorter than a webhook's\n * own timeout.\n */\nexport const MAX_WEBHOOK_TIMEOUT_MS: number = webhookTimeoutMsCeiling();\nexport const LOCK_WINDOW_MS: number = MAX_WEBHOOK_TIMEOUT_MS + 60_000; // ceiling + settle margin\n\n/** A sub's persistent delivery queue + in-flight counter. Lives for as long\n * as the sub has (or recently had) work — see `enqueueForSub`/`pumpSub`.\n * `sub` is refreshed on every enqueue so a status/concurrency change (a\n * pause, a resume, a config edit) is picked up by the next batch of rows\n * without waiting for anything to expire. */\ninterface SubQueue {\n\tsub: Webhook;\n\tqueue: WebhookOutbox[];\n\tinFlight: number;\n}\n\ninterface RunningState {\n\trunning: boolean;\n\t/** Per-webhook queue + concurrency counter — see `SubQueue`. Replaces a\n\t * bare in-flight counter so dispatch can be decoupled from the claim\n\t * transaction (see `claimAndDispatchOnce`): claiming a batch no longer\n\t * waits for a sub's HTTP calls to finish before the NEXT claim can run,\n\t * it just hands rows to that sub's queue and returns. */\n\tsubQueues: Map<string, SubQueue>;\n\tclaimInFlight: boolean;\n\t/** Set when a wake (NOTIFY) arrives while a claim cycle is already\n\t * running. The in-flight cycle checks this before releasing the lock —\n\t * see `claimAndDrain`'s \"drain-loop\" pass — so rows that land mid-drain\n\t * aren't stranded until an unrelated future wake or the safety poll. */\n\tclaimPending: boolean;\n\t/** The promise of whichever `claimAndDrain` call currently owns\n\t * `claimInFlight` (assigned by that call itself, before its first\n\t * `await`, so there is no race with a concurrent caller that just sets\n\t * `claimPending` and returns). `stopEmitter`'s clean-stop path awaits\n\t * this so shutdown doesn't race a claim pass that's mid-dispatch. */\n\tcurrentClaim: Promise<number> | null;\n\t/** Every `runOne` promise currently dispatching, added by `pumpSub` at\n\t * start and removed on settle. `stopEmitter` awaits this set (bounded)\n\t * so it never reports \"stopped\" while a delivery is still mid-flight. */\n\tinFlightRuns: Set<Promise<void>>;\n}\n\nfunction nextDelaySeconds(attempt: number): number {\n\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\treturn BACKOFF_SECONDS[Math.min(attempt, BACKOFF_SECONDS.length - 1)]!;\n}\n\n// ── SSRF guard ────────────────────────────────────────────────────────\n// Block deliveries to private/loopback/link-local ranges unless\n// SECONDLAYER_ALLOW_PRIVATE_EGRESS=true (self-host + local-dev opt-in).\n\nconst PRIVATE_V4_PATTERNS = [\n\t/^127\\./, // loopback\n\t/^10\\./, // private class A\n\t/^172\\.(1[6-9]|2\\d|3[01])\\./, // private class B\n\t/^192\\.168\\./, // private class C\n\t/^169\\.254\\./, // link-local\n\t/^0\\./, // \"this\" network\n\t/^100\\.(6[4-9]|[7-9]\\d|1[01]\\d|12[0-7])\\./, // CGNAT 100.64/10\n\t/^198\\.(1[89])\\./, // benchmarking 198.18.0.0/15\n\t/^(22[4-9]|23[0-9])\\./, // multicast 224.0.0.0/4\n\t/^(24[0-9]|25[0-5])\\./, // reserved 240.0.0.0/4 (incl. 255.255.255.255 broadcast)\n];\n\n/**\n * Classify a raw IP address literal (v4 or v6, no brackets, already lowercased\n * or not) as private/loopback/link-local/reserved. Covers v4 private ranges +\n * link-local (incl. `169.254.169.254`), `0.0.0.0`, benchmarking\n * (`198.18.0.0/15`), multicast (`224.0.0.0/4`), reserved/broadcast\n * (`240.0.0.0/4`, incl. `255.255.255.255`), IPv6 loopback (`::1`), unspecified\n * (`::`), unique-local (`fc00::/7`), link-local (`fe80::/10`), IPv6 multicast\n * (`ff00::/8`), IPv4-mapped IPv6 (`::ffff:127.0.0.1`, `::ffff:7f00:0001`), and\n * NAT64 (`64:ff9b::/96`, embedded v4 classified the same as IPv4-mapped).\n *\n * Shared by `isPrivateEgress` (literal-hostname fast-fail) and the resolved-\n * DNS-address check in `checkEgressAllowed` (rebinding mitigation).\n */\nfunction isPrivateIp(address: string): boolean {\n\tconst host = address.toLowerCase();\n\n\tif (host === \"0.0.0.0\") return true;\n\tif (host === \"::\" || host === \"::1\") return true;\n\t// Unique-local (fc00::/7) + link-local (fe80::/10) + multicast (ff00::/8)\n\tif (/^f[cd][0-9a-f]{2}:/.test(host)) return true;\n\tif (/^fe[89ab][0-9a-f]:/.test(host)) return true;\n\tif (/^ff[0-9a-f]{2}:/.test(host)) return true;\n\n\t// IPv4-mapped IPv6 — `::ffff:127.0.0.1` or `::ffff:7f00:0001`\n\tconst mapped = host.match(/^::ffff:(.+)$/);\n\tif (mapped) {\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\tconst inner = mapped[1]!;\n\t\t// Dotted form: rerun v4 checks.\n\t\tif (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(inner)) {\n\t\t\tfor (const p of PRIVATE_V4_PATTERNS) if (p.test(inner)) return true;\n\t\t}\n\t\t// Hex form: 7f00:0001 → 127.0.0.1\n\t\tconst hex = inner.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n\t\tif (hex) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst a = Number.parseInt(hex[1]!, 16);\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst b = Number.parseInt(hex[2]!, 16);\n\t\t\tconst dotted = `${(a >> 8) & 0xff}.${a & 0xff}.${(b >> 8) & 0xff}.${b & 0xff}`;\n\t\t\tfor (const p of PRIVATE_V4_PATTERNS) if (p.test(dotted)) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t// NAT64 (`64:ff9b::/96`) embeds an IPv4 address in the low 32 bits —\n\t// classify it exactly like the IPv4-mapped case above (dotted or hex).\n\tconst nat64 = host.match(/^64:ff9b::(.+)$/);\n\tif (nat64) {\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\tconst inner = nat64[1]!;\n\t\tif (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(inner)) {\n\t\t\tfor (const p of PRIVATE_V4_PATTERNS) if (p.test(inner)) return true;\n\t\t}\n\t\tconst hex = inner.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n\t\tif (hex) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst a = Number.parseInt(hex[1]!, 16);\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst b = Number.parseInt(hex[2]!, 16);\n\t\t\tconst dotted = `${(a >> 8) & 0xff}.${a & 0xff}.${(b >> 8) & 0xff}.${b & 0xff}`;\n\t\t\tfor (const p of PRIVATE_V4_PATTERNS) if (p.test(dotted)) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tfor (const p of PRIVATE_V4_PATTERNS) {\n\t\tif (p.test(host)) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Reject hostnames spelled as private IPs (cheap, synchronous, no I/O — a\n * fast-fail pre-filter). DNS-level rebinding (hostname that *resolves* to a\n * private IP at egress time) is NOT caught here — see `checkEgressAllowed`,\n * which resolves DNS and validates every returned address.\n */\nfunction isPrivateEgress(url: string): boolean {\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch {\n\t\treturn true; // malformed URL: reject\n\t}\n\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n\t\treturn true;\n\t}\n\n\t// Strip brackets from IPv6 literals.\n\tconst raw = parsed.hostname.toLowerCase();\n\tconst host =\n\t\traw.startsWith(\"[\") && raw.endsWith(\"]\") ? raw.slice(1, -1) : raw;\n\n\tif (host === \"localhost\") return true;\n\treturn isPrivateIp(host);\n}\n\n/** How often the emitter re-probes receivers' TLS certificates. */\nconst RECEIVER_CERT_INTERVAL_MS = 30 * 60_000;\n\nexport function allowPrivateEgress(): boolean {\n\treturn process.env.SECONDLAYER_ALLOW_PRIVATE_EGRESS === \"true\";\n}\n\ninterface ResolvedAddress {\n\taddress: string;\n\tfamily: number;\n}\n\ntype DnsLookupFn = (hostname: string) => Promise<ResolvedAddress[]>;\n\nasync function defaultDnsLookup(hostname: string): Promise<ResolvedAddress[]> {\n\treturn dnsLookup(hostname, { all: true });\n}\n\nlet dnsLookupImpl: DnsLookupFn = defaultDnsLookup;\n\n/**\n * Test-only seam: inject a fake DNS resolver so tests can simulate a hostname\n * resolving to a private/metadata IP without depending on real DNS or\n * network access. Pass `null` to restore the real `dns.lookup`-backed\n * resolver. Production code never calls this — only `ssrf.test.ts` does.\n */\nexport function __setDnsLookupForTest(fn: DnsLookupFn | null): void {\n\tdnsLookupImpl = fn ?? defaultDnsLookup;\n}\n\nconst ALLOW_HINT = \"(set SECONDLAYER_ALLOW_PRIVATE_EGRESS=true to allow)\";\n\n/**\n * Full egress check: literal fast-fail, then resolve DNS and reject if *any*\n * returned address (not just the first) is private/loopback/link-local —\n * a single private answer among several is enough for an attacker to abuse.\n *\n * Residual TOCTOU: this resolves-and-validates *immediately before* `fetch()`\n * but does not pin the actual connection to the validated address. True\n * pinning (resolve once, connect to that literal IP, keep the original `Host`\n * header/SNI) was attempted per plan f053 via a custom undici `Agent` with\n * `connect.lookup` passed as `fetch()`'s `dispatcher` — the standard Node\n * ecosystem pattern for this. Empirically, under Bun 1.3.10, that hook was\n * silently never invoked (confirmed with a throwaway smoke test hitting a\n * real local HTTP server: `lookupCalled` stayed `false` and the connection\n * failed even though the dispatcher was passed) — Bun's `fetch()` does not\n * implement undici's `connect.lookup` dispatcher hook, whether reached via\n * the global `fetch` or `import { fetch } from \"undici\"` (Bun overrides\n * \"undici\"'s `fetch` export with its own native implementation regardless of\n * an installed real `undici` package). Re-tested under Bun 1.4.2 (plan 043):\n * identical result — `lookupCalled` still stays `false` via both the global\n * `fetch` and `import { fetch } from \"undici\"`, so the gap remains unfixed at\n * this version too. So a second DNS answer between this check and `fetch()`'s\n * own resolution (true rebinding, not just a one-time private answer) could\n * in theory still slip through. This closes the practical rebinding gap\n * (attacker's hostname resolves private at delivery time) without adding a\n * dependency; a network-level egress allowlist/proxy is the recommended\n * defense-in-depth for the remaining TOCTOU sliver.\n */\nexport async function checkEgressAllowed(url: string): Promise<string | null> {\n\tif (isPrivateEgress(url)) {\n\t\treturn `refused private egress: literal address ${ALLOW_HINT}`;\n\t}\n\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch {\n\t\treturn `refused private egress: malformed URL ${ALLOW_HINT}`;\n\t}\n\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n\t\treturn `refused private egress: unsupported protocol ${ALLOW_HINT}`;\n\t}\n\n\tconst raw = parsed.hostname.toLowerCase();\n\tconst hostname =\n\t\traw.startsWith(\"[\") && raw.endsWith(\"]\") ? raw.slice(1, -1) : raw;\n\n\tlet resolved: ResolvedAddress[];\n\ttry {\n\t\tresolved = await dnsLookupImpl(hostname);\n\t} catch (err) {\n\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\treturn `refused private egress: DNS resolution failed (${msg}) ${ALLOW_HINT}`;\n\t}\n\tif (resolved.length === 0) {\n\t\treturn `refused private egress: DNS resolution returned no addresses ${ALLOW_HINT}`;\n\t}\n\tfor (const { address } of resolved) {\n\t\tif (isPrivateIp(address)) {\n\t\t\treturn `refused private egress: hostname resolves to private address ${address} ${ALLOW_HINT}`;\n\t\t}\n\t}\n\treturn null;\n}\n\n/** The wire result of one POST attempt (no DB side effect) — shared by the\n * emitter hot path and the `deliverTestEvent` test path. */\ninterface PostResult {\n\tok: boolean;\n\tstatusCode: number | null;\n\terror: string | null;\n\tdurationMs: number;\n\tresponseBody: string | null;\n\tresponseHeaders: Record<string, string> | null;\n}\n\n/**\n * Bound on redirect hops honored while delivering a webhook. `fetch` is\n * called with `redirect: \"manual\"` so a 3xx never auto-follows — each hop's\n * target is re-validated through `checkEgressAllowed` before it is fetched\n * (see `postToWebhook`), otherwise a `Location` header pointing at a\n * private/metadata address would bypass the egress guard entirely. Counts\n * every fetch issued (the initial request plus each redirect), so this is\n * also the max number of `fetch` calls one delivery attempt can make.\n */\nexport const MAX_REDIRECT_HOPS: number = 3;\n\n/** POST a pre-built body to a webhook URL with the SSRF guard + timeout.\n * Pure transport: returns the attempt result; the caller logs the delivery row.\n * Follows redirects manually (up to `MAX_REDIRECT_HOPS`), re-running the\n * egress guard against every hop's target — the guard only protects the\n * first request otherwise, and a webhook target can redirect to a private/\n * metadata address to read back the response after f053 pinned the guard to\n * just the original URL. */\nasync function postToWebhook(\n\turl: string,\n\tbody: string,\n\theaders: Record<string, string>,\n\ttimeoutMs: number,\n): Promise<PostResult> {\n\tconst start = performance.now();\n\tlet target = url;\n\tlet statusCode: number | null = null;\n\tlet error: string | null = null;\n\tlet ok = false;\n\tlet responseBody = \"\";\n\tlet responseHeaders: Record<string, string> | null = null;\n\ttry {\n\t\tfor (let hop = 0; ; hop++) {\n\t\t\tif (!allowPrivateEgress()) {\n\t\t\t\tconst refusal = await checkEgressAllowed(target);\n\t\t\t\tif (refusal) {\n\t\t\t\t\tlogger.warn(\"[emitter] refused private egress\", {\n\t\t\t\t\t\turl: target,\n\t\t\t\t\t\treason: refusal,\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\tstatusCode: null,\n\t\t\t\t\t\terror: refusal,\n\t\t\t\t\t\tdurationMs: Math.round(performance.now() - start),\n\t\t\t\t\t\tresponseBody: null,\n\t\t\t\t\t\tresponseHeaders: null,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hop >= MAX_REDIRECT_HOPS) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tstatusCode,\n\t\t\t\t\terror: `too many redirects (exceeded ${MAX_REDIRECT_HOPS} hops)`,\n\t\t\t\t\tdurationMs: Math.round(performance.now() - start),\n\t\t\t\t\tresponseBody: null,\n\t\t\t\t\tresponseHeaders: null,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst res = await fetch(target, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders,\n\t\t\t\tbody,\n\t\t\t\tredirect: \"manual\",\n\t\t\t\tsignal: AbortSignal.timeout(timeoutMs),\n\t\t\t});\n\t\t\tstatusCode = res.status;\n\n\t\t\tconst location = res.headers.get(\"location\");\n\t\t\tif (res.status >= 300 && res.status < 400 && location) {\n\t\t\t\ttarget = new URL(location, target).toString();\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tok = res.ok;\n\t\t\t// Collect small response preview for the delivery log (≤8KB).\n\t\t\tconst buf = await res.arrayBuffer();\n\t\t\tconst truncated = buf.byteLength > 8192 ? buf.slice(0, 8192) : buf;\n\t\t\tresponseBody = Buffer.from(truncated).toString(\"utf8\");\n\t\t\tresponseHeaders = Object.fromEntries(res.headers.entries());\n\t\t\tbreak;\n\t\t}\n\t} catch (err) {\n\t\terror = err instanceof Error ? err.message : String(err);\n\t}\n\treturn {\n\t\tok,\n\t\tstatusCode,\n\t\terror,\n\t\tdurationMs: Math.round(performance.now() - start),\n\t\tresponseBody: responseBody || null,\n\t\tresponseHeaders,\n\t};\n}\n\n/**\n * Test-only seam: exposes `postToWebhook` (otherwise module-private) so\n * redirect/egress behavior can be exercised directly against a stubbed\n * `fetch` + injected DNS lookup, without standing up the DB-backed emitter\n * loop. Production code never calls this — only tests do.\n */\nexport const __postToWebhookForTest: (\n\turl: string,\n\tbody: string,\n\theaders: Record<string, string>,\n\ttimeoutMs: number,\n) => Promise<PostResult> = postToWebhook;\n\nasync function dispatchOne(\n\tdb: Kysely<Database>,\n\toutboxRow: WebhookOutbox,\n\tsub: Webhook,\n): Promise<{\n\tok: boolean;\n\tstatusCode: number | null;\n\terror: string | null;\n\tdurationMs: number;\n}> {\n\tconst { body, headers } = buildForFormat(\n\t\toutboxRow,\n\t\tsub,\n\t\tgetWebhookSigningSecret(sub),\n\t);\n\tconst r = await postToWebhook(sub.url, body, headers, sub.timeout_ms);\n\n\tconst attempt = outboxRow.attempt + 1;\n\tawait db\n\t\t.insertInto(\"webhook_deliveries\")\n\t\t.values({\n\t\t\toutbox_id: outboxRow.id,\n\t\t\twebhook_id: outboxRow.webhook_id,\n\t\t\tattempt,\n\t\t\tstatus_code: r.statusCode,\n\t\t\tresponse_headers: r.responseHeaders,\n\t\t\tresponse_body: r.responseBody,\n\t\t\terror_message: r.error,\n\t\t\tduration_ms: r.durationMs,\n\t\t})\n\t\t.execute();\n\n\treturn {\n\t\tok: r.ok,\n\t\tstatusCode: r.statusCode,\n\t\terror: r.error,\n\t\tdurationMs: r.durationMs,\n\t};\n}\n\n/** A representative (non-persisted) outbox row for a test delivery, so\n * `buildForFormat` produces a realistic body. */\nfunction buildTestOutboxRow(sub: Webhook): WebhookOutbox {\n\tconst now = new Date();\n\treturn {\n\t\tid: randomUUID(),\n\t\twebhook_id: sub.id,\n\t\tkind: sub.kind,\n\t\tblock_height: 0,\n\t\ttx_id: null,\n\t\trow_pk: null,\n\t\tevent_type: \"chain.test.apply\",\n\t\tpayload: {\n\t\t\ttest: true,\n\t\t\tmessage: \"Secondlayer test delivery\",\n\t\t\twebhook_id: sub.id,\n\t\t\tsent_at: now.toISOString(),\n\t\t},\n\t\tdedup_key: `test:${sub.id}:${now.getTime()}`,\n\t\tattempt: 0,\n\t\tnext_attempt_at: now,\n\t\tstatus: \"pending\",\n\t\tis_replay: false,\n\t\tblock_time: null,\n\t\tdelivered_at: null,\n\t\tfailed_at: null,\n\t\tlocked_by: null,\n\t\tlocked_until: null,\n\t\tlast_error: null,\n\t\tcreated_at: now,\n\t};\n}\n\n/**\n * Build a representative webhook for `sub`'s configured format, POST it (same\n * SSRF guard + timeout + signing as a real delivery), and log a delivery row\n * with a null `outbox_id` so it appears under the webhook's deliveries\n * without being tied to a queued event. Powers `POST /:id/test`.\n */\nexport async function deliverTestEvent(\n\tdb: Kysely<Database>,\n\tsub: Webhook,\n): Promise<WebhookTestResult> {\n\tconst testRow = buildTestOutboxRow(sub);\n\tconst { body, headers } = buildForFormat(\n\t\ttestRow,\n\t\tsub,\n\t\tgetWebhookSigningSecret(sub),\n\t);\n\tconst r = await postToWebhook(sub.url, body, headers, sub.timeout_ms);\n\tconst inserted = await db\n\t\t.insertInto(\"webhook_deliveries\")\n\t\t.values({\n\t\t\toutbox_id: null,\n\t\t\twebhook_id: sub.id,\n\t\t\tattempt: 1,\n\t\t\tstatus_code: r.statusCode,\n\t\t\tresponse_headers: r.responseHeaders,\n\t\t\tresponse_body: r.responseBody,\n\t\t\terror_message: r.error,\n\t\t\tduration_ms: r.durationMs,\n\t\t})\n\t\t.returning(\"id\")\n\t\t.executeTakeFirstOrThrow();\n\treturn {\n\t\tok: r.ok,\n\t\tstatusCode: r.statusCode,\n\t\terror: r.error,\n\t\tdurationMs: r.durationMs,\n\t\tdeliveryId: inserted.id,\n\t};\n}\n\nasync function settleDelivered(\n\tdb: Kysely<Database>,\n\toutboxRow: WebhookOutbox,\n): Promise<void> {\n\tawait db.transaction().execute(async (tx) => {\n\t\tconst result = await tx\n\t\t\t.updateTable(\"webhook_outbox\")\n\t\t\t.set({\n\t\t\t\tstatus: \"delivered\",\n\t\t\t\tdelivered_at: new Date(),\n\t\t\t\tattempt: outboxRow.attempt + 1,\n\t\t\t\tlocked_by: null,\n\t\t\t\tlocked_until: null,\n\t\t\t})\n\t\t\t// Guard against a reorg that marked this row `dead` (orphaned) while\n\t\t\t// the POST was in flight — settling a delivery outcome must never\n\t\t\t// resurrect a row the reorg already decided is gone. `status='pending'`\n\t\t\t// is the only state a claimed row can settle from.\n\t\t\t.where(\"id\", \"=\", outboxRow.id)\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.executeTakeFirst();\n\t\tif (Number(result.numUpdatedRows ?? 0) === 0) {\n\t\t\tlogger.info(\"webhook.settle.orphaned\", {\n\t\t\t\toutboxId: outboxRow.id,\n\t\t\t\twebhookId: outboxRow.webhook_id,\n\t\t\t\toutcome: \"delivered\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tawait tx\n\t\t\t.updateTable(\"webhooks\")\n\t\t\t.set({\n\t\t\t\tlast_delivery_at: new Date(),\n\t\t\t\tlast_success_at: new Date(),\n\t\t\t\tcircuit_failures: 0,\n\t\t\t\tlast_error: null,\n\t\t\t\tupdated_at: new Date(),\n\t\t\t})\n\t\t\t.where(\"id\", \"=\", outboxRow.webhook_id)\n\t\t\t.execute();\n\n\t\t// Hosted-stack event meter (plan 044, step 5): counts a real delivery,\n\t\t// never a retry (this function only runs on the successful outcome) and\n\t\t// never a test delivery (`deliverTestEvent` never calls this). A no-op\n\t\t// on self-host (WEBHOOK_METER_SOCKET unset).\n\t\trecordDelivery();\n\t});\n}\n\nasync function settleFailed(\n\tdb: Kysely<Database>,\n\toutboxRow: WebhookOutbox,\n\tsub: Webhook,\n\terrText: string,\n): Promise<void> {\n\tconst attempt = outboxRow.attempt + 1;\n\tconst isDead = attempt >= sub.max_retries;\n\tconst nextAt = isDead\n\t\t? null\n\t\t: new Date(Date.now() + nextDelaySeconds(outboxRow.attempt) * 1000);\n\n\tawait db.transaction().execute(async (tx) => {\n\t\tconst result = await tx\n\t\t\t.updateTable(\"webhook_outbox\")\n\t\t\t.set({\n\t\t\t\tattempt,\n\t\t\t\tnext_attempt_at: nextAt ?? new Date(),\n\t\t\t\tstatus: isDead ? \"dead\" : \"pending\",\n\t\t\t\tfailed_at: isDead ? new Date() : null,\n\t\t\t\tlocked_by: null,\n\t\t\t\tlocked_until: null,\n\t\t\t})\n\t\t\t// Guard against a reorg that marked this row `dead` (orphaned) while\n\t\t\t// the POST was in flight — see the matching guard in `settleDelivered`.\n\t\t\t.where(\"id\", \"=\", outboxRow.id)\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.executeTakeFirst();\n\t\tif (Number(result.numUpdatedRows ?? 0) === 0) {\n\t\t\tlogger.info(\"webhook.settle.orphaned\", {\n\t\t\t\toutboxId: outboxRow.id,\n\t\t\t\twebhookId: outboxRow.webhook_id,\n\t\t\t\toutcome: \"failed\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Atomic increment — concurrent failures must not clobber each other.\n\t\t// `RETURNING circuit_failures` gives us the post-increment value to\n\t\t// decide whether this failure tripped the circuit.\n\t\tconst incResult = await sql<{ circuit_failures: number }>`\n\t\t\tUPDATE webhooks\n\t\t\tSET circuit_failures = circuit_failures + 1,\n\t\t\t\tlast_delivery_at = NOW(),\n\t\t\t\tlast_error = ${errText.slice(0, 500)},\n\t\t\t\tupdated_at = NOW()\n\t\t\tWHERE id = ${sub.id}\n\t\t\tRETURNING circuit_failures\n\t\t`.execute(tx);\n\t\tconst newFailures =\n\t\t\tincResult.rows[0]?.circuit_failures ?? sub.circuit_failures + 1;\n\t\tconst shouldTripCircuit = newFailures >= CIRCUIT_THRESHOLD;\n\n\t\tif (shouldTripCircuit) {\n\t\t\t// Transition to paused only on the first failure that crossed\n\t\t\t// the threshold — additional failures in-flight harmlessly\n\t\t\t// re-set the same fields.\n\t\t\tawait tx\n\t\t\t\t.updateTable(\"webhooks\")\n\t\t\t\t.set({\n\t\t\t\t\tstatus: \"paused\",\n\t\t\t\t\tcircuit_opened_at: new Date(),\n\t\t\t\t\tupdated_at: new Date(),\n\t\t\t\t})\n\t\t\t\t.where(\"id\", \"=\", sub.id)\n\t\t\t\t.execute();\n\t\t\tlogger.warn(\n\t\t\t\t\"Webhook circuit tripped — paused after consecutive failures\",\n\t\t\t\t{\n\t\t\t\t\twebhook: sub.name,\n\t\t\t\t\tfailures: newFailures,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t});\n}\n\n/** What woke this claim cycle — purely for the diagnostic log below; the\n * claim/dispatch logic itself doesn't branch on it. `\"drain-loop\"` marks a\n * pass this function re-ran on itself (see `claimAndDrain`) because a wake\n * arrived (or a per-lane batch cap was hit) while the previous pass was\n * still claiming. `\"changed\"` is a resume (or any webhook edit) — see the\n * `webhooks:changed` listener. */\ntype ClaimTrigger = \"notify\" | \"poll\" | \"startup\" | \"changed\" | \"drain-loop\";\n\n/**\n * The regression this closes: a NOTIFY that arrives while a claim cycle is\n * ALREADY running used to be dropped on the floor (the `claimInFlight` guard\n * below just returned 0), and nothing re-checked once that cycle finished.\n * Rows inserted mid-cycle — a normal burst of ~6 chain-webhook matches per\n * block — sat `pending` until an UNRELATED future wake happened to fire, or\n * the 2-minute safety poll.\n *\n * The holder of `claimInFlight` now keeps looping (`claimPending`, set by any\n * caller that finds the lock held) until a pass claims nothing NEW and no one\n * asked for a recheck while it ran — so a burst drains fully off one wake\n * instead of needing one wake per claim-sized chunk. Critically, this lock\n * wraps ONLY `claimAndDispatchOnce`'s DB claim query, never dispatch (see its\n * doc) — a slow or hanging receiver must never hold up the next claim.\n */\nasync function claimAndDrain(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\temitterId: string,\n\ttrigger: ClaimTrigger,\n): Promise<number> {\n\tif (state.claimInFlight) {\n\t\tstate.claimPending = true;\n\t\treturn 0;\n\t}\n\tstate.claimInFlight = true;\n\t// Assigned synchronously (before any `await` in `runClaimLoop` yields back\n\t// to the event loop) so `stopEmitter` can always await the pass that\n\t// actually owns the lock, never a concurrent caller's already-resolved\n\t// `claimPending` short-circuit above.\n\tconst drainPromise = runClaimLoop(db, state, emitterId, trigger);\n\tstate.currentClaim = drainPromise;\n\ttry {\n\t\treturn await drainPromise;\n\t} finally {\n\t\tif (state.currentClaim === drainPromise) state.currentClaim = null;\n\t}\n}\n\nasync function runClaimLoop(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\temitterId: string,\n\ttrigger: ClaimTrigger,\n): Promise<number> {\n\tlet totalClaimed = 0;\n\ttry {\n\t\tlet currentTrigger = trigger;\n\t\tfor (;;) {\n\t\t\t// Stop requested: claim no new rows. Anything already claimed by an\n\t\t\t// in-flight `claimAndDispatchOnce` call still gets handed to its\n\t\t\t// sub's queue, but `pumpSub`'s own `state.running` check means it\n\t\t\t// won't dispatch — those rows just keep their lock until the next\n\t\t\t// emitter re-claims them after LOCK_WINDOW_MS.\n\t\t\tif (!state.running) break;\n\t\t\tstate.claimPending = false;\n\t\t\tconst result = await claimAndDispatchOnce(\n\t\t\t\tdb,\n\t\t\t\tstate,\n\t\t\t\temitterId,\n\t\t\t\tcurrentTrigger,\n\t\t\t);\n\t\t\ttotalClaimed += result.claimed;\n\t\t\t// Keep going while either: a wake landed mid-pass (claimPending —\n\t\t\t// set by the guard above, from another caller), or either lane\n\t\t\t// (live/replay) came back full, meaning more may be waiting behind\n\t\t\t// it. Comparing against the LANE limits, not the combined batch\n\t\t\t// size, matters: live traffic alone is capped at `liveLimit` (90%\n\t\t\t// of BATCH_SIZE) and would never reach the full BATCH_SIZE on its\n\t\t\t// own, so that comparison never re-looped on a live-only backlog.\n\t\t\tif (!state.claimPending && !result.mayHaveMore) break;\n\t\t\tcurrentTrigger = \"drain-loop\";\n\t\t}\n\t} finally {\n\t\tstate.claimInFlight = false;\n\t}\n\treturn totalClaimed;\n}\n\ninterface ClaimResult {\n\tclaimed: number;\n\tdispatched: number;\n\treleased: number;\n\tmayHaveMore: boolean;\n}\n\n/**\n * One claim pass: SELECT a batch, mark it locked, then hand each sub's slice\n * to its persistent queue and return — WITHOUT waiting for any of it to\n * dispatch. Caller (`claimAndDrain`) owns the re-loop and the `claimInFlight`\n * lock, which now covers only this function's DB work.\n *\n * This decoupling is the fix for the emitter-wide latency regression: the\n * previous version awaited `Promise.all(subIds.map(drainForSub))` — every\n * sub's FULL dispatch — before returning, so the slowest receiver in a batch\n * (a hung connection, a multi-second response) held the process-wide claim\n * lock for as long as IT took, starving every other sub's claims (including\n * a fast sub's own fresh rows) for that whole time. Claiming is now a single\n * short transaction; delivery happens on each sub's own independent\n * queue/semaphore (`enqueueForSub`/`pumpSub`), so one sub's pace never\n * gates another's.\n *\n * Also fixes the \"stuck rows\" bug: a row claimed for a sub that turns out to\n * be `paused` (status read fresh here, after the claim) is released\n * IMMEDIATELY — `next_attempt_at` reset to now, lock cleared — instead of\n * being silently abandoned with its lock held for the full `LOCK_WINDOW_MS`.\n * The old code's `if (sub.status !== \"active\") return;` left the row\n * claimed-but-untouched: locked, `next_attempt_at` pushed far into the\n * future, never dispatched, never settled — a resumed webhook's backlog\n * then only drained once each row's stale lock happened to expire.\n */\nasync function claimAndDispatchOnce(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\temitterId: string,\n\ttrigger: ClaimTrigger,\n): Promise<ClaimResult> {\n\t// FOR UPDATE SKIP LOCKED — multiple emitters split the batch.\n\t// 90/10 live vs replay so a big replay doesn't starve live emits.\n\tconst liveLimit = Math.max(1, Math.round(BATCH_SIZE * LIVE_SHARE));\n\tconst replayLimit = BATCH_SIZE - liveLimit;\n\tconst { combined, liveCount, replayCount } = await db\n\t\t.transaction()\n\t\t.execute(async (tx) => {\n\t\t\tconst live = await sql<WebhookOutbox>`\n\t\t\t\t\tSELECT * FROM webhook_outbox\n\t\t\t\t\tWHERE status = 'pending'\n\t\t\t\t\t\tAND next_attempt_at <= NOW()\n\t\t\t\t\t\tAND is_replay = FALSE\n\t\t\t\t\tORDER BY next_attempt_at ASC\n\t\t\t\t\tFOR UPDATE SKIP LOCKED\n\t\t\t\t\tLIMIT ${sql.lit(liveLimit)}\n\t\t\t\t`.execute(tx);\n\t\t\tconst replay = await sql<WebhookOutbox>`\n\t\t\t\t\tSELECT * FROM webhook_outbox\n\t\t\t\t\tWHERE status = 'pending'\n\t\t\t\t\t\tAND next_attempt_at <= NOW()\n\t\t\t\t\t\tAND is_replay = TRUE\n\t\t\t\t\tORDER BY next_attempt_at ASC\n\t\t\t\t\tFOR UPDATE SKIP LOCKED\n\t\t\t\t\tLIMIT ${sql.lit(replayLimit)}\n\t\t\t\t`.execute(tx);\n\n\t\t\tconst rows = [...live.rows, ...replay.rows];\n\t\t\tif (rows.length === 0) {\n\t\t\t\treturn { combined: rows, liveCount: 0, replayCount: 0 };\n\t\t\t}\n\n\t\t\t// Push `next_attempt_at` forward by the lock window. This is\n\t\t\t// the only defense against double-dispatch if the emitter\n\t\t\t// process crashes mid-HTTP-call: the row won't be re-claimable\n\t\t\t// until `LOCK_WINDOW_MS` elapses, giving us a stale-lock\n\t\t\t// recovery window. `settleDelivered`/`settleFailed` overrides\n\t\t\t// this on the success/failure path (and the paused-sub release\n\t\t\t// below overrides it on the \"never got dispatched\" path).\n\t\t\tconst now = new Date();\n\t\t\tconst lockUntil = new Date(now.getTime() + LOCK_WINDOW_MS);\n\t\t\tawait tx\n\t\t\t\t.updateTable(\"webhook_outbox\")\n\t\t\t\t.set({\n\t\t\t\t\tlocked_by: emitterId,\n\t\t\t\t\tlocked_until: lockUntil,\n\t\t\t\t\tnext_attempt_at: lockUntil,\n\t\t\t\t})\n\t\t\t\t.where(\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"in\",\n\t\t\t\t\trows.map((r) => r.id),\n\t\t\t\t)\n\t\t\t\t.execute();\n\t\t\treturn {\n\t\t\t\tcombined: rows,\n\t\t\t\tliveCount: live.rows.length,\n\t\t\t\treplayCount: replay.rows.length,\n\t\t\t};\n\t\t});\n\n\tif (combined.length === 0) {\n\t\treturn { claimed: 0, dispatched: 0, released: 0, mayHaveMore: false };\n\t}\n\n\tconst bySubId = new Map<string, WebhookOutbox[]>();\n\tfor (const row of combined) {\n\t\tconst arr = bySubId.get(row.webhook_id);\n\t\tif (arr) arr.push(row);\n\t\telse bySubId.set(row.webhook_id, [row]);\n\t}\n\n\tconst subIds = Array.from(bySubId.keys());\n\tconst subs = await db\n\t\t.selectFrom(\"webhooks\")\n\t\t.selectAll()\n\t\t.where(\"id\", \"in\", subIds)\n\t\t.execute();\n\tconst subById = new Map(subs.map((s) => [s.id, s]));\n\n\tlet dispatched = 0;\n\tlet released = 0;\n\tconst releasedIds: string[] = [];\n\tfor (const subId of subIds) {\n\t\tconst sub = subById.get(subId);\n\t\t// biome-ignore lint/style/noNonNullAssertion: key came from bySubId itself\n\t\tconst rows = bySubId.get(subId)!;\n\t\tif (!sub || sub.status !== \"active\") {\n\t\t\treleased += rows.length;\n\t\t\treleasedIds.push(...rows.map((r) => r.id));\n\t\t\tcontinue;\n\t\t}\n\t\tdispatched += rows.length;\n\t\tenqueueForSub(db, state, sub, rows);\n\t}\n\n\tif (releasedIds.length > 0) {\n\t\t// Claimable again immediately: a webhook that's already resumed by the\n\t\t// time we notice the release loses nothing waiting for LOCK_WINDOW_MS\n\t\t// (up to several minutes) to expire on its own.\n\t\tawait db\n\t\t\t.updateTable(\"webhook_outbox\")\n\t\t\t.set({ next_attempt_at: new Date(), locked_by: null, locked_until: null })\n\t\t\t.where(\"id\", \"in\", releasedIds)\n\t\t\t.execute();\n\t}\n\n\t// One line per claim pass: what woke it, how much it found, how it split\n\t// between dispatched-now and released-back (paused), how stale the oldest\n\t// row was, and how loaded the in-flight pool already was — everything\n\t// needed to tell \"briefly busy\" apart from \"actually stuck\" without\n\t// reproducing it live. `in_flight`/`concurrency` sum across only the subs\n\t// THIS pass touched (a quiet sub's unrelated cap doesn't dilute the\n\t// reading).\n\tconst oldestCreatedAtMs = Math.min(\n\t\t...combined.map((r) => new Date(r.created_at).getTime()),\n\t);\n\tconst inFlight = subIds.reduce(\n\t\t(sum, id) => sum + (state.subQueues.get(id)?.inFlight ?? 0),\n\t\t0,\n\t);\n\tconst concurrency = subIds.reduce(\n\t\t(sum, id) => sum + (subById.get(id)?.concurrency || 4),\n\t\t0,\n\t);\n\tlogger.info(\"emitter claim cycle\", {\n\t\tevent: \"emitter_claim\",\n\t\ttrigger,\n\t\tclaimed: combined.length,\n\t\tdispatched,\n\t\treleased,\n\t\toldest_created_at_age_ms: Date.now() - oldestCreatedAtMs,\n\t\tin_flight: inFlight,\n\t\tconcurrency,\n\t});\n\n\treturn {\n\t\tclaimed: combined.length,\n\t\tdispatched,\n\t\treleased,\n\t\tmayHaveMore: liveCount >= liveLimit || replayCount >= replayLimit,\n\t};\n}\n\n/**\n * Hand `rows` to `sub`'s persistent queue and try to start dispatching\n * immediately. Decoupled from the claim transaction on purpose (see\n * `claimAndDispatchOnce`'s doc) — a slow or hanging sub's in-flight HTTP\n * calls must never hold up the next claim, for this sub or any other.\n *\n * `sub` is refreshed here on every call (not just on first creation) so a\n * status/concurrency change since the last batch — most importantly a\n * pause — is picked up by `pumpSub` without waiting for anything to expire.\n */\nfunction enqueueForSub(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\tsub: Webhook,\n\trows: WebhookOutbox[],\n): void {\n\tlet sq = state.subQueues.get(sub.id);\n\tif (!sq) {\n\t\tsq = { sub, queue: [], inFlight: 0 };\n\t\tstate.subQueues.set(sub.id, sq);\n\t} else {\n\t\tsq.sub = sub;\n\t}\n\tsq.queue.push(...rows);\n\tpumpSub(db, state, sub.id);\n}\n\n/**\n * Start as many workers as the sub's remaining concurrency allows, pulling\n * from its queue. Reentrant-safe without an explicit lock: every branch here\n * is synchronous (the only `await` lives in `runOne`, called but not\n * awaited), so JS's single-threaded execution means two calls — one from\n * `enqueueForSub`, one from a just-finished worker's `finally` — can never\n * interleave mid-loop; each runs to completion before the other starts.\n */\nfunction pumpSub(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\tsubId: string,\n): void {\n\tconst sq = state.subQueues.get(subId);\n\tif (!sq) return;\n\tconst cap = sq.sub.concurrency || 4;\n\twhile (\n\t\tstate.running &&\n\t\tsq.sub.status === \"active\" &&\n\t\tsq.inFlight < cap &&\n\t\tsq.queue.length > 0\n\t) {\n\t\tconst row = sq.queue.shift();\n\t\tif (!row) break;\n\t\tsq.inFlight++;\n\t\tconst runPromise = runOne(db, state, sq, row);\n\t\tstate.inFlightRuns.add(runPromise);\n\t\tvoid runPromise.finally(() => {\n\t\t\tstate.inFlightRuns.delete(runPromise);\n\t\t});\n\t}\n}\n\n/** Dispatch one claimed row end to end (POST, settle), then release its\n * in-flight slot and try to pull more work for the same sub. */\nasync function runOne(\n\tdb: Kysely<Database>,\n\tstate: RunningState,\n\tsq: SubQueue,\n\trow: WebhookOutbox,\n): Promise<void> {\n\ttry {\n\t\tconst result = await dispatchOne(db, row, sq.sub);\n\t\tif (result.ok) {\n\t\t\tawait settleDelivered(db, row);\n\t\t} else {\n\t\t\tconst err = result.error ?? `HTTP ${result.statusCode ?? \"?\"}`;\n\t\t\tawait settleFailed(db, row, sq.sub, err);\n\t\t}\n\t} catch (err) {\n\t\tlogger.error(\"Emitter dispatch crashed\", {\n\t\t\toutboxId: row.id,\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\tawait settleFailed(\n\t\t\tdb,\n\t\t\trow,\n\t\t\tsq.sub,\n\t\t\terr instanceof Error ? err.message : String(err),\n\t\t);\n\t} finally {\n\t\tsq.inFlight--;\n\t\tpumpSub(db, state, sq.sub.id);\n\t}\n}\n\nexport interface StartEmitterOptions {\n\t/** Interval for the background poll (ms). Defaults to 2 minutes. */\n\tpollIntervalMs?: number;\n\t/** Retention sweep interval (ms). Defaults to 1 hour. */\n\tretentionIntervalMs?: number;\n\t/** Bound for the returned stop function's clean-shutdown drain — how long\n\t * it waits for the current claim pass + in-flight dispatches before\n\t * giving up and reporting them abandoned. Defaults to\n\t * `MAX_WEBHOOK_TIMEOUT_MS + 5_000` (a dispatch can't legitimately run\n\t * longer than the webhook timeout ceiling). `MAX_WEBHOOK_TIMEOUT_MS` is\n\t * fixed at module load from `WEBHOOK_TIMEOUT_MS_CEILING`, so this exists\n\t * mainly for tests that need a short bound without a 5-minute wait. */\n\tstopDrainDeadlineMs?: number;\n}\n\nasync function runRetention(db: Kysely<Database>): Promise<void> {\n\t// Replays first: their final counts come from outbox rows the deletes below\n\t// remove. Then delivered outbox >7d, deliveries >30d, dead outbox >90d,\n\t// finished replay records >90d.\n\tawait finalizeReplays(db);\n\tawait sql`\n\t\tDELETE FROM webhook_outbox\n\t\tWHERE status = 'delivered' AND delivered_at < NOW() - interval '7 days'\n\t`.execute(db);\n\tawait sql`\n\t\tDELETE FROM webhook_deliveries\n\t\tWHERE dispatched_at < NOW() - interval '30 days'\n\t`.execute(db);\n\tawait sql`\n\t\tDELETE FROM webhook_outbox\n\t\tWHERE status = 'dead' AND failed_at < NOW() - interval '90 days'\n\t`.execute(db);\n\tawait sql`\n\t\tDELETE FROM webhook_replays\n\t\tWHERE finished_at < NOW() - interval '90 days'\n\t`.execute(db);\n}\n\nexport async function startEmitter(\n\topts?: StartEmitterOptions,\n): Promise<() => Promise<void>> {\n\tconst emitterId = `emitter-${Math.random().toString(36).slice(2, 10)}`;\n\tconst db = getTargetDb();\n\tconst state: RunningState = {\n\t\trunning: true,\n\t\tsubQueues: new Map(),\n\t\tclaimInFlight: false,\n\t\tclaimPending: false,\n\t\tcurrentClaim: null,\n\t\tinFlightRuns: new Set(),\n\t};\n\tconst pollIntervalMs = opts?.pollIntervalMs ?? 120_000;\n\tconst retentionIntervalMs = opts?.retentionIntervalMs ?? 60 * 60_000;\n\n\tlogger.info(\"[emitter] started\", { id: emitterId });\n\n\t// LISTEN on new outbox + sub changes. Both channels fire on the TARGET DB\n\t// (webhook_outbox + webhooks are control-plane tables), so bind the\n\t// listener there — under the split it is NOT `DATABASE_URL`.\n\tconst listenUrl = targetListenerUrl();\n\tconst stopNew = await listen(\n\t\t\"webhooks:new_outbox\",\n\t\t() => {\n\t\t\tif (!state.running) return;\n\t\t\tvoid claimAndDrain(db, state, emitterId, \"notify\").catch((err) =>\n\t\t\t\tlogger.error(\"[emitter] claim failed\", {\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\t{ connectionString: listenUrl },\n\t);\n\tconst stopChanged = await listen(\n\t\t\"webhooks:changed\",\n\t\t() => {\n\t\t\tif (!state.running) return;\n\t\t\t// A resume is exactly `webhooks:changed` — its rows were already\n\t\t\t// released back to claimable (see claimAndDispatchOnce's paused-sub\n\t\t\t// branch) as soon as we noticed the pause, so a resumed webhook's\n\t\t\t// backlog drains on the SAME event that flips it active again,\n\t\t\t// instead of waiting for an unrelated future notify or the poll.\n\t\t\tvoid claimAndDrain(db, state, emitterId, \"changed\").catch((err) =>\n\t\t\t\tlogger.error(\"[emitter] claim failed\", {\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\t{ connectionString: listenUrl },\n\t);\n\t// Names both channels + the exact host/db LISTENed on (no credentials) so\n\t// a split-DB misconfiguration — the wake never reaching this process — is\n\t// visible in `docker logs` at boot, not only inferred from a delivery\n\t// latency graph later.\n\tlogger.info(\"[emitter] wake listeners connected\", {\n\t\tchannels: [\"webhooks:new_outbox\", \"webhooks:changed\"],\n\t\tdb: describeDbUrl(listenUrl),\n\t});\n\n\t// Poll every pollIntervalMs as a safety net for missed notifications +\n\t// backoff wakeups (rows whose next_attempt_at has passed).\n\tconst poll = setInterval(() => {\n\t\tif (!state.running) return;\n\t\tvoid claimAndDrain(db, state, emitterId, \"poll\").catch((err) =>\n\t\t\tlogger.error(\"[emitter] poll claim failed\", {\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t}),\n\t\t);\n\t}, pollIntervalMs);\n\n\t// Kick once on startup so any rows that arrived before we started drain.\n\tvoid claimAndDrain(db, state, emitterId, \"startup\");\n\n\t// Retention sweep — hourly by default.\n\tconst retention = setInterval(() => {\n\t\tif (!state.running) return;\n\t\tvoid runRetention(db).catch((err) =>\n\t\t\tlogger.error(\"[emitter] retention failed\", {\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t}),\n\t\t);\n\t}, retentionIntervalMs);\n\n\t// Receiver TLS expiry probe: Bun's fetch can't read peer certificates.\n\tconst receiverCerts = setInterval(() => {\n\t\tif (!state.running) return;\n\t\tvoid refreshReceiverCerts(db).catch((err) =>\n\t\t\tlogger.error(\"[emitter] receiver cert refresh failed\", {\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t}),\n\t\t);\n\t}, RECEIVER_CERT_INTERVAL_MS);\n\n\treturn async () => {\n\t\t// No new claims start (`runClaimLoop`'s own check) and no new\n\t\t// dispatches start (`pumpSub`'s own check) from this point on — the\n\t\t// two sets we're about to await can only shrink from here.\n\t\tstate.running = false;\n\t\tclearInterval(poll);\n\t\tclearInterval(retention);\n\t\tclearInterval(receiverCerts);\n\t\tawait stopNew();\n\t\tawait stopChanged();\n\n\t\tconst pendingRuns = new Set(state.inFlightRuns);\n\t\tconst drainTarget = pendingRuns.size;\n\t\t// `runOne` never rejects (it catches into `settleFailed`), but a claim\n\t\t// pass could — swallow that here rather than let it crash shutdown; the\n\t\t// call site that kicked off the claim already logs its own errors.\n\t\tconst claimSettled = (state.currentClaim ?? Promise.resolve()).catch(\n\t\t\t() => {},\n\t\t);\n\t\tconst waitAll = Promise.all([claimSettled, ...pendingRuns]);\n\t\t// A dispatch can't legitimately run longer than the webhook timeout\n\t\t// ceiling — bound the wait so a hung receiver can't hold up shutdown\n\t\t// forever. Rows still claimed/locked at the deadline keep their lock\n\t\t// and are re-claimed by the next emitter after LOCK_WINDOW_MS.\n\t\tconst deadlineMs =\n\t\t\topts?.stopDrainDeadlineMs ?? MAX_WEBHOOK_TIMEOUT_MS + 5_000;\n\t\tlet timedOut = false;\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst timeout = new Promise<void>((resolve) => {\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\ttimedOut = true;\n\t\t\t\tresolve();\n\t\t\t}, deadlineMs);\n\t\t});\n\t\tawait Promise.race([waitAll, timeout]);\n\t\tclearTimeout(timer);\n\n\t\tconst abandoned = timedOut ? state.inFlightRuns.size : 0;\n\t\tconst drained = drainTarget - abandoned;\n\t\tlogger.info(\"[emitter] stopped\", {\n\t\t\tid: emitterId,\n\t\t\tevent: \"emitter_stopped\",\n\t\t\tdrained,\n\t\t\tabandoned,\n\t\t});\n\t};\n}\n",
6
6
  "import { signSecondlayerWebhook } from \"@secondlayer/shared/crypto/secondlayer-webhook\";\nimport type { Webhook, WebhookOutbox } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { buildCloudEvents } from \"./cloudevents.ts\";\nimport { buildCloudflare } from \"./cloudflare.ts\";\nimport { buildInngest } from \"./inngest.ts\";\nimport { buildRaw } from \"./raw.ts\";\nimport { buildStandardWebhooks } from \"./standard-webhooks.ts\";\nimport { buildTrigger } from \"./trigger.ts\";\n\nexport interface FormatBuildResult {\n\tbody: string;\n\theaders: Record<string, string>;\n}\n\nfunction buildBody(\n\toutboxRow: WebhookOutbox,\n\tsub: Webhook,\n\tsigningSecret: string,\n): FormatBuildResult {\n\tswitch (sub.format) {\n\t\tcase \"inngest\":\n\t\t\treturn buildInngest(outboxRow);\n\t\tcase \"trigger\":\n\t\t\treturn buildTrigger(outboxRow, sub);\n\t\tcase \"cloudflare\":\n\t\t\treturn buildCloudflare(outboxRow, sub);\n\t\tcase \"cloudevents\":\n\t\t\treturn buildCloudEvents(outboxRow, sub);\n\t\tcase \"raw\":\n\t\t\treturn buildRaw(outboxRow, sub);\n\t\tcase \"standard-webhooks\":\n\t\t\treturn buildStandardWebhooks(outboxRow, signingSecret);\n\t\tdefault:\n\t\t\tlogger.warn(\"Unknown webhook format, falling back to standard-webhooks\", {\n\t\t\t\tformat: sub.format,\n\t\t\t\twebhookId: sub.id,\n\t\t\t});\n\t\t\treturn buildStandardWebhooks(outboxRow, signingSecret);\n\t}\n}\n\n/**\n * Dispatch an outbox row through the format matching the webhook's\n * `format` column. Unknown formats fall back to `standard-webhooks` with\n * a warning log — receivers always get something deliverable.\n *\n * Every delivery, whatever its body shape, also gets the universal Secondlayer\n * authenticity headers (`webhook-id` + `X-Secondlayer-Signature`) so a receiver\n * can prove the payload came from us with one published public key — not just\n * the `standard-webhooks` format. The signature covers the exact body bytes\n * built here, so it must be attached after the body is final.\n */\nexport function buildForFormat(\n\toutboxRow: WebhookOutbox,\n\tsub: Webhook,\n\tsigningSecret: string,\n): FormatBuildResult {\n\tconst result = buildBody(outboxRow, sub, signingSecret);\n\tconst sigHeaders = signSecondlayerWebhook(outboxRow.id, result.body);\n\tif (sigHeaders) {\n\t\tresult.headers = { ...result.headers, ...sigHeaders };\n\t}\n\treturn result;\n}\n\nexport {\n\tbuildStandardWebhooks,\n\tbuildInngest,\n\tbuildTrigger,\n\tbuildCloudflare,\n\tbuildCloudEvents,\n\tbuildRaw,\n};\n",
7
7
  "import type { Webhook, WebhookOutbox } from \"@secondlayer/shared/db\";\n\n/**\n * CloudEvents 1.0 structured JSON — https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/formats/json-format.md\n *\n * Body shape:\n * {\n * \"specversion\": \"1.0\",\n * \"type\": \"chain.<trigger>.apply\",\n * \"source\": \"secondlayer:<chain>\", // stacks | bitcoin\n * \"id\": <outbox.id>, // UUID, used for dedup\n * \"time\": <ISO 8601>,\n * \"datacontenttype\": \"application/json\",\n * \"data\": { ...event }\n * }\n *\n * Content-Type is `application/cloudevents+json; charset=utf-8`. Binary\n * mode (headers as ce-*) isn't needed — structured mode is what every CE\n * SDK accepts out of the box.\n */\n\n/** The chain that produced the event. Runes (Bitcoin) payloads carry\n * `chain: \"bitcoin\"`; every other trigger matches Stacks events. */\nfunction chainOf(payload: unknown): \"stacks\" | \"bitcoin\" {\n\treturn (payload as { chain?: unknown } | null)?.chain === \"bitcoin\"\n\t\t? \"bitcoin\"\n\t\t: \"stacks\";\n}\n\nexport function buildCloudEvents(\n\toutboxRow: WebhookOutbox,\n\t_sub: Webhook,\n): { body: string; headers: Record<string, string> } {\n\tconst event = {\n\t\tspecversion: \"1.0\",\n\t\ttype: outboxRow.event_type,\n\t\tsource: `secondlayer:${chainOf(outboxRow.payload)}`,\n\t\tid: outboxRow.id,\n\t\ttime: new Date(outboxRow.created_at).toISOString(),\n\t\tdatacontenttype: \"application/json\",\n\t\tdata: outboxRow.payload,\n\t};\n\treturn {\n\t\tbody: JSON.stringify(event),\n\t\theaders: {\n\t\t\t\"content-type\": \"application/cloudevents+json; charset=utf-8\",\n\t\t},\n\t};\n}\n",
8
8
  "import { decryptSecret } from \"@secondlayer/shared/crypto/secrets\";\nimport type { Webhook, WebhookOutbox } from \"@secondlayer/shared/db\";\n\n/**\n * Cloudflare Workflows — https://developers.cloudflare.com/workflows/build/events-and-parameters/\n *\n * POST https://api.cloudflare.com/client/v4/accounts/{account}/workflows/{name}/instances\n * Authorization: Bearer <CF_API_TOKEN>\n *\n * Body: `{ params }` — the workflow entrypoint receives this as the\n * `event.payload` object. We slip the outbox id into `params._outboxId`\n * so Workflows can dedupe on replays.\n */\n\nfunction resolveBearer(sub: Webhook): string | null {\n\tconst cfg = sub.auth_config as { token?: string; tokenEnc?: string };\n\tif (cfg.tokenEnc) {\n\t\t// Let decrypt errors propagate — see trigger.ts comment.\n\t\treturn decryptSecret(Buffer.from(cfg.tokenEnc, \"base64\"));\n\t}\n\treturn cfg.token ?? null;\n}\n\nexport function buildCloudflare(\n\toutboxRow: WebhookOutbox,\n\tsub: Webhook,\n): { body: string; headers: Record<string, string> } {\n\tconst body = JSON.stringify({\n\t\tparams: {\n\t\t\t...(outboxRow.payload as Record<string, unknown>),\n\t\t\t_type: outboxRow.event_type,\n\t\t\t_outboxId: outboxRow.id,\n\t\t},\n\t});\n\tconst headers: Record<string, string> = {\n\t\t\"content-type\": \"application/json\",\n\t};\n\tconst token = resolveBearer(sub);\n\tif (token) headers.authorization = `Bearer ${token}`;\n\treturn { body, headers };\n}\n",
@@ -13,7 +13,7 @@
13
13
  "/**\n * Hosted-stack event meter counter (plan 044, step 5). Counts webhook\n * deliveries (never retries) and pushes the count to the provisioner over a\n * unix socket every 60s. Inert unless `WEBHOOK_METER_SOCKET` is set — a\n * self-host instance never has this env var, so this module is a total\n * no-op there (no socket, no interval, no behavior change).\n *\n * Runs only inside `webhook-processor` (`webhook-service.ts` /\n * `webhook-plane.ts`) — never the subgraph indexer, never `api`. Counts\n * never touch this instance's own Postgres, so once 046 runs customer\n * handler code in `api`, that code has no path to lower them (Design,\n * \"Open\" section).\n */\n\nimport { logger } from \"@secondlayer/shared\";\n\nconst FLUSH_INTERVAL_MS = 60_000;\n\nlet pending = 0;\nlet flushTimer: ReturnType<typeof setInterval> | undefined;\n\n/** Socket path this process pushes to, or `undefined` when the meter is\n * off (self-host, or hosted before this env is wired). Read once at\n * `startMeterSocketReporter()` time, not per-call, so a mid-process env\n * mutation (tests) can't half-apply. */\nfunction socketPath(env: NodeJS.ProcessEnv = process.env): string | undefined {\n\tconst path = env.WEBHOOK_METER_SOCKET?.trim();\n\treturn path && path.length > 0 ? path : undefined;\n}\n\n/** Count one delivered event (never a retry — call this only from the path\n * that already excludes retries, `emitter.ts`'s `settleDelivered`). A\n * no-op with zero overhead when the meter is off. */\nexport function recordDelivery(): void {\n\tif (!socketPath()) return;\n\tpending += 1;\n}\n\nasync function flush(path: string): Promise<void> {\n\tconst count = pending;\n\tif (count === 0) return;\n\t// Optimistic reset before the push: if the push fails we've undercounted\n\t// by at most one interval's worth once (logged below), never double-count\n\t// on a retry — the alternative (reset after success) risks double-adding\n\t// events recorded during a slow/failed push into the NEXT flush.\n\tpending = 0;\n\ttry {\n\t\tconst res = await fetch(\"http://localhost/\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({ delivered_events: count }),\n\t\t\tunix: path,\n\t\t});\n\t\tif (!res.ok) {\n\t\t\tlogger.warn(\"webhook.meter_socket.push_rejected\", {\n\t\t\t\tstatus: res.status,\n\t\t\t\tcount,\n\t\t\t});\n\t\t}\n\t} catch (err) {\n\t\t// The provisioner's socket may not be listening yet (mid-provision) or\n\t\t// briefly restarting — never fatal to webhook delivery, which is this\n\t\t// process's actual job.\n\t\tlogger.warn(\"webhook.meter_socket.push_failed\", {\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\tcount,\n\t\t});\n\t}\n}\n\n/** Starts the 60s flush loop when `WEBHOOK_METER_SOCKET` is set; a no-op\n * (returns a no-op stop function) otherwise. Idempotent — a second call\n * while already running clears the previous interval first. */\nexport function startMeterSocketReporter(): () => void {\n\tconst path = socketPath();\n\tif (!path) return () => {};\n\n\tif (flushTimer) clearInterval(flushTimer);\n\tflushTimer = setInterval(() => {\n\t\tflush(path).catch(() => {}); // flush() already logs; never throw into the timer\n\t}, FLUSH_INTERVAL_MS);\n\n\treturn () => {\n\t\tif (flushTimer) {\n\t\t\tclearInterval(flushTimer);\n\t\t\tflushTimer = undefined;\n\t\t}\n\t};\n}\n\n/** Test-only: reset the module-level counter between test files. */\nexport function resetMeterSocketCounterForTests(): void {\n\tpending = 0;\n}\n\n/** Test-only: read the current unflushed count. */\nexport function pendingCountForTests(): number {\n\treturn pending;\n}\n",
14
14
  "import { isIP } from \"node:net\";\nimport tls from \"node:tls\";\nimport type { Database } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { type Kysely, sql } from \"kysely\";\nimport { allowPrivateEgress, checkEgressAllowed } from \"./emitter.ts\";\n\n/**\n * Receiver TLS certificate expiry. Bun's `fetch` does not expose the peer\n * certificate, so the emitter probes each https origin out of band with\n * `node:tls` (works under Bun) and stores the result on `webhooks`.\n */\n\nconst PROBE_TIMEOUT_MS = 5_000;\nconst RECHECK_AFTER_HOURS = 6;\nconst BATCH_LIMIT = 50;\n\n/**\n * Leaf certificate expiry of an https receiver, or null for non-https URLs,\n * refused egress, connection errors and timeouts. Never throws. Passes the\n * same egress guard as deliveries.\n */\nexport async function probeCertExpiry(\n\turl: string,\n\topts?: { connect?: typeof tls.connect; timeoutMs?: number },\n): Promise<Date | null> {\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (parsed.protocol !== \"https:\") return null;\n\n\tif (!allowPrivateEgress()) {\n\t\tlet refusal: string | null;\n\t\ttry {\n\t\t\trefusal = await checkEgressAllowed(url);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t\tif (refusal) return null;\n\t}\n\n\tconst raw = parsed.hostname;\n\tconst host =\n\t\traw.startsWith(\"[\") && raw.endsWith(\"]\") ? raw.slice(1, -1) : raw;\n\tconst connect = opts?.connect ?? tls.connect;\n\tconst timeoutMs = opts?.timeoutMs ?? PROBE_TIMEOUT_MS;\n\n\treturn new Promise<Date | null>((resolve) => {\n\t\tconst open: { socket?: tls.TLSSocket } = {};\n\t\tlet settled = false;\n\t\tconst finish = (expires: Date | null) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tclearTimeout(timer);\n\t\t\ttry {\n\t\t\t\topen.socket?.destroy();\n\t\t\t} catch {\n\t\t\t\t// already closed\n\t\t\t}\n\t\t\tresolve(expires);\n\t\t};\n\t\tconst timer = setTimeout(() => finish(null), timeoutMs);\n\t\tlet probe: tls.TLSSocket;\n\t\ttry {\n\t\t\tprobe = connect({\n\t\t\t\thost,\n\t\t\t\tport: Number(parsed.port) || 443,\n\t\t\t\t...(isIP(host) ? {} : { servername: host }),\n\t\t\t\t// Only the leaf cert is read and no data is sent, so an expired or\n\t\t\t\t// self-signed cert must still report its expiry.\n\t\t\t\trejectUnauthorized: false,\n\t\t\t});\n\t\t} catch {\n\t\t\tfinish(null);\n\t\t\treturn;\n\t\t}\n\t\topen.socket = probe;\n\t\tprobe.once(\"secureConnect\", () => {\n\t\t\ttry {\n\t\t\t\tconst expires = new Date(probe.getPeerCertificate().valid_to);\n\t\t\t\tfinish(Number.isNaN(expires.getTime()) ? null : expires);\n\t\t\t} catch {\n\t\t\t\tfinish(null);\n\t\t\t}\n\t\t});\n\t\tprobe.once(\"error\", () => finish(null));\n\t});\n}\n\n/**\n * Probe the https receivers whose expiry is unknown or older than six hours.\n * One probe per distinct origin; every selected webhook on that origin gets\n * the result (which may be null) and a fresh `receiver_cert_checked_at`.\n */\nexport async function refreshReceiverCerts(\n\tdb: Kysely<Database>,\n\topts?: { probe?: (url: string) => Promise<Date | null> },\n): Promise<void> {\n\tconst probe = opts?.probe ?? probeCertExpiry;\n\tconst due = await db\n\t\t.selectFrom(\"webhooks\")\n\t\t.select([\"id\", \"url\"])\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.where(\"url\", \"like\", \"https:%\")\n\t\t.where((eb) =>\n\t\t\teb.or([\n\t\t\t\teb(\"receiver_cert_checked_at\", \"is\", null),\n\t\t\t\teb(\n\t\t\t\t\t\"receiver_cert_checked_at\",\n\t\t\t\t\t\"<\",\n\t\t\t\t\tsql<Date>`now() - make_interval(hours => ${RECHECK_AFTER_HOURS})`,\n\t\t\t\t),\n\t\t\t]),\n\t\t)\n\t\t.orderBy(sql`receiver_cert_checked_at asc nulls first`)\n\t\t.limit(BATCH_LIMIT)\n\t\t.execute();\n\n\tconst idsByOrigin = new Map<string, { url: string; ids: string[] }>();\n\tfor (const { id, url } of due) {\n\t\tlet origin: string;\n\t\ttry {\n\t\t\torigin = new URL(url).origin;\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tconst entry = idsByOrigin.get(origin) ?? { url, ids: [] };\n\t\tentry.ids.push(id);\n\t\tidsByOrigin.set(origin, entry);\n\t}\n\n\tfor (const [origin, { url, ids }] of idsByOrigin) {\n\t\tconst expires = await probe(url);\n\t\tawait db\n\t\t\t.updateTable(\"webhooks\")\n\t\t\t.set({\n\t\t\t\treceiver_cert_expires_at: expires,\n\t\t\t\treceiver_cert_checked_at: new Date(),\n\t\t\t})\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.execute();\n\t\tlogger.debug(\"[emitter] receiver cert probed\", {\n\t\t\torigin,\n\t\t\texpiresAt: expires?.toISOString() ?? null,\n\t\t});\n\t}\n}\n"
15
15
  ],
16
- "mappings": ";AAAA;AACA,mBAAS;AACT;AAAA;AAAA;AAAA;AAOA;AACA,mBAAS;AACT;AACA;AAAA;AAAA;AAIA,gBAAsB;;;AChBtB;AAEA;;;ACqBA,SAAS,OAAO,CAAC,SAAwC;AAAA,EACxD,OAAQ,SAAwC,UAAU,YACvD,YACA;AAAA;AAGG,SAAS,gBAAgB,CAC/B,WACA,MACoD;AAAA,EACpD,MAAM,QAAQ;AAAA,IACb,aAAa;AAAA,IACb,MAAM,UAAU;AAAA,IAChB,QAAQ,eAAe,QAAQ,UAAU,OAAO;AAAA,IAChD,IAAI,UAAU;AAAA,IACd,MAAM,IAAI,KAAK,UAAU,UAAU,EAAE,YAAY;AAAA,IACjD,iBAAiB;AAAA,IACjB,MAAM,UAAU;AAAA,EACjB;AAAA,EACA,OAAO;AAAA,IACN,MAAM,KAAK,UAAU,KAAK;AAAA,IAC1B,SAAS;AAAA,MACR,gBAAgB;AAAA,IACjB;AAAA,EACD;AAAA;;;AC/CD;AAcA,SAAS,aAAa,CAAC,KAA6B;AAAA,EACnD,MAAM,MAAM,IAAI;AAAA,EAChB,IAAI,IAAI,UAAU;AAAA,IAEjB,OAAO,cAAc,OAAO,KAAK,IAAI,UAAU,QAAQ,CAAC;AAAA,EACzD;AAAA,EACA,OAAO,IAAI,SAAS;AAAA;AAGd,SAAS,eAAe,CAC9B,WACA,KACoD;AAAA,EACpD,MAAM,OAAO,KAAK,UAAU;AAAA,IAC3B,QAAQ;AAAA,SACH,UAAU;AAAA,MACd,OAAO,UAAU;AAAA,MACjB,WAAW,U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A,IACf,qBAAqB,EAAE,EAAE,MAAM,CAAC,QACpC,QAAO,MAAM,0CAA0C;AAAA,MACtD,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,IACvD,CAAC,CACF;AAAA,KACE,yBAAyB;AAAA,EAE5B,OAAO,YAAY;AAAA,IAIlB,MAAM,UAAU;AAAA,IAChB,cAAc,IAAI;AAAA,IAClB,cAAc,SAAS;AAAA,IACvB,cAAc,aAAa;AAAA,IAC3B,MAAM,QAAQ;AAAA,IACd,MAAM,YAAY;AAAA,IAElB,MAAM,cAAc,IAAI,IAAI,MAAM,YAAY;AAAA,IAC9C,MAAM,cAAc,YAAY;AAAA,IAIhC,MAAM,gBAAgB,MAAM,gBAAgB,QAAQ,QAAQ,GAAG,MAC9D,MAAM,EACP;AAAA,IACA,MAAM,UAAU,QAAQ,IAAI,CAAC,cAAc,GAAG,WAAW,CAAC;AAAA,IAK1D,MAAM,aACL,MAAM,uBAAuB,yBAAyB;AAAA,IACvD,IAAI,WAAW;AAAA,IACf,IAAI;AAAA,IACJ,MAAM,UAAU,IAAI,QAAc,CAAC,YAAY;AAAA,MAC9C,QAAQ,WAAW,MAAM;AAAA,QACxB,WAAW;AAAA,QACX,QAAQ;AAAA,SACN,UAAU;AAAA,KACb;AAAA,IACD,MAAM,QAAQ,KAAK,CAAC,SAAS,OAAO,CAAC;AAAA,IACrC,aAAa,KAAK;AAAA,IAElB,MAAM,YAAY,WAAW,MAAM,aAAa,OAAO;AAAA,IACvD,MAAM,UAAU,cAAc;AAAA,IAC9B,QAAO,KAAK,qBAAqB;AAAA,MAChC,IAAI;AAAA,MACJ,OAAO;AAAA,MACP;AAAA,MACA;AAAA,IACD,CAAC;AAAA;AAAA;",
17
+ "debugId": "12212061F8671F0B64756E2164756E21",
18
18
  "names": []
19
19
  }
@@ -75,20 +75,7 @@ interface BlockSource {
75
75
  */
76
76
  getDecodedHeights?(): Record<string, number | null> | undefined;
77
77
  }
78
- /** Thrown by {@link replayWebhook} when a replay is already running for the
79
- * webhook. The route maps this to 409; `force` does not bypass it — a forced
80
- * re-delivery still has to wait for the previous replay to finish. */
81
- declare class ReplayInProgressError extends Error {
82
- constructor();
83
- }
84
- /**
85
- * Test-only seam: directly mark (or clear) a webhook as having an in-flight
86
- * replay. Two real concurrent `replayWebhook` calls race the same DB fetch,
87
- * so which one wins the guard isn't deterministic in a test; this lets a test
88
- * exercise the guard (and the route's 409 mapping) without that race.
89
- * Production code never calls this.
90
- */
91
- declare function __setReplayInFlightForTest(webhookId: string, inFlight: boolean): void;
78
+ import { ReplayInProgressError } from "@secondlayer/shared/db/queries/webhook-replays";
92
79
  interface ReplayInput {
93
80
  accountId: string;
94
81
  webhookId: string;
@@ -103,7 +90,9 @@ interface ReplayResult {
103
90
  enqueuedCount: number;
104
91
  scannedCount: number;
105
92
  }
106
- declare function replayWebhook(input: ReplayInput): Promise<ReplayResult>;
93
+ declare function replayWebhook(input: ReplayInput, opts?: {
94
+ source?: BlockSource;
95
+ }): Promise<ReplayResult>;
107
96
  /**
108
97
  * Replay a webhook by re-running the pure matcher over a historical
109
98
  * canonical block range and emitting fresh apply rows. The matcher is
@@ -117,4 +106,4 @@ declare function replayWebhook(input: ReplayInput): Promise<ReplayResult>;
117
106
  declare function replayChainWebhook(db: Kysely3<Database3>, sub: Webhook, input: ReplayInput, opts?: {
118
107
  source?: BlockSource;
119
108
  }): Promise<ReplayResult>;
120
- export { ReplayInProgressError, ReplayInput, ReplayResult, __setReplayInFlightForTest, replayChainWebhook, replayWebhook };
109
+ export { ReplayInProgressError, ReplayInput, ReplayResult, replayChainWebhook, replayWebhook };
@@ -1,7 +1,13 @@
1
1
  // src/runtime/replay.ts
2
2
  import { createHash as createHash2 } from "node:crypto";
3
3
  import { getTargetDb } from "@secondlayer/shared/db";
4
+ import {
5
+ beginReplay,
6
+ failScan,
7
+ finishScan
8
+ } from "@secondlayer/shared/db/queries/webhook-replays";
4
9
  import { getWebhook } from "@secondlayer/shared/db/queries/webhooks";
10
+ import { getErrorMessage } from "@secondlayer/shared/errors";
5
11
  import { logger as logger2 } from "@secondlayer/shared/logger";
6
12
 
7
13
  // src/runtime/block-source.ts
@@ -17,7 +23,7 @@ import { createHash } from "node:crypto";
17
23
  // package.json
18
24
  var package_default = {
19
25
  name: "@secondlayer/subgraphs",
20
- version: "7.6.0",
26
+ version: "7.7.1",
21
27
  description: "Describe the Stacks data you want as one TypeScript file; it fills itself and survives reorgs.",
22
28
  license: "MIT",
23
29
  repository: {
@@ -77,8 +83,8 @@ var package_default = {
77
83
  prepublishOnly: "bun run build"
78
84
  },
79
85
  dependencies: {
80
- "@secondlayer/shared": "^13.5.0",
81
- "@secondlayer/stacks": "^6.4.0",
86
+ "@secondlayer/shared": "^14.0.0",
87
+ "@secondlayer/stacks": "^6.5.1",
82
88
  "@secondlayer/verify": "^0.6.0",
83
89
  esbuild: "^0.28.2",
84
90
  kysely: "0.28.17",
@@ -1818,7 +1824,7 @@ function applyRow(meta, blockHeight, blockHash, txId, eventIndex, event, replayI
1818
1824
  event_type: `chain.${meta.triggerType}.apply`,
1819
1825
  payload,
1820
1826
  dedup_key: chainDedupKey(meta.webhookId, txId, eventIndex, blockHash, replayId, clock),
1821
- ...replayId ? { is_replay: true } : {},
1827
+ ...replayId ? { is_replay: true, replay_id: replayId } : {},
1822
1828
  ...blockTime ? { block_time: blockTime } : {}
1823
1829
  };
1824
1830
  }
@@ -2002,6 +2008,7 @@ async function emitSbtcOutbox(db, chainSubs, blockHeight, blockHash, blockTime,
2002
2008
  }
2003
2009
 
2004
2010
  // src/runtime/replay.ts
2011
+ import { ReplayInProgressError } from "@secondlayer/shared/db/queries/webhook-replays";
2005
2012
  var WEBHOOK_REPLAY_MAX_BLOCKS_DEFAULT = 1e5;
2006
2013
  function webhookReplayMaxBlocks() {
2007
2014
  const raw = process.env.WEBHOOK_REPLAY_MAX_BLOCKS;
@@ -2013,25 +2020,11 @@ function webhookReplayMaxBlocks() {
2013
2020
  function formatBlockCount(n) {
2014
2021
  return n % 1000 === 0 ? `${n / 1000}k` : `${n}`;
2015
2022
  }
2016
- var inFlightReplays = new Set;
2017
-
2018
- class ReplayInProgressError extends Error {
2019
- constructor() {
2020
- super("replay already in progress for this webhook");
2021
- this.name = "ReplayInProgressError";
2022
- }
2023
- }
2024
- function __setReplayInFlightForTest(webhookId, inFlight) {
2025
- if (inFlight)
2026
- inFlightReplays.add(webhookId);
2027
- else
2028
- inFlightReplays.delete(webhookId);
2029
- }
2030
2023
  function deterministicReplayId(webhookId, fromBlock, toBlock, suffix) {
2031
2024
  const canonical = `${webhookId}:${fromBlock}:${toBlock}${suffix ? `:${suffix}` : ""}`;
2032
2025
  return createHash2("sha256").update(canonical).digest("hex").slice(0, 16);
2033
2026
  }
2034
- async function replayWebhook(input) {
2027
+ async function replayWebhook(input, opts) {
2035
2028
  if (input.fromBlock > input.toBlock) {
2036
2029
  throw new Error("fromBlock must be <= toBlock");
2037
2030
  }
@@ -2043,14 +2036,23 @@ async function replayWebhook(input) {
2043
2036
  const sub = await getWebhook(db, input.accountId, input.webhookId);
2044
2037
  if (!sub)
2045
2038
  throw new Error("Webhook not found");
2046
- if (inFlightReplays.has(sub.id)) {
2047
- throw new ReplayInProgressError;
2048
- }
2049
- inFlightReplays.add(sub.id);
2039
+ const replayId = deterministicReplayId(sub.id, input.fromBlock, input.toBlock, input.replayIdSuffix);
2040
+ await beginReplay(db, {
2041
+ id: replayId,
2042
+ webhookId: sub.id,
2043
+ fromBlock: input.fromBlock,
2044
+ toBlock: input.toBlock
2045
+ });
2050
2046
  try {
2051
- return await replayChainWebhook(db, sub, input);
2052
- } finally {
2053
- inFlightReplays.delete(sub.id);
2047
+ const result = await replayChainWebhook(db, sub, input, opts);
2048
+ await finishScan(db, replayId, {
2049
+ scanned: result.scannedCount,
2050
+ enqueued: result.enqueuedCount
2051
+ });
2052
+ return result;
2053
+ } catch (err) {
2054
+ await failScan(db, replayId, getErrorMessage(err));
2055
+ throw err;
2054
2056
  }
2055
2057
  }
2056
2058
  var CHAIN_REPLAY_BATCH = 200;
@@ -2098,10 +2100,9 @@ async function replayChainWebhook(db, sub, input, opts) {
2098
2100
  }
2099
2101
  export {
2100
2102
  ReplayInProgressError,
2101
- __setReplayInFlightForTest,
2102
2103
  replayChainWebhook,
2103
2104
  replayWebhook
2104
2105
  };
2105
2106
 
2106
- //# debugId=CCB8A7AC4502FC8864756E2164756E21
2107
+ //# debugId=2D04DFEBDA1A131664756E2164756E21
2107
2108
  //# sourceMappingURL=replay.js.map