@secondlayer/shared 15.3.4 → 15.4.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.
Files changed (60) hide show
  1. package/dist/src/archive/range-digest.d.ts +2 -0
  2. package/dist/src/archive/semantic-digest-builder.d.ts +2 -0
  3. package/dist/src/classify/index.js +16 -2
  4. package/dist/src/classify/index.js.map +3 -3
  5. package/dist/src/coverage/index.d.ts +2 -0
  6. package/dist/src/coverage/index.js +35 -1
  7. package/dist/src/coverage/index.js.map +3 -3
  8. package/dist/src/crypto/secondlayer-webhook.js +16 -2
  9. package/dist/src/crypto/secondlayer-webhook.js.map +3 -3
  10. package/dist/src/crypto/secrets.d.ts +8 -2
  11. package/dist/src/crypto/secrets.js +21 -7
  12. package/dist/src/crypto/secrets.js.map +3 -3
  13. package/dist/src/db/index.d.ts +10 -1
  14. package/dist/src/db/index.js +29 -7
  15. package/dist/src/db/index.js.map +5 -5
  16. package/dist/src/db/queries/chain-reorgs.d.ts +2 -0
  17. package/dist/src/db/queries/chain-reorgs.js +27 -7
  18. package/dist/src/db/queries/chain-reorgs.js.map +5 -5
  19. package/dist/src/db/queries/contracts.d.ts +2 -0
  20. package/dist/src/db/queries/contracts.js.map +2 -2
  21. package/dist/src/db/queries/instance.d.ts +28 -5
  22. package/dist/src/db/queries/instance.js +224 -14
  23. package/dist/src/db/queries/instance.js.map +6 -5
  24. package/dist/src/db/queries/integrity.d.ts +2 -0
  25. package/dist/src/db/queries/integrity.js +221 -14
  26. package/dist/src/db/queries/integrity.js.map +6 -5
  27. package/dist/src/db/queries/subgraph-gaps.d.ts +2 -0
  28. package/dist/src/db/queries/subgraph-operations.d.ts +2 -0
  29. package/dist/src/db/queries/subgraphs.d.ts +2 -0
  30. package/dist/src/db/queries/sync-scope.d.ts +2 -0
  31. package/dist/src/db/queries/webhook-replays.d.ts +2 -0
  32. package/dist/src/db/queries/webhook-replays.js +20 -7
  33. package/dist/src/db/queries/webhook-replays.js.map +3 -3
  34. package/dist/src/db/queries/webhooks.d.ts +2 -0
  35. package/dist/src/db/queries/webhooks.js +20 -7
  36. package/dist/src/db/queries/webhooks.js.map +3 -3
  37. package/dist/src/db/schema.d.ts +2 -0
  38. package/dist/src/db/schema.js.map +2 -2
  39. package/dist/src/email/index.js +16 -2
  40. package/dist/src/email/index.js.map +3 -3
  41. package/dist/src/env.d.ts +8 -1
  42. package/dist/src/env.js +18 -3
  43. package/dist/src/env.js.map +3 -3
  44. package/dist/src/index.d.ts +45 -1
  45. package/dist/src/index.js +68 -7
  46. package/dist/src/index.js.map +6 -6
  47. package/dist/src/insights/index.d.ts +2 -0
  48. package/dist/src/insights/index.js +16 -2
  49. package/dist/src/insights/index.js.map +3 -3
  50. package/dist/src/leader.js +915 -27
  51. package/dist/src/leader.js.map +13 -6
  52. package/dist/src/logger.js +16 -2
  53. package/dist/src/logger.js.map +3 -3
  54. package/dist/src/node/local-client.d.ts +2 -0
  55. package/dist/src/node/tx-summary.js +16 -2
  56. package/dist/src/node/tx-summary.js.map +3 -3
  57. package/dist/src/queue/listener.js +27 -7
  58. package/dist/src/queue/listener.js.map +5 -5
  59. package/migrations/0202_instances_secrets_key_canary.ts +36 -0
  60. package/package.json +2 -2
@@ -64,11 +64,25 @@ function getEnv() {
64
64
  } else if (result.data.NETWORK) {
65
65
  enabledNetworks = [result.data.NETWORK];
66
66
  } else {
67
- enabledNetworks = ["mainnet"];
67
+ const named = stacksNetwork();
68
+ enabledNetworks = named === "testnet" ? ["testnet"] : ["mainnet"];
68
69
  }
69
70
  cachedEnv = { ...result.data, enabledNetworks };
70
71
  return cachedEnv;
71
72
  }
73
+ var warnedNetworkFallback = false;
74
+ function stacksNetwork(env = process.env) {
75
+ if (env.STACKS_NETWORK)
76
+ return env.STACKS_NETWORK;
77
+ if (env.NETWORK) {
78
+ if (!warnedNetworkFallback) {
79
+ warnedNetworkFallback = true;
80
+ console.warn("NETWORK is deprecated: set STACKS_NETWORK instead");
81
+ }
82
+ return env.NETWORK;
83
+ }
84
+ return "mainnet";
85
+ }
72
86
  function isProductionEnv() {
73
87
  return process.env["NODE_ENV"] === "production";
74
88
  }
@@ -202,5 +216,5 @@ export {
202
216
  verifySecondlayerSignatureValues
203
217
  };
204
218
 
205
- //# debugId=991B6B4B05E2159564756E2164756E21
219
+ //# debugId=20F9CC32F7CDC2CD64756E2164756E21
206
220
  //# sourceMappingURL=secondlayer-webhook.js.map
@@ -2,11 +2,11 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/env.ts", "../src/crypto/ed25519.ts", "../src/crypto/secondlayer-webhook.ts"],
4
4
  "sourcesContent": [
5
- "import { z } from \"zod\";\n\n// Parse comma-separated networks\nconst networksSchema = z.string().transform((val) => {\n\tconst networks = val\n\t\t.split(\",\")\n\t\t.map((n) => n.trim())\n\t\t.filter(Boolean);\n\tconst valid = [\"mainnet\", \"testnet\"];\n\tfor (const n of networks) {\n\t\tif (!valid.includes(n)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid network: ${n}. Must be one of: ${valid.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn networks as (\"mainnet\" | \"testnet\")[];\n});\n\ninterface EnvSchemaOutput {\n\tDATABASE_URL?: string;\n\t/**\n\t * Shared indexer DB (blocks/txs/events). Falls back to DATABASE_URL.\n\t * Set this alongside TARGET_DATABASE_URL to enable dual-DB mode.\n\t */\n\tSOURCE_DATABASE_URL?: string;\n\t/**\n\t * Tenant DB (subgraph schemas + subgraphs table). Falls back to DATABASE_URL.\n\t * Set this alongside SOURCE_DATABASE_URL to enable dual-DB mode.\n\t */\n\tTARGET_DATABASE_URL?: string;\n\tNETWORK?: \"mainnet\" | \"testnet\";\n\tNETWORKS?: (\"mainnet\" | \"testnet\")[];\n\tLOG_LEVEL: \"debug\" | \"info\" | \"warn\" | \"error\";\n\tNODE_ENV: \"development\" | \"production\" | \"test\";\n}\n\n// Cast needed: z.preprocess / z.default create different _input vs _output types\n// that z.ZodType<T> can't represent without explicit input type param\nconst envSchema: z.ZodType<EnvSchemaOutput> = z.object({\n\tDATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tSOURCE_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tTARGET_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tNETWORK: z.enum([\"mainnet\", \"testnet\"]).optional(),\n\tNETWORKS: networksSchema.optional(),\n\tLOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n\tNODE_ENV: z\n\t\t.enum([\"development\", \"production\", \"test\"])\n\t\t.default(\"development\"),\n}) as unknown as z.ZodType<EnvSchemaOutput>;\n\nexport type Env = EnvSchemaOutput & {\n\tenabledNetworks: (\"mainnet\" | \"testnet\")[];\n};\n\nlet cachedEnv: Env | null = null;\n\nexport function getEnv(): Env {\n\tif (cachedEnv) {\n\t\treturn cachedEnv;\n\t}\n\n\tconst result = envSchema.safeParse(process.env);\n\n\tif (!result.success) {\n\t\tconsole.error(\"❌ Invalid environment configuration:\");\n\t\tconsole.error(z.treeifyError(result.error));\n\t\tthrow new Error(\"Invalid environment configuration\");\n\t}\n\n\t// Compute enabled networks from NETWORKS or NETWORK\n\tlet enabledNetworks: (\"mainnet\" | \"testnet\")[];\n\tif (result.data.NETWORKS && result.data.NETWORKS.length > 0) {\n\t\tenabledNetworks = result.data.NETWORKS;\n\t} else if (result.data.NETWORK) {\n\t\tenabledNetworks = [result.data.NETWORK];\n\t} else {\n\t\tenabledNetworks = [\"mainnet\"]; // Default\n\t}\n\n\tcachedEnv = { ...result.data, enabledNetworks };\n\treturn cachedEnv;\n}\n\n/**\n * True when `NODE_ENV=production`, read at RUNTIME — the single source of truth\n * for prod-vs-dev branching in this package.\n *\n * Why a helper instead of inlining `process.env.NODE_ENV === \"production\"`:\n * bunup/esbuild constant-folds the dot-access `process.env.NODE_ENV` to its\n * BUILD-time value. `@secondlayer/shared` is consumed by other services as its\n * built `dist`, so an inlined check freezes to a literal in the shipped bundle\n * (e.g. `const isProd = false`) and silently ignores the container's real\n * NODE_ENV. The bracket access below is NOT folded, so it stays a runtime read.\n * Route every prod check through here so the footgun lives in exactly one place.\n */\nexport function isProductionEnv(): boolean {\n\t// biome-ignore lint/complexity/useLiteralKeys: bracket access is deliberate — dot-access gets constant-folded by the bundler, freezing this to a build-time literal in the shipped dist.\n\treturn process.env[\"NODE_ENV\"] === \"production\";\n}\n\ntype EnvMap = NodeJS.ProcessEnv;\n\n/**\n * PoX-4 stacking decoder is ON by default — `/v1/index/stacking` is part of the\n * public surface, so the decoder that fills `pox4_calls` runs unless explicitly\n * opted out with `POX4_DECODER_ENABLED=false` (mirrors the sBTC decoder policy).\n */\nexport function isPox4DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX4_DECODER_ENABLED !== \"false\";\n}\n\n/**\n * PoX-5 print-event decoder is ON by default (mirrors pox-4/sBTC policy).\n * No activation gating needed: pox-5 events cannot exist before the Epoch 4.0\n * hard fork (Bitcoin block 960,230), so pre-activation the decoder idles at\n * tip. Opt out with `POX5_DECODER_ENABLED=false`.\n */\nexport function isPox5DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX5_DECODER_ENABLED !== \"false\";\n}\n\n/** Default ON. Opt out with `SBTC_DECODER_ENABLED=false`. */\nexport function isSbtcDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.SBTC_DECODER_ENABLED !== \"false\";\n}\n\n/** Default OFF. Opt in with `BNS_DECODER_ENABLED=true`. */\nexport function isBnsDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.BNS_DECODER_ENABLED === \"true\";\n}\n\n// Export for testing\nexport { envSchema };\n",
5
+ "import { z } from \"zod\";\n\n// Parse comma-separated networks\nconst networksSchema = z.string().transform((val) => {\n\tconst networks = val\n\t\t.split(\",\")\n\t\t.map((n) => n.trim())\n\t\t.filter(Boolean);\n\tconst valid = [\"mainnet\", \"testnet\"];\n\tfor (const n of networks) {\n\t\tif (!valid.includes(n)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid network: ${n}. Must be one of: ${valid.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn networks as (\"mainnet\" | \"testnet\")[];\n});\n\ninterface EnvSchemaOutput {\n\tDATABASE_URL?: string;\n\t/**\n\t * Shared indexer DB (blocks/txs/events). Falls back to DATABASE_URL.\n\t * Set this alongside TARGET_DATABASE_URL to enable dual-DB mode.\n\t */\n\tSOURCE_DATABASE_URL?: string;\n\t/**\n\t * Tenant DB (subgraph schemas + subgraphs table). Falls back to DATABASE_URL.\n\t * Set this alongside SOURCE_DATABASE_URL to enable dual-DB mode.\n\t */\n\tTARGET_DATABASE_URL?: string;\n\tNETWORK?: \"mainnet\" | \"testnet\";\n\tNETWORKS?: (\"mainnet\" | \"testnet\")[];\n\tLOG_LEVEL: \"debug\" | \"info\" | \"warn\" | \"error\";\n\tNODE_ENV: \"development\" | \"production\" | \"test\";\n}\n\n// Cast needed: z.preprocess / z.default create different _input vs _output types\n// that z.ZodType<T> can't represent without explicit input type param\nconst envSchema: z.ZodType<EnvSchemaOutput> = z.object({\n\tDATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tSOURCE_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tTARGET_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tNETWORK: z.enum([\"mainnet\", \"testnet\"]).optional(),\n\tNETWORKS: networksSchema.optional(),\n\tLOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n\tNODE_ENV: z\n\t\t.enum([\"development\", \"production\", \"test\"])\n\t\t.default(\"development\"),\n}) as unknown as z.ZodType<EnvSchemaOutput>;\n\nexport type Env = EnvSchemaOutput & {\n\tenabledNetworks: (\"mainnet\" | \"testnet\")[];\n};\n\nlet cachedEnv: Env | null = null;\n\nexport function getEnv(): Env {\n\tif (cachedEnv) {\n\t\treturn cachedEnv;\n\t}\n\n\tconst result = envSchema.safeParse(process.env);\n\n\tif (!result.success) {\n\t\tconsole.error(\"❌ Invalid environment configuration:\");\n\t\tconsole.error(z.treeifyError(result.error));\n\t\tthrow new Error(\"Invalid environment configuration\");\n\t}\n\n\t// Compute enabled networks from NETWORKS or NETWORK\n\tlet enabledNetworks: (\"mainnet\" | \"testnet\")[];\n\tif (result.data.NETWORKS && result.data.NETWORKS.length > 0) {\n\t\tenabledNetworks = result.data.NETWORKS;\n\t} else if (result.data.NETWORK) {\n\t\tenabledNetworks = [result.data.NETWORK];\n\t} else {\n\t\tconst named = stacksNetwork();\n\t\tenabledNetworks = named === \"testnet\" ? [\"testnet\"] : [\"mainnet\"];\n\t}\n\n\tcachedEnv = { ...result.data, enabledNetworks };\n\treturn cachedEnv;\n}\n\nlet warnedNetworkFallback = false;\n\n/**\n * The Stacks network this process serves, and the only place that decides it:\n * `STACKS_NETWORK`, else the deprecated `NETWORK` (warned once so a deployment\n * that only sets it is not silently re-keyed), else mainnet. Not validated;\n * `instanceNetworkFromEnv` is the strict form.\n */\nexport function stacksNetwork(env: NodeJS.ProcessEnv = process.env): string {\n\tif (env.STACKS_NETWORK) return env.STACKS_NETWORK;\n\tif (env.NETWORK) {\n\t\tif (!warnedNetworkFallback) {\n\t\t\twarnedNetworkFallback = true;\n\t\t\tconsole.warn(\"NETWORK is deprecated: set STACKS_NETWORK instead\");\n\t\t}\n\t\treturn env.NETWORK;\n\t}\n\treturn \"mainnet\";\n}\n\n/**\n * True when `NODE_ENV=production`, read at RUNTIME — the single source of truth\n * for prod-vs-dev branching in this package.\n *\n * Why a helper instead of inlining `process.env.NODE_ENV === \"production\"`:\n * bunup/esbuild constant-folds the dot-access `process.env.NODE_ENV` to its\n * BUILD-time value. `@secondlayer/shared` is consumed by other services as its\n * built `dist`, so an inlined check freezes to a literal in the shipped bundle\n * (e.g. `const isProd = false`) and silently ignores the container's real\n * NODE_ENV. The bracket access below is NOT folded, so it stays a runtime read.\n * Route every prod check through here so the footgun lives in exactly one place.\n */\nexport function isProductionEnv(): boolean {\n\t// biome-ignore lint/complexity/useLiteralKeys: bracket access is deliberate — dot-access gets constant-folded by the bundler, freezing this to a build-time literal in the shipped dist.\n\treturn process.env[\"NODE_ENV\"] === \"production\";\n}\n\ntype EnvMap = NodeJS.ProcessEnv;\n\n/**\n * PoX-4 stacking decoder is ON by default — `/v1/index/stacking` is part of the\n * public surface, so the decoder that fills `pox4_calls` runs unless explicitly\n * opted out with `POX4_DECODER_ENABLED=false` (mirrors the sBTC decoder policy).\n */\nexport function isPox4DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX4_DECODER_ENABLED !== \"false\";\n}\n\n/**\n * PoX-5 print-event decoder is ON by default (mirrors pox-4/sBTC policy).\n * No activation gating needed: pox-5 events cannot exist before the Epoch 4.0\n * hard fork (Bitcoin block 960,230), so pre-activation the decoder idles at\n * tip. Opt out with `POX5_DECODER_ENABLED=false`.\n */\nexport function isPox5DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX5_DECODER_ENABLED !== \"false\";\n}\n\n/** Default ON. Opt out with `SBTC_DECODER_ENABLED=false`. */\nexport function isSbtcDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.SBTC_DECODER_ENABLED !== \"false\";\n}\n\n/** Default OFF. Opt in with `BNS_DECODER_ENABLED=true`. */\nexport function isBnsDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.BNS_DECODER_ENABLED === \"true\";\n}\n\n// Export for testing\nexport { envSchema };\n",
6
6
  "import {\n\ttype KeyObject,\n\tcreateHash,\n\tcreatePrivateKey,\n\tcreatePublicKey,\n\tgenerateKeyPairSync,\n\tsign as nodeSign,\n\tverify as nodeVerify,\n} from \"node:crypto\";\n\n/**\n * Asymmetric ed25519 signing for Streams response proofs.\n *\n * Asymmetric (not HMAC) so the proof is real: only the server holds the private\n * key, and any consumer verifies with the published public key — no shared\n * secret to leak. ed25519 uses node's `sign`/`verify` with a `null` algorithm.\n * Keys are PEM (PKCS8 private / SPKI public) for env transport; load once and\n * reuse the KeyObject on hot paths.\n */\n\nexport function generateEd25519KeyPair(): {\n\tprivateKeyPem: string;\n\tpublicKeyPem: string;\n} {\n\tconst { privateKey, publicKey } = generateKeyPairSync(\"ed25519\");\n\treturn {\n\t\tprivateKeyPem: privateKey\n\t\t\t.export({ format: \"pem\", type: \"pkcs8\" })\n\t\t\t.toString(),\n\t\tpublicKeyPem: publicKey.export({ format: \"pem\", type: \"spki\" }).toString(),\n\t};\n}\n\nexport function loadEd25519PrivateKey(pem: string): KeyObject {\n\treturn createPrivateKey(pem);\n}\n\nexport function loadEd25519PublicKey(pem: string): KeyObject {\n\treturn createPublicKey(pem);\n}\n\nexport function publicKeyPemFromPrivate(privateKeyPem: string): string {\n\treturn createPublicKey(createPrivateKey(privateKeyPem))\n\t\t.export({ format: \"pem\", type: \"spki\" })\n\t\t.toString();\n}\n\n/** Stable short id for a public key (rotation hint via X-Signature-KeyId). */\nexport function ed25519KeyId(publicKeyPem: string): string {\n\tconst der = createPublicKey(publicKeyPem).export({\n\t\tformat: \"der\",\n\t\ttype: \"spki\",\n\t});\n\treturn createHash(\"sha256\").update(der).digest(\"base64url\").slice(0, 16);\n}\n\nexport function signEd25519(payload: string, privateKey: KeyObject): string {\n\treturn nodeSign(null, Buffer.from(payload, \"utf8\"), privateKey).toString(\n\t\t\"base64\",\n\t);\n}\n\nexport function verifyEd25519(\n\tpayload: string,\n\tsignatureBase64: string,\n\tpublicKey: KeyObject,\n): boolean {\n\ttry {\n\t\treturn nodeVerify(\n\t\t\tnull,\n\t\t\tBuffer.from(payload, \"utf8\"),\n\t\t\tpublicKey,\n\t\t\tBuffer.from(signatureBase64, \"base64\"),\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n",
7
7
  "import { isProductionEnv } from \"../env.ts\";\nimport {\n\ted25519KeyId,\n\tloadEd25519PrivateKey,\n\tloadEd25519PublicKey,\n\tpublicKeyPemFromPrivate,\n\tsignEd25519,\n\tverifyEd25519,\n} from \"./ed25519.ts\";\n\n/**\n * Universal Secondlayer webhook authenticity — an ed25519 signature attached to\n * EVERY delivery regardless of body format.\n *\n * Only the `standard-webhooks` format carries an HMAC; `raw`/`cloudevents`/etc.\n * carried no Secondlayer proof, so a receiver had no way to know a payload came\n * from us. This signs each delivery with a single platform ed25519 key so any\n * receiver verifies with the published public key — no per-webhook secret,\n * and the body shape stays format-specific.\n *\n * Header names are lowercase to match the format builders' header maps (HTTP\n * header names are case-insensitive on the wire).\n */\nexport const WEBHOOK_ID_HEADER = \"webhook-id\";\nexport const SECONDLAYER_SIGNATURE_HEADER = \"x-secondlayer-signature\";\nexport const SECONDLAYER_KEY_ID_HEADER = \"x-secondlayer-signature-keyid\";\n\nexport type SecondlayerWebhookSigner = {\n\tkeyId: string;\n\tpublicKeyPem: string;\n\tsign(payload: string): string;\n};\n\nlet cached: SecondlayerWebhookSigner | null | undefined;\n\nfunction signingKeyFromEnv(): string | undefined {\n\t// A dedicated webhook key if provided, else the platform Streams key — both\n\t// are the same ed25519 \"single platform identity\", so reusing it keeps key\n\t// distribution to one published public key.\n\treturn (\n\t\tprocess.env.SECONDLAYER_WEBHOOK_SIGNING_PRIVATE_KEY ||\n\t\tprocess.env.STREAMS_SIGNING_PRIVATE_KEY ||\n\t\tundefined\n\t);\n}\n\n/**\n * Memoized webhook signer, or null when no key is configured (signing is then a\n * no-op, so the universal header is safe to ship before a key is provisioned).\n */\nexport function getSecondlayerWebhookSigner(): SecondlayerWebhookSigner | null {\n\tif (cached !== undefined) return cached;\n\tconst raw = signingKeyFromEnv();\n\tif (!raw) {\n\t\tcached = null;\n\t\treturn null;\n\t}\n\t// Env transport often escapes newlines; restore real PEM line breaks.\n\tconst pem = raw.includes(\"\\\\n\") ? raw.replace(/\\\\n/g, \"\\n\") : raw;\n\tconst privateKey = loadEd25519PrivateKey(pem);\n\tconst publicKeyPem = publicKeyPemFromPrivate(pem);\n\tcached = {\n\t\tkeyId: ed25519KeyId(publicKeyPem),\n\t\tpublicKeyPem,\n\t\tsign: (payload) => signEd25519(payload, privateKey),\n\t};\n\treturn cached;\n}\n\n/** Reset the memoized signer. Tests only. */\nexport function resetSecondlayerWebhookSignerForTest(): void {\n\tcached = undefined;\n}\n\n/**\n * Boot-time guard for any service whose job is to DELIVER signed webhooks (the\n * webhook-processor). We market every delivery as carrying a verifiable\n * ed25519 signature; if no signing key is configured the signer is a silent\n * no-op and deliveries ship UNSIGNED. That's worse than a missing feature — a\n * partner's verify step fails on data we told them was signed.\n *\n * Unlike `assertDbSplit` (fail-soft: only ever logs), this is fail-HARD in prod:\n * refuse to boot so the misconfig surfaces as a crash-loop instead of unsigned\n * traffic. Keep the throw — don't \"soften\" it back to a warning. Set\n * `ALLOW_UNSIGNED_WEBHOOKS=true` to opt out (self-host / intentional unsigned),\n * which logs the posture loudly in every env so it's never silent.\n */\nexport function assertWebhookSigningConfigured(): void {\n\tif (getSecondlayerWebhookSigner()) return;\n\n\tconst optedOut = process.env.ALLOW_UNSIGNED_WEBHOOKS === \"true\";\n\t// isProductionEnv() reads NODE_ENV at runtime; do NOT inline a\n\t// `process.env.NODE_ENV` check — the bundler constant-folds it and the prod\n\t// throw would silently die in the shipped dist. See env.ts for the why.\n\tconst isProd = isProductionEnv();\n\tconst msg =\n\t\t\"No webhook signing key (SECONDLAYER_WEBHOOK_SIGNING_PRIVATE_KEY / STREAMS_SIGNING_PRIVATE_KEY) — deliveries would ship UNSIGNED while we market signed webhooks\";\n\n\tif (optedOut) {\n\t\tconsole.warn(`⚠️ ${msg}; continuing because ALLOW_UNSIGNED_WEBHOOKS=true`);\n\t\treturn;\n\t}\n\tif (isProd) {\n\t\tthrow new Error(\n\t\t\t`${msg}. Refusing to boot. Set the signing key, or ALLOW_UNSIGNED_WEBHOOKS=true to override.`,\n\t\t);\n\t}\n\tconsole.warn(`⚠️ ${msg} (non-prod: continuing)`);\n}\n\n/**\n * The exact bytes the signature covers: `${webhookId}.${body}`. Binding the id\n * into the signed content stops a captured body from being replayed under a\n * different delivery id.\n */\nfunction signedContent(webhookId: string, body: string): string {\n\treturn `${webhookId}.${body}`;\n}\n\n/**\n * Build the universal authenticity headers for a delivery. Returns null when no\n * signing key is configured (caller leaves the delivery unsigned).\n */\nexport function signSecondlayerWebhook(\n\twebhookId: string,\n\tbody: string,\n): Record<string, string> | null {\n\tconst signer = getSecondlayerWebhookSigner();\n\tif (!signer) return null;\n\treturn {\n\t\t[WEBHOOK_ID_HEADER]: webhookId,\n\t\t[SECONDLAYER_SIGNATURE_HEADER]: signer.sign(signedContent(webhookId, body)),\n\t\t[SECONDLAYER_KEY_ID_HEADER]: signer.keyId,\n\t};\n}\n\n/**\n * Verify a delivery's ed25519 signature over `${webhookId}.${rawBody}` against\n * the published public key. Low-level (raw values); receivers use the SDK's\n * `verifySecondlayerSignature`, which extracts the headers ergonomically.\n */\nexport function verifySecondlayerSignatureValues(\n\trawBody: string,\n\twebhookId: string | undefined,\n\tsignatureBase64: string | undefined,\n\tpublicKeyPem: string,\n): boolean {\n\tif (!webhookId || !signatureBase64) return false;\n\tconst publicKey = loadEd25519PublicKey(publicKeyPem);\n\treturn verifyEd25519(\n\t\tsignedContent(webhookId, rawBody),\n\t\tsignatureBase64,\n\t\tpublicKey,\n\t);\n}\n"
8
8
  ],
9
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAGA,IAAM,iBAAiB,EAAE,OAAO,EAAE,UAAU,CAAC,QAAQ;AAAA,EACpD,MAAM,WAAW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WAAmB,MAAsB;AAAA,EAC/D,OAAO,GAAG,aAAa;AAAA;AAOjB,SAAS,sBAAsB,CACrC,WACA,MACgC;AAAA,EAChC,MAAM,SAAS,4BAA4B;AAAA,EAC3C,IAAI,CAAC;AAAA,IAAQ,OAAO;AAAA,EACpB,OAAO;AAAA,KACL,oBAAoB;AAAA,KACpB,+BAA+B,OAAO,KAAK,cAAc,WAAW,IAAI,CAAC;AAAA,KACzE,4BAA4B,OAAO;AAAA,EACrC;AAAA;AAQM,SAAS,gCAAgC,CAC/C,SACA,WACA,iBACA,cACU;AAAA,EACV,IAAI,CAAC,aAAa,CAAC;AAAA,IAAiB,OAAO;AAAA,EAC3C,MAAM,YAAY,qBAAqB,YAAY;AAAA,EACnD,OAAO,cACN,cAAc,WAAW,OAAO,GAChC,iBACA,SACD;AAAA;",
10
+ "debugId": "20F9CC32F7CDC2CD64756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -1,14 +1,20 @@
1
1
  /**
2
2
  * Non-throwing check for whether a secrets key is currently resolvable —
3
3
  * same resolution order as {@link loadKey} (env var, then the OSS
4
- * `.env.local` fallback), but never bootstraps a new key (that would
4
+ * key file), but never bootstraps a new key (that would
5
5
  * generate+persist a key as a side effect of a mere existence check), never
6
6
  * throws, and never returns or logs the key itself. Used by callers that
7
7
  * need to fail loud on a missing key BEFORE attempting a decrypt (f072).
8
8
  */
9
9
  declare function secretsKeyAvailable(): boolean;
10
+ /**
11
+ * The secrets key as hex, resolved the way encrypt/decrypt resolve it (and
12
+ * bootstrapped the same way in OSS mode). Boot calls this once so every module
13
+ * it spawns inherits the one key through the environment.
14
+ */
15
+ declare function resolveSecretsKeyHex(): string;
10
16
  declare function encryptSecret(plaintext: string): Buffer;
11
17
  declare function decryptSecret(envelope: Buffer): string;
12
18
  /** Generate a fresh 32-byte hex key suitable for `SECONDLAYER_SECRETS_KEY`. */
13
19
  declare function generateSecretsKey(): string;
14
- export { decryptSecret, encryptSecret, generateSecretsKey, secretsKeyAvailable };
20
+ export { decryptSecret, encryptSecret, generateSecretsKey, resolveSecretsKeyHex, secretsKeyAvailable };
@@ -4,11 +4,12 @@ import {
4
4
  appendFileSync,
5
5
  closeSync,
6
6
  existsSync,
7
+ mkdirSync,
7
8
  openSync,
8
9
  readFileSync,
9
10
  unlinkSync
10
11
  } from "node:fs";
11
- import { resolve } from "node:path";
12
+ import { dirname, resolve } from "node:path";
12
13
 
13
14
  // src/mode.ts
14
15
  var VALID_MODES = [
@@ -55,6 +56,13 @@ function isWebhookAccountScoped() {
55
56
  var KEY_ENV = "SECONDLAYER_SECRETS_KEY";
56
57
  var IV_LEN = 12;
57
58
  var TAG_LEN = 16;
59
+ function keyFilePath() {
60
+ const dataDir = process.env.DATA_DIR?.trim();
61
+ return dataDir ? resolve(dataDir, "secrets.env") : resolve(process.cwd(), ".env.local");
62
+ }
63
+ function legacyKeyFilePath() {
64
+ return resolve(process.cwd(), ".env.local");
65
+ }
58
66
  function readExistingKey(envPath) {
59
67
  if (!existsSync(envPath))
60
68
  return null;
@@ -65,12 +73,13 @@ function readExistingKey(envPath) {
65
73
  var STALE_LOCK_MS = 1e4;
66
74
  var POLL_MS = 25;
67
75
  function bootstrapOssKey() {
68
- const envPath = resolve(process.cwd(), ".env.local");
76
+ const envPath = keyFilePath();
69
77
  const existing = readExistingKey(envPath);
70
78
  if (existing) {
71
79
  process.env[KEY_ENV] = existing;
72
80
  return existing;
73
81
  }
82
+ mkdirSync(dirname(envPath), { recursive: true });
74
83
  const lockPath = `${envPath}.secret-bootstrap.lock`;
75
84
  let lockFd = null;
76
85
  try {
@@ -96,13 +105,15 @@ function bootstrapOssKey() {
96
105
  return bootstrapOssKey();
97
106
  }
98
107
  try {
99
- const hex = randomBytes(32).toString("hex");
108
+ const legacy = legacyKeyFilePath();
109
+ const carried = legacy === envPath ? null : readExistingKey(legacy);
110
+ const hex = carried ?? randomBytes(32).toString("hex");
100
111
  const line = `${existsSync(envPath) ? `
101
112
  ` : ""}${KEY_ENV}=${hex}
102
113
  `;
103
114
  appendFileSync(envPath, line, { mode: 384 });
104
115
  process.env[KEY_ENV] = hex;
105
- console.log(`[secondlayer] generated ${KEY_ENV}; saved to ${envPath} (mode 0600)`);
116
+ console.log(`[secondlayer] ${carried ? `moved ${KEY_ENV} from ${legacy} to` : `generated ${KEY_ENV}; saved to`} ${envPath} (mode 0600)`);
106
117
  return hex;
107
118
  } finally {
108
119
  closeSync(lockFd);
@@ -136,11 +147,13 @@ function secretsKeyAvailable() {
136
147
  if (process.env[KEY_ENV])
137
148
  return true;
138
149
  if (getInstanceMode() === "oss") {
139
- const envPath = resolve(process.cwd(), ".env.local");
140
- return readExistingKey(envPath) !== null;
150
+ return readExistingKey(keyFilePath()) !== null || readExistingKey(legacyKeyFilePath()) !== null;
141
151
  }
142
152
  return false;
143
153
  }
154
+ function resolveSecretsKeyHex() {
155
+ return getKey().toString("hex");
156
+ }
144
157
  function encryptSecret(plaintext) {
145
158
  const key = getKey();
146
159
  const iv = randomBytes(IV_LEN);
@@ -168,8 +181,9 @@ export {
168
181
  decryptSecret,
169
182
  encryptSecret,
170
183
  generateSecretsKey,
184
+ resolveSecretsKeyHex,
171
185
  secretsKeyAvailable
172
186
  };
173
187
 
174
- //# debugId=51EEBBA19639DF0764756E2164756E21
188
+ //# debugId=B141B5A0B19A949D64756E2164756E21
175
189
  //# sourceMappingURL=secrets.js.map
@@ -2,10 +2,10 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/crypto/secrets.ts", "../src/mode.ts"],
4
4
  "sourcesContent": [
5
- "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",
5
+ "import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\nimport {\n\tappendFileSync,\n\tcloseSync,\n\texistsSync,\n\tmkdirSync,\n\topenSync,\n\treadFileSync,\n\tunlinkSync,\n} from \"node:fs\";\nimport { dirname, 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 `secrets.env` under `DATA_DIR` (a volume, so it survives a container\n * recreate) so subsequent restarts pick it up without user intervention.\n * With no `DATA_DIR` (a bare `bun run`) it goes to `.env.local` in the\n * current working directory. A key already in `.env.local` is carried into\n * `DATA_DIR` on first boot. Dedicated/platform modes throw — those runtimes\n * 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\n/** Where an OSS instance keeps its generated key: the `DATA_DIR` volume when\n * there is one, else `.env.local` beside the process. */\nfunction keyFilePath(): string {\n\tconst dataDir = process.env.DATA_DIR?.trim();\n\treturn dataDir\n\t\t? resolve(dataDir, \"secrets.env\")\n\t\t: resolve(process.cwd(), \".env.local\");\n}\n\n/** Where earlier versions wrote the key, before `DATA_DIR` held it. */\nfunction legacyKeyFilePath(): string {\n\treturn resolve(process.cwd(), \".env.local\");\n}\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 = keyFilePath();\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\tmkdirSync(dirname(envPath), { recursive: true });\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\t// A key an earlier version wrote beside the process moves into the volume\n\t\t// instead of being replaced: a new key would orphan every secret sealed\n\t\t// under it.\n\t\tconst legacy = legacyKeyFilePath();\n\t\tconst carried = legacy === envPath ? null : readExistingKey(legacy);\n\t\tconst hex = carried ?? 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] ${carried ? `moved ${KEY_ENV} from ${legacy} to` : `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 * key file), 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\treturn (\n\t\t\treadExistingKey(keyFilePath()) !== null ||\n\t\t\treadExistingKey(legacyKeyFilePath()) !== null\n\t\t);\n\t}\n\treturn false;\n}\n\n/**\n * The secrets key as hex, resolved the way encrypt/decrypt resolve it (and\n * bootstrapped the same way in OSS mode). Boot calls this once so every module\n * it spawns inherits the one key through the environment.\n */\nexport function resolveSecretsKeyHex(): string {\n\treturn getKey().toString(\"hex\");\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",
6
6
  "/**\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"
7
7
  ],
8
- "mappings": ";AAAA;AACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA;;;ACUA,IAAM,cAA+C;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AACD;AAEA,SAAS,YAAY,GAAyB;AAAA,EAC7C,MAAM,MAAM,QAAQ,IAAI,eAAe,KAAK,EAAE,YAAY;AAAA,EAC1D,IAAI,OAAQ,YAAkC,SAAS,GAAG,GAAG;AAAA,IAC5D,OAAO;AAAA,EACR;AAAA,EACA,OAAO;AAAA;AAUD,SAAS,eAAe,GAAiB;AAAA,EAC/C,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;AAAA,EAE3C;AAAA,EACA,OAAO;AAAA;AAQD,SAAS,oBAAoB,GAAW;AAAA,EAC9C,OAAO,OAAO,EAAE,SAAS,KAAK;AAAA;AAGxB,SAAS,aAAa,CAAC,WAA2B;AAAA,EACxD,MAAM,MAAM,OAAO;AAAA,EACnB,MAAM,KAAK,YAAY,MAAM;AAAA,EAC7B,MAAM,SAAS,eAAe,eAAe,KAAK,EAAE;AAAA,EACpD,MAAM,aAAa,OAAO,OAAO;AAAA,IAChC,OAAO,OAAO,WAAW,MAAM;AAAA,IAC/B,OAAO,MAAM;AAAA,EACd,CAAC;AAAA,EACD,MAAM,MAAM,OAAO,WAAW;AAAA,EAC9B,OAAO,OAAO,OAAO,CAAC,IAAI,KAAK,UAAU,CAAC;AAAA;AAGpC,SAAS,aAAa,CAAC,UAA0B;AAAA,EACvD,MAAM,MAAM,OAAO;AAAA,EACnB,MAAM,KAAK,SAAS,SAAS,GAAG,MAAM;AAAA,EACtC,MAAM,MAAM,SAAS,SAAS,QAAQ,SAAS,OAAO;AAAA,EACtD,MAAM,aAAa,SAAS,SAAS,SAAS,OAAO;AAAA,EACrD,MAAM,WAAW,iBAAiB,eAAe,KAAK,EAAE;AAAA,EACxD,SAAS,WAAW,GAAG;AAAA,EACvB,OAAO,SAAS,OAAO,UAAU,EAAE,SAAS,MAAM,IAAI,SAAS,MAAM,MAAM;AAAA;AAIrE,SAAS,kBAAkB,GAAW;AAAA,EAC5C,OAAO,YAAY,EAAE,EAAE,SAAS,KAAK;AAAA;",
9
+ "debugId": "B141B5A0B19A949D64756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -322,6 +322,8 @@ interface ApiKeysTable {
322
322
  interface InstancesTable {
323
323
  id: Generated<string>;
324
324
  network: string;
325
+ /** `SECONDLAYER_SECRETS_KEY` sealed under itself; see `ensureSecretsKeyCanary`. */
326
+ secrets_key_canary: ColumnType<string | null, string | null | undefined, string | null>;
325
327
  created_at: Generated<Date>;
326
328
  }
327
329
  interface AccountsTable {
@@ -2567,6 +2569,13 @@ declare function applicationDatabaseUrl(): string;
2567
2569
  declare function resolveSourceUrl(): string;
2568
2570
  /** Canonical target-DB URL — see {@link resolveSourceUrl}. */
2569
2571
  declare function resolveTargetUrl(): string;
2572
+ /** The source URL the environment actually names, or undefined: unlike
2573
+ * {@link resolveSourceUrl} it never falls back to the dev default, so a tool
2574
+ * that writes (migrate) can refuse instead of touching a database nobody
2575
+ * configured. */
2576
+ declare function configuredSourceUrl(): string | undefined;
2577
+ /** See {@link configuredSourceUrl}. */
2578
+ declare function configuredTargetUrl(): string | undefined;
2570
2579
  /** Host[:port]/dbname for a connection URL — credentials stripped. Exported
2571
2580
  * so anything logging which database it connected to (a LISTEN channel's
2572
2581
  * startup log, an ops health check) can describe it without ever printing a
@@ -2643,4 +2652,4 @@ declare function closeDb(): Promise<void>;
2643
2652
  * actual work is done.
2644
2653
  */
2645
2654
  declare function closeDbOrTimeout(timeoutMs?: number, closeFn?: () => Promise<void>): Promise<void>;
2646
- export { ABI_STATUSES, AbiStatus, Account, AccountBalanceAlerts, AccountBalanceAlertsTable, AccountCredits, AccountCreditsTable, AccountSpendCap, AccountSpendCapsTable, AccountsTable, ApiFailedRequest, ApiFailedRequestsTable, ApiKey, ApiKeyStatus, ApiKeysTable, ApiRequestLogRow, ApiRequestLogTable, ArchiveFetch, ArchiveFetchesTable, Block, BlocksTable, BnsMarketplaceAction, BnsMarketplaceEventsTable, BnsNameEventTopic, BnsNameEventsTable, BnsNamesTable, BnsNamespaceEventStatus, BnsNamespaceEventsTable, BnsNamespacesTable, BurnBlockRewardSlotsTable, BurnBlockRewardsTable, ChainReadCacheTable, ChainReorgsTable, CliDeviceLogin, CliDeviceLoginStatus, CliDeviceLoginsTable, CliDeviceProduct, ContactRequest, ContactRequestsTable, Contract, ContractsTable, CoverageSegmentsTable, Database, DbPlane, DbReadRow, DbSplitStatus, DeadLetterEventsTable, DeadReason, DecodedEventsTable, DecoderCheckpointsTable, Event, EventsArchiveTable, EventsTable, FailureClass, FailureUnit, FeedbackTicket, FeedbackTicketsTable, GapReason, HostedStackStateTable, IndexColumn, IndexColumnType, IndexPrimaryKey, IndexProgress, IndexProgressTable, InsertAccount, InsertAccountBalanceAlerts, InsertAccountCredits, InsertAccountSpendCap, InsertApiFailedRequest, InsertApiKey, InsertApiRequestLogRow, InsertArchiveFetch, InsertBlock, InsertContactRequest, InsertContract, InsertEvent, InsertFeedbackTicket, InsertIndexProgress, InsertMagicLink, InsertMempoolTransaction, InsertSession, InsertStateWrite, InsertSubgraph, InsertSubgraphGap, InsertSubgraphHealthSnapshot, InsertSubgraphOperation, InsertTransaction, InsertUpdateSubscriber, InsertUsageLedgerRow, InsertVmEvent, InsertWaitlistSignup, InsertWebhook, InsertWebhookDelivery, InsertWebhookOutbox, InsightMutesTable, InsightsTable, InstancesTable, MagicLink, MagicLinksTable, MempoolTransaction, MempoolTransactionsTable, MigrationRole, NativeClock, NumericAsText, OBSERVER_JOURNAL_STATUSES, OauthClient, OauthClientsTable, OauthCodesTable, OauthGrant, OauthGrantsTable, OauthRefreshRetiredTable, OauthRequestStatus, OauthRequestsTable, OauthTokenKind, OauthTokensTable, ObserverJournalStatus, ObserverJournalTable, OutboxStatus, PendingForkBlocksTable, Pox4CallsTable, Pox4FunctionName, Pox5CycleSignersTable, Pox5CyclesTable, Pox5EventTopic, Pox5EventsTable, ProcessedStripeEventsTable, PushPrefs, PushPrefsTable, PushSentTable, PushSubscription, PushSubscriptionsTable, RepairMode, RetryState, RunStatus, SOURCE_READ_COLUMNS, SOURCE_READ_PKS, SOURCE_READ_TYPES, SbtcEventTopic, SbtcEventsTable, SbtcSettlementsTable, SbtcTokenEventType, SbtcTokenEventsTable, SentinelAccount, SentinelAccountsTable, ServiceHeartbeatsTable, Session, SessionsTable, StageBlockReceiptsTable, StageFailuresTable, StageKind, StageRegistryTable, StageRunsTable, StateWrite, StateWritesArchiveTable, StateWritesTable, Subgraph, SubgraphErrorGroupsTable, SubgraphGap, SubgraphGapsTable, SubgraphHealthSnapshot, SubgraphHealthSnapshotsTable, SubgraphOperation, SubgraphOperationKind, SubgraphOperationStatus, SubgraphOperationsTable, SubgraphProcessingStatsTable, SubgraphViolationsTable, SubgraphsTable, SyncScopesTable, TABLE_TO_DB, Transaction, TransactionsArchiveTable, TransactionsTable, TriggerEvaluatorState, TriggerEvaluatorStateTable, UpdateAccountBalanceAlerts, UpdateAccountCredits, UpdateAccountSpendCap, UpdateApiKey, UpdateArchiveFetch, UpdateBlock, UpdateContract, UpdateEvent, UpdateIndexProgress, UpdateSendsTable, UpdateSubgraph, UpdateSubgraphOperation, UpdateSubscriber, UpdateSubscribersTable, UpdateTransaction, UpdateUsageLedgerRow, UpdateVmEvent, UpdateWebhook, UpdateWebhookOutbox, UsageLedgerRow, UsageLedgerTable, VmEvent, VmEventsArchiveTable, VmEventsTable, Waitlist, WaitlistSignup, WaitlistSignupsTable, WaitlistsTable, Webhook, WebhookDeliveriesTable, WebhookDelivery, WebhookDeliveryHoursTable, WebhookFormat, WebhookIncidentAlert, WebhookIncidentAlertsTable, WebhookKind, WebhookOutbox, WebhookOutboxTable, WebhookPauseReason, WebhookReplay, WebhookReplayStatus, WebhookReplaysTable, WebhookStatus, WebhooksTable, applicationDatabaseUrl, assertDbSplit, closeDb, closeDbOrTimeout, describeDbUrl, getDb, getDbSplitStatus, getMigrationRole, getRawClient, getSourceDb, getTargetDb, jsonb, onChainPlane, onControlPlane, parseJsonb, resolveSourceUrl, resolveTargetUrl, setMigrationRole, sql };
2655
+ export { ABI_STATUSES, AbiStatus, Account, AccountBalanceAlerts, AccountBalanceAlertsTable, AccountCredits, AccountCreditsTable, AccountSpendCap, AccountSpendCapsTable, AccountsTable, ApiFailedRequest, ApiFailedRequestsTable, ApiKey, ApiKeyStatus, ApiKeysTable, ApiRequestLogRow, ApiRequestLogTable, ArchiveFetch, ArchiveFetchesTable, Block, BlocksTable, BnsMarketplaceAction, BnsMarketplaceEventsTable, BnsNameEventTopic, BnsNameEventsTable, BnsNamesTable, BnsNamespaceEventStatus, BnsNamespaceEventsTable, BnsNamespacesTable, BurnBlockRewardSlotsTable, BurnBlockRewardsTable, ChainReadCacheTable, ChainReorgsTable, CliDeviceLogin, CliDeviceLoginStatus, CliDeviceLoginsTable, CliDeviceProduct, ContactRequest, ContactRequestsTable, Contract, ContractsTable, CoverageSegmentsTable, Database, DbPlane, DbReadRow, DbSplitStatus, DeadLetterEventsTable, DeadReason, DecodedEventsTable, DecoderCheckpointsTable, Event, EventsArchiveTable, EventsTable, FailureClass, FailureUnit, FeedbackTicket, FeedbackTicketsTable, GapReason, HostedStackStateTable, IndexColumn, IndexColumnType, IndexPrimaryKey, IndexProgress, IndexProgressTable, InsertAccount, InsertAccountBalanceAlerts, InsertAccountCredits, InsertAccountSpendCap, InsertApiFailedRequest, InsertApiKey, InsertApiRequestLogRow, InsertArchiveFetch, InsertBlock, InsertContactRequest, InsertContract, InsertEvent, InsertFeedbackTicket, InsertIndexProgress, InsertMagicLink, InsertMempoolTransaction, InsertSession, InsertStateWrite, InsertSubgraph, InsertSubgraphGap, InsertSubgraphHealthSnapshot, InsertSubgraphOperation, InsertTransaction, InsertUpdateSubscriber, InsertUsageLedgerRow, InsertVmEvent, InsertWaitlistSignup, InsertWebhook, InsertWebhookDelivery, InsertWebhookOutbox, InsightMutesTable, InsightsTable, InstancesTable, MagicLink, MagicLinksTable, MempoolTransaction, MempoolTransactionsTable, MigrationRole, NativeClock, NumericAsText, OBSERVER_JOURNAL_STATUSES, OauthClient, OauthClientsTable, OauthCodesTable, OauthGrant, OauthGrantsTable, OauthRefreshRetiredTable, OauthRequestStatus, OauthRequestsTable, OauthTokenKind, OauthTokensTable, ObserverJournalStatus, ObserverJournalTable, OutboxStatus, PendingForkBlocksTable, Pox4CallsTable, Pox4FunctionName, Pox5CycleSignersTable, Pox5CyclesTable, Pox5EventTopic, Pox5EventsTable, ProcessedStripeEventsTable, PushPrefs, PushPrefsTable, PushSentTable, PushSubscription, PushSubscriptionsTable, RepairMode, RetryState, RunStatus, SOURCE_READ_COLUMNS, SOURCE_READ_PKS, SOURCE_READ_TYPES, SbtcEventTopic, SbtcEventsTable, SbtcSettlementsTable, SbtcTokenEventType, SbtcTokenEventsTable, SentinelAccount, SentinelAccountsTable, ServiceHeartbeatsTable, Session, SessionsTable, StageBlockReceiptsTable, StageFailuresTable, StageKind, StageRegistryTable, StageRunsTable, StateWrite, StateWritesArchiveTable, StateWritesTable, Subgraph, SubgraphErrorGroupsTable, SubgraphGap, SubgraphGapsTable, SubgraphHealthSnapshot, SubgraphHealthSnapshotsTable, SubgraphOperation, SubgraphOperationKind, SubgraphOperationStatus, SubgraphOperationsTable, SubgraphProcessingStatsTable, SubgraphViolationsTable, SubgraphsTable, SyncScopesTable, TABLE_TO_DB, Transaction, TransactionsArchiveTable, TransactionsTable, TriggerEvaluatorState, TriggerEvaluatorStateTable, UpdateAccountBalanceAlerts, UpdateAccountCredits, UpdateAccountSpendCap, UpdateApiKey, UpdateArchiveFetch, UpdateBlock, UpdateContract, UpdateEvent, UpdateIndexProgress, UpdateSendsTable, UpdateSubgraph, UpdateSubgraphOperation, UpdateSubscriber, UpdateSubscribersTable, UpdateTransaction, UpdateUsageLedgerRow, UpdateVmEvent, UpdateWebhook, UpdateWebhookOutbox, UsageLedgerRow, UsageLedgerTable, VmEvent, VmEventsArchiveTable, VmEventsTable, Waitlist, WaitlistSignup, WaitlistSignupsTable, WaitlistsTable, Webhook, WebhookDeliveriesTable, WebhookDelivery, WebhookDeliveryHoursTable, WebhookFormat, WebhookIncidentAlert, WebhookIncidentAlertsTable, WebhookKind, WebhookOutbox, WebhookOutboxTable, WebhookPauseReason, WebhookReplay, WebhookReplayStatus, WebhookReplaysTable, WebhookStatus, WebhooksTable, applicationDatabaseUrl, assertDbSplit, closeDb, closeDbOrTimeout, configuredSourceUrl, configuredTargetUrl, describeDbUrl, getDb, getDbSplitStatus, getMigrationRole, getRawClient, getSourceDb, getTargetDb, jsonb, onChainPlane, onControlPlane, parseJsonb, resolveSourceUrl, resolveTargetUrl, setMigrationRole, sql };
@@ -41,11 +41,25 @@ function getEnv() {
41
41
  } else if (result.data.NETWORK) {
42
42
  enabledNetworks = [result.data.NETWORK];
43
43
  } else {
44
- enabledNetworks = ["mainnet"];
44
+ const named = stacksNetwork();
45
+ enabledNetworks = named === "testnet" ? ["testnet"] : ["mainnet"];
45
46
  }
46
47
  cachedEnv = { ...result.data, enabledNetworks };
47
48
  return cachedEnv;
48
49
  }
50
+ var warnedNetworkFallback = false;
51
+ function stacksNetwork(env = process.env) {
52
+ if (env.STACKS_NETWORK)
53
+ return env.STACKS_NETWORK;
54
+ if (env.NETWORK) {
55
+ if (!warnedNetworkFallback) {
56
+ warnedNetworkFallback = true;
57
+ console.warn("NETWORK is deprecated: set STACKS_NETWORK instead");
58
+ }
59
+ return env.NETWORK;
60
+ }
61
+ return "mainnet";
62
+ }
49
63
  function isProductionEnv() {
50
64
  return process.env["NODE_ENV"] === "production";
51
65
  }
@@ -880,14 +894,20 @@ function applicationDatabaseUrl() {
880
894
  return process.env.DATABASE_URL || DEFAULT_URL;
881
895
  }
882
896
  function resolveSourceUrl() {
883
- if (!isPlatformMode())
884
- return applicationDatabaseUrl();
885
- return process.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL;
897
+ return configuredSourceUrl() ?? DEFAULT_URL;
886
898
  }
887
899
  function resolveTargetUrl() {
900
+ return configuredTargetUrl() ?? DEFAULT_URL;
901
+ }
902
+ function configuredSourceUrl() {
903
+ if (!isPlatformMode())
904
+ return process.env.DATABASE_URL || undefined;
905
+ return process.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || undefined;
906
+ }
907
+ function configuredTargetUrl() {
888
908
  if (!isPlatformMode())
889
- return applicationDatabaseUrl();
890
- return process.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL;
909
+ return process.env.DATABASE_URL || undefined;
910
+ return process.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || undefined;
891
911
  }
892
912
  function describeDbUrl(url) {
893
913
  try {
@@ -1030,6 +1050,8 @@ export {
1030
1050
  assertDbSplit,
1031
1051
  closeDb,
1032
1052
  closeDbOrTimeout,
1053
+ configuredSourceUrl,
1054
+ configuredTargetUrl,
1033
1055
  describeDbUrl,
1034
1056
  getDb,
1035
1057
  getDbSplitStatus,
@@ -1047,5 +1069,5 @@ export {
1047
1069
  sql2 as sql
1048
1070
  };
1049
1071
 
1050
- //# debugId=3120E9B3F1B4866A64756E2164756E21
1072
+ //# debugId=9F87BBC92FD19A1764756E2164756E21
1051
1073
  //# sourceMappingURL=index.js.map