@secondlayer/shared 6.3.5 → 6.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/src/crypto/secrets.js +2 -5
  2. package/dist/src/crypto/secrets.js.map +3 -3
  3. package/dist/src/db/index.d.ts +3 -1
  4. package/dist/src/db/queries/account-spend-caps.d.ts +3 -1
  5. package/dist/src/db/queries/account-usage.d.ts +3 -1
  6. package/dist/src/db/queries/accounts.d.ts +3 -1
  7. package/dist/src/db/queries/chain-reorgs.d.ts +3 -1
  8. package/dist/src/db/queries/integrity.d.ts +3 -1
  9. package/dist/src/db/queries/projects.d.ts +3 -1
  10. package/dist/src/db/queries/provisioning-audit.d.ts +3 -1
  11. package/dist/src/db/queries/subgraph-gaps.d.ts +3 -1
  12. package/dist/src/db/queries/subgraph-operations.d.ts +3 -1
  13. package/dist/src/db/queries/subgraphs.d.ts +3 -1
  14. package/dist/src/db/queries/subscriptions.d.ts +3 -1
  15. package/dist/src/db/queries/subscriptions.js +2 -5
  16. package/dist/src/db/queries/subscriptions.js.map +3 -3
  17. package/dist/src/db/queries/tenant-compute-addons.d.ts +3 -1
  18. package/dist/src/db/queries/usage.d.ts +3 -1
  19. package/dist/src/db/schema.d.ts +3 -1
  20. package/dist/src/index.d.ts +3 -1
  21. package/dist/src/mode.d.ts +6 -12
  22. package/dist/src/mode.js +2 -6
  23. package/dist/src/mode.js.map +3 -3
  24. package/dist/src/node/local-client.d.ts +3 -1
  25. package/migrations/0075_restore_subgraphs_on_platform.ts +166 -0
  26. package/migrations/0076_deprecate_tenants.ts +19 -0
  27. package/migrations/0077_subscription_deliveries_outbox_set_null.ts +50 -0
  28. package/package.json +1 -1
  29. package/dist/src/db/queries/tenants.d.ts +0 -800
  30. package/dist/src/db/queries/tenants.js +0 -308
  31. package/dist/src/db/queries/tenants.js.map +0 -12
@@ -15,7 +15,7 @@ var __export = (target, all) => {
15
15
  };
16
16
 
17
17
  // src/mode.ts
18
- var VALID_MODES = ["oss", "dedicated", "platform"];
18
+ var VALID_MODES = ["oss", "platform"];
19
19
  function getInstanceMode() {
20
20
  const raw = process.env.INSTANCE_MODE?.trim().toLowerCase();
21
21
  if (raw && VALID_MODES.includes(raw)) {
@@ -29,9 +29,6 @@ function isPlatformMode() {
29
29
  function isOssMode() {
30
30
  return getInstanceMode() === "oss";
31
31
  }
32
- function isDedicatedMode() {
33
- return getInstanceMode() === "dedicated";
34
- }
35
32
 
36
33
  // src/crypto/secrets.ts
37
34
  import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
@@ -153,5 +150,5 @@ export {
153
150
  decryptSecret
154
151
  };
155
152
 
156
- //# debugId=B9CC14B7680BC22364756E2164756E21
153
+ //# debugId=40A784140E79E07464756E2164756E21
157
154
  //# sourceMappingURL=secrets.js.map
@@ -2,10 +2,10 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/mode.ts", "../src/crypto/secrets.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * Instance modes for the Secondlayer platform.\n *\n * - `oss`: self-hosted, single-tenant. No auth middleware, no platform routes\n * (projects, admin, tenants). Everything runs against a single\n * `DATABASE_URL`. Intended for `docker compose up`.\n *\n * - `dedicated`: per-customer managed instance. JWT-based auth (anon =\n * read-only, service = full). Dual-DB mode — shared source indexer DB for\n * block reads, per-tenant target DB for subgraph data. No platform-wide\n * routes mounted (no cross-tenant accounts).\n *\n * - `platform`: control-plane mode. Magic-link auth, API keys, projects,\n * tenants, admin. Serves the dashboard + CLI against a single shared DB.\n */\n\nexport type InstanceMode = \"oss\" | \"dedicated\" | \"platform\";\n\nconst VALID_MODES: readonly InstanceMode[] = [\"oss\", \"dedicated\", \"platform\"];\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.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as InstanceMode;\n\t}\n\treturn \"oss\";\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/** True when the active mode is `\"dedicated\"` (per-tenant managed). */\nexport function isDedicatedMode(): boolean {\n\treturn getInstanceMode() === \"dedicated\";\n}\n",
5
+ "/**\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`: control-plane mode. Magic-link auth, API keys, projects,\n * admin. Serves the dashboard + CLI against a single shared DB. Post\n * 2026-05-14 shared-rip this also serves subgraphs + subscriptions.\n */\n\nexport type InstanceMode = \"oss\" | \"platform\";\n\nconst VALID_MODES: readonly InstanceMode[] = [\"oss\", \"platform\"];\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.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as InstanceMode;\n\t}\n\treturn \"oss\";\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",
6
6
  "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 * subscription 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\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"
7
7
  ],
8
- "mappings": ";;;;;;;;;;;;;;;;;AAkBA,IAAM,cAAuC,CAAC,OAAO,aAAa,UAAU;AAOrE,SAAS,eAAe,GAAiB;AAAA,EAC/C,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;AAID,SAAS,cAAc,GAAY;AAAA,EACzC,OAAO,gBAAgB,MAAM;AAAA;AAIvB,SAAS,SAAS,GAAY;AAAA,EACpC,OAAO,gBAAgB,MAAM;AAAA;AAIvB,SAAS,eAAe,GAAY;AAAA,EAC1C,OAAO,gBAAgB,MAAM;AAAA;;;AC7C9B;AACA;AAAA;AAAA;AAAA;AA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,MAAM,MAAM;AAAA;AAIrE,SAAS,kBAAkB,GAAW;AAAA,EAC5C,OAAO,YAAY,EAAE,EAAE,SAAS,KAAK;AAAA;",
9
+ "debugId": "40A784140E79E07464756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -789,7 +789,9 @@ type InsertSubscriptionOutbox = Insertable<SubscriptionOutboxTable>;
789
789
  type UpdateSubscriptionOutbox = Updateable<SubscriptionOutboxTable>;
790
790
  interface SubscriptionDeliveriesTable {
791
791
  id: Generated<string>;
792
- outbox_id: string;
792
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
793
+ * delivery telemetry is retained. */
794
+ outbox_id: string | null;
793
795
  subscription_id: string;
794
796
  attempt: number;
795
797
  status_code: number | null;
@@ -702,7 +702,9 @@ interface SubscriptionOutboxTable {
702
702
  }
703
703
  interface SubscriptionDeliveriesTable {
704
704
  id: Generated<string>;
705
- outbox_id: string;
705
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
706
+ * delivery telemetry is retained. */
707
+ outbox_id: string | null;
706
708
  subscription_id: string;
707
709
  attempt: number;
708
710
  status_code: number | null;
@@ -700,7 +700,9 @@ interface SubscriptionOutboxTable {
700
700
  }
701
701
  interface SubscriptionDeliveriesTable {
702
702
  id: Generated<string>;
703
- outbox_id: string;
703
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
704
+ * delivery telemetry is retained. */
705
+ outbox_id: string | null;
704
706
  subscription_id: string;
705
707
  attempt: number;
706
708
  status_code: number | null;
@@ -702,7 +702,9 @@ interface SubscriptionOutboxTable {
702
702
  }
703
703
  interface SubscriptionDeliveriesTable {
704
704
  id: Generated<string>;
705
- outbox_id: string;
705
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
706
+ * delivery telemetry is retained. */
707
+ outbox_id: string | null;
706
708
  subscription_id: string;
707
709
  attempt: number;
708
710
  status_code: number | null;
@@ -699,7 +699,9 @@ interface SubscriptionOutboxTable {
699
699
  }
700
700
  interface SubscriptionDeliveriesTable {
701
701
  id: Generated<string>;
702
- outbox_id: string;
702
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
703
+ * delivery telemetry is retained. */
704
+ outbox_id: string | null;
703
705
  subscription_id: string;
704
706
  attempt: number;
705
707
  status_code: number | null;
@@ -700,7 +700,9 @@ interface SubscriptionOutboxTable {
700
700
  }
701
701
  interface SubscriptionDeliveriesTable {
702
702
  id: Generated<string>;
703
- outbox_id: string;
703
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
704
+ * delivery telemetry is retained. */
705
+ outbox_id: string | null;
704
706
  subscription_id: string;
705
707
  attempt: number;
706
708
  status_code: number | null;
@@ -702,7 +702,9 @@ interface SubscriptionOutboxTable {
702
702
  }
703
703
  interface SubscriptionDeliveriesTable {
704
704
  id: Generated<string>;
705
- outbox_id: string;
705
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
706
+ * delivery telemetry is retained. */
707
+ outbox_id: string | null;
706
708
  subscription_id: string;
707
709
  attempt: number;
708
710
  status_code: number | null;
@@ -701,7 +701,9 @@ interface SubscriptionOutboxTable {
701
701
  }
702
702
  interface SubscriptionDeliveriesTable {
703
703
  id: Generated<string>;
704
- outbox_id: string;
704
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
705
+ * delivery telemetry is retained. */
706
+ outbox_id: string | null;
705
707
  subscription_id: string;
706
708
  attempt: number;
707
709
  status_code: number | null;
@@ -700,7 +700,9 @@ interface SubscriptionOutboxTable {
700
700
  }
701
701
  interface SubscriptionDeliveriesTable {
702
702
  id: Generated<string>;
703
- outbox_id: string;
703
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
704
+ * delivery telemetry is retained. */
705
+ outbox_id: string | null;
704
706
  subscription_id: string;
705
707
  attempt: number;
706
708
  status_code: number | null;
@@ -701,7 +701,9 @@ interface SubscriptionOutboxTable {
701
701
  }
702
702
  interface SubscriptionDeliveriesTable {
703
703
  id: Generated<string>;
704
- outbox_id: string;
704
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
705
+ * delivery telemetry is retained. */
706
+ outbox_id: string | null;
705
707
  subscription_id: string;
706
708
  attempt: number;
707
709
  status_code: number | null;
@@ -701,7 +701,9 @@ interface SubscriptionOutboxTable {
701
701
  }
702
702
  interface SubscriptionDeliveriesTable {
703
703
  id: Generated<string>;
704
- outbox_id: string;
704
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
705
+ * delivery telemetry is retained. */
706
+ outbox_id: string | null;
705
707
  subscription_id: string;
706
708
  attempt: number;
707
709
  status_code: number | null;
@@ -701,7 +701,9 @@ interface SubscriptionOutboxTable {
701
701
  }
702
702
  interface SubscriptionDeliveriesTable {
703
703
  id: Generated<string>;
704
- outbox_id: string;
704
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
705
+ * delivery telemetry is retained. */
706
+ outbox_id: string | null;
705
707
  subscription_id: string;
706
708
  attempt: number;
707
709
  status_code: number | null;
@@ -69,7 +69,7 @@ function verifySignatureHeader(payload, header, secret, toleranceSeconds = 300)
69
69
  }
70
70
 
71
71
  // src/mode.ts
72
- var VALID_MODES = ["oss", "dedicated", "platform"];
72
+ var VALID_MODES = ["oss", "platform"];
73
73
  function getInstanceMode() {
74
74
  const raw = process.env.INSTANCE_MODE?.trim().toLowerCase();
75
75
  if (raw && VALID_MODES.includes(raw)) {
@@ -83,9 +83,6 @@ function isPlatformMode() {
83
83
  function isOssMode() {
84
84
  return getInstanceMode() === "oss";
85
85
  }
86
- function isDedicatedMode() {
87
- return getInstanceMode() === "dedicated";
88
- }
89
86
 
90
87
  // src/crypto/secrets.ts
91
88
  import { createCipheriv, createDecipheriv, randomBytes as randomBytes2 } from "node:crypto";
@@ -304,5 +301,5 @@ export {
304
301
  createSubscription
305
302
  };
306
303
 
307
- //# debugId=3124E45584A2D0BB64756E2164756E21
304
+ //# debugId=4D43E7402662E23964756E2164756E21
308
305
  //# sourceMappingURL=subscriptions.js.map
@@ -3,11 +3,11 @@
3
3
  "sources": ["../src/crypto/hmac.ts", "../src/mode.ts", "../src/crypto/secrets.ts", "../src/db/queries/subscriptions.ts"],
4
4
  "sourcesContent": [
5
5
  "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",
6
- "/**\n * Instance modes for the Secondlayer platform.\n *\n * - `oss`: self-hosted, single-tenant. No auth middleware, no platform routes\n * (projects, admin, tenants). Everything runs against a single\n * `DATABASE_URL`. Intended for `docker compose up`.\n *\n * - `dedicated`: per-customer managed instance. JWT-based auth (anon =\n * read-only, service = full). Dual-DB mode — shared source indexer DB for\n * block reads, per-tenant target DB for subgraph data. No platform-wide\n * routes mounted (no cross-tenant accounts).\n *\n * - `platform`: control-plane mode. Magic-link auth, API keys, projects,\n * tenants, admin. Serves the dashboard + CLI against a single shared DB.\n */\n\nexport type InstanceMode = \"oss\" | \"dedicated\" | \"platform\";\n\nconst VALID_MODES: readonly InstanceMode[] = [\"oss\", \"dedicated\", \"platform\"];\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.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as InstanceMode;\n\t}\n\treturn \"oss\";\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/** True when the active mode is `\"dedicated\"` (per-tenant managed). */\nexport function isDedicatedMode(): boolean {\n\treturn getInstanceMode() === \"dedicated\";\n}\n",
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`: control-plane mode. Magic-link auth, API keys, projects,\n * admin. Serves the dashboard + CLI against a single shared DB. Post\n * 2026-05-14 shared-rip this also serves subgraphs + subscriptions.\n */\n\nexport type InstanceMode = \"oss\" | \"platform\";\n\nconst VALID_MODES: readonly InstanceMode[] = [\"oss\", \"platform\"];\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.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as InstanceMode;\n\t}\n\treturn \"oss\";\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",
7
7
  "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 * subscription 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\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",
8
8
  "import { type Kysely, sql } from \"kysely\";\nimport { generateSecret } from \"../../crypto/hmac.ts\";\nimport { decryptSecret, encryptSecret } from \"../../crypto/secrets.ts\";\nimport type {\n\tDatabase,\n\tInsertSubscription,\n\tSubscription,\n\tSubscriptionFormat,\n\tSubscriptionRuntime,\n\tSubscriptionStatus,\n\tUpdateSubscription,\n} from \"../types.ts\";\n\n/**\n * Subscription 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 CreateSubscriptionInput {\n\taccountId: string;\n\tprojectId?: string | null;\n\tname: string;\n\tsubgraphName: string;\n\ttableName: string;\n\tfilter?: unknown;\n\tformat?: SubscriptionFormat;\n\truntime?: SubscriptionRuntime | null;\n\turl: string;\n\tauthConfig?: unknown;\n\tmaxRetries?: number;\n\ttimeoutMs?: number;\n\tconcurrency?: number;\n}\n\nexport interface CreateSubscriptionResult {\n\tsubscription: Subscription;\n\t/** Plaintext signing secret — surfaced once, never stored decrypted. */\n\tsigningSecret: string;\n}\n\nexport async function createSubscription(\n\tdb: Kysely<Database>,\n\tinput: CreateSubscriptionInput,\n): Promise<CreateSubscriptionResult> {\n\tconst signingSecret = generateSecret();\n\tconst row: InsertSubscription = {\n\t\taccount_id: input.accountId,\n\t\tproject_id: input.projectId ?? null,\n\t\tname: input.name,\n\t\tstatus: \"active\",\n\t\tsubgraph_name: input.subgraphName,\n\t\ttable_name: input.tableName,\n\t\tfilter: input.filter ?? {},\n\t\tformat: input.format ?? \"standard-webhooks\",\n\t\truntime: input.runtime ?? null,\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 subscription = await db\n\t\t.insertInto(\"subscriptions\")\n\t\t.values(row)\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n\treturn { subscription, signingSecret };\n}\n\nexport async function listSubscriptions(\n\tdb: Kysely<Database>,\n\taccountId: string,\n): Promise<Subscription[]> {\n\treturn db\n\t\t.selectFrom(\"subscriptions\")\n\t\t.selectAll()\n\t\t.where(\"account_id\", \"=\", accountId)\n\t\t.orderBy(\"created_at\", \"desc\")\n\t\t.execute();\n}\n\nexport async function getSubscription(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n): Promise<Subscription | null> {\n\tconst row = await db\n\t\t.selectFrom(\"subscriptions\")\n\t\t.selectAll()\n\t\t.where(\"account_id\", \"=\", accountId)\n\t\t.where(\"id\", \"=\", id)\n\t\t.executeTakeFirst();\n\treturn row ?? null;\n}\n\nexport async function getSubscriptionByName(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tname: string,\n): Promise<Subscription | null> {\n\tconst row = await db\n\t\t.selectFrom(\"subscriptions\")\n\t\t.selectAll()\n\t\t.where(\"account_id\", \"=\", accountId)\n\t\t.where(\"name\", \"=\", name)\n\t\t.executeTakeFirst();\n\treturn row ?? null;\n}\n\nexport interface UpdateSubscriptionInput {\n\tname?: string;\n\tfilter?: unknown;\n\tformat?: SubscriptionFormat;\n\truntime?: SubscriptionRuntime | null;\n\turl?: string;\n\tauthConfig?: unknown;\n\tmaxRetries?: number;\n\ttimeoutMs?: number;\n\tconcurrency?: number;\n}\n\nexport async function updateSubscription(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n\tpatch: UpdateSubscriptionInput,\n): Promise<Subscription | null> {\n\tconst update: UpdateSubscription = { updated_at: new Date() };\n\tif (patch.name !== undefined) update.name = patch.name;\n\tif (patch.filter !== undefined) update.filter = patch.filter;\n\tif (patch.format !== undefined) update.format = patch.format;\n\tif (patch.runtime !== undefined) update.runtime = patch.runtime;\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\tconst row = await db\n\t\t.updateTable(\"subscriptions\")\n\t\t.set(update)\n\t\t.where(\"account_id\", \"=\", accountId)\n\t\t.where(\"id\", \"=\", id)\n\t\t.returningAll()\n\t\t.executeTakeFirst();\n\treturn row ?? null;\n}\n\nexport async function toggleSubscriptionStatus(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n\tstatus: SubscriptionStatus,\n): Promise<Subscription | null> {\n\tconst row = await db\n\t\t.updateTable(\"subscriptions\")\n\t\t.set({\n\t\t\tstatus,\n\t\t\tupdated_at: new Date(),\n\t\t\t...(status === \"active\"\n\t\t\t\t? {\n\t\t\t\t\t\tcircuit_failures: 0,\n\t\t\t\t\t\tcircuit_opened_at: null,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t})\n\t\t.where(\"account_id\", \"=\", accountId)\n\t\t.where(\"id\", \"=\", id)\n\t\t.returningAll()\n\t\t.executeTakeFirst();\n\treturn row ?? null;\n}\n\nexport async function deleteSubscription(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n): Promise<boolean> {\n\tconst res = await db\n\t\t.deleteFrom(\"subscriptions\")\n\t\t.where(\"account_id\", \"=\", accountId)\n\t\t.where(\"id\", \"=\", id)\n\t\t.executeTakeFirst();\n\treturn Number(res.numDeletedRows ?? 0) > 0;\n}\n\nexport interface RotateSecretResult {\n\tsubscription: Subscription;\n\tsigningSecret: string;\n}\n\nexport async function rotateSubscriptionSecret(\n\tdb: Kysely<Database>,\n\taccountId: string,\n\tid: string,\n): Promise<RotateSecretResult | null> {\n\tconst signingSecret = generateSecret();\n\tconst row = await db\n\t\t.updateTable(\"subscriptions\")\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(\"account_id\", \"=\", accountId)\n\t\t.where(\"id\", \"=\", id)\n\t\t.returningAll()\n\t\t.executeTakeFirst();\n\tif (!row) return null;\n\treturn { subscription: row, signingSecret };\n}\n\n/** Decrypt a subscription's signing secret for HMAC signing at emit time. */\nexport function getSubscriptionSigningSecret(sub: Subscription): string {\n\treturn decryptSecret(sub.signing_secret_enc);\n}\n\n/** Fire `subscriptions:changed` notify so the emitter hot-reloads its cache. */\nexport async function notifySubscriptionsChanged(\n\tdb: Kysely<Database>,\n\taccountId: string,\n): Promise<void> {\n\tawait sql`SELECT pg_notify('subscriptions:changed', ${accountId})`.execute(\n\t\tdb,\n\t);\n}\n"
9
9
  ],
10
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAMO,SAAS,cAAc,GAAW;AAAA,EACxC,OAAO,YAAY,EAAE,EAAE,SAAS,KAAK;AAAA;AAO/B,SAAS,WAAW,CAAC,SAAiB,QAAwB;AAAA,EACpE,MAAM,OAAO,WAAW,UAAU,MAAM;AAAA,EACxC,KAAK,OAAO,OAAO;AAAA,EACnB,OAAO,KAAK,OAAO,KAAK;AAAA;AAOlB,SAAS,eAAe,CAC9B,SACA,WACA,QACU;AAAA,EACV,MAAM,oBAAoB,YAAY,SAAS,MAAM;AAAA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c;AAAA;AAIpC,SAAS,4BAA4B,CAAC,KAA2B;AAAA,EACvE,OAAO,cAAc,IAAI,kBAAkB;AAAA;AAI5C,eAAsB,0BAA0B,CAC/C,IACA,WACgB;AAAA,EAChB,MAAM,gDAAgD,aAAa,QAClE,EACD;AAAA;",
11
+ "debugId": "4D43E7402662E23964756E2164756E21",
12
12
  "names": []
13
13
  }
@@ -701,7 +701,9 @@ interface SubscriptionOutboxTable {
701
701
  }
702
702
  interface SubscriptionDeliveriesTable {
703
703
  id: Generated<string>;
704
- outbox_id: string;
704
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
705
+ * delivery telemetry is retained. */
706
+ outbox_id: string | null;
705
707
  subscription_id: string;
706
708
  attempt: number;
707
709
  status_code: number | null;
@@ -700,7 +700,9 @@ interface SubscriptionOutboxTable {
700
700
  }
701
701
  interface SubscriptionDeliveriesTable {
702
702
  id: Generated<string>;
703
- outbox_id: string;
703
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
704
+ * delivery telemetry is retained. */
705
+ outbox_id: string | null;
704
706
  subscription_id: string;
705
707
  attempt: number;
706
708
  status_code: number | null;
@@ -770,7 +770,9 @@ type InsertSubscriptionOutbox = Insertable<SubscriptionOutboxTable>;
770
770
  type UpdateSubscriptionOutbox = Updateable<SubscriptionOutboxTable>;
771
771
  interface SubscriptionDeliveriesTable {
772
772
  id: Generated<string>;
773
- outbox_id: string;
773
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
774
+ * delivery telemetry is retained. */
775
+ outbox_id: string | null;
774
776
  subscription_id: string;
775
777
  attempt: number;
776
778
  status_code: number | null;
@@ -770,7 +770,9 @@ type InsertSubscriptionOutbox = Insertable<SubscriptionOutboxTable>;
770
770
  type UpdateSubscriptionOutbox = Updateable<SubscriptionOutboxTable>;
771
771
  interface SubscriptionDeliveriesTable {
772
772
  id: Generated<string>;
773
- outbox_id: string;
773
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
774
+ * delivery telemetry is retained. */
775
+ outbox_id: string | null;
774
776
  subscription_id: string;
775
777
  attempt: number;
776
778
  status_code: number | null;
@@ -2,18 +2,14 @@
2
2
  * Instance modes for the Secondlayer platform.
3
3
  *
4
4
  * - `oss`: self-hosted, single-tenant. No auth middleware, no platform routes
5
- * (projects, admin, tenants). Everything runs against a single
6
- * `DATABASE_URL`. Intended for `docker compose up`.
7
- *
8
- * - `dedicated`: per-customer managed instance. JWT-based auth (anon =
9
- * read-only, service = full). Dual-DB mode — shared source indexer DB for
10
- * block reads, per-tenant target DB for subgraph data. No platform-wide
11
- * routes mounted (no cross-tenant accounts).
5
+ * (projects, admin). Everything runs against a single `DATABASE_URL`.
6
+ * Intended for `docker compose up`.
12
7
  *
13
8
  * - `platform`: control-plane mode. Magic-link auth, API keys, projects,
14
- * tenants, admin. Serves the dashboard + CLI against a single shared DB.
9
+ * admin. Serves the dashboard + CLI against a single shared DB. Post
10
+ * 2026-05-14 shared-rip this also serves subgraphs + subscriptions.
15
11
  */
16
- type InstanceMode = "oss" | "dedicated" | "platform";
12
+ type InstanceMode = "oss" | "platform";
17
13
  /**
18
14
  * Resolve the active instance mode from `process.env.INSTANCE_MODE`.
19
15
  * Defaults to `"oss"` — the safest default for self-hosters who deploy
@@ -24,6 +20,4 @@ declare function getInstanceMode(): InstanceMode;
24
20
  declare function isPlatformMode(): boolean;
25
21
  /** True when the active mode is `"oss"` (self-hosted). */
26
22
  declare function isOssMode(): boolean;
27
- /** True when the active mode is `"dedicated"` (per-tenant managed). */
28
- declare function isDedicatedMode(): boolean;
29
- export { isPlatformMode, isOssMode, isDedicatedMode, getInstanceMode, InstanceMode };
23
+ export { isPlatformMode, isOssMode, getInstanceMode, InstanceMode };
package/dist/src/mode.js CHANGED
@@ -15,7 +15,7 @@ var __export = (target, all) => {
15
15
  };
16
16
 
17
17
  // src/mode.ts
18
- var VALID_MODES = ["oss", "dedicated", "platform"];
18
+ var VALID_MODES = ["oss", "platform"];
19
19
  function getInstanceMode() {
20
20
  const raw = process.env.INSTANCE_MODE?.trim().toLowerCase();
21
21
  if (raw && VALID_MODES.includes(raw)) {
@@ -29,15 +29,11 @@ function isPlatformMode() {
29
29
  function isOssMode() {
30
30
  return getInstanceMode() === "oss";
31
31
  }
32
- function isDedicatedMode() {
33
- return getInstanceMode() === "dedicated";
34
- }
35
32
  export {
36
33
  isPlatformMode,
37
34
  isOssMode,
38
- isDedicatedMode,
39
35
  getInstanceMode
40
36
  };
41
37
 
42
- //# debugId=51EB3CB7EC43958964756E2164756E21
38
+ //# debugId=B04DA9673CE8B2EF64756E2164756E21
43
39
  //# sourceMappingURL=mode.js.map
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/mode.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * Instance modes for the Secondlayer platform.\n *\n * - `oss`: self-hosted, single-tenant. No auth middleware, no platform routes\n * (projects, admin, tenants). Everything runs against a single\n * `DATABASE_URL`. Intended for `docker compose up`.\n *\n * - `dedicated`: per-customer managed instance. JWT-based auth (anon =\n * read-only, service = full). Dual-DB mode — shared source indexer DB for\n * block reads, per-tenant target DB for subgraph data. No platform-wide\n * routes mounted (no cross-tenant accounts).\n *\n * - `platform`: control-plane mode. Magic-link auth, API keys, projects,\n * tenants, admin. Serves the dashboard + CLI against a single shared DB.\n */\n\nexport type InstanceMode = \"oss\" | \"dedicated\" | \"platform\";\n\nconst VALID_MODES: readonly InstanceMode[] = [\"oss\", \"dedicated\", \"platform\"];\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.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as InstanceMode;\n\t}\n\treturn \"oss\";\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/** True when the active mode is `\"dedicated\"` (per-tenant managed). */\nexport function isDedicatedMode(): boolean {\n\treturn getInstanceMode() === \"dedicated\";\n}\n"
5
+ "/**\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`: control-plane mode. Magic-link auth, API keys, projects,\n * admin. Serves the dashboard + CLI against a single shared DB. Post\n * 2026-05-14 shared-rip this also serves subgraphs + subscriptions.\n */\n\nexport type InstanceMode = \"oss\" | \"platform\";\n\nconst VALID_MODES: readonly InstanceMode[] = [\"oss\", \"platform\"];\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.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as InstanceMode;\n\t}\n\treturn \"oss\";\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"
6
6
  ],
7
- "mappings": ";;;;;;;;;;;;;;;;;AAkBA,IAAM,cAAuC,CAAC,OAAO,aAAa,UAAU;AAOrE,SAAS,eAAe,GAAiB;AAAA,EAC/C,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;AAID,SAAS,cAAc,GAAY;AAAA,EACzC,OAAO,gBAAgB,MAAM;AAAA;AAIvB,SAAS,SAAS,GAAY;AAAA,EACpC,OAAO,gBAAgB,MAAM;AAAA;AAIvB,SAAS,eAAe,GAAY;AAAA,EAC1C,OAAO,gBAAgB,MAAM;AAAA;",
8
- "debugId": "51EB3CB7EC43958964756E2164756E21",
7
+ "mappings": ";;;;;;;;;;;;;;;;;AAcA,IAAM,cAAuC,CAAC,OAAO,UAAU;AAOxD,SAAS,eAAe,GAAiB;AAAA,EAC/C,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;AAID,SAAS,cAAc,GAAY;AAAA,EACzC,OAAO,gBAAgB,MAAM;AAAA;AAIvB,SAAS,SAAS,GAAY;AAAA,EACpC,OAAO,gBAAgB,MAAM;AAAA;",
8
+ "debugId": "B04DA9673CE8B2EF64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -700,7 +700,9 @@ interface SubscriptionOutboxTable {
700
700
  }
701
701
  interface SubscriptionDeliveriesTable {
702
702
  id: Generated<string>;
703
- outbox_id: string;
703
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
704
+ * delivery telemetry is retained. */
705
+ outbox_id: string | null;
704
706
  subscription_id: string;
705
707
  attempt: number;
706
708
  status_code: number | null;
@@ -0,0 +1,166 @@
1
+ import { type Kysely, sql } from "kysely";
2
+
3
+ /**
4
+ * Restore `subgraphs` + `subgraph_operations` on platform DBs that lost them
5
+ * during the shared→dedicated cutover (manual drop after 0041; see note in
6
+ * 0045). After the 2026-05-14 shared-rip pivot, the platform subgraph-processor
7
+ * crashes with `relation "subgraphs" does not exist` because no migration ever
8
+ * recreated the parent table — only the satellite tables (gaps, stats,
9
+ * snapshots, usage_daily) survived.
10
+ *
11
+ * Idempotent: each step is guarded so this is a no-op on DBs that already have
12
+ * the tables (OSS, fresh dev, or any tenant DB).
13
+ */
14
+
15
+ async function tableExists(
16
+ db: Kysely<unknown>,
17
+ tableName: string,
18
+ ): Promise<boolean> {
19
+ const { rows } = await sql<{ exists: boolean }>`
20
+ SELECT to_regclass(${`public.${tableName}`}) IS NOT NULL AS exists
21
+ `.execute(db);
22
+ return rows[0]?.exists === true;
23
+ }
24
+
25
+ export async function up(db: Kysely<unknown>): Promise<void> {
26
+ if (!(await tableExists(db, "subgraphs"))) {
27
+ await sql`
28
+ CREATE TABLE subgraphs (
29
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
30
+ name text NOT NULL,
31
+ version text NOT NULL DEFAULT '1.0.0',
32
+ status text NOT NULL DEFAULT 'active',
33
+ definition jsonb NOT NULL,
34
+ schema_hash text NOT NULL,
35
+ handler_path text NOT NULL,
36
+ schema_name text,
37
+ start_block bigint NOT NULL DEFAULT 0,
38
+ last_processed_block bigint NOT NULL DEFAULT 0,
39
+ reindex_from_block bigint,
40
+ reindex_to_block bigint,
41
+ last_error text,
42
+ last_error_at timestamptz,
43
+ total_processed bigint NOT NULL DEFAULT 0,
44
+ total_errors bigint NOT NULL DEFAULT 0,
45
+ account_id text NOT NULL,
46
+ handler_code text,
47
+ source_code text,
48
+ project_id uuid REFERENCES projects(id) ON DELETE SET NULL,
49
+ created_at timestamptz NOT NULL DEFAULT now(),
50
+ updated_at timestamptz NOT NULL DEFAULT now()
51
+ )
52
+ `.execute(db);
53
+
54
+ await sql`CREATE INDEX subgraphs_name_idx ON subgraphs (name)`.execute(db);
55
+ await sql`CREATE INDEX subgraphs_status_idx ON subgraphs (status)`.execute(
56
+ db,
57
+ );
58
+ await sql`CREATE UNIQUE INDEX subgraphs_name_account_id_unique ON subgraphs (name, account_id)`.execute(
59
+ db,
60
+ );
61
+ await sql`CREATE INDEX subgraphs_account_id_idx ON subgraphs (account_id)`.execute(
62
+ db,
63
+ );
64
+
65
+ await sql`
66
+ CREATE OR REPLACE FUNCTION notify_subgraph_changes() RETURNS trigger AS $$
67
+ BEGIN
68
+ PERFORM pg_notify('subgraph_changes', json_build_object(
69
+ 'operation', TG_OP,
70
+ 'name', COALESCE(NEW.name, OLD.name)
71
+ )::text);
72
+ RETURN COALESCE(NEW, OLD);
73
+ END;
74
+ $$ LANGUAGE plpgsql
75
+ `.execute(db);
76
+
77
+ await sql`DROP TRIGGER IF EXISTS subgraphs_notify_trigger ON subgraphs`.execute(
78
+ db,
79
+ );
80
+ await sql`
81
+ CREATE TRIGGER subgraphs_notify_trigger
82
+ AFTER INSERT OR UPDATE OR DELETE ON subgraphs
83
+ FOR EACH ROW EXECUTE FUNCTION notify_subgraph_changes()
84
+ `.execute(db);
85
+ }
86
+
87
+ if (!(await tableExists(db, "subgraph_operations"))) {
88
+ await sql`
89
+ CREATE TABLE subgraph_operations (
90
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
91
+ subgraph_id uuid NOT NULL REFERENCES subgraphs(id) ON DELETE CASCADE,
92
+ subgraph_name text NOT NULL,
93
+ account_id text,
94
+ kind text NOT NULL CHECK (kind IN ('reindex', 'backfill')),
95
+ status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'running', 'completed', 'failed', 'cancelled')),
96
+ from_block bigint,
97
+ to_block bigint,
98
+ cancel_requested boolean NOT NULL DEFAULT false,
99
+ locked_by text,
100
+ locked_until timestamptz,
101
+ started_at timestamptz,
102
+ finished_at timestamptz,
103
+ processed_blocks bigint,
104
+ error text,
105
+ created_at timestamptz NOT NULL DEFAULT now(),
106
+ updated_at timestamptz NOT NULL DEFAULT now()
107
+ )
108
+ `.execute(db);
109
+
110
+ await sql`
111
+ CREATE UNIQUE INDEX subgraph_operations_active_unique
112
+ ON subgraph_operations (subgraph_id)
113
+ WHERE status IN ('queued', 'running')
114
+ `.execute(db);
115
+
116
+ await sql`
117
+ CREATE INDEX subgraph_operations_claim_idx
118
+ ON subgraph_operations (created_at)
119
+ WHERE status = 'queued'
120
+ `.execute(db);
121
+
122
+ await sql`
123
+ CREATE INDEX subgraph_operations_stale_running_idx
124
+ ON subgraph_operations (locked_until)
125
+ WHERE status = 'running'
126
+ `.execute(db);
127
+
128
+ await sql`
129
+ CREATE OR REPLACE FUNCTION notify_subgraph_operation_new()
130
+ RETURNS trigger AS $$
131
+ BEGIN
132
+ PERFORM pg_notify('subgraph_operations:new', NEW.id::text);
133
+ RETURN NEW;
134
+ END;
135
+ $$ LANGUAGE plpgsql
136
+ `.execute(db);
137
+
138
+ await sql`DROP TRIGGER IF EXISTS subgraph_operations_insert_notify ON subgraph_operations`.execute(
139
+ db,
140
+ );
141
+ await sql`
142
+ CREATE TRIGGER subgraph_operations_insert_notify
143
+ AFTER INSERT ON subgraph_operations
144
+ FOR EACH ROW
145
+ WHEN (NEW.status = 'queued')
146
+ EXECUTE FUNCTION notify_subgraph_operation_new()
147
+ `.execute(db);
148
+
149
+ await sql`DROP TRIGGER IF EXISTS subgraph_operations_cancel_notify ON subgraph_operations`.execute(
150
+ db,
151
+ );
152
+ await sql`
153
+ CREATE TRIGGER subgraph_operations_cancel_notify
154
+ AFTER UPDATE OF cancel_requested ON subgraph_operations
155
+ FOR EACH ROW
156
+ WHEN (NEW.cancel_requested = true AND OLD.cancel_requested IS DISTINCT FROM NEW.cancel_requested)
157
+ EXECUTE FUNCTION notify_subgraph_operation_new()
158
+ `.execute(db);
159
+ }
160
+ }
161
+
162
+ export async function down(_db: Kysely<unknown>): Promise<void> {
163
+ // No-op. Rolling back would drop tables that existed pre-migration on the
164
+ // dedicated-tenant + OSS code paths and risk data loss on platform once the
165
+ // processor starts writing. If a true rollback is needed, do it manually.
166
+ }