@secondlayer/shared 15.2.0 → 15.3.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.
- package/dist/src/archive/range-digest.d.ts +61 -9
- package/dist/src/archive/semantic-digest-builder.d.ts +61 -9
- package/dist/src/coverage/index.d.ts +64 -9
- package/dist/src/coverage/index.js.map +2 -2
- package/dist/src/db/index.d.ts +63 -10
- package/dist/src/db/index.js +19 -1
- package/dist/src/db/index.js.map +5 -4
- package/dist/src/db/queries/chain-reorgs.d.ts +61 -9
- package/dist/src/db/queries/chain-reorgs.js +17 -1
- package/dist/src/db/queries/chain-reorgs.js.map +5 -4
- package/dist/src/db/queries/contracts.d.ts +108 -28
- package/dist/src/db/queries/contracts.js +115 -15
- package/dist/src/db/queries/contracts.js.map +7 -5
- package/dist/src/db/queries/instance.d.ts +69 -10
- package/dist/src/db/queries/instance.js +147 -3
- package/dist/src/db/queries/instance.js.map +6 -4
- package/dist/src/db/queries/integrity.d.ts +77 -10
- package/dist/src/db/queries/integrity.js +236 -2
- package/dist/src/db/queries/integrity.js.map +7 -4
- package/dist/src/db/queries/subgraph-gaps.d.ts +69 -12
- package/dist/src/db/queries/subgraph-gaps.js +7 -3
- package/dist/src/db/queries/subgraph-gaps.js.map +3 -3
- package/dist/src/db/queries/subgraph-operations.d.ts +61 -9
- package/dist/src/db/queries/subgraphs.d.ts +122 -42
- package/dist/src/db/queries/subgraphs.js +85 -27
- package/dist/src/db/queries/subgraphs.js.map +7 -6
- package/dist/src/db/queries/sync-scope.d.ts +61 -9
- package/dist/src/db/queries/webhook-replays.d.ts +73 -13
- package/dist/src/db/queries/webhook-replays.js +468 -19
- package/dist/src/db/queries/webhook-replays.js.map +9 -4
- package/dist/src/db/queries/webhooks.d.ts +96 -21
- package/dist/src/db/queries/webhooks.js +72 -17
- package/dist/src/db/queries/webhooks.js.map +6 -5
- package/dist/src/db/schema.d.ts +62 -10
- package/dist/src/db/schema.js +20 -1
- package/dist/src/db/schema.js.map +4 -3
- package/dist/src/db/transition.d.ts +46 -0
- package/dist/src/db/transition.js +38 -0
- package/dist/src/db/transition.js.map +10 -0
- package/dist/src/email/index.d.ts +16 -1
- package/dist/src/email/index.js +186 -130
- package/dist/src/email/index.js.map +5 -4
- package/dist/src/errors.d.ts +7 -1
- package/dist/src/errors.js +12 -1
- package/dist/src/errors.js.map +3 -3
- package/dist/src/index-http.d.ts +19 -10
- package/dist/src/index-http.js +5 -4
- package/dist/src/index-http.js.map +3 -3
- package/dist/src/index.d.ts +98 -19
- package/dist/src/index.js +41 -8
- package/dist/src/index.js.map +8 -7
- package/dist/src/insights/index.d.ts +62 -9
- package/dist/src/insights/index.js +55 -5
- package/dist/src/insights/index.js.map +7 -6
- package/dist/src/node/local-client.d.ts +61 -9
- package/dist/src/queue/listener.js +17 -1
- package/dist/src/queue/listener.js.map +5 -4
- package/dist/src/runtime/index.d.ts +0 -4
- package/dist/src/runtime/index.js +54 -4
- package/dist/src/runtime/index.js.map +6 -5
- package/dist/src/schemas/index.d.ts +36 -10
- package/dist/src/schemas/index.js +12 -8
- package/dist/src/schemas/index.js.map +4 -4
- package/dist/src/schemas/subgraphs.d.ts +22 -9
- package/dist/src/schemas/subgraphs.js +10 -6
- package/dist/src/schemas/subgraphs.js.map +3 -3
- package/dist/src/schemas/webhooks.d.ts +15 -2
- package/dist/src/schemas/webhooks.js +2 -2
- package/dist/src/schemas/webhooks.js.map +3 -3
- package/dist/src/subgraphs/spec.d.ts +5 -1
- package/dist/src/webhooks/health.d.ts +27 -0
- package/dist/src/webhooks/health.js +84 -0
- package/dist/src/webhooks/health.js.map +11 -0
- package/migrations/0184_status_checks.ts +92 -0
- package/migrations/0185_reorg_generation_settlement_seq.ts +89 -0
- package/migrations/0186_api_keys_one_active_tenant_per_name.ts +43 -0
- package/migrations/0187_accounts_email_lower_unique.ts +27 -0
- package/migrations/0188_webhook_reasons.ts +124 -0
- package/migrations/0189_subgraph_lifecycle.ts +83 -0
- package/migrations/0190_usage_ledger_debited_usd_micros.ts +59 -0
- package/migrations/0191_indexer_state_machines.ts +83 -0
- package/migrations/0192_hosted_stack_state.ts +37 -0
- package/migrations/0193_accounts_ghost_has_no_email.ts +34 -0
- package/package.json +9 -1
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/db/queries/webhook-replays.ts"],
|
|
3
|
+
"sources": ["../src/db/queries/webhook-replays.ts", "../src/db/queries/webhooks.ts", "../src/crypto/hmac.ts", "../src/crypto/secrets.ts", "../src/mode.ts", "../src/db/transition.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import { type Kysely, sql } from \"kysely\";\nimport type { ReplayProgress } from \"../../schemas/webhooks.ts\";\nimport type { Database, WebhookReplay } from \"../types.ts\";\n\n/**\n * Stored record of each webhook replay. A replay is `scanning` while the\n * request scans its block range, `running` once its outbox rows exist, `done`\n * when none are pending, `failed` if the scan threw or the process died.\n *\n * Progress while running is `enqueued - pending`, where pending is counted\n * through the existing partial index on pending outbox rows (`webhook_outbox`\n * has no index on `replay_id` on purpose). Rows that gave up are counted once,\n * when the replay finalizes.\n */\n\n/** A `scanning` row older than this is a crashed process, not a live scan. */\nconst STALE_SCAN_MINUTES = 30;\n\n/** Thrown by {@link beginReplay} when a replay is still scanning for the\n * webhook. The route maps this to 409; `force` does not bypass it. */\nexport class ReplayInProgressError extends Error {\n\tconstructor() {\n\t\tsuper(\"replay already in progress for this webhook\");\n\t\tthis.name = \"ReplayInProgressError\";\n\t}\n}\n\nconst ONE_SCANNING_CONSTRAINT = \"webhook_replays_one_scanning\";\n\nfunction isOneScanningConflict(err: unknown): boolean {\n\tif (!(err instanceof Error)) return false;\n\tconst candidate = err as Error & {\n\t\tcode?: string;\n\t\tconstraint?: string;\n\t\tconstraint_name?: string;\n\t};\n\treturn (\n\t\tcandidate.code === \"23505\" &&\n\t\t(candidate.constraint === ONE_SCANNING_CONSTRAINT ||\n\t\t\tcandidate.constraint_name === ONE_SCANNING_CONSTRAINT)\n\t);\n}\n\nexport async function beginReplay(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tid: string;\n\t\twebhookId: string;\n\t\tfromBlock: number;\n\t\ttoBlock: number;\n\t},\n): Promise<void> {\n\ttry {\n\t\tawait db.transaction().execute(async (trx) => {\n\t\t\tawait trx\n\t\t\t\t.updateTable(\"webhook_replays\")\n\t\t\t\t.set({\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\terror: \"scan interrupted\",\n\t\t\t\t\tfinished_at: sql`now()`,\n\t\t\t\t})\n\t\t\t\t.where(\"webhook_id\", \"=\", input.webhookId)\n\t\t\t\t.where(\"status\", \"=\", \"scanning\")\n\t\t\t\t.where(\n\t\t\t\t\t\"started_at\",\n\t\t\t\t\t\"<\",\n\t\t\t\t\tsql<Date>`now() - ${sql.lit(`${STALE_SCAN_MINUTES} minutes`)}::interval`,\n\t\t\t\t)\n\t\t\t\t.execute();\n\t\t\t// Re-running a range reuses its record. A row of this very id that is\n\t\t\t// still scanning is a concurrent scan: the WHERE leaves it untouched and\n\t\t\t// no row comes back.\n\t\t\tconst row = await trx\n\t\t\t\t.insertInto(\"webhook_replays\")\n\t\t\t\t.values({\n\t\t\t\t\tid: input.id,\n\t\t\t\t\twebhook_id: input.webhookId,\n\t\t\t\t\tfrom_block: input.fromBlock,\n\t\t\t\t\tto_block: input.toBlock,\n\t\t\t\t\tstatus: \"scanning\",\n\t\t\t\t})\n\t\t\t\t.onConflict((oc) =>\n\t\t\t\t\toc\n\t\t\t\t\t\t.column(\"id\")\n\t\t\t\t\t\t.doUpdateSet({\n\t\t\t\t\t\t\tstatus: \"scanning\",\n\t\t\t\t\t\t\tstarted_at: sql`now()`,\n\t\t\t\t\t\t\tfinished_at: null,\n\t\t\t\t\t\t\terror: null,\n\t\t\t\t\t\t\ttotal: null,\n\t\t\t\t\t\t\tdelivered: null,\n\t\t\t\t\t\t\tgave_up: null,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(\"webhook_replays.status\", \"<>\", \"scanning\"),\n\t\t\t\t)\n\t\t\t\t.returning(\"id\")\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (!row) throw new ReplayInProgressError();\n\t\t});\n\t} catch (err) {\n\t\tif (isOneScanningConflict(err)) throw new ReplayInProgressError();\n\t\tthrow err;\n\t}\n}\n\nexport async function finishScan(\n\tdb: Kysely<Database>,\n\tid: string,\n\tcounts: { scanned: number; enqueued: number },\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"webhook_replays\")\n\t\t.set({\n\t\t\tstatus: \"running\",\n\t\t\tscanned_count: counts.scanned,\n\t\t\tenqueued_count: sql`enqueued_count + ${counts.enqueued}`,\n\t\t})\n\t\t.where(\"id\", \"=\", id)\n\t\t.execute();\n}\n\nexport async function failScan(\n\tdb: Kysely<Database>,\n\tid: string,\n\terror: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"webhook_replays\")\n\t\t.set({ status: \"failed\", error, finished_at: sql`now()` })\n\t\t.where(\"id\", \"=\", id)\n\t\t.execute();\n}\n\n/** Outbox rows of this replay still waiting to be delivered or to give up. */\nexport async function pendingCount(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<number> {\n\tconst row = await db\n\t\t.selectFrom(\"webhook_outbox\")\n\t\t.select(sql<string>`count(*)`.as(\"n\"))\n\t\t.where(\"status\", \"=\", \"pending\")\n\t\t.where(\"replay_id\", \"=\", id)\n\t\t.executeTakeFirstOrThrow();\n\treturn Number(row.n);\n}\n\n/** Outbox rows of this replay that gave up. Finalize only; never on a poll. */\nexport async function deadCount(\n\tdb: Kysely<Database>,\n\twebhookId: string,\n\tid: string,\n): Promise<number> {\n\tconst row = await db\n\t\t.selectFrom(\"webhook_outbox\")\n\t\t.select(sql<string>`count(*)`.as(\"n\"))\n\t\t.where(\"webhook_id\", \"=\", webhookId)\n\t\t.where(\"replay_id\", \"=\", id)\n\t\t.where(\"status\", \"=\", \"dead\")\n\t\t.executeTakeFirstOrThrow();\n\treturn Number(row.n);\n}\n\nexport function progressOf(\n\trecord: WebhookReplay,\n\tpending: number,\n): ReplayProgress {\n\tconst done = record.status === \"done\";\n\tconst total = done\n\t\t? (record.total ?? record.enqueued_count)\n\t\t: record.enqueued_count;\n\treturn {\n\t\treplayId: record.id,\n\t\twebhookId: record.webhook_id,\n\t\tstatus: record.status,\n\t\tfromBlock: Number(record.from_block),\n\t\ttoBlock: Number(record.to_block),\n\t\ttotal,\n\t\tprocessed: done ? total : Math.max(0, total - pending),\n\t\tpending: done ? 0 : pending,\n\t\tdelivered: done ? record.delivered : null,\n\t\tgaveUp: done ? record.gave_up : null,\n\t\tstartedAt: record.started_at.toISOString(),\n\t\tfinishedAt: record.finished_at ? record.finished_at.toISOString() : null,\n\t\terror: record.error,\n\t};\n}\n\n/** Progress for one record, finalizing it once nothing is pending. */\nasync function progressWithFinalize(\n\tdb: Kysely<Database>,\n\trecord: WebhookReplay,\n): Promise<ReplayProgress> {\n\tif (record.status !== \"running\") return progressOf(record, 0);\n\tconst pending = await pendingCount(db, record.id);\n\tif (pending > 0) return progressOf(record, pending);\n\n\tconst dead = await deadCount(db, record.webhook_id, record.id);\n\tconst finalized = await db\n\t\t.updateTable(\"webhook_replays\")\n\t\t.set({\n\t\t\tstatus: \"done\",\n\t\t\tfinished_at: sql`now()`,\n\t\t\ttotal: sql`enqueued_count`,\n\t\t\tgave_up: dead,\n\t\t\tdelivered: sql`enqueued_count - ${dead}`,\n\t\t})\n\t\t.where(\"id\", \"=\", record.id)\n\t\t.where(\"status\", \"=\", \"running\")\n\t\t.returningAll()\n\t\t.executeTakeFirst();\n\tif (finalized) return progressOf(finalized, 0);\n\t// Lost a race to another finalizer (or a requeue): re-read.\n\tconst fresh = await db\n\t\t.selectFrom(\"webhook_replays\")\n\t\t.selectAll()\n\t\t.where(\"id\", \"=\", record.id)\n\t\t.executeTakeFirstOrThrow();\n\treturn progressOf(\n\t\tfresh,\n\t\tfresh.status === \"running\" ? await pendingCount(db, fresh.id) : 0,\n\t);\n}\n\nexport async function readReplay(\n\tdb: Kysely<Database>,\n\twebhookId: string,\n\tid: string,\n): Promise<ReplayProgress | null> {\n\tconst record = await db\n\t\t.selectFrom(\"webhook_replays\")\n\t\t.selectAll()\n\t\t.where(\"id\", \"=\", id)\n\t\t.where(\"webhook_id\", \"=\", webhookId)\n\t\t.executeTakeFirst();\n\treturn record ? progressWithFinalize(db, record) : null;\n}\n\n/** Replays in progress or started within `sinceHours`, newest first. */\nexport async function listReplays(\n\tdb: Kysely<Database>,\n\tinput: { webhookIds: string[]; sinceHours: number; limit: number },\n): Promise<ReplayProgress[]> {\n\tif (input.webhookIds.length === 0) return [];\n\tconst cutoff = new Date(Date.now() - input.sinceHours * 3_600_000);\n\tconst records = await db\n\t\t.selectFrom(\"webhook_replays\")\n\t\t.selectAll()\n\t\t.where(\"webhook_id\", \"in\", input.webhookIds)\n\t\t.where((eb) =>\n\t\t\teb.or([\n\t\t\t\teb(\"status\", \"in\", [\"scanning\", \"running\"]),\n\t\t\t\teb(\"started_at\", \">\", cutoff),\n\t\t\t]),\n\t\t)\n\t\t.orderBy(\"started_at\", \"desc\")\n\t\t.limit(input.limit)\n\t\t.execute();\n\treturn Promise.all(records.map((r) => progressWithFinalize(db, r)));\n}\n\n/** Newest replays of one webhook, finalizing any that have drained. */\nexport async function listWebhookReplays(\n\tdb: Kysely<Database>,\n\twebhookId: string,\n\tlimit: number,\n): Promise<ReplayProgress[]> {\n\tconst records = await db\n\t\t.selectFrom(\"webhook_replays\")\n\t\t.selectAll()\n\t\t.where(\"webhook_id\", \"=\", webhookId)\n\t\t.orderBy(\"started_at\", \"desc\")\n\t\t.limit(limit)\n\t\t.execute();\n\treturn Promise.all(records.map((r) => progressWithFinalize(db, r)));\n}\n\n/** Retention backstop: finalize every running replay that has drained. */\nexport async function finalizeReplays(db: Kysely<Database>): Promise<void> {\n\tconst running = await db\n\t\t.selectFrom(\"webhook_replays\")\n\t\t.selectAll()\n\t\t.where(\"status\", \"=\", \"running\")\n\t\t.execute();\n\tfor (const record of running) await progressWithFinalize(db, record);\n}\n\nexport async function deadSince(\n\tdb: Kysely<Database>,\n\twebhookId: string,\n\tsince: Date | null,\n): Promise<number> {\n\tlet q = db\n\t\t.selectFrom(\"webhook_outbox\")\n\t\t.select(sql<string>`count(*)`.as(\"n\"))\n\t\t.where(\"webhook_id\", \"=\", webhookId)\n\t\t.where(\"status\", \"=\", \"dead\");\n\tif (since) q = q.where(\"failed_at\", \">=\", since);\n\treturn Number((await q.executeTakeFirstOrThrow()).n);\n}\n\nexport async function knownEventsInRange(\n\tdb: Kysely<Database>,\n\twebhookId: string,\n\tfrom: number,\n\tto: number,\n): Promise<number> {\n\tconst row = await db\n\t\t.selectFrom(\"webhook_outbox\")\n\t\t.select(sql<string>`count(*)`.as(\"n\"))\n\t\t.where(\"webhook_id\", \"=\", webhookId)\n\t\t.where(\"block_height\", \">=\", from)\n\t\t.where(\"block_height\", \"<=\", to)\n\t\t.executeTakeFirstOrThrow();\n\treturn Number(row.n);\n}\n"
|
|
5
|
+
"import { type Kysely, sql } from \"kysely\";\nimport type { ReplayProgress } from \"../../schemas/webhooks.ts\";\nimport type { Database, WebhookReplay } from \"../types.ts\";\nimport { notReorgOrphaned } from \"./webhooks.ts\";\n\n/**\n * Stored record of each webhook replay. A replay is `scanning` while the\n * request scans its block range, `running` once its outbox rows exist, `done`\n * when none are pending, `failed` if the scan threw or the process died.\n *\n * Progress while running is `enqueued - pending`, where pending is counted\n * through the existing partial index on pending outbox rows (`webhook_outbox`\n * has no index on `replay_id` on purpose). Rows that gave up are counted once,\n * when the replay finalizes.\n */\n\n/** A `scanning` row older than this is a crashed process, not a live scan. */\nconst STALE_SCAN_MINUTES = 30;\n\n/** Thrown by {@link beginReplay} when a replay is still scanning for the\n * webhook. The route maps this to 409; `force` does not bypass it. */\nexport class ReplayInProgressError extends Error {\n\tconstructor() {\n\t\tsuper(\"replay already in progress for this webhook\");\n\t\tthis.name = \"ReplayInProgressError\";\n\t}\n}\n\nconst ONE_SCANNING_CONSTRAINT = \"webhook_replays_one_scanning\";\n\nfunction isOneScanningConflict(err: unknown): boolean {\n\tif (!(err instanceof Error)) return false;\n\tconst candidate = err as Error & {\n\t\tcode?: string;\n\t\tconstraint?: string;\n\t\tconstraint_name?: string;\n\t};\n\treturn (\n\t\tcandidate.code === \"23505\" &&\n\t\t(candidate.constraint === ONE_SCANNING_CONSTRAINT ||\n\t\t\tcandidate.constraint_name === ONE_SCANNING_CONSTRAINT)\n\t);\n}\n\n/** Fail every `scanning` replay older than `STALE_SCAN_MINUTES` (its process\n * died) and stamp `finished_at` so retention can delete it. Scoped to one\n * webhook when `webhookId` is given; otherwise sweeps them all. */\nexport async function reapStaleScans(\n\tdb: Kysely<Database>,\n\twebhookId?: string,\n): Promise<void> {\n\tlet q = db\n\t\t.updateTable(\"webhook_replays\")\n\t\t.set({\n\t\t\tstatus: \"failed\",\n\t\t\terror: \"scan interrupted\",\n\t\t\tfinished_at: sql`now()`,\n\t\t})\n\t\t.where(\"status\", \"=\", \"scanning\")\n\t\t.where(\n\t\t\t\"started_at\",\n\t\t\t\"<\",\n\t\t\tsql<Date>`now() - ${sql.lit(`${STALE_SCAN_MINUTES} minutes`)}::interval`,\n\t\t);\n\tif (webhookId) q = q.where(\"webhook_id\", \"=\", webhookId);\n\tawait q.execute();\n}\n\nexport async function beginReplay(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tid: string;\n\t\twebhookId: string;\n\t\tfromBlock: number;\n\t\ttoBlock: number;\n\t},\n): Promise<void> {\n\ttry {\n\t\tawait db.transaction().execute(async (trx) => {\n\t\t\tawait reapStaleScans(trx, input.webhookId);\n\t\t\t// Re-running a range reuses its record. A row of this very id that is\n\t\t\t// still scanning is a concurrent scan: the WHERE leaves it untouched and\n\t\t\t// no row comes back.\n\t\t\tconst row = await trx\n\t\t\t\t.insertInto(\"webhook_replays\")\n\t\t\t\t.values({\n\t\t\t\t\tid: input.id,\n\t\t\t\t\twebhook_id: input.webhookId,\n\t\t\t\t\tfrom_block: input.fromBlock,\n\t\t\t\t\tto_block: input.toBlock,\n\t\t\t\t\tstatus: \"scanning\",\n\t\t\t\t})\n\t\t\t\t.onConflict((oc) =>\n\t\t\t\t\toc\n\t\t\t\t\t\t.column(\"id\")\n\t\t\t\t\t\t.doUpdateSet({\n\t\t\t\t\t\t\tstatus: \"scanning\",\n\t\t\t\t\t\t\tstarted_at: sql`now()`,\n\t\t\t\t\t\t\tfinished_at: null,\n\t\t\t\t\t\t\terror: null,\n\t\t\t\t\t\t\ttotal: null,\n\t\t\t\t\t\t\tdelivered: null,\n\t\t\t\t\t\t\tgave_up: null,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(\"webhook_replays.status\", \"<>\", \"scanning\"),\n\t\t\t\t)\n\t\t\t\t.returning(\"id\")\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (!row) throw new ReplayInProgressError();\n\t\t});\n\t} catch (err) {\n\t\tif (isOneScanningConflict(err)) throw new ReplayInProgressError();\n\t\tthrow err;\n\t}\n}\n\n/** Both scan writes only move a replay that is still `scanning`: a replay the\n * sweep already finalized, or a newer run that restarted the same id, is not\n * overwritten by a late scan. Returns false when nothing was updated. */\nexport async function finishScan(\n\tdb: Kysely<Database>,\n\tid: string,\n\tcounts: { scanned: number; enqueued: number },\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"webhook_replays\")\n\t\t.set({\n\t\t\tstatus: \"running\",\n\t\t\tscanned_count: counts.scanned,\n\t\t\tenqueued_count: sql`enqueued_count + ${counts.enqueued}`,\n\t\t})\n\t\t.where(\"id\", \"=\", id)\n\t\t.where(\"status\", \"=\", \"scanning\")\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0) > 0;\n}\n\nexport async function failScan(\n\tdb: Kysely<Database>,\n\tid: string,\n\terror: string,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"webhook_replays\")\n\t\t.set({ status: \"failed\", error, finished_at: sql`now()` })\n\t\t.where(\"id\", \"=\", id)\n\t\t.where(\"status\", \"=\", \"scanning\")\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0) > 0;\n}\n\n/** Outbox rows of this replay still waiting to be delivered or to give up. */\nexport async function pendingCount(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<number> {\n\tconst row = await db\n\t\t.selectFrom(\"webhook_outbox\")\n\t\t.select(sql<string>`count(*)`.as(\"n\"))\n\t\t.where(\"status\", \"=\", \"pending\")\n\t\t.where(\"replay_id\", \"=\", id)\n\t\t.executeTakeFirstOrThrow();\n\treturn Number(row.n);\n}\n\n/** Outbox rows of this replay that gave up. Finalize only; never on a poll. */\nexport async function deadCount(\n\tdb: Kysely<Database>,\n\twebhookId: string,\n\tid: string,\n): Promise<number> {\n\tconst row = await db\n\t\t.selectFrom(\"webhook_outbox\")\n\t\t.select(sql<string>`count(*)`.as(\"n\"))\n\t\t.where(\"webhook_id\", \"=\", webhookId)\n\t\t.where(\"replay_id\", \"=\", id)\n\t\t.where(\"status\", \"=\", \"dead\")\n\t\t.executeTakeFirstOrThrow();\n\treturn Number(row.n);\n}\n\nexport function progressOf(\n\trecord: WebhookReplay,\n\tpending: number,\n): ReplayProgress {\n\tconst done = record.status === \"done\";\n\tconst total = done\n\t\t? (record.total ?? record.enqueued_count)\n\t\t: record.enqueued_count;\n\treturn {\n\t\treplayId: record.id,\n\t\twebhookId: record.webhook_id,\n\t\tstatus: record.status,\n\t\tfromBlock: Number(record.from_block),\n\t\ttoBlock: Number(record.to_block),\n\t\ttotal,\n\t\tprocessed: done ? total : Math.max(0, total - pending),\n\t\tpending: done ? 0 : pending,\n\t\tdelivered: done ? record.delivered : null,\n\t\tgaveUp: done ? record.gave_up : null,\n\t\tstartedAt: record.started_at.toISOString(),\n\t\tfinishedAt: record.finished_at ? record.finished_at.toISOString() : null,\n\t\terror: record.error,\n\t};\n}\n\n/** Progress for one record, finalizing it once nothing is pending. */\nasync function progressWithFinalize(\n\tdb: Kysely<Database>,\n\trecord: WebhookReplay,\n): Promise<ReplayProgress> {\n\tif (record.status !== \"running\") return progressOf(record, 0);\n\tconst pending = await pendingCount(db, record.id);\n\tif (pending > 0) return progressOf(record, pending);\n\n\tconst dead = await deadCount(db, record.webhook_id, record.id);\n\tconst finalized = await db\n\t\t.updateTable(\"webhook_replays\")\n\t\t.set({\n\t\t\tstatus: \"done\",\n\t\t\tfinished_at: sql`now()`,\n\t\t\ttotal: sql`enqueued_count`,\n\t\t\tgave_up: dead,\n\t\t\tdelivered: sql`enqueued_count - ${dead}`,\n\t\t})\n\t\t.where(\"id\", \"=\", record.id)\n\t\t.where(\"status\", \"=\", \"running\")\n\t\t.returningAll()\n\t\t.executeTakeFirst();\n\tif (finalized) return progressOf(finalized, 0);\n\t// Lost a race to another finalizer (or a requeue): re-read.\n\tconst fresh = await db\n\t\t.selectFrom(\"webhook_replays\")\n\t\t.selectAll()\n\t\t.where(\"id\", \"=\", record.id)\n\t\t.executeTakeFirstOrThrow();\n\treturn progressOf(\n\t\tfresh,\n\t\tfresh.status === \"running\" ? await pendingCount(db, fresh.id) : 0,\n\t);\n}\n\nexport async function readReplay(\n\tdb: Kysely<Database>,\n\twebhookId: string,\n\tid: string,\n): Promise<ReplayProgress | null> {\n\tconst record = await db\n\t\t.selectFrom(\"webhook_replays\")\n\t\t.selectAll()\n\t\t.where(\"id\", \"=\", id)\n\t\t.where(\"webhook_id\", \"=\", webhookId)\n\t\t.executeTakeFirst();\n\treturn record ? progressWithFinalize(db, record) : null;\n}\n\n/** Replays in progress or started within `sinceHours`, newest first. */\nexport async function listReplays(\n\tdb: Kysely<Database>,\n\tinput: { webhookIds: string[]; sinceHours: number; limit: number },\n): Promise<ReplayProgress[]> {\n\tif (input.webhookIds.length === 0) return [];\n\tconst cutoff = new Date(Date.now() - input.sinceHours * 3_600_000);\n\tconst records = await db\n\t\t.selectFrom(\"webhook_replays\")\n\t\t.selectAll()\n\t\t.where(\"webhook_id\", \"in\", input.webhookIds)\n\t\t.where((eb) =>\n\t\t\teb.or([\n\t\t\t\teb(\"status\", \"in\", [\"scanning\", \"running\"]),\n\t\t\t\teb(\"started_at\", \">\", cutoff),\n\t\t\t]),\n\t\t)\n\t\t.orderBy(\"started_at\", \"desc\")\n\t\t.limit(input.limit)\n\t\t.execute();\n\treturn Promise.all(records.map((r) => progressWithFinalize(db, r)));\n}\n\n/** Newest replays of one webhook, finalizing any that have drained. */\nexport async function listWebhookReplays(\n\tdb: Kysely<Database>,\n\twebhookId: string,\n\tlimit: number,\n): Promise<ReplayProgress[]> {\n\tconst records = await db\n\t\t.selectFrom(\"webhook_replays\")\n\t\t.selectAll()\n\t\t.where(\"webhook_id\", \"=\", webhookId)\n\t\t.orderBy(\"started_at\", \"desc\")\n\t\t.limit(limit)\n\t\t.execute();\n\treturn Promise.all(records.map((r) => progressWithFinalize(db, r)));\n}\n\n/** Retention backstop: fail stale scans, then finalize every running replay\n * that has drained. */\nexport async function finalizeReplays(db: Kysely<Database>): Promise<void> {\n\tawait reapStaleScans(db);\n\tconst running = await db\n\t\t.selectFrom(\"webhook_replays\")\n\t\t.selectAll()\n\t\t.where(\"status\", \"=\", \"running\")\n\t\t.execute();\n\tfor (const record of running) await progressWithFinalize(db, record);\n}\n\nexport async function deadSince(\n\tdb: Kysely<Database>,\n\twebhookId: string,\n\tsince: Date | null,\n): Promise<number> {\n\tlet q = db\n\t\t.selectFrom(\"webhook_outbox\")\n\t\t.select(sql<string>`count(*)`.as(\"n\"))\n\t\t.where(\"webhook_id\", \"=\", webhookId)\n\t\t.where(\"status\", \"=\", \"dead\")\n\t\t.where(notReorgOrphaned);\n\tif (since) q = q.where(\"failed_at\", \">=\", since);\n\treturn Number((await q.executeTakeFirstOrThrow()).n);\n}\n\nexport async function knownEventsInRange(\n\tdb: Kysely<Database>,\n\twebhookId: string,\n\tfrom: number,\n\tto: number,\n): Promise<number> {\n\tconst row = await db\n\t\t.selectFrom(\"webhook_outbox\")\n\t\t.select(sql<string>`count(*)`.as(\"n\"))\n\t\t.where(\"webhook_id\", \"=\", webhookId)\n\t\t.where(\"block_height\", \">=\", from)\n\t\t.where(\"block_height\", \"<=\", to)\n\t\t.executeTakeFirstOrThrow();\n\treturn Number(row.n);\n}\n",
|
|
6
|
+
"import {\n\ttype ExpressionBuilder,\n\ttype ExpressionWrapper,\n\ttype Kysely,\n\ttype SqlBool,\n\tsql,\n} from \"kysely\";\nimport { generateSecret } from \"../../crypto/hmac.ts\";\nimport { decryptSecret, encryptSecret } from \"../../crypto/secrets.ts\";\nimport { isWebhookAccountScoped } from \"../../mode.ts\";\nimport { type Machine, casTransition, defineMachine } from \"../transition.ts\";\nimport type {\n\tDatabase,\n\tInsertWebhook,\n\tUpdateWebhook,\n\tWebhook,\n\tWebhookFormat,\n\tWebhookStatus,\n} from \"../types.ts\";\n\n/**\n * Webhook CRUD. `signing_secret_enc` is transparently encrypted via\n * `encryptSecret`/`decryptSecret`. Plaintext secrets only leave via the\n * return value of `create` (one-time display) and `rotateSecret`.\n */\n\nexport interface CreateWebhookInput {\n\taccountId: string;\n\tprojectId?: string | null;\n\tname: string;\n\t/** Chain-trigger filter array. */\n\ttriggers: unknown;\n\tformat?: WebhookFormat;\n\turl: string;\n\tauthConfig?: unknown;\n\tmaxRetries?: number;\n\ttimeoutMs?: number;\n\tconcurrency?: number;\n}\n\nexport interface CreateWebhookResult {\n\twebhook: Webhook;\n\t/** Plaintext signing secret — surfaced once, never stored decrypted. */\n\tsigningSecret: string;\n}\n\nexport async function createWebhook(\n\tdb: Kysely<Database>,\n\tinput: CreateWebhookInput,\n): Promise<CreateWebhookResult> {\n\tconst signingSecret = generateSecret();\n\tconst row: InsertWebhook = {\n\t\taccount_id: isWebhookAccountScoped() ? input.accountId : \"\",\n\t\tproject_id: input.projectId ?? null,\n\t\tname: input.name,\n\t\tstatus: \"active\",\n\t\tkind: \"chain\",\n\t\ttriggers: input.triggers,\n\t\tformat: input.format ?? \"standard-webhooks\",\n\t\turl: input.url,\n\t\tsigning_secret_enc: encryptSecret(signingSecret),\n\t\tauth_config: input.authConfig ?? {},\n\t\t...(input.maxRetries !== undefined\n\t\t\t? { max_retries: input.maxRetries }\n\t\t\t: {}),\n\t\t...(input.timeoutMs !== undefined ? { timeout_ms: input.timeoutMs } : {}),\n\t\t...(input.concurrency !== undefined\n\t\t\t? { concurrency: input.concurrency }\n\t\t\t: {}),\n\t};\n\tconst webhook = await db\n\t\t.insertInto(\"webhooks\")\n\t\t.values(row)\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n\treturn { webhook, signingSecret };\n}\n\nexport async function listWebhooks(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\topts?: { limit?: number; offset?: number },\n): Promise<Webhook[]> {\n\tlet q = db.selectFrom(\"webhooks\").selectAll().orderBy(\"created_at\", \"desc\");\n\tif (isWebhookAccountScoped()) q = q.where(\"account_id\", \"=\", accountId);\n\tif (opts?.limit !== undefined) q = q.limit(opts.limit);\n\tif (opts?.offset !== undefined) q = q.offset(opts.offset);\n\treturn q.execute();\n}\n\n/**\n * All active chain webhooks across every account — the input to the global\n * trigger evaluator (one loop serves them all).\n */\nexport async function listActiveChainWebhooks(\n\tdb: Kysely<Database>,\n): Promise<Webhook[]> {\n\treturn db\n\t\t.selectFrom(\"webhooks\")\n\t\t.selectAll()\n\t\t.where(\"kind\", \"=\", \"chain\")\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.execute();\n}\n\n/** Webhook ids are UUIDs. Any other string names no webhook, and passing it\n * to the uuid column would make Postgres throw (a 500 for a typo'd URL). */\nconst WEBHOOK_ID_RE =\n\t/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nexport const isWebhookId = (id: string): boolean => WEBHOOK_ID_RE.test(id);\n\n/** `last_error` prefix a reorg writes next to `dead_reason = 'orphaned'`, for\n * humans reading the row. Code reads `dead_reason`, never this text. */\nexport const REORG_ORPHANED_ERROR_PREFIX = \"orphaned by reorg at \";\n\n/** `where` predicate keeping only outbox rows a reorg did NOT orphan. An\n * orphaned row must stay dead: resending it would deliver an event the chain\n * no longer contains. */\nexport function notReorgOrphaned(\n\teb: ExpressionBuilder<Database, \"webhook_outbox\">,\n): ExpressionWrapper<Database, \"webhook_outbox\", SqlBool> {\n\treturn eb.or([\n\t\teb(\"dead_reason\", \"is\", null),\n\t\teb(\"dead_reason\", \"!=\", \"orphaned\"),\n\t]);\n}\n\nexport async function getWebhook(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n): Promise<Webhook | null> {\n\tif (!isWebhookId(id)) return null;\n\tlet q = db.selectFrom(\"webhooks\").selectAll().where(\"id\", \"=\", id);\n\tif (isWebhookAccountScoped()) q = q.where(\"account_id\", \"=\", accountId);\n\treturn (await q.executeTakeFirst()) ?? null;\n}\n\nexport async function getWebhookByName(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tname: string,\n): Promise<Webhook | null> {\n\tlet q = db.selectFrom(\"webhooks\").selectAll().where(\"name\", \"=\", name);\n\tif (isWebhookAccountScoped()) q = q.where(\"account_id\", \"=\", accountId);\n\treturn (await q.executeTakeFirst()) ?? null;\n}\n\nexport interface UpdateWebhookInput {\n\tname?: string;\n\tformat?: WebhookFormat;\n\turl?: string;\n\tauthConfig?: unknown;\n\tmaxRetries?: number;\n\ttimeoutMs?: number;\n\tconcurrency?: number;\n}\n\nexport async function updateWebhook(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n\tpatch: UpdateWebhookInput,\n): Promise<Webhook | null> {\n\tif (!isWebhookId(id)) return null;\n\tconst update: UpdateWebhook = { updated_at: new Date() };\n\tif (patch.name !== undefined) update.name = patch.name;\n\tif (patch.format !== undefined) update.format = patch.format;\n\tif (patch.url !== undefined) update.url = patch.url;\n\tif (patch.authConfig !== undefined) update.auth_config = patch.authConfig;\n\tif (patch.maxRetries !== undefined) update.max_retries = patch.maxRetries;\n\tif (patch.timeoutMs !== undefined) update.timeout_ms = patch.timeoutMs;\n\tif (patch.concurrency !== undefined) update.concurrency = patch.concurrency;\n\n\tlet q = db.updateTable(\"webhooks\").set(update).where(\"id\", \"=\", id);\n\tif (isWebhookAccountScoped()) q = q.where(\"account_id\", \"=\", accountId);\n\treturn (await q.returningAll().executeTakeFirst()) ?? null;\n}\n\n/** Webhook status machine. Both moves are idempotent so a repeated pause or\n * resume call succeeds; the circuit breaker only trips an `active` row. */\nexport const webhookMachine: Machine<WebhookStatus> =\n\tdefineMachine<WebhookStatus>({\n\t\tstates: [\"active\", \"paused\"],\n\t\ttransitions: { active: [\"active\", \"paused\"], paused: [\"active\", \"paused\"] },\n\t});\n\n/** Pause (always as the customer: `pause_reason = 'user'`, even over a circuit\n * pause) or resume. Either ends any circuit incident. */\nexport async function toggleWebhookStatus(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n\tstatus: WebhookStatus,\n): Promise<Webhook | null> {\n\tif (!(await getWebhook(db, accountId, id))) return null;\n\treturn casTransition<WebhookStatus, Webhook>(db, {\n\t\ttable: \"webhooks\",\n\t\tid,\n\t\tfrom: webhookMachine.states,\n\t\tto: status,\n\t\tset: {\n\t\t\tpause_reason: status === \"paused\" ? \"user\" : null,\n\t\t\tcircuit_failures: 0,\n\t\t\tcircuit_opened_at: null,\n\t\t},\n\t});\n}\n\n/** Rows removed per statement. Small enough that one batch stays well\n * under the API idle timeout, and each batch commits on its own so a\n * client that gives up keeps the rows already removed. */\nconst WEBHOOK_DELETE_BATCH = 5_000;\n\n/** Delete a webhook's deliveries, then its outbox, in batches.\n *\n * Deliveries go first. The outbox FK is `ON DELETE SET NULL`, so deleting\n * an outbox row updates every delivery that points at it. Doing that for\n * a high-volume chain webhook (on the order of 1e5 `stx_transfer` rows)\n * sequential-scans `webhook_deliveries` once per outbox row unless\n * `webhook_deliveries_outbox_id_idx` (migration 0149) is present, and the\n * scan still reads dead tuples until vacuum. That single cascaded\n * `DELETE FROM webhooks` runs past the API's 90s idle timeout: the socket\n * closes, the gateway returns 502, and a retry queues on the same lock.\n *\n * Batches are separate statements. A timed-out request leaves a smaller\n * webhook, and the next delete finishes it. */\nasync function deleteWebhookChildren(\n\tdb: Kysely<Database>,\n\twebhookId: string,\n): Promise<void> {\n\tfor (const table of [\"webhook_deliveries\", \"webhook_outbox\"] as const) {\n\t\tfor (;;) {\n\t\t\tconst result = await sql`\n\t\t\t\tDELETE FROM ${sql.table(table)}\n\t\t\t\tWHERE id IN (\n\t\t\t\t\tSELECT id FROM ${sql.table(table)}\n\t\t\t\t\tWHERE webhook_id = ${webhookId}\n\t\t\t\t\tLIMIT ${WEBHOOK_DELETE_BATCH}\n\t\t\t\t)\n\t\t\t`.execute(db);\n\t\t\tif (Number(result.numAffectedRows ?? 0n) === 0) break;\n\t\t}\n\t}\n}\n\nexport async function deleteWebhook(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n): Promise<boolean> {\n\tif (!isWebhookId(id)) return false;\n\tlet owned = db.selectFrom(\"webhooks\").select(\"id\").where(\"id\", \"=\", id);\n\tif (isWebhookAccountScoped())\n\t\towned = owned.where(\"account_id\", \"=\", accountId);\n\tconst row = await owned.executeTakeFirst();\n\tif (!row) return false;\n\n\t// Stop the emitter claiming new rows before the children go.\n\tawait casTransition(db, {\n\t\ttable: \"webhooks\",\n\t\tid,\n\t\tfrom: [\"active\"],\n\t\tto: \"paused\",\n\t\tset: { pause_reason: \"user\" },\n\t});\n\tawait deleteWebhookChildren(db, id);\n\n\tlet q = db.deleteFrom(\"webhooks\").where(\"id\", \"=\", id);\n\tif (isWebhookAccountScoped()) q = q.where(\"account_id\", \"=\", accountId);\n\tconst res = await q.executeTakeFirst();\n\treturn Number(res.numDeletedRows ?? 0) > 0;\n}\n\nexport interface RotateSecretResult {\n\twebhook: Webhook;\n\tsigningSecret: string;\n}\n\nexport async function rotateWebhookSecret(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n): Promise<RotateSecretResult | null> {\n\tif (!isWebhookId(id)) return null;\n\tconst signingSecret = generateSecret();\n\tlet q = db\n\t\t.updateTable(\"webhooks\")\n\t\t.set({\n\t\t\tsigning_secret_enc: encryptSecret(signingSecret),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", id);\n\tif (isWebhookAccountScoped()) q = q.where(\"account_id\", \"=\", accountId);\n\tconst row = await q.returningAll().executeTakeFirst();\n\tif (!row) return null;\n\treturn { webhook: row, signingSecret };\n}\n\n/** Decrypt a webhook's signing secret for HMAC signing at emit time. */\nexport function getWebhookSigningSecret(webhook: Webhook): string {\n\treturn decryptSecret(webhook.signing_secret_enc);\n}\n\n/** Fire `webhooks:changed` notify so the emitter hot-reloads its cache. */\nexport async function notifyWebhooksChanged(\n\tdb: Kysely<Database>,\n\taccountId: string,\n): Promise<void> {\n\tawait sql`SELECT pg_notify('webhooks:changed', ${accountId})`.execute(db);\n}\n",
|
|
7
|
+
"import { createHmac, randomBytes } from \"node:crypto\";\n\n/**\n * Generate a random secret for delivery signing\n * Returns 32 bytes as a 64-character hex string\n */\nexport function generateSecret(): string {\n\treturn randomBytes(32).toString(\"hex\");\n}\n\n/**\n * Sign a payload with HMAC-SHA256\n * Returns the signature as a hex string\n */\nexport function signPayload(payload: string, secret: string): string {\n\tconst hmac = createHmac(\"sha256\", secret);\n\thmac.update(payload);\n\treturn hmac.digest(\"hex\");\n}\n\n/**\n * Verify an HMAC signature\n * Uses constant-time comparison to prevent timing attacks\n */\nexport function verifySignature(\n\tpayload: string,\n\tsignature: string,\n\tsecret: string,\n): boolean {\n\tconst expectedSignature = signPayload(payload, secret);\n\n\t// Constant-time comparison\n\tif (signature.length !== expectedSignature.length) {\n\t\treturn false;\n\t}\n\n\tlet result = 0;\n\tfor (let i = 0; i < signature.length; i++) {\n\t\tresult |= signature.charCodeAt(i) ^ expectedSignature.charCodeAt(i);\n\t}\n\n\treturn result === 0;\n}\n\n/**\n * Create a Stripe-style signature header\n * Format: t=timestamp,v1=signature\n */\nexport function createSignatureHeader(\n\tpayload: string,\n\tsecret: string,\n\ttimestamp?: number,\n): string {\n\tconst ts = timestamp ?? Math.floor(Date.now() / 1000);\n\tconst signedPayload = `${ts}.${payload}`;\n\tconst signature = signPayload(signedPayload, secret);\n\n\treturn `t=${ts},v1=${signature}`;\n}\n\n/**\n * Parse and verify a Stripe-style signature header\n * Returns true if valid, false otherwise\n */\nexport function verifySignatureHeader(\n\tpayload: string,\n\theader: string,\n\tsecret: string,\n\ttoleranceSeconds = 300, // 5 minutes\n): boolean {\n\t// Parse header\n\tconst parts = header.split(\",\");\n\tconst timestamp = parts.find((p) => p.startsWith(\"t=\"))?.slice(2);\n\tconst signature = parts.find((p) => p.startsWith(\"v1=\"))?.slice(3);\n\n\tif (!timestamp || !signature) {\n\t\treturn false;\n\t}\n\n\tconst ts = Number.parseInt(timestamp, 10);\n\tif (Number.isNaN(ts)) {\n\t\treturn false;\n\t}\n\n\t// Check timestamp is within tolerance\n\tconst now = Math.floor(Date.now() / 1000);\n\tif (Math.abs(now - ts) > toleranceSeconds) {\n\t\treturn false;\n\t}\n\n\t// Verify signature\n\tconst signedPayload = `${ts}.${payload}`;\n\treturn verifySignature(signedPayload, signature, secret);\n}\n",
|
|
8
|
+
"import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\nimport {\n\tappendFileSync,\n\tcloseSync,\n\texistsSync,\n\topenSync,\n\treadFileSync,\n\tunlinkSync,\n} from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { getInstanceMode } from \"../mode.ts\";\n\n/**\n * AES-256-GCM symmetric envelope for encrypted secrets at rest (tenant keys,\n * webhook signing secrets, etc.).\n *\n * Ciphertext layout: `iv (12 bytes) || authTag (16 bytes) || ciphertext`\n *\n * The key comes from `SECONDLAYER_SECRETS_KEY` — 32 bytes hex. In OSS mode,\n * if the env var is unset on first use we autogenerate a key and persist it\n * to `.env.local` in the current working directory so subsequent restarts\n * pick it up without user intervention. Dedicated/platform modes throw —\n * those runtimes must provision the key explicitly.\n *\n * Rotation strategy: re-encrypt all rows with the new key and swap the env\n * var. Not zero-downtime, but acceptable at v2 scale. For real KMS (AWS\n * KMS, Vault, GCP KMS), wrap the same byte layout behind an\n * `EncryptSecret`/`DecryptSecret` interface and swap at startup.\n */\n\nconst KEY_ENV = \"SECONDLAYER_SECRETS_KEY\";\nconst IV_LEN = 12;\nconst TAG_LEN = 16;\n\nfunction readExistingKey(envPath: string): string | null {\n\tif (!existsSync(envPath)) return null;\n\tconst contents = readFileSync(envPath, \"utf8\");\n\tconst match = contents.match(/^SECONDLAYER_SECRETS_KEY=([a-fA-F0-9]{64})/m);\n\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\treturn match ? match[1]! : null;\n}\n\n/**\n * Atomic file lock via `openSync(..., \"wx\")` — O_CREAT | O_EXCL. If two\n * processes race on cold-compose start, exactly one creates the lock\n * file; the loser polls until the winner finishes writing `.env.local`,\n * then reads the winner's key. Stale locks (process crashed mid-write)\n * are cleaned after `STALE_LOCK_MS`.\n */\nconst STALE_LOCK_MS = 10_000;\nconst POLL_MS = 25;\n\nfunction bootstrapOssKey(): string {\n\tconst envPath = resolve(process.cwd(), \".env.local\");\n\n\t// Fast path — key already on disk from a prior run.\n\tconst existing = readExistingKey(envPath);\n\tif (existing) {\n\t\tprocess.env[KEY_ENV] = existing;\n\t\treturn existing;\n\t}\n\n\tconst lockPath = `${envPath}.secret-bootstrap.lock`;\n\tlet lockFd: number | null = null;\n\ttry {\n\t\tlockFd = openSync(lockPath, \"wx\", 0o600);\n\t} catch (err) {\n\t\tconst e = err as NodeJS.ErrnoException;\n\t\tif (e.code !== \"EEXIST\") throw err;\n\t}\n\n\tif (lockFd === null) {\n\t\t// Another process is bootstrapping. Poll for its result.\n\t\tconst deadline = Date.now() + STALE_LOCK_MS;\n\t\twhile (Date.now() < deadline) {\n\t\t\tconst key = readExistingKey(envPath);\n\t\t\tif (key) {\n\t\t\t\tprocess.env[KEY_ENV] = key;\n\t\t\t\treturn key;\n\t\t\t}\n\t\t\tBun.sleepSync(POLL_MS);\n\t\t}\n\t\t// Lock holder died mid-write — force-clean and retry once.\n\t\ttry {\n\t\t\tunlinkSync(lockPath);\n\t\t} catch {}\n\t\treturn bootstrapOssKey();\n\t}\n\n\ttry {\n\t\tconst hex = randomBytes(32).toString(\"hex\");\n\t\tconst line = `${existsSync(envPath) ? \"\\n\" : \"\"}${KEY_ENV}=${hex}\\n`;\n\t\tappendFileSync(envPath, line, { mode: 0o600 });\n\t\tprocess.env[KEY_ENV] = hex;\n\t\tconsole.log(\n\t\t\t`[secondlayer] generated ${KEY_ENV}; saved to ${envPath} (mode 0600)`,\n\t\t);\n\t\treturn hex;\n\t} finally {\n\t\tcloseSync(lockFd);\n\t\ttry {\n\t\t\tunlinkSync(lockPath);\n\t\t} catch {}\n\t}\n}\n\nfunction loadKey(): Buffer {\n\tlet hex = process.env[KEY_ENV];\n\tif (!hex) {\n\t\tif (getInstanceMode() === \"oss\") {\n\t\t\thex = bootstrapOssKey();\n\t\t} else {\n\t\t\tthrow new Error(\n\t\t\t\t`${KEY_ENV} not set. Generate one with: openssl rand -hex 32`,\n\t\t\t);\n\t\t}\n\t}\n\tconst key = Buffer.from(hex, \"hex\");\n\tif (key.length !== 32) {\n\t\tthrow new Error(`${KEY_ENV} must be 32 bytes hex (got ${key.length})`);\n\t}\n\treturn key;\n}\n\nlet _cachedKey: Buffer | null = null;\nfunction getKey(): Buffer {\n\tif (!_cachedKey) _cachedKey = loadKey();\n\treturn _cachedKey;\n}\n\n/**\n * Non-throwing check for whether a secrets key is currently resolvable —\n * same resolution order as {@link loadKey} (env var, then the OSS\n * `.env.local` fallback), but never bootstraps a new key (that would\n * generate+persist a key as a side effect of a mere existence check), never\n * throws, and never returns or logs the key itself. Used by callers that\n * need to fail loud on a missing key BEFORE attempting a decrypt (f072).\n */\nexport function secretsKeyAvailable(): boolean {\n\tif (process.env[KEY_ENV]) return true;\n\tif (getInstanceMode() === \"oss\") {\n\t\tconst envPath = resolve(process.cwd(), \".env.local\");\n\t\treturn readExistingKey(envPath) !== null;\n\t}\n\treturn false;\n}\n\nexport function encryptSecret(plaintext: string): Buffer {\n\tconst key = getKey();\n\tconst iv = randomBytes(IV_LEN);\n\tconst cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n\tconst ciphertext = Buffer.concat([\n\t\tcipher.update(plaintext, \"utf8\"),\n\t\tcipher.final(),\n\t]);\n\tconst tag = cipher.getAuthTag();\n\treturn Buffer.concat([iv, tag, ciphertext]);\n}\n\nexport function decryptSecret(envelope: Buffer): string {\n\tconst key = getKey();\n\tconst iv = envelope.subarray(0, IV_LEN);\n\tconst tag = envelope.subarray(IV_LEN, IV_LEN + TAG_LEN);\n\tconst ciphertext = envelope.subarray(IV_LEN + TAG_LEN);\n\tconst decipher = createDecipheriv(\"aes-256-gcm\", key, iv);\n\tdecipher.setAuthTag(tag);\n\treturn decipher.update(ciphertext).toString(\"utf8\") + decipher.final(\"utf8\");\n}\n\n/** Generate a fresh 32-byte hex key suitable for `SECONDLAYER_SECRETS_KEY`. */\nexport function generateSecretsKey(): string {\n\treturn randomBytes(32).toString(\"hex\");\n}\n",
|
|
9
|
+
"/**\n * Instance modes for the Secondlayer platform.\n *\n * - `oss`: self-hosted, single-tenant. No auth middleware, no platform routes\n * (projects, admin). Everything runs against a single `DATABASE_URL`.\n * Intended for `docker compose up`.\n *\n * - `platform`: the metered archive deployment. Magic-link auth, API keys,\n * accounts, credits, and metered `/v1` reads (Index + Streams + subgraphs)\n * against a single shared DB. No paid tier ladder — one metered `free`\n * tier plus first-party internal service credentials.\n */\n\nexport type InstanceMode = \"oss\" | \"platform\";\n\n/** What the operator wrote in the env — `archive` is the honest name for the\n * metered public-archive deployment and aliases `platform` behaviorally. */\nexport type DeclaredInstanceMode = InstanceMode | \"archive\";\n\nconst VALID_MODES: readonly DeclaredInstanceMode[] = [\n\t\"oss\",\n\t\"platform\",\n\t\"archive\",\n];\n\nfunction declaredMode(): DeclaredInstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as DeclaredInstanceMode;\n\t}\n\treturn \"oss\";\n}\n\n/**\n * Resolve the active instance mode from `process.env.INSTANCE_MODE`.\n * Defaults to `\"oss\"` — the safest default for self-hosters who deploy\n * without setting the variable. `archive` normalizes to `platform` here so\n * every behavioral branch stays a two-way choice; use\n * `getDeclaredInstanceMode()` for display surfaces.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst declared = declaredMode();\n\treturn declared === \"archive\" ? \"platform\" : declared;\n}\n\n/** The mode as declared in the env, for status/identity surfaces. */\nexport function getDeclaredInstanceMode(): DeclaredInstanceMode {\n\treturn declaredMode();\n}\n\n/**\n * True when public reads are credit-metered (the free window, retention, and\n * credits gates arm). Platform/archive deployments meter by default;\n * self-host never does unless the operator explicitly sets\n * `METERED_READS=true`. `METERED_READS=false` disarms a metered deployment.\n */\nexport function isMeteredReads(): boolean {\n\tconst override = process.env.METERED_READS?.trim().toLowerCase();\n\tif (override === \"true\") return true;\n\tif (override === \"false\") return false;\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"platform\"` (shared multi-tenant). */\nexport function isPlatformMode(): boolean {\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"oss\"` (self-hosted). */\nexport function isOssMode(): boolean {\n\treturn getInstanceMode() === \"oss\";\n}\n\n/** The one shared testnet webhook stack (hosted). Off everywhere else. */\nexport function isTestnetWebhookStack(): boolean {\n\treturn process.env.TESTNET_WEBHOOK_STACK === \"true\";\n}\n\n/** Webhook rows are per-account: platform, or the shared testnet stack. */\nexport function isWebhookAccountScoped(): boolean {\n\treturn isPlatformMode() || isTestnetWebhookStack();\n}\n",
|
|
10
|
+
"import { type Kysely, sql } from \"kysely\";\n\n/**\n * The one convention for state machines: states are a const array (mirrored by\n * a DB CHECK), transitions are a table next to the states, and every status\n * write goes through `casTransition`.\n */\n\nexport interface Machine<S extends string> {\n\treadonly states: readonly S[];\n\tcanTransition(from: S, to: S): boolean;\n\t/** Throws on an illegal move. */\n\tassert(from: S, to: S): void;\n}\n\n/** Pure transition table. `transitions` lists, per state, the states it may move to. */\nexport function defineMachine<const S extends string>(def: {\n\tstates: readonly S[];\n\ttransitions: { readonly [K in S]?: readonly S[] };\n}): Machine<S> {\n\tconst canTransition = (from: S, to: S) =>\n\t\tdef.transitions[from]?.includes(to) ?? false;\n\treturn {\n\t\tstates: def.states,\n\t\tcanTransition,\n\t\tassert(from, to) {\n\t\t\tif (!canTransition(from, to)) {\n\t\t\t\tthrow new Error(`illegal transition ${from} -> ${to}`);\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport interface CasTransition<S extends string> {\n\ttable: string;\n\t/** Value of the row key. */\n\tid: string | number;\n\t/** Row key column, `id` unless the table is addressed by another unique column (`name`). */\n\tkey?: string;\n\t/** Status column, `status` unless the machine lives in another column. */\n\tcolumn?: string;\n\t/** The row moves only if it is currently in one of these states. */\n\tfrom: readonly S[];\n\tto: S;\n\t/** Extra columns written in the same statement. Wrap jsonb values with `jsonb()`. */\n\tset?: Record<string, unknown>;\n\t/** Stamp `updated_at = now()`. Pass `false` for tables without that column. */\n\tstampUpdatedAt?: boolean;\n\t/** Columns to return, `*` unless the row carries a large payload (`[\"sequence\"]`). */\n\treturning?: readonly string[];\n}\n\n/**\n * Compare-and-swap a status column: `UPDATE ... WHERE key = ? AND column = ANY(from)`.\n * Returns the updated row (or the `returning` columns), or `null` when the row was missing or not in a `from`\n * state (a lost race). The caller decides what `null` means; usually log and stop.\n * Works with `db` and inside a transaction (`trx`).\n */\nexport async function casTransition<\n\tS extends string,\n\t// biome-ignore lint/suspicious/noExplicitAny: dynamic table name, row shape is the caller's\n\tRow = Record<string, any>,\n>(\n\t// biome-ignore lint/suspicious/noExplicitAny: accepts Kysely<Database> and Transaction<Database>\n\tdb: Kysely<any>,\n\tt: CasTransition<S>,\n): Promise<Row | null> {\n\tconst column = sql.id(t.column ?? \"status\");\n\tconst assignments = [sql`${column} = ${t.to}`];\n\tif (t.stampUpdatedAt !== false) assignments.push(sql`updated_at = now()`);\n\tfor (const [key, value] of Object.entries(t.set ?? {})) {\n\t\tassignments.push(sql`${sql.id(key)} = ${value}`);\n\t}\n\n\tconst returning = t.returning\n\t\t? sql.join(t.returning.map((c) => sql.id(c)))\n\t\t: sql.raw(\"*\");\n\n\tconst { rows } = await sql<Row>`\n\t\tUPDATE ${sql.table(t.table)}\n\t\tSET ${sql.join(assignments)}\n\t\tWHERE ${sql.id(t.key ?? \"id\")} = ${t.id} AND ${column} = ANY(${sql.val([...t.from])})\n\t\tRETURNING ${returning}\n\t`.execute(db);\n\treturn rows[0] ?? null;\n}\n"
|
|
6
11
|
],
|
|
7
|
-
"mappings": ";AAAA;AAgBA,IAAM,qBAAqB;AAAA;AAIpB,MAAM,8BAA8B,MAAM;AAAA,EAChD,WAAW,GAAG;AAAA,IACb,MAAM,6CAA6C;AAAA,IACnD,KAAK,OAAO;AAAA;AAEd;AAEA,IAAM,0BAA0B;AAEhC,SAAS,qBAAqB,CAAC,KAAuB;AAAA,EACrD,IAAI,EAAE,eAAe;AAAA,IAAQ,OAAO;AAAA,EACpC,MAAM,YAAY;AAAA,EAKlB,OACC,UAAU,SAAS,YAClB,UAAU,eAAe,2BACzB,UAAU,oBAAoB;AAAA;AAIjC,eAAsB,WAAW,CAChC,IACA,OAMgB;AAAA,EAChB,IAAI;AAAA,IACH,MAAM,GAAG,YAAY,EAAE,QAAQ,OAAO,QAAQ;AAAA,MAC7C,MAAM,IACJ,YAAY,iBAAiB,EAC7B,IAAI;AAAA,QACJ,QAAQ;AAAA,QACR,OAAO;AAAA,QACP,aAAa;AAAA,MACd,CAAC,EACA,MAAM,cAAc,KAAK,MAAM,SAAS,EACxC,MAAM,UAAU,KAAK,UAAU,EAC/B,MACA,cACA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EACX,QAAQ;AAAA,EACV,OAAO,QAAQ,IAAI,QAAQ,IAAI,CAAC,MAAM,qBAAqB,IAAI,CAAC,CAAC,CAAC;AAAA;AAKnE,eAAsB,eAAe,CAAC,IAAqC;AAAA,EAC1E,MAAM,eAAe,EAAE;AAAA,EACvB,MAAM,UAAU,MAAM,GACpB,WAAW,iBAAiB,EAC5B,UAAU,EACV,MAAM,UAAU,KAAK,SAAS,EAC9B,QAAQ;AAAA,EACV,WAAW,UAAU;AAAA,IAAS,MAAM,qBAAqB,IAAI,MAAM;AAAA;AAGpE,eAAsB,SAAS,CAC9B,IACA,WACA,OACkB;AAAA,EAClB,IAAI,IAAI,GACN,WAAW,gBAAgB,EAC3B,OAAO,eAAsB,GAAG,GAAG,CAAC,EACpC,MAAM,cAAc,KAAK,SAAS,EAClC,MAAM,UAAU,KAAK,MAAM,EAC3B,MAAM,gBAAgB;AAAA,EACxB,IAAI;AAAA,IAAO,IAAI,EAAE,MAAM,aAAa,MAAM,KAAK;AAAA,EAC/C,OAAO,QAAQ,MAAM,EAAE,wBAAwB,GAAG,CAAC;AAAA;AAGpD,eAAsB,kBAAkB,CACvC,IACA,WACA,MACA,IACkB;AAAA,EAClB,MAAM,MAAM,MAAM,GAChB,WAAW,gBAAgB,EAC3B,OAAO,eAAsB,GAAG,GAAG,CAAC,EACpC,MAAM,cAAc,KAAK,SAAS,EAClC,MAAM,gBAAgB,MAAM,IAAI,EAChC,MAAM,gBAAgB,MAAM,EAAE,EAC9B,wBAAwB;AAAA,EAC1B,OAAO,OAAO,IAAI,CAAC;AAAA;",
|
|
13
|
+
"debugId": "1C69B30BE979C07264756E2164756E21",
|
|
9
14
|
"names": []
|
|
10
15
|
}
|
|
@@ -1,4 +1,15 @@
|
|
|
1
|
-
import { Kysely } from "kysely";
|
|
1
|
+
import { ExpressionBuilder, ExpressionWrapper, Kysely as Kysely2, SqlBool } from "kysely";
|
|
2
|
+
/**
|
|
3
|
+
* The one convention for state machines: states are a const array (mirrored by
|
|
4
|
+
* a DB CHECK), transitions are a table next to the states, and every status
|
|
5
|
+
* write goes through `casTransition`.
|
|
6
|
+
*/
|
|
7
|
+
interface Machine<S extends string> {
|
|
8
|
+
readonly states: readonly S[];
|
|
9
|
+
canTransition(from: S, to: S): boolean;
|
|
10
|
+
/** Throws on an illegal move. */
|
|
11
|
+
assert(from: S, to: S): void;
|
|
12
|
+
}
|
|
2
13
|
import { ColumnType, Generated, Selectable } from "kysely";
|
|
3
14
|
/**
|
|
4
15
|
* Coverage-kernel constraints. SQL CHECKs in migration 0116 must stay
|
|
@@ -40,6 +51,12 @@ interface SubgraphVerification {
|
|
|
40
51
|
/** What stays unproven even at this level, e.g. tx attribution of writes. */
|
|
41
52
|
unproven: string[];
|
|
42
53
|
}
|
|
54
|
+
/** Every state `subgraphs.status` can hold; mirrored by the
|
|
55
|
+
* `subgraphs_status_check` CHECK (migration 0189). */
|
|
56
|
+
declare const SUBGRAPH_STATES: readonly ["active", "reindexing", "error"];
|
|
57
|
+
type SubgraphStatus = (typeof SUBGRAPH_STATES)[number];
|
|
58
|
+
/** Why a webhook is paused: the customer did it, or the circuit breaker did. */
|
|
59
|
+
type WebhookPauseReason = "user" | "circuit";
|
|
43
60
|
interface BlocksTable {
|
|
44
61
|
height: number;
|
|
45
62
|
hash: string;
|
|
@@ -179,7 +196,7 @@ interface SubgraphsTable {
|
|
|
179
196
|
id: Generated<string>;
|
|
180
197
|
name: string;
|
|
181
198
|
version: Generated<string>;
|
|
182
|
-
status: Generated<
|
|
199
|
+
status: Generated<SubgraphStatus>;
|
|
183
200
|
definition: Record<string, unknown>;
|
|
184
201
|
schema_hash: string;
|
|
185
202
|
handler_path: string;
|
|
@@ -196,8 +213,10 @@ interface SubgraphsTable {
|
|
|
196
213
|
handler_code: string | null;
|
|
197
214
|
source_code: string | null;
|
|
198
215
|
project_id: string | null;
|
|
199
|
-
/**
|
|
200
|
-
|
|
216
|
+
/** Set while the account's metered reads are refused (spend cap, credits).
|
|
217
|
+
* Both columns are set or both null; `last_error` stays for real errors. */
|
|
218
|
+
billing_paused_at: Date | null;
|
|
219
|
+
billing_paused_code: string | null;
|
|
201
220
|
/** (event type, contract) probe pairs persisted at deploy for weight classification. */
|
|
202
221
|
sparse_probe_targets: unknown | null;
|
|
203
222
|
/** sha256 over everything that shapes rows (schema, handler bundle,
|
|
@@ -211,6 +230,9 @@ interface SubgraphsTable {
|
|
|
211
230
|
created_at: Generated<Date>;
|
|
212
231
|
updated_at: Generated<Date>;
|
|
213
232
|
}
|
|
233
|
+
/** Mirrored by the CHECK on `contracts.abi_status`. */
|
|
234
|
+
declare const ABI_STATUSES: readonly ["pending", "fetched", "unparseable", "failed"];
|
|
235
|
+
type AbiStatus = (typeof ABI_STATUSES)[number];
|
|
214
236
|
interface ContractsTable {
|
|
215
237
|
contract_id: string;
|
|
216
238
|
deployer: string;
|
|
@@ -219,17 +241,23 @@ interface ContractsTable {
|
|
|
219
241
|
abi: unknown | null;
|
|
220
242
|
declared_traits: Generated<string[]>;
|
|
221
243
|
inferred_standards: Generated<string[]>;
|
|
222
|
-
abi_status: Generated<
|
|
244
|
+
abi_status: Generated<AbiStatus>;
|
|
223
245
|
abi_fetched_at: Date | null;
|
|
246
|
+
/** Failed fetches so far; `failed` re-polls until the registry's attempt cap. */
|
|
247
|
+
abi_attempts: Generated<number>;
|
|
248
|
+
/** When a `failed` row is next due; NULL once attempts are exhausted. */
|
|
249
|
+
abi_next_attempt_at: Date | null;
|
|
224
250
|
created_at: Generated<Date>;
|
|
225
251
|
}
|
|
252
|
+
/** The only reasons the runtime records; mirrored by a CHECK on `subgraph_gaps.reason`. */
|
|
253
|
+
type GapReason = "block_missing" | "processing_error";
|
|
226
254
|
interface SubgraphGapsTable {
|
|
227
255
|
id: Generated<string>;
|
|
228
256
|
subgraph_id: string;
|
|
229
257
|
subgraph_name: string;
|
|
230
258
|
gap_start: number;
|
|
231
259
|
gap_end: number;
|
|
232
|
-
reason:
|
|
260
|
+
reason: GapReason;
|
|
233
261
|
detected_at: Generated<Date>;
|
|
234
262
|
resolved_at: Date | null;
|
|
235
263
|
}
|
|
@@ -275,12 +303,13 @@ interface SubgraphOperationsTable {
|
|
|
275
303
|
* (those checkpoint on subgraphs.last_processed_block). */
|
|
276
304
|
cursor_block: string | number | bigint | null;
|
|
277
305
|
}
|
|
306
|
+
type ApiKeyStatus = "active" | "revoked";
|
|
278
307
|
interface ApiKeysTable {
|
|
279
308
|
id: Generated<string>;
|
|
280
309
|
key_hash: string;
|
|
281
310
|
key_prefix: string;
|
|
282
311
|
name: string | null;
|
|
283
|
-
status: Generated<
|
|
312
|
+
status: Generated<ApiKeyStatus>;
|
|
284
313
|
rate_limit: Generated<number>;
|
|
285
314
|
ip_address: string;
|
|
286
315
|
account_id: string;
|
|
@@ -641,6 +670,10 @@ interface SbtcSettlementsTable {
|
|
|
641
670
|
last_checked_at: Generated<Date>;
|
|
642
671
|
/** Set once, when `settlement_confirmed` first flips true. */
|
|
643
672
|
confirmed_at: Date | null;
|
|
673
|
+
/** Monotonic stamp from `sbtc_settlements_seq`, retaken each time the sweep
|
|
674
|
+
* becomes confirmed. The webhook scan's watermark. BIGINT: a string at
|
|
675
|
+
* runtime. */
|
|
676
|
+
seq: Generated<number | string>;
|
|
644
677
|
updated_at: Generated<Date>;
|
|
645
678
|
}
|
|
646
679
|
type BnsNameEventTopic = "new-name" | "transfer-name" | "renew-name" | "burn-name" | "new-airdrop";
|
|
@@ -760,7 +793,9 @@ interface PendingForkBlocksTable {
|
|
|
760
793
|
payload: ColumnType<unknown, unknown, unknown>;
|
|
761
794
|
received_at: Generated<Date>;
|
|
762
795
|
}
|
|
763
|
-
|
|
796
|
+
/** Mirrored by the CHECK on `observer_journal.status`. */
|
|
797
|
+
declare const OBSERVER_JOURNAL_STATUSES: readonly ["received", "processed", "failed", "retried", "poisoned", "skipped"];
|
|
798
|
+
type ObserverJournalStatus = (typeof OBSERVER_JOURNAL_STATUSES)[number];
|
|
764
799
|
/**
|
|
765
800
|
* Exact observer callback receipt. `raw_body` is immutable evidence; the
|
|
766
801
|
* processing columns are updated only after the current derived-state write
|
|
@@ -795,7 +830,7 @@ interface StageRegistryTable {
|
|
|
795
830
|
enabled: Generated<boolean>;
|
|
796
831
|
created_at: Generated<Date>;
|
|
797
832
|
}
|
|
798
|
-
/** One versioned sweep of a stage. */
|
|
833
|
+
/** One versioned sweep of a stage. Nothing writes this table yet; kept because the receipts and failures tables reference it. */
|
|
799
834
|
interface StageRunsTable {
|
|
800
835
|
id: Generated<string>;
|
|
801
836
|
stage_id: string;
|
|
@@ -929,6 +964,7 @@ interface Database {
|
|
|
929
964
|
archive_fetches: ArchiveFetchesTable;
|
|
930
965
|
usage_ledger: UsageLedgerTable;
|
|
931
966
|
account_balance_alerts: AccountBalanceAlertsTable;
|
|
967
|
+
hosted_stack_state: HostedStackStateTable;
|
|
932
968
|
webhook_incident_alerts: WebhookIncidentAlertsTable;
|
|
933
969
|
cli_device_logins: CliDeviceLoginsTable;
|
|
934
970
|
oauth_clients: OauthClientsTable;
|
|
@@ -1012,7 +1048,11 @@ interface UsageLedgerTable {
|
|
|
1012
1048
|
* floor to observe past. */
|
|
1013
1049
|
observed_quantity: string | number | null;
|
|
1014
1050
|
usd_micros: string | number | bigint;
|
|
1051
|
+
/** True when the whole price was taken; derived from `debited_usd_micros`. */
|
|
1015
1052
|
debited: Generated<boolean>;
|
|
1053
|
+
/** Amount actually taken from the balance, `0..usd_micros` (bounded the
|
|
1054
|
+
* other way for a negative top-up/grant row). Unpaid = price - this. */
|
|
1055
|
+
debited_usd_micros: Generated<string | number | bigint>;
|
|
1016
1056
|
source: string;
|
|
1017
1057
|
/** API key behind a metered read; null for non-read units and older rows. */
|
|
1018
1058
|
api_key_id: string | null;
|
|
@@ -1030,6 +1070,14 @@ interface AccountBalanceAlertsTable {
|
|
|
1030
1070
|
sent_2d_at: Date | null;
|
|
1031
1071
|
sent_stopped_at: Date | null;
|
|
1032
1072
|
}
|
|
1073
|
+
/** The workload host's report of one account's hosted stack. Written only by
|
|
1074
|
+
* `POST /internal/stack-state`; `reported_at` is the host's observation time. */
|
|
1075
|
+
interface HostedStackStateTable {
|
|
1076
|
+
account_id: string;
|
|
1077
|
+
state: "provisioning" | "running" | "stopped" | "destroyed";
|
|
1078
|
+
stop_reason: "credits" | "cap" | "idle" | null;
|
|
1079
|
+
reported_at: Date;
|
|
1080
|
+
}
|
|
1033
1081
|
/** Debounce state for the webhook-down email: one row per incident, open
|
|
1034
1082
|
* while `resolved_at` is null. No preference columns by design. */
|
|
1035
1083
|
interface WebhookIncidentAlertsTable {
|
|
@@ -1166,7 +1214,7 @@ interface SentinelAccountsTable {
|
|
|
1166
1214
|
linked_at: Generated<Date>;
|
|
1167
1215
|
via: "created" | "consent";
|
|
1168
1216
|
}
|
|
1169
|
-
type WebhookStatus = "active" | "paused"
|
|
1217
|
+
type WebhookStatus = "active" | "paused";
|
|
1170
1218
|
/** Webhooks react to raw chain events matched directly off the Index/Streams
|
|
1171
1219
|
* clock. `chain` is the only kind since migration 0159 removed subgraph-row
|
|
1172
1220
|
* webhooks; the column stays as the discriminator. */
|
|
@@ -1192,6 +1240,8 @@ interface WebhooksTable {
|
|
|
1192
1240
|
concurrency: Generated<number>;
|
|
1193
1241
|
circuit_failures: Generated<number>;
|
|
1194
1242
|
circuit_opened_at: Date | null;
|
|
1243
|
+
/** Why a paused webhook is paused. Set exactly while `status` is `paused`. */
|
|
1244
|
+
pause_reason: WebhookPauseReason | null;
|
|
1195
1245
|
last_delivery_at: Date | null;
|
|
1196
1246
|
last_success_at: Date | null;
|
|
1197
1247
|
last_error: string | null;
|
|
@@ -1203,6 +1253,10 @@ interface WebhooksTable {
|
|
|
1203
1253
|
}
|
|
1204
1254
|
type Webhook = Selectable<WebhooksTable>;
|
|
1205
1255
|
type OutboxStatus = "pending" | "delivered" | "dead";
|
|
1256
|
+
/** Why a row is dead: retries ran out, or a reorg removed its event. An
|
|
1257
|
+
* orphaned row stays dead; requeueing it would resend an event the chain no
|
|
1258
|
+
* longer contains. */
|
|
1259
|
+
type DeadReason = "exhausted" | "orphaned";
|
|
1206
1260
|
interface WebhookOutboxTable {
|
|
1207
1261
|
id: Generated<string>;
|
|
1208
1262
|
webhook_id: string;
|
|
@@ -1232,6 +1286,8 @@ interface WebhookOutboxTable {
|
|
|
1232
1286
|
* into an orphaned fork. Null otherwise — delivery failures track their
|
|
1233
1287
|
* history on `webhooks.last_error`, not per-row. */
|
|
1234
1288
|
last_error: string | null;
|
|
1289
|
+
/** Set exactly while `status` is `dead`. */
|
|
1290
|
+
dead_reason: DeadReason | null;
|
|
1235
1291
|
created_at: Generated<Date>;
|
|
1236
1292
|
}
|
|
1237
1293
|
type WebhookReplayStatus = "scanning" | "running" | "done" | "failed";
|
|
@@ -1281,6 +1337,13 @@ interface TriggerEvaluatorStateTable {
|
|
|
1281
1337
|
/** Watermark for the async sBTC settlement-confirmed webhook scan; null until
|
|
1282
1338
|
* the evaluator fast-forwards it on first run. */
|
|
1283
1339
|
last_settlement_scan_at: ColumnType<Date | null, Date | null | undefined, Date | null>;
|
|
1340
|
+
/** `sbtc_settlements.seq` watermark. Null until the first settlement row is
|
|
1341
|
+
* scanned; `last_settlement_scan_at` is the forward-only floor until then. */
|
|
1342
|
+
last_settlement_scan_seq: ColumnType<bigint | null, bigint | number | null | undefined, bigint | number | null>;
|
|
1343
|
+
/** Counts reorg rewinds. The evaluator checks it under the row lock in the
|
|
1344
|
+
* transaction that emits a batch and advances the cursor, so a reorg that
|
|
1345
|
+
* lands mid-tick rolls the batch back. */
|
|
1346
|
+
reorg_generation: ColumnType<bigint, bigint | number | undefined, bigint | number>;
|
|
1284
1347
|
/** Streams cursor (`<block_height>:<event_index>`) for the Bitcoin (Runes)
|
|
1285
1348
|
* chain-trigger evaluator (plan 060) — a separate clock from
|
|
1286
1349
|
* `last_processed_block` (Stacks). Null until the evaluator fast-forwards
|
|
@@ -1435,8 +1498,8 @@ interface CreateWebhookResult {
|
|
|
1435
1498
|
/** Plaintext signing secret — surfaced once, never stored decrypted. */
|
|
1436
1499
|
signingSecret: string;
|
|
1437
1500
|
}
|
|
1438
|
-
declare function createWebhook(db:
|
|
1439
|
-
declare function listWebhooks(db:
|
|
1501
|
+
declare function createWebhook(db: Kysely2<Database>, input: CreateWebhookInput): Promise<CreateWebhookResult>;
|
|
1502
|
+
declare function listWebhooks(db: Kysely2<Database>, accountId: string, opts?: {
|
|
1440
1503
|
limit?: number
|
|
1441
1504
|
offset?: number
|
|
1442
1505
|
}): Promise<Webhook[]>;
|
|
@@ -1444,10 +1507,17 @@ declare function listWebhooks(db: Kysely<Database>, accountId: string, opts?: {
|
|
|
1444
1507
|
* All active chain webhooks across every account — the input to the global
|
|
1445
1508
|
* trigger evaluator (one loop serves them all).
|
|
1446
1509
|
*/
|
|
1447
|
-
declare function listActiveChainWebhooks(db:
|
|
1510
|
+
declare function listActiveChainWebhooks(db: Kysely2<Database>): Promise<Webhook[]>;
|
|
1448
1511
|
declare const isWebhookId: (id: string) => boolean;
|
|
1449
|
-
|
|
1450
|
-
|
|
1512
|
+
/** `last_error` prefix a reorg writes next to `dead_reason = 'orphaned'`, for
|
|
1513
|
+
* humans reading the row. Code reads `dead_reason`, never this text. */
|
|
1514
|
+
declare const REORG_ORPHANED_ERROR_PREFIX = "orphaned by reorg at ";
|
|
1515
|
+
/** `where` predicate keeping only outbox rows a reorg did NOT orphan. An
|
|
1516
|
+
* orphaned row must stay dead: resending it would deliver an event the chain
|
|
1517
|
+
* no longer contains. */
|
|
1518
|
+
declare function notReorgOrphaned(eb: ExpressionBuilder<Database, "webhook_outbox">): ExpressionWrapper<Database, "webhook_outbox", SqlBool>;
|
|
1519
|
+
declare function getWebhook(db: Kysely2<Database>, accountId: string, id: string): Promise<Webhook | null>;
|
|
1520
|
+
declare function getWebhookByName(db: Kysely2<Database>, accountId: string, name: string): Promise<Webhook | null>;
|
|
1451
1521
|
interface UpdateWebhookInput {
|
|
1452
1522
|
name?: string;
|
|
1453
1523
|
format?: WebhookFormat;
|
|
@@ -1457,16 +1527,21 @@ interface UpdateWebhookInput {
|
|
|
1457
1527
|
timeoutMs?: number;
|
|
1458
1528
|
concurrency?: number;
|
|
1459
1529
|
}
|
|
1460
|
-
declare function updateWebhook(db:
|
|
1461
|
-
|
|
1462
|
-
|
|
1530
|
+
declare function updateWebhook(db: Kysely2<Database>, accountId: string, id: string, patch: UpdateWebhookInput): Promise<Webhook | null>;
|
|
1531
|
+
/** Webhook status machine. Both moves are idempotent so a repeated pause or
|
|
1532
|
+
* resume call succeeds; the circuit breaker only trips an `active` row. */
|
|
1533
|
+
declare const webhookMachine: Machine<WebhookStatus>;
|
|
1534
|
+
/** Pause (always as the customer: `pause_reason = 'user'`, even over a circuit
|
|
1535
|
+
* pause) or resume. Either ends any circuit incident. */
|
|
1536
|
+
declare function toggleWebhookStatus(db: Kysely2<Database>, accountId: string, id: string, status: WebhookStatus): Promise<Webhook | null>;
|
|
1537
|
+
declare function deleteWebhook(db: Kysely2<Database>, accountId: string, id: string): Promise<boolean>;
|
|
1463
1538
|
interface RotateSecretResult {
|
|
1464
1539
|
webhook: Webhook;
|
|
1465
1540
|
signingSecret: string;
|
|
1466
1541
|
}
|
|
1467
|
-
declare function rotateWebhookSecret(db:
|
|
1542
|
+
declare function rotateWebhookSecret(db: Kysely2<Database>, accountId: string, id: string): Promise<RotateSecretResult | null>;
|
|
1468
1543
|
/** Decrypt a webhook's signing secret for HMAC signing at emit time. */
|
|
1469
1544
|
declare function getWebhookSigningSecret(webhook: Webhook): string;
|
|
1470
1545
|
/** Fire `webhooks:changed` notify so the emitter hot-reloads its cache. */
|
|
1471
|
-
declare function notifyWebhooksChanged(db:
|
|
1472
|
-
export { CreateWebhookInput, CreateWebhookResult, RotateSecretResult, UpdateWebhookInput, createWebhook, deleteWebhook, getWebhook, getWebhookByName, getWebhookSigningSecret, isWebhookId, listActiveChainWebhooks, listWebhooks, notifyWebhooksChanged, rotateWebhookSecret, toggleWebhookStatus, updateWebhook };
|
|
1546
|
+
declare function notifyWebhooksChanged(db: Kysely2<Database>, accountId: string): Promise<void>;
|
|
1547
|
+
export { CreateWebhookInput, CreateWebhookResult, REORG_ORPHANED_ERROR_PREFIX, RotateSecretResult, UpdateWebhookInput, createWebhook, deleteWebhook, getWebhook, getWebhookByName, getWebhookSigningSecret, isWebhookId, listActiveChainWebhooks, listWebhooks, notReorgOrphaned, notifyWebhooksChanged, rotateWebhookSecret, toggleWebhookStatus, updateWebhook, webhookMachine };
|
|
@@ -25,7 +25,9 @@ __export(exports_hmac, {
|
|
|
25
25
|
});
|
|
26
26
|
|
|
27
27
|
// src/db/queries/webhooks.ts
|
|
28
|
-
import {
|
|
28
|
+
import {
|
|
29
|
+
sql as sql2
|
|
30
|
+
} from "kysely";
|
|
29
31
|
|
|
30
32
|
// src/crypto/hmac.ts
|
|
31
33
|
import { createHmac, randomBytes } from "node:crypto";
|
|
@@ -240,6 +242,38 @@ function generateSecretsKey() {
|
|
|
240
242
|
return randomBytes2(32).toString("hex");
|
|
241
243
|
}
|
|
242
244
|
|
|
245
|
+
// src/db/transition.ts
|
|
246
|
+
import { sql } from "kysely";
|
|
247
|
+
function defineMachine(def) {
|
|
248
|
+
const canTransition = (from, to) => def.transitions[from]?.includes(to) ?? false;
|
|
249
|
+
return {
|
|
250
|
+
states: def.states,
|
|
251
|
+
canTransition,
|
|
252
|
+
assert(from, to) {
|
|
253
|
+
if (!canTransition(from, to)) {
|
|
254
|
+
throw new Error(`illegal transition ${from} -> ${to}`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
async function casTransition(db, t) {
|
|
260
|
+
const column = sql.id(t.column ?? "status");
|
|
261
|
+
const assignments = [sql`${column} = ${t.to}`];
|
|
262
|
+
if (t.stampUpdatedAt !== false)
|
|
263
|
+
assignments.push(sql`updated_at = now()`);
|
|
264
|
+
for (const [key, value] of Object.entries(t.set ?? {})) {
|
|
265
|
+
assignments.push(sql`${sql.id(key)} = ${value}`);
|
|
266
|
+
}
|
|
267
|
+
const returning = t.returning ? sql.join(t.returning.map((c) => sql.id(c))) : sql.raw("*");
|
|
268
|
+
const { rows } = await sql`
|
|
269
|
+
UPDATE ${sql.table(t.table)}
|
|
270
|
+
SET ${sql.join(assignments)}
|
|
271
|
+
WHERE ${sql.id(t.key ?? "id")} = ${t.id} AND ${column} = ANY(${sql.val([...t.from])})
|
|
272
|
+
RETURNING ${returning}
|
|
273
|
+
`.execute(db);
|
|
274
|
+
return rows[0] ?? null;
|
|
275
|
+
}
|
|
276
|
+
|
|
243
277
|
// src/db/queries/webhooks.ts
|
|
244
278
|
async function createWebhook(db, input) {
|
|
245
279
|
const signingSecret = generateSecret();
|
|
@@ -276,6 +310,13 @@ async function listActiveChainWebhooks(db) {
|
|
|
276
310
|
}
|
|
277
311
|
var WEBHOOK_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
278
312
|
var isWebhookId = (id) => WEBHOOK_ID_RE.test(id);
|
|
313
|
+
var REORG_ORPHANED_ERROR_PREFIX = "orphaned by reorg at ";
|
|
314
|
+
function notReorgOrphaned(eb) {
|
|
315
|
+
return eb.or([
|
|
316
|
+
eb("dead_reason", "is", null),
|
|
317
|
+
eb("dead_reason", "!=", "orphaned")
|
|
318
|
+
]);
|
|
319
|
+
}
|
|
279
320
|
async function getWebhook(db, accountId, id) {
|
|
280
321
|
if (!isWebhookId(id))
|
|
281
322
|
return null;
|
|
@@ -313,29 +354,33 @@ async function updateWebhook(db, accountId, id, patch) {
|
|
|
313
354
|
q = q.where("account_id", "=", accountId);
|
|
314
355
|
return await q.returningAll().executeTakeFirst() ?? null;
|
|
315
356
|
}
|
|
357
|
+
var webhookMachine = defineMachine({
|
|
358
|
+
states: ["active", "paused"],
|
|
359
|
+
transitions: { active: ["active", "paused"], paused: ["active", "paused"] }
|
|
360
|
+
});
|
|
316
361
|
async function toggleWebhookStatus(db, accountId, id, status) {
|
|
317
|
-
if (!
|
|
362
|
+
if (!await getWebhook(db, accountId, id))
|
|
318
363
|
return null;
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
364
|
+
return casTransition(db, {
|
|
365
|
+
table: "webhooks",
|
|
366
|
+
id,
|
|
367
|
+
from: webhookMachine.states,
|
|
368
|
+
to: status,
|
|
369
|
+
set: {
|
|
370
|
+
pause_reason: status === "paused" ? "user" : null,
|
|
323
371
|
circuit_failures: 0,
|
|
324
372
|
circuit_opened_at: null
|
|
325
|
-
}
|
|
326
|
-
})
|
|
327
|
-
if (isWebhookAccountScoped())
|
|
328
|
-
q = q.where("account_id", "=", accountId);
|
|
329
|
-
return await q.returningAll().executeTakeFirst() ?? null;
|
|
373
|
+
}
|
|
374
|
+
});
|
|
330
375
|
}
|
|
331
376
|
var WEBHOOK_DELETE_BATCH = 5000;
|
|
332
377
|
async function deleteWebhookChildren(db, webhookId) {
|
|
333
378
|
for (const table of ["webhook_deliveries", "webhook_outbox"]) {
|
|
334
379
|
for (;; ) {
|
|
335
|
-
const result = await
|
|
336
|
-
DELETE FROM ${
|
|
380
|
+
const result = await sql2`
|
|
381
|
+
DELETE FROM ${sql2.table(table)}
|
|
337
382
|
WHERE id IN (
|
|
338
|
-
SELECT id FROM ${
|
|
383
|
+
SELECT id FROM ${sql2.table(table)}
|
|
339
384
|
WHERE webhook_id = ${webhookId}
|
|
340
385
|
LIMIT ${WEBHOOK_DELETE_BATCH}
|
|
341
386
|
)
|
|
@@ -354,6 +399,13 @@ async function deleteWebhook(db, accountId, id) {
|
|
|
354
399
|
const row = await owned.executeTakeFirst();
|
|
355
400
|
if (!row)
|
|
356
401
|
return false;
|
|
402
|
+
await casTransition(db, {
|
|
403
|
+
table: "webhooks",
|
|
404
|
+
id,
|
|
405
|
+
from: ["active"],
|
|
406
|
+
to: "paused",
|
|
407
|
+
set: { pause_reason: "user" }
|
|
408
|
+
});
|
|
357
409
|
await deleteWebhookChildren(db, id);
|
|
358
410
|
let q = db.deleteFrom("webhooks").where("id", "=", id);
|
|
359
411
|
if (isWebhookAccountScoped())
|
|
@@ -380,9 +432,10 @@ function getWebhookSigningSecret(webhook) {
|
|
|
380
432
|
return decryptSecret(webhook.signing_secret_enc);
|
|
381
433
|
}
|
|
382
434
|
async function notifyWebhooksChanged(db, accountId) {
|
|
383
|
-
await
|
|
435
|
+
await sql2`SELECT pg_notify('webhooks:changed', ${accountId})`.execute(db);
|
|
384
436
|
}
|
|
385
437
|
export {
|
|
438
|
+
REORG_ORPHANED_ERROR_PREFIX,
|
|
386
439
|
createWebhook,
|
|
387
440
|
deleteWebhook,
|
|
388
441
|
getWebhook,
|
|
@@ -391,11 +444,13 @@ export {
|
|
|
391
444
|
isWebhookId,
|
|
392
445
|
listActiveChainWebhooks,
|
|
393
446
|
listWebhooks,
|
|
447
|
+
notReorgOrphaned,
|
|
394
448
|
notifyWebhooksChanged,
|
|
395
449
|
rotateWebhookSecret,
|
|
396
450
|
toggleWebhookStatus,
|
|
397
|
-
updateWebhook
|
|
451
|
+
updateWebhook,
|
|
452
|
+
webhookMachine
|
|
398
453
|
};
|
|
399
454
|
|
|
400
|
-
//# debugId=
|
|
455
|
+
//# debugId=21BA9528B28A972864756E2164756E21
|
|
401
456
|
//# sourceMappingURL=webhooks.js.map
|