@secondlayer/subgraphs 6.6.1 → 7.0.0

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.
@@ -1,20 +1,18 @@
1
1
  {
2
2
  "version": 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/webhook-state.ts", "src/runtime/emitter-matcher.ts"],
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"],
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 { refreshMatcher } from \"./webhook-state.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\nfunction 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, shaped to the\n * webhook's kind so `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\tsubgraph_name: sub.subgraph_name ?? null,\n\t\ttable_name: sub.table_name ?? null,\n\t\tblock_height: 0,\n\t\ttx_id: null,\n\t\trow_pk: null,\n\t\tevent_type:\n\t\t\tsub.kind === \"chain\"\n\t\t\t\t? \"chain.test.apply\"\n\t\t\t\t: `${sub.subgraph_name ?? \"subgraph\"}.${sub.table_name ?? \"test\"}.created`,\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// Bootstrap matcher from active subs. Retry with backoff — if this\n\t// stays broken, fail loud rather than run with an empty matcher (which\n\t// would silently drop every block's outbox emissions until the next\n\t// webhook CRUD fired `webhooks:changed`).\n\tconst MATCHER_BOOT_ATTEMPTS = 5;\n\tlet lastErr: unknown = null;\n\tfor (let i = 0; i < MATCHER_BOOT_ATTEMPTS; i++) {\n\t\ttry {\n\t\t\tawait refreshMatcher(db);\n\t\t\tlastErr = null;\n\t\t\tbreak;\n\t\t} catch (err) {\n\t\t\tlastErr = err;\n\t\t\tconst delayMs = 500 * 2 ** i; // 500ms, 1s, 2s, 4s, 8s\n\t\t\tlogger.warn(\"[emitter] matcher refresh failed, retrying\", {\n\t\t\t\tattempt: i + 1,\n\t\t\t\tdelayMs,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\tawait new Promise((r) => setTimeout(r, delayMs));\n\t\t}\n\t}\n\tif (lastErr) {\n\t\tthrow new Error(\n\t\t\t`[emitter] matcher refresh failed ${MATCHER_BOOT_ATTEMPTS}×; aborting boot: ${\n\t\t\t\tlastErr instanceof Error ? lastErr.message : String(lastErr)\n\t\t\t}`,\n\t\t);\n\t}\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\tvoid refreshMatcher(db).catch((err) =>\n\t\t\t\tlogger.error(\"[emitter] matcher refresh 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\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\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\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 { 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\";\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\nfunction 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\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\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
- "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\": \"<subgraph>.<table>.<created|updated|deleted>\",\n * \"source\": \"secondlayer:<subgraph_name>\",\n * \"id\": <outbox.id>, // UUID, used for dedup\n * \"time\": <ISO 8601>,\n * \"datacontenttype\": \"application/json\",\n * \"data\": { ...row }\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\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:${outboxRow.subgraph_name}`,\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",
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",
9
- "import type { WebhookOutbox } from \"@secondlayer/shared/db\";\n\n/**\n * Inngest event format — https://www.inngest.com/docs/events/sending-events\n *\n * POST body is a JSON array of one or more events. The Inngest event key\n * goes in the URL path (`https://inn.gs/e/{EVENT_KEY}`), so the user sets\n * that on `webhook.url` directly — no auth header needed.\n *\n * Body per event:\n * - `name` — event name `<subgraph>.<table>.<created|updated|deleted>`\n * so it matches Inngest fn `event` triggers out of the box\n * - `data` — row payload\n * - `id` — dedupes on Inngest's side (mirrors outbox id)\n * - `ts` — unix millis when the event occurred\n * - `v` — version tag, fixed at `\"2026-04-23.v1\"` for forward compat\n */\n\nexport const INNGEST_VERSION = \"2026-04-23.v1\";\n\nexport function buildInngest(outboxRow: WebhookOutbox): {\n\tbody: string;\n\theaders: Record<string, string>;\n} {\n\tconst event = {\n\t\tname: outboxRow.event_type,\n\t\tdata: outboxRow.payload,\n\t\tid: outboxRow.id,\n\t\tts: new Date(outboxRow.created_at).getTime(),\n\t\tv: INNGEST_VERSION,\n\t};\n\treturn {\n\t\tbody: JSON.stringify([event]),\n\t\theaders: {\n\t\t\t\"content-type\": \"application/json\",\n\t\t},\n\t};\n}\n",
9
+ "import type { WebhookOutbox } from \"@secondlayer/shared/db\";\n\n/**\n * Inngest event format — https://www.inngest.com/docs/events/sending-events\n *\n * POST body is a JSON array of one or more events. The Inngest event key\n * goes in the URL path (`https://inn.gs/e/{EVENT_KEY}`), so the user sets\n * that on `webhook.url` directly — no auth header needed.\n *\n * Body per event:\n * - `name` — event name, e.g. `chain.stx_transfer.apply`, so it\n * matches Inngest fn `event` triggers out of the box\n * - `data` — event payload\n * - `id` — dedupes on Inngest's side (mirrors outbox id)\n * - `ts` — unix millis when the event occurred\n * - `v` — version tag, fixed at `\"2026-04-23.v1\"` for forward compat\n */\n\nexport const INNGEST_VERSION = \"2026-04-23.v1\";\n\nexport function buildInngest(outboxRow: WebhookOutbox): {\n\tbody: string;\n\theaders: Record<string, string>;\n} {\n\tconst event = {\n\t\tname: outboxRow.event_type,\n\t\tdata: outboxRow.payload,\n\t\tid: outboxRow.id,\n\t\tts: new Date(outboxRow.created_at).getTime(),\n\t\tv: INNGEST_VERSION,\n\t};\n\treturn {\n\t\tbody: JSON.stringify([event]),\n\t\theaders: {\n\t\t\t\"content-type\": \"application/json\",\n\t\t},\n\t};\n}\n",
10
10
  "import type { Webhook, WebhookOutbox } from \"@secondlayer/shared/db\";\n\n/**\n * Raw JSON — the row payload, nothing else. User controls Content-Type +\n * arbitrary headers via `sub.auth_config.headers`. Useful for targets that\n * already have their own wire contract (e.g. Zapier hooks, internal\n * services, Slack webhooks with raw-shaped bodies).\n *\n * Special-case: if `auth_config.authType === \"basic\"` and `basicAuth` is\n * set (`user:pass` base64 or plain user/pass object), emit a Basic header.\n * If `authType === \"bearer\"` with `token`/`tokenEnc`, emit a Bearer header.\n * Otherwise no auth is set — user URLs often include a token in the query\n * string (Slack) or an HMAC at the receiver (Zapier).\n */\n\nexport function buildRaw(\n\toutboxRow: WebhookOutbox,\n\tsub: Webhook,\n): { body: string; headers: Record<string, string> } {\n\tconst cfg = sub.auth_config as {\n\t\tcontentType?: string;\n\t\theaders?: Record<string, string>;\n\t\tauthType?: \"bearer\" | \"basic\" | \"none\";\n\t\ttoken?: string;\n\t\tbasicAuth?: string;\n\t};\n\tconst headers: Record<string, string> = {\n\t\t\"content-type\": cfg.contentType ?? \"application/json\",\n\t\t...(cfg.headers ?? {}),\n\t};\n\tif (cfg.authType === \"bearer\" && cfg.token) {\n\t\theaders.authorization = `Bearer ${cfg.token}`;\n\t} else if (cfg.authType === \"basic\" && cfg.basicAuth) {\n\t\theaders.authorization = `Basic ${cfg.basicAuth}`;\n\t}\n\treturn {\n\t\tbody: JSON.stringify(outboxRow.payload),\n\t\theaders,\n\t};\n}\n",
11
- "import { sign } from \"@secondlayer/shared/crypto/standard-webhooks\";\nimport type { WebhookOutbox } from \"@secondlayer/shared/db\";\n\n/**\n * Build a Standard Webhooks POST body + headers for an outbox row.\n * https://standardwebhooks.com\n *\n * Body shape: `{ type, timestamp, data }`\n * - `type` — `<subgraph>.<table>.<verb>` where verb is `created`, `updated`,\n * or `deleted`, mapped from the flush op so a receiver sees the full row\n * lifecycle, not just the initial insert.\n * - `timestamp` — ISO 8601 at DISPATCH time (not row creation). Receivers\n * verify `webhook-timestamp` against a tolerance window (default 300s per\n * Svix); stamping at creation would fail verification on every retry\n * beyond the first, since retries fire up to 72h after the row was\n * written. The `webhook-id` header stays stable across retries for\n * receiver dedup.\n * - `data` — row payload (bigints already stringified by flush manifest).\n *\n * Headers: the three standardwebhooks.com headers + Content-Type.\n */\n\nexport interface StandardWebhooksPayload {\n\ttype: string;\n\ttimestamp: string;\n\tdata: Record<string, unknown>;\n}\n\nexport function buildStandardWebhooks(\n\toutboxRow: WebhookOutbox,\n\tsigningSecret: string,\n): { body: string; headers: Record<string, string> } {\n\tconst nowSeconds = Math.floor(Date.now() / 1000);\n\tconst payload: StandardWebhooksPayload = {\n\t\ttype: outboxRow.event_type,\n\t\ttimestamp: new Date(nowSeconds * 1000).toISOString(),\n\t\tdata: outboxRow.payload as Record<string, unknown>,\n\t};\n\tconst body = JSON.stringify(payload);\n\tconst sigHeaders = sign(body, signingSecret, {\n\t\tid: outboxRow.id,\n\t\ttimestampSeconds: nowSeconds,\n\t});\n\treturn {\n\t\tbody,\n\t\theaders: {\n\t\t\t\"content-type\": \"application/json\",\n\t\t\t...sigHeaders,\n\t\t},\n\t};\n}\n",
11
+ "import { sign } from \"@secondlayer/shared/crypto/standard-webhooks\";\nimport type { WebhookOutbox } from \"@secondlayer/shared/db\";\n\n/**\n * Build a Standard Webhooks POST body + headers for an outbox row.\n * https://standardwebhooks.com\n *\n * Body shape: `{ type, timestamp, data }`\n * - `type` — the outbox `event_type`, e.g. `chain.stx_transfer.apply`.\n * - `timestamp` — ISO 8601 at DISPATCH time (not row creation). Receivers\n * verify `webhook-timestamp` against a tolerance window (default 300s per\n * Svix); stamping at creation would fail verification on every retry\n * beyond the first, since retries fire up to 72h after the row was\n * written. The `webhook-id` header stays stable across retries for\n * receiver dedup.\n * - `data` — the event payload.\n *\n * Headers: the three standardwebhooks.com headers + Content-Type.\n */\n\nexport interface StandardWebhooksPayload {\n\ttype: string;\n\ttimestamp: string;\n\tdata: Record<string, unknown>;\n}\n\nexport function buildStandardWebhooks(\n\toutboxRow: WebhookOutbox,\n\tsigningSecret: string,\n): { body: string; headers: Record<string, string> } {\n\tconst nowSeconds = Math.floor(Date.now() / 1000);\n\tconst payload: StandardWebhooksPayload = {\n\t\ttype: outboxRow.event_type,\n\t\ttimestamp: new Date(nowSeconds * 1000).toISOString(),\n\t\tdata: outboxRow.payload as Record<string, unknown>,\n\t};\n\tconst body = JSON.stringify(payload);\n\tconst sigHeaders = sign(body, signingSecret, {\n\t\tid: outboxRow.id,\n\t\ttimestampSeconds: nowSeconds,\n\t});\n\treturn {\n\t\tbody,\n\t\theaders: {\n\t\t\t\"content-type\": \"application/json\",\n\t\t\t...sigHeaders,\n\t\t},\n\t};\n}\n",
12
12
  "import { decryptSecret } from \"@secondlayer/shared/crypto/secrets\";\nimport type { Webhook, WebhookOutbox } from \"@secondlayer/shared/db\";\n\n/**\n * Trigger.dev v3 task trigger — https://trigger.dev/docs/tasks/overview\n *\n * POST https://api.trigger.dev/api/v1/tasks/{taskId}/trigger\n * Authorization: Bearer <TRIGGER_SECRET_KEY>\n *\n * Body:\n * - `payload` — the row payload\n * - `options` — currently `{ idempotencyKey }` so Trigger dedupes replays\n *\n * The Trigger secret lives in `sub.auth_config.tokenEnc` (encrypted by\n * `crypto/secrets`) or `sub.auth_config.token` (plaintext, dev only).\n */\n\nfunction resolveBearer(sub: Webhook): string | null {\n\tconst cfg = sub.auth_config as {\n\t\tauthType?: string;\n\t\ttoken?: string;\n\t\ttokenEnc?: string;\n\t};\n\tif (cfg.tokenEnc) {\n\t\t// Let decrypt errors propagate — silently sending unauthenticated\n\t\t// requests produces downstream 401s with no hint the secret failed\n\t\t// to decrypt. Surface as a dispatch-time error so the delivery log\n\t\t// records the real cause.\n\t\treturn decryptSecret(Buffer.from(cfg.tokenEnc, \"base64\"));\n\t}\n\treturn cfg.token ?? null;\n}\n\nexport function buildTrigger(\n\toutboxRow: WebhookOutbox,\n\tsub: Webhook,\n): { body: string; headers: Record<string, string> } {\n\tconst body = JSON.stringify({\n\t\tpayload: outboxRow.payload,\n\t\toptions: {\n\t\t\tidempotencyKey: 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
- "/**\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
- "import type { Database, Webhook } from \"@secondlayer/shared/db\";\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\nimport { WebhookMatcher } from \"./emitter-matcher.ts\";\n\n/**\n * Singleton matcher populated at processor startup and hot-reloaded via\n * `pg_notify('webhooks:changed')`. The block-processor reads from it\n * to decide which outbox rows to emit for each flushed write.\n */\n\nexport const matcher = new WebhookMatcher();\n\nexport async function refreshMatcher(db: Kysely<Database>): Promise<number> {\n\tconst rows = await sql<Webhook>`\n\t\tSELECT * FROM webhooks WHERE status = 'active'\n\t`.execute(db);\n\tmatcher.setAll(rows.rows);\n\treturn matcher.size();\n}\n",
15
- "import type { Webhook } from \"@secondlayer/shared/db\";\n\n/**\n * Webhook matcher — holds the active-webhooks cache keyed by\n * `(subgraph_name, table_name)` and evaluates each sub's scalar-only\n * JSONB filter against a row.\n *\n * Filter DSL (v1): scalar operators over string/number/boolean columns.\n * { column: value } → column === value\n * { column: { eq: value } } → column === value\n * { column: { neq: value } } → column !== value\n * { column: { gt|gte|lt|lte: N } } → numeric compare\n * { column: { in: [a, b, c] } } → column ∈ set\n * { } → match all\n *\n * Nested objects, arrays, and non-scalar values are rejected with `false`\n * (never match) — subscribers get logged warnings at sub create time.\n *\n * Multiple conditions AND together. OR is deliberately absent in v1.\n */\n\nexport type FilterPrimitive = string | number | boolean;\nexport type FilterOperator =\n\t| { eq: FilterPrimitive }\n\t| { neq: FilterPrimitive }\n\t| { gt: number | string }\n\t| { gte: number | string }\n\t| { lt: number | string }\n\t| { lte: number | string }\n\t| { in: FilterPrimitive[] };\n\nexport type FilterClause = FilterPrimitive | FilterOperator;\nexport type WebhookFilter = Record<string, FilterClause>;\n\nfunction isPrimitive(v: unknown): v is FilterPrimitive {\n\tconst t = typeof v;\n\treturn t === \"string\" || t === \"number\" || t === \"boolean\";\n}\n\n/**\n * Coerce a value to BigInt for arbitrary-precision compare — avoids the\n * silent precision loss of `Number()` on integers past 2^53. Returns\n * `null` for non-integer numerics, which is fine because the filter DSL\n * is documented as scalar-only + integer-amount-aware (Stacks uses\n * uint128 bigint columns everywhere).\n */\nfunction coerceBigInt(v: unknown): bigint | null {\n\tif (typeof v === \"bigint\") return v;\n\tif (typeof v === \"number\") {\n\t\tif (!Number.isFinite(v)) return null;\n\t\tif (!Number.isInteger(v)) return null;\n\t\treturn BigInt(v);\n\t}\n\tif (typeof v === \"string\" && /^-?\\d+$/.test(v)) {\n\t\ttry {\n\t\t\treturn BigInt(v);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Float compare fallback — used when a value isn't a clean integer\n * (rare in subgraph columns but defensible for user-supplied filters).\n */\nfunction coerceFloat(v: unknown): number | null {\n\tif (typeof v === \"number\" && Number.isFinite(v)) return v;\n\tif (typeof v === \"bigint\") return Number(v);\n\tif (typeof v === \"string\" && v !== \"\" && !Number.isNaN(Number(v))) {\n\t\treturn Number(v);\n\t}\n\treturn null;\n}\n\nfunction compareNumeric(a: unknown, b: unknown): 0 | 1 | -1 | null {\n\tconst ba = coerceBigInt(a);\n\tconst bb = coerceBigInt(b);\n\tif (ba !== null && bb !== null) {\n\t\tif (ba === bb) return 0;\n\t\treturn ba > bb ? 1 : -1;\n\t}\n\tconst fa = coerceFloat(a);\n\tconst fb = coerceFloat(b);\n\tif (fa === null || fb === null) return null;\n\tif (fa === fb) return 0;\n\treturn fa > fb ? 1 : -1;\n}\n\nfunction matchClause(rowValue: unknown, clause: FilterClause): boolean {\n\t// Reject non-primitive row values — `{ value: {...} }` should not\n\t// match `filter: { value: \"[object Object]\" }` via loose stringify.\n\t// Bigints are not primitives in the JSON sense but are supported\n\t// scalar inputs from subgraph rows.\n\tconst rowIsPrimitive = isPrimitive(rowValue) || typeof rowValue === \"bigint\";\n\n\tif (isPrimitive(clause)) {\n\t\tif (!rowIsPrimitive) return false;\n\t\tif (\n\t\t\ttypeof clause === \"number\" ||\n\t\t\ttypeof rowValue === \"number\" ||\n\t\t\ttypeof rowValue === \"bigint\"\n\t\t) {\n\t\t\tconst cmp = compareNumeric(rowValue, clause);\n\t\t\tif (cmp !== null) return cmp === 0;\n\t\t}\n\t\treturn rowValue === clause || String(rowValue) === String(clause);\n\t}\n\n\tif (clause === null || typeof clause !== \"object\" || Array.isArray(clause)) {\n\t\treturn false;\n\t}\n\n\tconst keys = Object.keys(clause);\n\tif (keys.length !== 1) return false;\n\tconst op = keys[0];\n\n\tconst c = clause as Record<string, unknown>;\n\tswitch (op) {\n\t\tcase \"eq\":\n\t\t\treturn matchClause(rowValue, c.eq as FilterPrimitive);\n\t\tcase \"neq\":\n\t\t\treturn !matchClause(rowValue, c.neq as FilterPrimitive);\n\t\tcase \"gt\":\n\t\tcase \"gte\":\n\t\tcase \"lt\":\n\t\tcase \"lte\": {\n\t\t\tif (!rowIsPrimitive) return false;\n\t\t\tconst cmp = compareNumeric(rowValue, c[op]);\n\t\t\tif (cmp === null) return false;\n\t\t\tif (op === \"gt\") return cmp > 0;\n\t\t\tif (op === \"gte\") return cmp >= 0;\n\t\t\tif (op === \"lt\") return cmp < 0;\n\t\t\treturn cmp <= 0;\n\t\t}\n\t\tcase \"in\": {\n\t\t\tconst list = c.in;\n\t\t\tif (!Array.isArray(list)) return false;\n\t\t\tif (!rowIsPrimitive) return false;\n\t\t\treturn list.some(\n\t\t\t\t(item) => isPrimitive(item) && matchClause(rowValue, item),\n\t\t\t);\n\t\t}\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nexport function matchesFilter(\n\tfilter: WebhookFilter | null | undefined,\n\trow: Record<string, unknown>,\n): boolean {\n\tif (!filter || Object.keys(filter).length === 0) return true;\n\tfor (const [col, clause] of Object.entries(filter)) {\n\t\tif (!matchClause(row[col], clause)) return false;\n\t}\n\treturn true;\n}\n\n// ── Cache keyed by (subgraph_name, table_name) ──────────────────────────\n\ntype MatcherKey = string;\n\nfunction key(subgraphName: string, tableName: string): MatcherKey {\n\treturn `${subgraphName}\u0000${tableName}`;\n}\n\nexport class WebhookMatcher {\n\tprivate readonly byKey = new Map<MatcherKey, Webhook[]>();\n\tprivate readonly byId = new Map<string, Webhook>();\n\n\t/** Replace the entire cache with a fresh snapshot. */\n\tsetAll(subs: Webhook[]): void {\n\t\tthis.byKey.clear();\n\t\tthis.byId.clear();\n\t\tfor (const sub of subs) {\n\t\t\tif (sub.status !== \"active\") continue;\n\t\t\t// This matcher keys on (subgraph, table) row writes; chain\n\t\t\t// webhooks react to raw chain events and never flow through it.\n\t\t\tif (sub.kind !== \"subgraph\" || !sub.subgraph_name || !sub.table_name)\n\t\t\t\tcontinue;\n\t\t\tthis.byId.set(sub.id, sub);\n\t\t\tconst k = key(sub.subgraph_name, sub.table_name);\n\t\t\tconst arr = this.byKey.get(k);\n\t\t\tif (arr) arr.push(sub);\n\t\t\telse this.byKey.set(k, [sub]);\n\t\t}\n\t}\n\n\t/** Returns active subs for a (subgraph, table) whose filter matches the row. */\n\tmatch(\n\t\tsubgraphName: string,\n\t\ttableName: string,\n\t\trow: Record<string, unknown>,\n\t): Webhook[] {\n\t\tconst bucket = this.byKey.get(key(subgraphName, tableName));\n\t\tif (!bucket) return [];\n\t\tconst hits: Webhook[] = [];\n\t\tfor (const sub of bucket) {\n\t\t\tif (matchesFilter(sub.filter as WebhookFilter, row)) hits.push(sub);\n\t\t}\n\t\treturn hits;\n\t}\n\n\thas(subgraphName: string, tableName: string): boolean {\n\t\treturn this.byKey.has(key(subgraphName, tableName));\n\t}\n\n\tsize(): number {\n\t\treturn this.byId.size;\n\t}\n\n\tget(id: string): Webhook | undefined {\n\t\treturn this.byId.get(id);\n\t}\n}\n"
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"
16
14
  ],
17
- "mappings": ";AAAA;AACA,mBAAS;AACT;AAAA;AAAA;AAAA;AAOA;AACA,mBAAS;AACT;AACA;AAAA;AAAA;AAIA,gBAAsB;;;AChBtB;AAEA;;;ACmBO,SAAS,gBAAgB,CAC/B,WACA,MACoD;AAAA,EACpD,MAAM,QAAQ;AAAA,IACb,aAAa;AAAA,IACb,MAAM,UAAU;AAAA,IAChB,QAAQ,eAAe,UAAU;AAAA,IACjC,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;;;ACvCD;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,eAA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,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;",
16
+ "debugId": "CAA46708A06EDDEB64756E2164756E21",
19
17
  "names": []
20
18
  }
@@ -40,7 +40,7 @@ interface BlockData {
40
40
  * Where the subgraph runtime reads canonical chain data. Today it taps the
41
41
  * indexer Postgres directly (`PostgresBlockSource`); the re-point adds a
42
42
  * `PublicApiBlockSource` that consumes the Streams clock + Index data over
43
- * HTTP. `matchSources` / handlers / flush / outbox are unchanged — only the
43
+ * HTTP. `matchSources` / handlers / flush are unchanged — only the
44
44
  * loader + tip swap behind this seam.
45
45
  */
46
46
  interface BlockSource {
@@ -102,10 +102,10 @@ interface ReplayResult {
102
102
  }
103
103
  declare function replayWebhook(input: ReplayInput): Promise<ReplayResult>;
104
104
  /**
105
- * Replay a chain webhook by re-running the pure matcher over a historical
106
- * canonical block range and emitting fresh apply rows. Unlike subgraph replay
107
- * there is no processed table to scan — the matcher is range-driven, so we
108
- * reload canonical blocks off the public Index/Streams clock and re-match.
105
+ * Replay a webhook by re-running the pure matcher over a historical
106
+ * canonical block range and emitting fresh apply rows. The matcher is
107
+ * range-driven, so we reload canonical blocks off the public Index/Streams
108
+ * clock and re-match.
109
109
  *
110
110
  * Rows are emitted with `is_replay=TRUE` and replay-namespaced dedup keys, and —
111
111
  * critically — this never advances `trigger_evaluator_state`: replay is
@@ -3,22 +3,6 @@ import { createHash as createHash2 } from "node:crypto";
3
3
  import { getTargetDb } from "@secondlayer/shared/db";
4
4
  import { getWebhook } from "@secondlayer/shared/db/queries/webhooks";
5
5
  import { logger as logger2 } from "@secondlayer/shared/logger";
6
- import { sql as sql2 } from "kysely";
7
-
8
- // src/schema/utils.ts
9
- import { pgSchemaName } from "@secondlayer/shared/db/queries/subgraphs";
10
- function quotePgIdent(name) {
11
- if (/^[a-z_][a-z0-9_]*$/i.test(name))
12
- return name;
13
- return `"${name.replace(/"/g, '""')}"`;
14
- }
15
- function snakeToCamel(name) {
16
- return name.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
17
- }
18
- function pascalCase(name) {
19
- const camel = snakeToCamel(name);
20
- return camel.charAt(0).toUpperCase() + camel.slice(1);
21
- }
22
6
 
23
7
  // src/runtime/block-source.ts
24
8
  import { getSourceDb } from "@secondlayer/shared/db";
@@ -33,7 +17,7 @@ import { createHash } from "node:crypto";
33
17
  // package.json
34
18
  var package_default = {
35
19
  name: "@secondlayer/subgraphs",
36
- version: "6.6.1",
20
+ version: "7.0.0",
37
21
  description: "Describe the Stacks data you want as one TypeScript file; it fills itself and survives reorgs.",
38
22
  license: "MIT",
39
23
  repository: {
@@ -92,9 +76,9 @@ var package_default = {
92
76
  prepublishOnly: "bun run build"
93
77
  },
94
78
  dependencies: {
95
- "@secondlayer/shared": "^11.24.0",
79
+ "@secondlayer/shared": "^12.0.0",
96
80
  "@secondlayer/stacks": "^6.2.0",
97
- "@secondlayer/verify": "^0.3.0",
81
+ "@secondlayer/verify": "^0.4.0",
98
82
  esbuild: "^0.28.2",
99
83
  kysely: "0.28.17",
100
84
  zod: "^4.3.6"
@@ -1596,8 +1580,6 @@ function applyRow(meta, blockHeight, blockHash, txId, eventIndex, event, replayI
1596
1580
  return {
1597
1581
  webhook_id: meta.webhookId,
1598
1582
  kind: "chain",
1599
- subgraph_name: null,
1600
- table_name: null,
1601
1583
  block_height: blockHeight,
1602
1584
  tx_id: txId,
1603
1585
  row_pk: clock === "vm" ? { tx_id: txId, event_index: eventIndex, clock } : { tx_id: txId, event_index: eventIndex },
@@ -1771,7 +1753,6 @@ async function emitSbtcOutbox(db, chainSubs, blockHeight, blockHash, blockTime,
1771
1753
  }
1772
1754
 
1773
1755
  // src/runtime/replay.ts
1774
- var BATCH_SIZE = 500;
1775
1756
  var WEBHOOK_REPLAY_MAX_BLOCKS_DEFAULT = 1e5;
1776
1757
  function webhookReplayMaxBlocks() {
1777
1758
  const raw = process.env.WEBHOOK_REPLAY_MAX_BLOCKS;
@@ -1797,28 +1778,10 @@ function __setReplayInFlightForTest(webhookId, inFlight) {
1797
1778
  else
1798
1779
  inFlightReplays.delete(webhookId);
1799
1780
  }
1800
- function replayDedupKey(subgraphName, tableName, row, replayId) {
1801
- const canonical = `replay:${replayId}:${subgraphName}:${tableName}:${stableStringify(row)}`;
1802
- return createHash2("sha256").update(canonical).digest("hex").slice(0, 32);
1803
- }
1804
- function stableStringify(obj) {
1805
- const keys = Object.keys(obj).sort();
1806
- return JSON.stringify(keys.reduce((acc, k) => {
1807
- acc[k] = obj[k];
1808
- return acc;
1809
- }, {}));
1810
- }
1811
1781
  function deterministicReplayId(webhookId, fromBlock, toBlock, suffix) {
1812
1782
  const canonical = `${webhookId}:${fromBlock}:${toBlock}${suffix ? `:${suffix}` : ""}`;
1813
1783
  return createHash2("sha256").update(canonical).digest("hex").slice(0, 16);
1814
1784
  }
1815
- async function resolveSchemaName(db, subgraphName) {
1816
- const row = await db.selectFrom("subgraphs").select("schema_name").where("name", "=", subgraphName).executeTakeFirst();
1817
- if (!row) {
1818
- throw new Error(`Subgraph "${subgraphName}" not registered — cannot replay its rows. Deploy the subgraph first.`);
1819
- }
1820
- return row.schema_name ?? pgSchemaName(subgraphName);
1821
- }
1822
1785
  async function replayWebhook(input) {
1823
1786
  if (input.fromBlock > input.toBlock) {
1824
1787
  throw new Error("fromBlock must be <= toBlock");
@@ -1836,60 +1799,7 @@ async function replayWebhook(input) {
1836
1799
  }
1837
1800
  inFlightReplays.add(sub.id);
1838
1801
  try {
1839
- if (sub.kind === "chain") {
1840
- return await replayChainWebhook(db, sub, input);
1841
- }
1842
- const subgraphName = sub.subgraph_name;
1843
- const tableName = sub.table_name;
1844
- if (sub.kind !== "subgraph" || !subgraphName || !tableName) {
1845
- throw new Error("replay is only supported for subgraph or chain webhooks");
1846
- }
1847
- const schema = await resolveSchemaName(db, subgraphName);
1848
- const replayId = deterministicReplayId(sub.id, input.fromBlock, input.toBlock, input.replayIdSuffix);
1849
- let scanned = 0;
1850
- let enqueued = 0;
1851
- let lastId = 0n;
1852
- while (true) {
1853
- const { rows } = await sql2`SELECT * FROM ${sql2.raw(`"${schema}"."${tableName}"`)}
1854
- WHERE _block_height >= ${sql2.lit(input.fromBlock)}
1855
- AND _block_height <= ${sql2.lit(input.toBlock)}
1856
- AND _id > ${sql2.lit(lastId)}
1857
- ORDER BY _id ASC
1858
- LIMIT ${sql2.lit(BATCH_SIZE)}`.execute(db);
1859
- if (rows.length === 0)
1860
- break;
1861
- scanned += rows.length;
1862
- const inserts = rows.map((row) => ({
1863
- webhook_id: sub.id,
1864
- subgraph_name: subgraphName,
1865
- table_name: tableName,
1866
- block_height: Number(row._block_height),
1867
- tx_id: row._tx_id ?? null,
1868
- row_pk: {
1869
- blockHeight: Number(row._block_height),
1870
- txId: row._tx_id ?? "",
1871
- replayId
1872
- },
1873
- event_type: `${subgraphName}.${tableName}.replay`,
1874
- payload: row,
1875
- dedup_key: replayDedupKey(subgraphName, tableName, row, replayId),
1876
- is_replay: true
1877
- }));
1878
- const result = await db.insertInto("webhook_outbox").values(inserts).onConflict((oc) => oc.columns(["webhook_id", "dedup_key"]).doNothing()).executeTakeFirst();
1879
- enqueued += Number(result.numInsertedOrUpdatedRows ?? 0);
1880
- lastId = BigInt(String(rows[rows.length - 1]?._id));
1881
- if (rows.length < BATCH_SIZE)
1882
- break;
1883
- }
1884
- logger2.info("Replay enqueued", {
1885
- webhook: sub.name,
1886
- replayId,
1887
- scanned,
1888
- enqueued,
1889
- fromBlock: input.fromBlock,
1890
- toBlock: input.toBlock
1891
- });
1892
- return { replayId, enqueuedCount: enqueued, scannedCount: scanned };
1802
+ return await replayChainWebhook(db, sub, input);
1893
1803
  } finally {
1894
1804
  inFlightReplays.delete(sub.id);
1895
1805
  }
@@ -1939,5 +1849,5 @@ export {
1939
1849
  replayWebhook
1940
1850
  };
1941
1851
 
1942
- //# debugId=B58C7555A96EE03D64756E2164756E21
1852
+ //# debugId=F0DFD50675BA0F5064756E2164756E21
1943
1853
  //# sourceMappingURL=replay.js.map