@selvajs/selva 4.21.0-beta.8 → 4.21.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/adapter-node.js +1 -1
- package/build/client/_app/immutable/entry/{app.DPVyoSCt.js → app.GRcSFliG.js} +2 -2
- package/build/client/_app/immutable/entry/app.GRcSFliG.js.br +0 -0
- package/build/client/_app/immutable/entry/app.GRcSFliG.js.gz +0 -0
- package/build/client/_app/immutable/nodes/15._hpTnSzc.js +36 -0
- package/build/client/_app/immutable/nodes/15._hpTnSzc.js.br +0 -0
- package/build/client/_app/immutable/nodes/15._hpTnSzc.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{25.D6EkgNRa.js → 25.BacveQsm.js} +1 -1
- package/build/client/_app/immutable/nodes/25.BacveQsm.js.br +0 -0
- package/build/client/_app/immutable/nodes/25.BacveQsm.js.gz +0 -0
- package/build/client/_app/version.json +1 -1
- package/build/client/_app/version.json.br +0 -0
- package/build/client/_app/version.json.gz +0 -0
- package/build/server/chunks/bootHealth.server.js +23 -23
- package/build/server/chunks/bootHealth.server.js.map +1 -1
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/package.js +2 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/providers.server.js +70 -15
- package/build/server/chunks/providers.server.js.map +1 -1
- package/build/server/chunks/server-config-write.js +5 -5
- package/build/server/chunks/server-config-write.js.map +1 -1
- package/build/server/chunks/update-outcome.js +11 -0
- package/build/server/chunks/update-outcome.js.map +1 -1
- package/build/server/chunks/updateCheck.server.js +23 -11
- package/build/server/chunks/updateCheck.server.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js +2 -1
- package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js +31 -0
- package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js.map +1 -1
- package/build/server/entries/pages/admin/system/_page.server.ts.js +5 -0
- package/build/server/entries/pages/admin/system/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/admin/system/_page.svelte.js +17 -1
- package/build/server/entries/pages/admin/system/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/projects/_page.svelte.js +2 -0
- package/build/server/entries/pages/projects/_page.svelte.js.map +1 -1
- package/build/server/manifest-full.js +1 -1
- package/build/server/manifest.js +1 -1
- package/build/server/nodes/15.js +1 -1
- package/build/server/nodes/25.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +11 -8
- package/build/client/_app/immutable/entry/app.DPVyoSCt.js.br +0 -0
- package/build/client/_app/immutable/entry/app.DPVyoSCt.js.gz +0 -0
- package/build/client/_app/immutable/nodes/15.0NRg5Hm0.js +0 -32
- package/build/client/_app/immutable/nodes/15.0NRg5Hm0.js.br +0 -0
- package/build/client/_app/immutable/nodes/15.0NRg5Hm0.js.gz +0 -0
- package/build/client/_app/immutable/nodes/25.D6EkgNRa.js.br +0 -0
- package/build/client/_app/immutable/nodes/25.D6EkgNRa.js.gz +0 -0
|
@@ -91,14 +91,14 @@ function validateIncomingServers(servers) {
|
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
93
|
/**
|
|
94
|
-
* A key
|
|
95
|
-
* the field omitted would write `undefined` over
|
|
96
|
-
*
|
|
97
|
-
*
|
|
94
|
+
* A key the store could not open reads as `hasApiKey` with no `apiKey`. Saving with
|
|
95
|
+
* the field omitted would write `undefined` over it, destroying the key the logs
|
|
96
|
+
* tell the operator how to recover. Replacing or clearing it is a decision, so
|
|
97
|
+
* those pass.
|
|
98
98
|
*/
|
|
99
99
|
function assertStoredKeysReadable(incoming, stored) {
|
|
100
100
|
const unreadable = new Set(stored.filter((s) => s.hasApiKey && !s.apiKey).map((s) => s.id));
|
|
101
|
-
for (const s of incoming) if (unreadable.has(s.id) && (s.apiKey === void 0 || s.apiKey === "")) apiError(409, ApiErrorCode.CONFLICT, `The stored key for server ${s.id} cannot be
|
|
101
|
+
for (const s of incoming) if (unreadable.has(s.id) && (s.apiKey === void 0 || s.apiKey === "")) apiError(409, ApiErrorCode.CONFLICT, `The stored key for server ${s.id} cannot be read. Re-enter the key, or see the server log for how to recover it.`);
|
|
102
102
|
}
|
|
103
103
|
/**
|
|
104
104
|
* An omitted key is kept, so without this check anyone who may save the config
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-config-write.js","names":[],"sources":["../../../../server/src/compute/evict-changed-servers.ts","../../../../server/src/compute/server-config-write.ts"],"sourcesContent":["/**\n * A warm compute client caches on server `id`, so a rotated `serverUrl`/`apiKey`\n * keeps the same cache key with stale connection details — it never ages out on\n * its own. The config-write path has to evict explicitly.\n *\n * The eviction sink is a parameter rather than an import: which cache holds the\n * warm clients is the host's decision, and importing one would drag a whole\n * solve engine into every consumer that only wants the diff.\n */\n\n/** The connection-identifying fields — a change in either makes the warm client stale. */\nexport interface ServerConnection {\n\tid: string;\n\tserverUrl: string;\n\tapiKey?: string;\n}\n\n/**\n * Drop the warm client for every server that was removed or whose connection\n * details changed. `prev` and `next` are the scoped server sets before and\n * after the write; unchanged servers are left alone.\n */\nexport function evictChangedServers(\n\tprev: readonly ServerConnection[],\n\tnext: readonly ServerConnection[],\n\tevict: (id: string) => void\n): void {\n\tconst nextById = new Map(next.map((s) => [s.id, s]));\n\n\t// Removed: no longer in `next`.\n\tfor (const before of prev) {\n\t\tif (!nextById.has(before.id)) evict(before.id);\n\t}\n\n\t// Rotated: same id, different URL or key.\n\tconst prevById = new Map(prev.map((s) => [s.id, s]));\n\tfor (const after of next) {\n\t\tconst before = prevById.get(after.id);\n\t\tif (before && (before.serverUrl !== after.serverUrl || before.apiKey !== after.apiKey)) {\n\t\t\tevict(after.id);\n\t\t}\n\t}\n}\n","/**\n * Shared write-path rules for compute server config.\n *\n * Two routes accept a server set: `/api/admin/compute` (platform scope,\n * `manage_compute`) and `/api/v1/orgs/{orgId}/compute` (org scope,\n * `manage_org_compute`). They differ in who may call them, what extra fields\n * they carry (`sharedWith` vs `ownerOrgId`), and how they validate the default\n * selection — but the field validation and the apiKey merge below must behave\n * identically in both, so they live here rather than in either handler.\n *\n * The apiKey merge is why this file exists: if the two copies disagree, a\n * stored credential silently gets cleared or leaked, and nothing fails at\n * build time.\n */\n\nimport { GuidSchema, trimTrailing } from '@selvajs/platform';\nimport { isEncryptedSecret } from '@selvajs/platform/computeServer';\nimport { isLinkLocalUrl } from './safe-url.js';\nimport { apiError, ApiErrorCode } from '../api/errors.js';\n\n/**\n * A stored `serverUrl` is fetched server-side on every status probe, every\n * purge/shutdown action, and every solve, so an unfiltered one is an SSRF\n * primitive handed to whoever holds `manage_compute`. Two rules:\n *\n * - Scheme allowlist: `http`/`https`. `file:`, `gopher:` and friends are never\n * a Rhino.Compute endpoint.\n * - Link-local (`169.254.0.0/16`) is refused. That range carries the cloud\n * metadata service at `169.254.169.254`, which hands out the host's own IAM\n * credentials to anything running on the box.\n *\n * **Loopback and RFC1918 are deliberately allowed.** Running compute on\n * `localhost:6500` or a LAN box is the ordinary self-hosted layout, not an\n * attack — most deployments reach their compute server over exactly those\n * addresses. Blocking them by default would break those instances on upgrade\n * and push every operator toward an opt-out flag, and a guard that everyone\n * disables protects nobody. So the check is narrowed to the range where no\n * legitimate compute server ever lives.\n *\n * What this does not stop: a privileged admin pointing the app at an internal\n * host to probe it. That is a real but much weaker concern than credential\n * theft, it needs `manage_compute` already, and it is inseparable from the\n * legitimate case. Revisit if `manage_org_compute` is ever delegated widely on\n * a multi-tenant instance.\n *\n * `isLinkLocalUrl` is reused rather than hand-rolled because a string compare\n * against `169.254.169.254` misses the encodings that reach the same address:\n * `http://2852039166/`, `http://0xa9fea9fe/`, `http://0251.0376.0251.0376/`.\n */\nfunction assertUsableServerUrl(serverUrl: string): void {\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(serverUrl);\n\t} catch {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Invalid serverUrl: ${serverUrl}`);\n\t}\n\tif (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `serverUrl must use http or https: ${serverUrl}`);\n\t}\n\tif (isLinkLocalUrl(serverUrl)) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`serverUrl points at the link-local range, which carries the cloud metadata service: ${serverUrl}`\n\t\t);\n\t}\n}\n\n/** The fields every incoming server carries, whatever its scope. */\nexport interface IncomingServerBase {\n\tid: string;\n\tlabel: string;\n\tserverUrl: string;\n\t/**\n\t * `undefined` → preserve the stored key; `null` → clear it;\n\t * non-empty string → replace it. See {@link resolveApiKey}.\n\t */\n\tapiKey?: string | null;\n}\n\n/**\n * Validates the scope-independent fields of every submitted server. Throws the\n * first failure as a 400; scope-specific fields (`sharedWith`, `ownerOrgId`)\n * are the caller's business.\n */\nexport function validateIncomingServers(servers: readonly IncomingServerBase[]): void {\n\tconst seen = new Set<string>();\n\tfor (const s of servers) {\n\t\tif (!s.id || typeof s.id !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs an id');\n\t\tif (!GuidSchema.safeParse(s.id).success)\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Server id must be a UUID: ${s.id}`);\n\t\tif (seen.has(s.id))\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Server id appears more than once: ${s.id}`);\n\t\tseen.add(s.id);\n\t\tif (!s.label || typeof s.label !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs a label');\n\t\tif (!s.serverUrl || typeof s.serverUrl !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs a serverUrl');\n\t\tassertUsableServerUrl(s.serverUrl);\n\t\tif (s.apiKey !== undefined && s.apiKey !== null && typeof s.apiKey !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'apiKey must be a string, null, or omitted');\n\t\t// Clients never receive stored keys, so an envelope here is someone else's\n\t\t// ciphertext being replayed against a URL they control.\n\t\tif (s.apiKey && isEncryptedSecret(s.apiKey))\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'apiKey must be a plaintext key');\n\t}\n}\n\n/**\n * A key that failed to decrypt reads as `hasApiKey` with no `apiKey`. Saving with\n * the field omitted would write `undefined` over the ciphertext, destroying the\n * key the logs tell the operator to recover by restoring `SELVA_AT_REST_KEY`.\n * Replacing or clearing it is a decision, so those pass.\n */\nexport function assertStoredKeysReadable(\n\tincoming: readonly Pick<IncomingServerBase, 'id' | 'apiKey'>[],\n\tstored: readonly { id: string; apiKey?: string; hasApiKey?: boolean }[]\n): void {\n\tconst unreadable = new Set(stored.filter((s) => s.hasApiKey && !s.apiKey).map((s) => s.id));\n\tfor (const s of incoming) {\n\t\tif (unreadable.has(s.id) && (s.apiKey === undefined || s.apiKey === '')) {\n\t\t\tapiError(\n\t\t\t\t409,\n\t\t\t\tApiErrorCode.CONFLICT,\n\t\t\t\t`The stored key for server ${s.id} cannot be decrypted. Restore the original SELVA_AT_REST_KEY, or re-enter the key.`\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * An omitted key is kept, so without this check anyone who may save the config\n * could point a server at their own host and have the next solve send them the\n * stored key, which they never saw. Moving a server needs the key re-entered or\n * cleared.\n */\nexport function assertKeyNotRetargeted(\n\tincoming: readonly Pick<IncomingServerBase, 'id' | 'serverUrl' | 'apiKey'>[],\n\tstored: readonly { id: string; serverUrl: string; apiKey?: string; hasApiKey?: boolean }[]\n): void {\n\tconst byId = new Map(stored.map((s) => [s.id, s]));\n\tfor (const s of incoming) {\n\t\tconst prev = byId.get(s.id);\n\t\tif (!prev || !(prev.hasApiKey || prev.apiKey)) continue;\n\t\tif (s.apiKey === null || (typeof s.apiKey === 'string' && s.apiKey !== '')) continue;\n\t\tif (sameServerUrl(prev.serverUrl, s.serverUrl)) continue;\n\t\tapiError(\n\t\t\t409,\n\t\t\tApiErrorCode.CONFLICT,\n\t\t\t`Server ${s.id} has a new URL. Re-enter its API key, or clear it, to save.`\n\t\t);\n\t}\n}\n\nfunction sameServerUrl(a: string, b: string): boolean {\n\tconst normalize = (u: string) => {\n\t\ttry {\n\t\t\treturn trimTrailing(new URL(u.trim()).href, '/');\n\t\t} catch {\n\t\t\treturn trimTrailing(u.trim(), '/');\n\t\t}\n\t};\n\treturn normalize(a) === normalize(b);\n}\n\n/**\n * The UI never receives stored keys — it sends back `hasApiKey` and omits the\n * field for servers the operator didn't touch. So \"omitted\" cannot mean \"clear\":\n * it has to preserve, or every save through the settings form would wipe the\n * keys of every server the operator left alone. Clearing is explicit (`null`);\n * an empty string is treated as \"not provided\" since that's what an untouched\n * password input submits.\n */\nexport function resolveApiKey(\n\tsubmitted: string | null | undefined,\n\tstoredKey: string | undefined\n): string | undefined {\n\tif (submitted === null) return undefined;\n\treturn submitted ? submitted : storedKey;\n}\n\n/**\n * Builds the id → stored-key lookup the merge reads. The caller passes only the\n * servers in its own scope, so one scope's write can never resolve a key from\n * another's rows.\n */\nexport function storedKeysById(\n\tscopedServers: readonly { id: string; apiKey?: string }[]\n): Map<string, string | undefined> {\n\treturn new Map(scopedServers.map((s) => [s.id, s.apiKey]));\n}\n\n/**\n * The whole apiKey merge for one scope's write: refuses an unreadable or\n * retargeted key with 409, then returns the key to store for each submitted id.\n * `scopedStored` must be read with `includeApiKeys` and hold only the caller's\n * scope.\n */\nexport function mergeApiKeys(\n\tincoming: readonly Pick<IncomingServerBase, 'id' | 'serverUrl' | 'apiKey'>[],\n\tscopedStored: readonly { id: string; serverUrl: string; apiKey?: string; hasApiKey?: boolean }[]\n): Map<string, string | undefined> {\n\tassertStoredKeysReadable(incoming, scopedStored);\n\tassertKeyNotRetargeted(incoming, scopedStored);\n\tconst stored = storedKeysById(scopedStored);\n\treturn new Map(incoming.map((s) => [s.id, resolveApiKey(s.apiKey, stored.get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c,GAAW,GAAoB;CACrD,MAAM,aAAa,MAAc;EAChC,IAAI;GACH,OAAO,aAAa,IAAI,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,MAAM,GAAG;EAChD,QAAQ;GACP,OAAO,aAAa,EAAE,KAAK,GAAG,GAAG;EAClC;CACD;CACA,OAAO,UAAU,CAAC,MAAM,UAAU,CAAC;AACpC;;;;;;;;;AAUA,SAAgB,cACf,WACA,WACqB;CACrB,IAAI,cAAc,MAAM,OAAO,KAAA;CAC/B,OAAO,YAAY,YAAY;AAChC;;;;;;AAOA,SAAgB,eACf,eACkC;CAClC,OAAO,IAAI,IAAI,cAAc,KAAK,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAC1D;;;;;;;AAQA,SAAgB,aACf,UACA,cACkC;CAClC,yBAAyB,UAAU,YAAY;CAC/C,uBAAuB,UAAU,YAAY;CAC7C,MAAM,SAAS,eAAe,YAAY;CAC1C,OAAO,IAAI,IAAI,SAAS,KAAK,MAAM,CAAC,EAAE,IAAI,cAAc,EAAE,QAAQ,OAAO,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACtF"}
|
|
1
|
+
{"version":3,"file":"server-config-write.js","names":[],"sources":["../../../../server/src/compute/evict-changed-servers.ts","../../../../server/src/compute/server-config-write.ts"],"sourcesContent":["/**\n * A warm compute client caches on server `id`, so a rotated `serverUrl`/`apiKey`\n * keeps the same cache key with stale connection details — it never ages out on\n * its own. The config-write path has to evict explicitly.\n *\n * The eviction sink is a parameter rather than an import: which cache holds the\n * warm clients is the host's decision, and importing one would drag a whole\n * solve engine into every consumer that only wants the diff.\n */\n\n/** The connection-identifying fields — a change in either makes the warm client stale. */\nexport interface ServerConnection {\n\tid: string;\n\tserverUrl: string;\n\tapiKey?: string;\n}\n\n/**\n * Drop the warm client for every server that was removed or whose connection\n * details changed. `prev` and `next` are the scoped server sets before and\n * after the write; unchanged servers are left alone.\n */\nexport function evictChangedServers(\n\tprev: readonly ServerConnection[],\n\tnext: readonly ServerConnection[],\n\tevict: (id: string) => void\n): void {\n\tconst nextById = new Map(next.map((s) => [s.id, s]));\n\n\t// Removed: no longer in `next`.\n\tfor (const before of prev) {\n\t\tif (!nextById.has(before.id)) evict(before.id);\n\t}\n\n\t// Rotated: same id, different URL or key.\n\tconst prevById = new Map(prev.map((s) => [s.id, s]));\n\tfor (const after of next) {\n\t\tconst before = prevById.get(after.id);\n\t\tif (before && (before.serverUrl !== after.serverUrl || before.apiKey !== after.apiKey)) {\n\t\t\tevict(after.id);\n\t\t}\n\t}\n}\n","/**\n * Shared write-path rules for compute server config.\n *\n * Two routes accept a server set: `/api/admin/compute` (platform scope,\n * `manage_compute`) and `/api/v1/orgs/{orgId}/compute` (org scope,\n * `manage_org_compute`). They differ in who may call them, what extra fields\n * they carry (`sharedWith` vs `ownerOrgId`), and how they validate the default\n * selection — but the field validation and the apiKey merge below must behave\n * identically in both, so they live here rather than in either handler.\n *\n * The apiKey merge is why this file exists: if the two copies disagree, a\n * stored credential silently gets cleared or leaked, and nothing fails at\n * build time.\n */\n\nimport { GuidSchema, trimTrailing } from '@selvajs/platform';\nimport { isEncryptedSecret } from '@selvajs/platform/computeServer';\nimport { isLinkLocalUrl } from './safe-url.js';\nimport { apiError, ApiErrorCode } from '../api/errors.js';\n\n/**\n * A stored `serverUrl` is fetched server-side on every status probe, every\n * purge/shutdown action, and every solve, so an unfiltered one is an SSRF\n * primitive handed to whoever holds `manage_compute`. Two rules:\n *\n * - Scheme allowlist: `http`/`https`. `file:`, `gopher:` and friends are never\n * a Rhino.Compute endpoint.\n * - Link-local (`169.254.0.0/16`) is refused. That range carries the cloud\n * metadata service at `169.254.169.254`, which hands out the host's own IAM\n * credentials to anything running on the box.\n *\n * **Loopback and RFC1918 are deliberately allowed.** Running compute on\n * `localhost:6500` or a LAN box is the ordinary self-hosted layout, not an\n * attack — most deployments reach their compute server over exactly those\n * addresses. Blocking them by default would break those instances on upgrade\n * and push every operator toward an opt-out flag, and a guard that everyone\n * disables protects nobody. So the check is narrowed to the range where no\n * legitimate compute server ever lives.\n *\n * What this does not stop: a privileged admin pointing the app at an internal\n * host to probe it. That is a real but much weaker concern than credential\n * theft, it needs `manage_compute` already, and it is inseparable from the\n * legitimate case. Revisit if `manage_org_compute` is ever delegated widely on\n * a multi-tenant instance.\n *\n * `isLinkLocalUrl` is reused rather than hand-rolled because a string compare\n * against `169.254.169.254` misses the encodings that reach the same address:\n * `http://2852039166/`, `http://0xa9fea9fe/`, `http://0251.0376.0251.0376/`.\n */\nfunction assertUsableServerUrl(serverUrl: string): void {\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(serverUrl);\n\t} catch {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Invalid serverUrl: ${serverUrl}`);\n\t}\n\tif (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `serverUrl must use http or https: ${serverUrl}`);\n\t}\n\tif (isLinkLocalUrl(serverUrl)) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`serverUrl points at the link-local range, which carries the cloud metadata service: ${serverUrl}`\n\t\t);\n\t}\n}\n\n/** The fields every incoming server carries, whatever its scope. */\nexport interface IncomingServerBase {\n\tid: string;\n\tlabel: string;\n\tserverUrl: string;\n\t/**\n\t * `undefined` → preserve the stored key; `null` → clear it;\n\t * non-empty string → replace it. See {@link resolveApiKey}.\n\t */\n\tapiKey?: string | null;\n}\n\n/**\n * Validates the scope-independent fields of every submitted server. Throws the\n * first failure as a 400; scope-specific fields (`sharedWith`, `ownerOrgId`)\n * are the caller's business.\n */\nexport function validateIncomingServers(servers: readonly IncomingServerBase[]): void {\n\tconst seen = new Set<string>();\n\tfor (const s of servers) {\n\t\tif (!s.id || typeof s.id !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs an id');\n\t\tif (!GuidSchema.safeParse(s.id).success)\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Server id must be a UUID: ${s.id}`);\n\t\tif (seen.has(s.id))\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Server id appears more than once: ${s.id}`);\n\t\tseen.add(s.id);\n\t\tif (!s.label || typeof s.label !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs a label');\n\t\tif (!s.serverUrl || typeof s.serverUrl !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'Each server needs a serverUrl');\n\t\tassertUsableServerUrl(s.serverUrl);\n\t\tif (s.apiKey !== undefined && s.apiKey !== null && typeof s.apiKey !== 'string')\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'apiKey must be a string, null, or omitted');\n\t\t// Clients never receive stored keys, so an envelope here is someone else's\n\t\t// ciphertext being replayed against a URL they control.\n\t\tif (s.apiKey && isEncryptedSecret(s.apiKey))\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'apiKey must be a plaintext key');\n\t}\n}\n\n/**\n * A key the store could not open reads as `hasApiKey` with no `apiKey`. Saving with\n * the field omitted would write `undefined` over it, destroying the key the logs\n * tell the operator how to recover. Replacing or clearing it is a decision, so\n * those pass.\n */\nexport function assertStoredKeysReadable(\n\tincoming: readonly Pick<IncomingServerBase, 'id' | 'apiKey'>[],\n\tstored: readonly { id: string; apiKey?: string; hasApiKey?: boolean }[]\n): void {\n\tconst unreadable = new Set(stored.filter((s) => s.hasApiKey && !s.apiKey).map((s) => s.id));\n\tfor (const s of incoming) {\n\t\tif (unreadable.has(s.id) && (s.apiKey === undefined || s.apiKey === '')) {\n\t\t\tapiError(\n\t\t\t\t409,\n\t\t\t\tApiErrorCode.CONFLICT,\n\t\t\t\t`The stored key for server ${s.id} cannot be read. Re-enter the key, or see the server log for how to recover it.`\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * An omitted key is kept, so without this check anyone who may save the config\n * could point a server at their own host and have the next solve send them the\n * stored key, which they never saw. Moving a server needs the key re-entered or\n * cleared.\n */\nexport function assertKeyNotRetargeted(\n\tincoming: readonly Pick<IncomingServerBase, 'id' | 'serverUrl' | 'apiKey'>[],\n\tstored: readonly { id: string; serverUrl: string; apiKey?: string; hasApiKey?: boolean }[]\n): void {\n\tconst byId = new Map(stored.map((s) => [s.id, s]));\n\tfor (const s of incoming) {\n\t\tconst prev = byId.get(s.id);\n\t\tif (!prev || !(prev.hasApiKey || prev.apiKey)) continue;\n\t\tif (s.apiKey === null || (typeof s.apiKey === 'string' && s.apiKey !== '')) continue;\n\t\tif (sameServerUrl(prev.serverUrl, s.serverUrl)) continue;\n\t\tapiError(\n\t\t\t409,\n\t\t\tApiErrorCode.CONFLICT,\n\t\t\t`Server ${s.id} has a new URL. Re-enter its API key, or clear it, to save.`\n\t\t);\n\t}\n}\n\nfunction sameServerUrl(a: string, b: string): boolean {\n\tconst normalize = (u: string) => {\n\t\ttry {\n\t\t\treturn trimTrailing(new URL(u.trim()).href, '/');\n\t\t} catch {\n\t\t\treturn trimTrailing(u.trim(), '/');\n\t\t}\n\t};\n\treturn normalize(a) === normalize(b);\n}\n\n/**\n * The UI never receives stored keys — it sends back `hasApiKey` and omits the\n * field for servers the operator didn't touch. So \"omitted\" cannot mean \"clear\":\n * it has to preserve, or every save through the settings form would wipe the\n * keys of every server the operator left alone. Clearing is explicit (`null`);\n * an empty string is treated as \"not provided\" since that's what an untouched\n * password input submits.\n */\nexport function resolveApiKey(\n\tsubmitted: string | null | undefined,\n\tstoredKey: string | undefined\n): string | undefined {\n\tif (submitted === null) return undefined;\n\treturn submitted ? submitted : storedKey;\n}\n\n/**\n * Builds the id → stored-key lookup the merge reads. The caller passes only the\n * servers in its own scope, so one scope's write can never resolve a key from\n * another's rows.\n */\nexport function storedKeysById(\n\tscopedServers: readonly { id: string; apiKey?: string }[]\n): Map<string, string | undefined> {\n\treturn new Map(scopedServers.map((s) => [s.id, s.apiKey]));\n}\n\n/**\n * The whole apiKey merge for one scope's write: refuses an unreadable or\n * retargeted key with 409, then returns the key to store for each submitted id.\n * `scopedStored` must be read with `includeApiKeys` and hold only the caller's\n * scope.\n */\nexport function mergeApiKeys(\n\tincoming: readonly Pick<IncomingServerBase, 'id' | 'serverUrl' | 'apiKey'>[],\n\tscopedStored: readonly { id: string; serverUrl: string; apiKey?: string; hasApiKey?: boolean }[]\n): Map<string, string | undefined> {\n\tassertStoredKeysReadable(incoming, scopedStored);\n\tassertKeyNotRetargeted(incoming, scopedStored);\n\tconst stored = storedKeysById(scopedStored);\n\treturn new Map(incoming.map((s) => [s.id, resolveApiKey(s.apiKey, stored.get(s.id))]));\n}\n"],"mappings":";;;;;;;;;;AAsBA,SAAgB,oBACf,MACA,MACA,OACO;CACP,MAAM,WAAW,IAAI,IAAI,KAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;CAGnD,KAAK,MAAM,UAAU,MACpB,IAAI,CAAC,SAAS,IAAI,OAAO,EAAE,GAAG,MAAM,OAAO,EAAE;CAI9C,MAAM,WAAW,IAAI,IAAI,KAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;CACnD,KAAK,MAAM,SAAS,MAAM;EACzB,MAAM,SAAS,SAAS,IAAI,MAAM,EAAE;EACpC,IAAI,WAAW,OAAO,cAAc,MAAM,aAAa,OAAO,WAAW,MAAM,SAC9E,MAAM,MAAM,EAAE;CAEhB;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACOA,SAAS,sBAAsB,WAAyB;CACvD,IAAI;CACJ,IAAI;EACH,SAAS,IAAI,IAAI,SAAS;CAC3B,QAAQ;EACP,SAAS,KAAK,aAAa,mBAAmB,sBAAsB,WAAW;CAChF;CACA,IAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UACtD,SAAS,KAAK,aAAa,mBAAmB,qCAAqC,WAAW;CAE/F,IAAI,eAAe,SAA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|
};
|
|
64
|
+
if (exitCode === 10 || has(logs, "DATA_FORMAT:")) {
|
|
65
|
+
const target = firstMatch(logs, /reads data format (\d+),/);
|
|
66
|
+
const installed = firstMatch(logs, /this deployment is on format (\d+)\./);
|
|
67
|
+
return {
|
|
68
|
+
severity: "warning",
|
|
69
|
+
title: `Update cancelled — ${to ?? "the target version"} cannot read this deployment's data. The app is untouched.`,
|
|
70
|
+
detail: (target && installed ? `It reads data format ${target}; this deployment is on format ${installed}. ` : "") + "Installing it would leave stored data, such as Compute API keys, unreadable. Switch the release channel back to stay on the installed version. To go back anyway, follow \"Going back to an older release\" in the admin guide.",
|
|
71
|
+
from,
|
|
72
|
+
to
|
|
73
|
+
};
|
|
74
|
+
}
|
|
64
75
|
if (exitCode === 8 || has(logs, "PM2_SKEW")) {
|
|
65
76
|
const daemon = firstMatch(logs, /daemon \(v(\d+\.\d+\.\d+)\)/);
|
|
66
77
|
const local = firstMatch(logs, /deployment's pm2 \(v(\d+\.\d+\.\d+)\)/);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"update-outcome.js","names":[],"sources":["../../../src/lib/update-outcome.ts"],"sourcesContent":["// ============================================================================\n// Update-outcome derivation\n// ============================================================================\n//\n// The update runner (admin/api/system/update/+server.ts) emits structured log\n// lines and a small set of meaningful exit codes; `deriveOutcome` turns those\n// into a severity an operator can act on without reading the log. Ranking:\n// anything that leaves the app DOWN is `critical`; a safe rollback is\n// `warning`, not an error, because the site is still serving.\n\nexport type OutcomeSeverity = 'success' | 'info' | 'warning' | 'critical' | 'pending';\n\n/**\n * Synthetic exit code for a run that never reported one — the SSE handler's\n * 15-minute group-kill, or the reconciler giving up on a missing [EXIT] marker.\n * Outside the 0-255 range a real process can produce, so it can't collide.\n */\nexport const TIMED_OUT = -2;\n\nexport interface UpdateOutcome {\n\tseverity: OutcomeSeverity;\n\t/** Must be unambiguous about app up/down state. */\n\ttitle: string;\n\t/** What to do next when something is off. */\n\tdetail?: string;\n\tfrom?: string;\n\tto?: string;\n}\n\nfunction firstMatch(logs: string, re: RegExp): string | undefined {\n\tconst m = re.exec(logs);\n\treturn m ? m[1] : undefined;\n}\n\nfunction parseVersions(logs: string): { from?: string; to?: string } {\n\t// Pre-flight transition line, printed before npm runs — the only source of a\n\t// target version when the update fails early or is a no-op, e.g.\n\t// \"[INFO] Target (beta): 4.2.0 → 4.2.1-beta.1\". `Available:` is the\n\t// pre-channel spelling, kept so logs from an older runner still parse.\n\tconst version = String.raw`\\d+\\.\\d+\\.\\d+[^\\s]*`;\n\tconst transition = new RegExp(\n\t\tString.raw`(?:Target \\([^)]*\\)|Available):\\s*(${version})\\s*(?:→|->)\\s*(${version})`\n\t);\n\tconst arrow = transition.exec(logs);\n\n\t// The post-install lines are authoritative for what actually landed — prefer\n\t// them over the pre-flight target, which is only ever an intent.\n\tconst from = firstMatch(logs, /Current @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[1];\n\tconst to = firstMatch(logs, /New @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[2];\n\treturn { from, to };\n}\n\nfunction has(logs: string, needle: string): boolean {\n\treturn logs.includes(needle);\n}\n\nexport function deriveOutcome(exitCode: number | null, logs: string): UpdateOutcome {\n\tconst { from, to } = parseVersions(logs);\n\n\tif (exitCode === null) {\n\t\treturn { severity: 'pending', title: 'Update in progress…' };\n\t}\n\n\t// --- Critical: app is or may be DOWN. Rank these first. -------------------\n\tif (\n\t\texitCode === 6 ||\n\t\thas(logs, 'Manual recovery required') ||\n\t\thas(logs, 'manual intervention required')\n\t) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed AND rollback failed — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'Both the new version and the rollback failed their health check. ' +\n\t\t\t\t'SSH into the server and run: `pm2 logs selva-compute`, then ' +\n\t\t\t\t'`pm2 start ecosystem.config.cjs` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The SSE handler's 15-minute group-kill, and the reconciler's own poll cap.\n\t// Neither is an exit code the runner chose, so they carry no [EXIT] marker.\n\tif (exitCode === TIMED_OUT) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'App did not come back online within 15 minutes',\n\t\t\tdetail:\n\t\t\t\t'The update may still be finishing in the background, or the new ' +\n\t\t\t\t'process is crash-looping. Check `pm2 logs selva-compute`. Do not ' +\n\t\t\t\t're-run the update until you have confirmed the current state.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 4: the rollback's own npm install failed, so node_modules is\n\t// half-written and the EXIT trap's restart is the only thing that may have\n\t// brought the app back. Same urgency as a failed rollback restart.\n\tif (exitCode === 4) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed and the rollback could not reinstall — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'The previous version could not be restored from npm. SSH into the ' +\n\t\t\t\t'server and run `pm2 logs selva-compute`; if the app is down, reinstall ' +\n\t\t\t\t'explicitly with `npm install --prefer-online @selvajs/cli@<version> ' +\n\t\t\t\t'@selvajs/selva@<version>` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 3: unhealthy with no recorded prior version, so no rollback was even\n\t// attempted. The EXIT trap tried to restart whatever is on disk.\n\tif (exitCode === 3) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed its health check and could not be rolled back automatically',\n\t\t\tdetail:\n\t\t\t\t'No prior version was recorded, so the previous build could not be ' +\n\t\t\t\t'restored. Check `pm2 logs selva-compute` to confirm whether the app ' +\n\t\t\t\t'came back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// Killed mid-run (128+signal). Nothing was installed, and whether the app\n\t// came back depends on how far the EXIT trap got before it died too. Rank\n\t// with the criticals: an unattended half-update is worse than a clean\n\t// failure.\n\tif (exitCode === 143 || exitCode === 130 || exitCode === 129 || has(logs, 'KILLED')) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update was killed before it finished — nothing was installed',\n\t\t\tdetail:\n\t\t\t\t'The runner was terminated mid-update, most often by a systemd-supervised ' +\n\t\t\t\t'PM2 restarting its whole control group. The version on disk is unchanged. ' +\n\t\t\t\t'Check `pm2 logs selva-compute` and confirm the app is online before retrying; ' +\n\t\t\t\t'if a global pm2 owns the daemon, reconcile that first.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Warning: update did not fully succeed, but the app IS up. ------------\n\t// Aborted at the systemd guard, before `pm2 update` could recycle the\n\t// daemon and take this runner down with it.\n\tif (exitCode === 9 || has(logs, 'SYSTEMD_PM2')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\t'Update cancelled — PM2 needs a resync that only a shell can do safely. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t\"This deployment's PM2 runs under systemd, where `pm2 update` restarts the \" +\n\t\t\t\t'unit and kills the update mid-run. Nothing was installed and the app is ' +\n\t\t\t\t'still serving. SSH in and run `./node_modules/.bin/pm2 update` from the ' +\n\t\t\t\t'deployment directory, then retry the update here.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted at the pm2 skew check, before anything was stopped — nothing was\n\t// installed and the app never went down.\n\tif (exitCode === 8 || has(logs, 'PM2_SKEW')) {\n\t\tconst daemon = firstMatch(logs, /daemon \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\tconst local = firstMatch(logs, /deployment's pm2 \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\tdaemon && local\n\t\t\t\t\t? `Update cancelled — a global PM2 (v${daemon}) owns the daemon, not this deployment's (v${local}). The app is untouched.`\n\t\t\t\t\t: 'Update cancelled — a conflicting global PM2 owns the daemon. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t'Resyncing would have downgraded the daemon and dropped its process ' +\n\t\t\t\t'table, so the update stopped before taking the app down. On the server: ' +\n\t\t\t\t'`which -a pm2`, `pm2 -v`, `pm2 ping` — remove or align the global pm2, then retry.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// A rollback whose cause is the DATABASE, not the release. Ranked ahead of\n\t// the generic rollback case: \"review the log before retrying\" is actively\n\t// misleading here, because the log holds nothing about the new version —\n\t// it is fine, and retrying without touching the database repeats verbatim.\n\tif (has(logs, 'SCHEMA_SKEW')) {\n\t\tconst expected = firstMatch(logs, /expects database migration head (\\S+?),/);\n\t\tconst actual = firstMatch(logs, /this database is at (\\S+?)\\./);\n\t\tconst skew =\n\t\t\texpected && actual ? ` The database is at ${actual}; ${to ?? 'it'} needs ${expected}.` : '';\n\t\t// `latest` is the stable line, which ships none of a beta's migrations.\n\t\tconst providerTag =\n\t\t\tfirstMatch(logs, /@selvajs\\/supabase-provider@([\\w.-]+)/) ??\n\t\t\t(has(logs, 'channel: beta') ? 'beta' : 'latest');\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — the database migrations for ${to ?? 'the new version'} have not been applied.${skew} The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'Nothing is wrong with the new version. Selva does not apply migrations ' +\n\t\t\t\t'during an update, because they cannot be rolled back — auto-migrating ' +\n\t\t\t\t'and then rolling the code back would leave the app and database on ' +\n\t\t\t\t'different heads. Apply them on the server, then re-run this update: ' +\n\t\t\t\t`\\`npm install --prefer-online @selvajs/supabase-provider@${providerTag}\\`, then ` +\n\t\t\t\t'`npx selva-supabase`, then `npx supabase db push`. The provider install ' +\n\t\t\t\t'is not optional — the migration SQL ships inside that package, and the ' +\n\t\t\t\t'update only moves @selvajs/cli and @selvajs/selva, so a sync without it ' +\n\t\t\t\t'copies nothing and the push reports \"up to date\" having done nothing. ' +\n\t\t\t\t'Retrying without this will fail in exactly the same way.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Same shape: the rollback was caused by host configuration, not the release.\n\tif (has(logs, 'AT_REST_SECRETS')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — stored compute server keys do not decrypt under this host's SELVA_AT_REST_KEY. The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'This is a configuration problem on the server, not a fault in the new ' +\n\t\t\t\t'version, so retrying alone will fail identically. Re-enter the affected ' +\n\t\t\t\t'keys at /admin/compute, or restore the SELVA_AT_REST_KEY the values were ' +\n\t\t\t\t'encrypted with, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (exitCode === 5 || has(logs, 'Rolled back')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update failed — safely rolled back${from ? ` to ${from}` : ''}. The app is online.`,\n\t\t\tdetail:\n\t\t\t\t'The new version failed its health check, so the previous version ' +\n\t\t\t\t'was restored and is serving normally. Review the log below for why ' +\n\t\t\t\t'the new version failed before retrying.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The install completed and the app is up, but on a Node the release doesn't\n\t// support. The health probe passes (it exercises nothing version-specific),\n\t// so this would otherwise read as a clean success right up until a real\n\t// request hits a newer API and throws (issue #176).\n\tif (has(logs, 'ENGINE_MISMATCH') || has(logs, 'EBADENGINE')) {\n\t\tconst required = firstMatch(logs, /requires Node ([^\\s]+(?:\\s*[<>=]+\\s*[\\d.]+)*)/);\n\t\tconst running = firstMatch(logs, /this host runs v?(\\d+\\.\\d+\\.\\d+)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: running\n\t\t\t\t? `Updated${to ? ` to ${to}` : ''}, but this release needs Node ${required ?? '(newer)'} — the host runs v${running}. Expect runtime failures.`\n\t\t\t\t: `Updated${to ? ` to ${to}` : ''}, but this release requires a newer Node than the host provides. Expect runtime failures.`,\n\t\t\tdetail:\n\t\t\t\t'npm installed it anyway (engine-strict is off) and the health check ' +\n\t\t\t\t'passed, but it does not exercise the newer APIs — routes that do will ' +\n\t\t\t\t'throw at request time. Upgrade Node on the server, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The runner moved pm2 to the release's pin but could not swap the daemon\n\t// (refused under systemd, or `pm2 update` failed). The app runs; the next\n\t// pm2 command warns about the skew until someone runs the swap by hand.\n\tif (has(logs, 'PM2_RESYNC_NEEDED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but the pm2 daemon still runs the old pm2.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online. On the server, run `npx pm2 update` in the deployment ' +\n\t\t\t\t'directory, let it finish, then check `npx pm2 list` shows selva-compute online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'PM2_PIN_FAILED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but pm2 stayed on the previous version.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online on the old pm2. On the server, run `npx selva migrate` in ' +\n\t\t\t\t'the deployment directory to move it to the pinned version.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'npm cache may be stale') || has(logs, 'No version change')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: 'No version change — npm installed the same version.',\n\t\t\tdetail:\n\t\t\t\t'Your npm cache may be stale. On the server: `npm cache clean --force`, ' +\n\t\t\t\t'remove node_modules + package-lock.json, then `npm install --prefer-online`.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Success variants -----------------------------------------------------\n\tif (exitCode === 0) {\n\t\t// \"Already on the 'beta' channel version (4.2.0)\" — the channel name is\n\t\t// interpolated, so match the stable prefix rather than a whole line.\n\t\tif (has(logs, 'Already on the') || has(logs, 'Nothing to do')) {\n\t\t\treturn {\n\t\t\t\tseverity: 'info',\n\t\t\t\ttitle: `Already up to date${from ? ` (${from})` : ''} — nothing to install.`,\n\t\t\t\tdetail: 'No changes were made and the app was not restarted.',\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (from && to && from !== to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Updated ${from} → ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Update complete — now on ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tseverity: 'success',\n\t\t\ttitle: 'Update completed and the app is back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Anything else: a non-zero exit we don't have a named case for. -------\n\t// Be explicit that we couldn't classify it rather than implying success.\n\treturn {\n\t\tseverity: 'critical',\n\t\ttitle: `Update failed (exit code ${exitCode}).`,\n\t\tdetail:\n\t\t\t'The update did not complete cleanly. Review the log below, and check ' +\n\t\t\t'`pm2 logs selva-compute` to confirm whether the app is currently online.',\n\t\tfrom,\n\t\tto\n\t};\n}\n"],"mappings":"AA6BA,SAAS,WAAW,MAAc,IAAgC;CACjE,MAAM,IAAI,GAAG,KAAK,IAAI;CACtB,OAAO,IAAI,EAAE,KAAK,KAAA;AACnB;AAEA,SAAS,cAAc,MAA8C;CAKpE,MAAM,UAAU,OAAO,GAAG;CAI1B,MAAM,QAAQ,IAHS,OACtB,OAAO,GAAG,sCAAsC,QAAQ,kBAAkB,QAAQ,EAErE,CAAA,CAAW,KAAK,IAAI;CAMlC,OAAO;EAAE,MAFI,WAAW,MAAM,oDAAoD,KAAK,QA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GAAG;EAGnB,IAAI,IAAI,MAAM,gBAAgB,KAAK,IAAI,MAAM,eAAe,GAC3D,OAAO;GACN,UAAU;GACV,OAAO,qBAAqB,OAAO,KAAK,KAAK,KAAK,GAAG;GACrD,QAAQ;GACR;GACA;EACD;EAED,IAAI,QAAQ,MAAM,SAAS,IAC1B,OAAO;GACN,UAAU;GACV,OAAO,WAAW,KAAK,KAAK,GAAG;GAC/B;GACA;EACD;EAED,IAAI,IACH,OAAO;GACN,UAAU;GACV,OAAO,4BAA4B,GAAG;GACtC;GACA;EACD;EAED,OAAO;GACN,UAAU;GACV,OAAO;GACP;GACA;EACD;CACD;CAIA,OAAO;EACN,UAAU;EACV,OAAO,4BAA4B,SAAS;EAC5C,QACC;EAED;EACA;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"update-outcome.js","names":[],"sources":["../../../src/lib/update-outcome.ts"],"sourcesContent":["// ============================================================================\n// Update-outcome derivation\n// ============================================================================\n//\n// The update runner (admin/api/system/update/+server.ts) emits structured log\n// lines and a small set of meaningful exit codes; `deriveOutcome` turns those\n// into a severity an operator can act on without reading the log. Ranking:\n// anything that leaves the app DOWN is `critical`; a safe rollback is\n// `warning`, not an error, because the site is still serving.\n\nexport type OutcomeSeverity = 'success' | 'info' | 'warning' | 'critical' | 'pending';\n\n/**\n * Synthetic exit code for a run that never reported one — the SSE handler's\n * 15-minute group-kill, or the reconciler giving up on a missing [EXIT] marker.\n * Outside the 0-255 range a real process can produce, so it can't collide.\n */\nexport const TIMED_OUT = -2;\n\nexport interface UpdateOutcome {\n\tseverity: OutcomeSeverity;\n\t/** Must be unambiguous about app up/down state. */\n\ttitle: string;\n\t/** What to do next when something is off. */\n\tdetail?: string;\n\tfrom?: string;\n\tto?: string;\n}\n\nfunction firstMatch(logs: string, re: RegExp): string | undefined {\n\tconst m = re.exec(logs);\n\treturn m ? m[1] : undefined;\n}\n\nfunction parseVersions(logs: string): { from?: string; to?: string } {\n\t// Pre-flight transition line, printed before npm runs — the only source of a\n\t// target version when the update fails early or is a no-op, e.g.\n\t// \"[INFO] Target (beta): 4.2.0 → 4.2.1-beta.1\". `Available:` is the\n\t// pre-channel spelling, kept so logs from an older runner still parse.\n\tconst version = String.raw`\\d+\\.\\d+\\.\\d+[^\\s]*`;\n\tconst transition = new RegExp(\n\t\tString.raw`(?:Target \\([^)]*\\)|Available):\\s*(${version})\\s*(?:→|->)\\s*(${version})`\n\t);\n\tconst arrow = transition.exec(logs);\n\n\t// The post-install lines are authoritative for what actually landed — prefer\n\t// them over the pre-flight target, which is only ever an intent.\n\tconst from = firstMatch(logs, /Current @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[1];\n\tconst to = firstMatch(logs, /New @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[2];\n\treturn { from, to };\n}\n\nfunction has(logs: string, needle: string): boolean {\n\treturn logs.includes(needle);\n}\n\nexport function deriveOutcome(exitCode: number | null, logs: string): UpdateOutcome {\n\tconst { from, to } = parseVersions(logs);\n\n\tif (exitCode === null) {\n\t\treturn { severity: 'pending', title: 'Update in progress…' };\n\t}\n\n\t// --- Critical: app is or may be DOWN. Rank these first. -------------------\n\tif (\n\t\texitCode === 6 ||\n\t\thas(logs, 'Manual recovery required') ||\n\t\thas(logs, 'manual intervention required')\n\t) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed AND rollback failed — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'Both the new version and the rollback failed their health check. ' +\n\t\t\t\t'SSH into the server and run: `pm2 logs selva-compute`, then ' +\n\t\t\t\t'`pm2 start ecosystem.config.cjs` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The SSE handler's 15-minute group-kill, and the reconciler's own poll cap.\n\t// Neither is an exit code the runner chose, so they carry no [EXIT] marker.\n\tif (exitCode === TIMED_OUT) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'App did not come back online within 15 minutes',\n\t\t\tdetail:\n\t\t\t\t'The update may still be finishing in the background, or the new ' +\n\t\t\t\t'process is crash-looping. Check `pm2 logs selva-compute`. Do not ' +\n\t\t\t\t're-run the update until you have confirmed the current state.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 4: the rollback's own npm install failed, so node_modules is\n\t// half-written and the EXIT trap's restart is the only thing that may have\n\t// brought the app back. Same urgency as a failed rollback restart.\n\tif (exitCode === 4) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed and the rollback could not reinstall — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'The previous version could not be restored from npm. SSH into the ' +\n\t\t\t\t'server and run `pm2 logs selva-compute`; if the app is down, reinstall ' +\n\t\t\t\t'explicitly with `npm install --prefer-online @selvajs/cli@<version> ' +\n\t\t\t\t'@selvajs/selva@<version>` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 3: unhealthy with no recorded prior version, so no rollback was even\n\t// attempted. The EXIT trap tried to restart whatever is on disk.\n\tif (exitCode === 3) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed its health check and could not be rolled back automatically',\n\t\t\tdetail:\n\t\t\t\t'No prior version was recorded, so the previous build could not be ' +\n\t\t\t\t'restored. Check `pm2 logs selva-compute` to confirm whether the app ' +\n\t\t\t\t'came back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// Killed mid-run (128+signal). Nothing was installed, and whether the app\n\t// came back depends on how far the EXIT trap got before it died too. Rank\n\t// with the criticals: an unattended half-update is worse than a clean\n\t// failure.\n\tif (exitCode === 143 || exitCode === 130 || exitCode === 129 || has(logs, 'KILLED')) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update was killed before it finished — nothing was installed',\n\t\t\tdetail:\n\t\t\t\t'The runner was terminated mid-update, most often by a systemd-supervised ' +\n\t\t\t\t'PM2 restarting its whole control group. The version on disk is unchanged. ' +\n\t\t\t\t'Check `pm2 logs selva-compute` and confirm the app is online before retrying; ' +\n\t\t\t\t'if a global pm2 owns the daemon, reconcile that first.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Warning: update did not fully succeed, but the app IS up. ------------\n\t// Aborted at the systemd guard, before `pm2 update` could recycle the\n\t// daemon and take this runner down with it.\n\tif (exitCode === 9 || has(logs, 'SYSTEMD_PM2')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\t'Update cancelled — PM2 needs a resync that only a shell can do safely. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t\"This deployment's PM2 runs under systemd, where `pm2 update` restarts the \" +\n\t\t\t\t'unit and kills the update mid-run. Nothing was installed and the app is ' +\n\t\t\t\t'still serving. SSH in and run `./node_modules/.bin/pm2 update` from the ' +\n\t\t\t\t'deployment directory, then retry the update here.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted at the data format check, before anything was stopped.\n\tif (exitCode === 10 || has(logs, 'DATA_FORMAT:')) {\n\t\tconst target = firstMatch(logs, /reads data format (\\d+),/);\n\t\tconst installed = firstMatch(logs, /this deployment is on format (\\d+)\\./);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update cancelled — ${to ?? 'the target version'} cannot read this deployment's data. The app is untouched.`,\n\t\t\tdetail:\n\t\t\t\t(target && installed\n\t\t\t\t\t? `It reads data format ${target}; this deployment is on format ${installed}. `\n\t\t\t\t\t: '') +\n\t\t\t\t'Installing it would leave stored data, such as Compute API keys, unreadable. ' +\n\t\t\t\t'Switch the release channel back to stay on the installed version. To go back ' +\n\t\t\t\t'anyway, follow \"Going back to an older release\" in the admin guide.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted at the pm2 skew check, before anything was stopped — nothing was\n\t// installed and the app never went down.\n\tif (exitCode === 8 || has(logs, 'PM2_SKEW')) {\n\t\tconst daemon = firstMatch(logs, /daemon \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\tconst local = firstMatch(logs, /deployment's pm2 \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\tdaemon && local\n\t\t\t\t\t? `Update cancelled — a global PM2 (v${daemon}) owns the daemon, not this deployment's (v${local}). The app is untouched.`\n\t\t\t\t\t: 'Update cancelled — a conflicting global PM2 owns the daemon. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t'Resyncing would have downgraded the daemon and dropped its process ' +\n\t\t\t\t'table, so the update stopped before taking the app down. On the server: ' +\n\t\t\t\t'`which -a pm2`, `pm2 -v`, `pm2 ping` — remove or align the global pm2, then retry.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// A rollback whose cause is the DATABASE, not the release. Ranked ahead of\n\t// the generic rollback case: \"review the log before retrying\" is actively\n\t// misleading here, because the log holds nothing about the new version —\n\t// it is fine, and retrying without touching the database repeats verbatim.\n\tif (has(logs, 'SCHEMA_SKEW')) {\n\t\tconst expected = firstMatch(logs, /expects database migration head (\\S+?),/);\n\t\tconst actual = firstMatch(logs, /this database is at (\\S+?)\\./);\n\t\tconst skew =\n\t\t\texpected && actual ? ` The database is at ${actual}; ${to ?? 'it'} needs ${expected}.` : '';\n\t\t// `latest` is the stable line, which ships none of a beta's migrations.\n\t\tconst providerTag =\n\t\t\tfirstMatch(logs, /@selvajs\\/supabase-provider@([\\w.-]+)/) ??\n\t\t\t(has(logs, 'channel: beta') ? 'beta' : 'latest');\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — the database migrations for ${to ?? 'the new version'} have not been applied.${skew} The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'Nothing is wrong with the new version. Selva does not apply migrations ' +\n\t\t\t\t'during an update, because they cannot be rolled back — auto-migrating ' +\n\t\t\t\t'and then rolling the code back would leave the app and database on ' +\n\t\t\t\t'different heads. Apply them on the server, then re-run this update: ' +\n\t\t\t\t`\\`npm install --prefer-online @selvajs/supabase-provider@${providerTag}\\`, then ` +\n\t\t\t\t'`npx selva-supabase`, then `npx supabase db push`. The provider install ' +\n\t\t\t\t'is not optional — the migration SQL ships inside that package, and the ' +\n\t\t\t\t'update only moves @selvajs/cli and @selvajs/selva, so a sync without it ' +\n\t\t\t\t'copies nothing and the push reports \"up to date\" having done nothing. ' +\n\t\t\t\t'Retrying without this will fail in exactly the same way.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Same shape: the rollback was caused by host configuration, not the release.\n\tif (has(logs, 'AT_REST_SECRETS')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — stored compute server keys do not decrypt under this host's SELVA_AT_REST_KEY. The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'This is a configuration problem on the server, not a fault in the new ' +\n\t\t\t\t'version, so retrying alone will fail identically. Re-enter the affected ' +\n\t\t\t\t'keys at /admin/compute, or restore the SELVA_AT_REST_KEY the values were ' +\n\t\t\t\t'encrypted with, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (exitCode === 5 || has(logs, 'Rolled back')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update failed — safely rolled back${from ? ` to ${from}` : ''}. The app is online.`,\n\t\t\tdetail:\n\t\t\t\t'The new version failed its health check, so the previous version ' +\n\t\t\t\t'was restored and is serving normally. Review the log below for why ' +\n\t\t\t\t'the new version failed before retrying.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The install completed and the app is up, but on a Node the release doesn't\n\t// support. The health probe passes (it exercises nothing version-specific),\n\t// so this would otherwise read as a clean success right up until a real\n\t// request hits a newer API and throws (issue #176).\n\tif (has(logs, 'ENGINE_MISMATCH') || has(logs, 'EBADENGINE')) {\n\t\tconst required = firstMatch(logs, /requires Node ([^\\s]+(?:\\s*[<>=]+\\s*[\\d.]+)*)/);\n\t\tconst running = firstMatch(logs, /this host runs v?(\\d+\\.\\d+\\.\\d+)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: running\n\t\t\t\t? `Updated${to ? ` to ${to}` : ''}, but this release needs Node ${required ?? '(newer)'} — the host runs v${running}. Expect runtime failures.`\n\t\t\t\t: `Updated${to ? ` to ${to}` : ''}, but this release requires a newer Node than the host provides. Expect runtime failures.`,\n\t\t\tdetail:\n\t\t\t\t'npm installed it anyway (engine-strict is off) and the health check ' +\n\t\t\t\t'passed, but it does not exercise the newer APIs — routes that do will ' +\n\t\t\t\t'throw at request time. Upgrade Node on the server, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The runner moved pm2 to the release's pin but could not swap the daemon\n\t// (refused under systemd, or `pm2 update` failed). The app runs; the next\n\t// pm2 command warns about the skew until someone runs the swap by hand.\n\tif (has(logs, 'PM2_RESYNC_NEEDED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but the pm2 daemon still runs the old pm2.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online. On the server, run `npx pm2 update` in the deployment ' +\n\t\t\t\t'directory, let it finish, then check `npx pm2 list` shows selva-compute online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'PM2_PIN_FAILED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but pm2 stayed on the previous version.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online on the old pm2. On the server, run `npx selva migrate` in ' +\n\t\t\t\t'the deployment directory to move it to the pinned version.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'npm cache may be stale') || has(logs, 'No version change')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: 'No version change — npm installed the same version.',\n\t\t\tdetail:\n\t\t\t\t'Your npm cache may be stale. On the server: `npm cache clean --force`, ' +\n\t\t\t\t'remove node_modules + package-lock.json, then `npm install --prefer-online`.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Success variants -----------------------------------------------------\n\tif (exitCode === 0) {\n\t\t// \"Already on the 'beta' channel version (4.2.0)\" — the channel name is\n\t\t// interpolated, so match the stable prefix rather than a whole line.\n\t\tif (has(logs, 'Already on the') || has(logs, 'Nothing to do')) {\n\t\t\treturn {\n\t\t\t\tseverity: 'info',\n\t\t\t\ttitle: `Already up to date${from ? ` (${from})` : ''} — nothing to install.`,\n\t\t\t\tdetail: 'No changes were made and the app was not restarted.',\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (from && to && from !== to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Updated ${from} → ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Update complete — now on ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tseverity: 'success',\n\t\t\ttitle: 'Update completed and the app is back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Anything else: a non-zero exit we don't have a named case for. -------\n\t// Be explicit that we couldn't classify it rather than implying success.\n\treturn {\n\t\tseverity: 'critical',\n\t\ttitle: `Update failed (exit code ${exitCode}).`,\n\t\tdetail:\n\t\t\t'The update did not complete cleanly. Review the log below, and check ' +\n\t\t\t'`pm2 logs selva-compute` to confirm whether the app is currently online.',\n\t\tfrom,\n\t\tto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,WAAW,WAAW,MAAM,+CAA+C;EACjF,MAAM,UAAU,WAAW,MAAM,kCAAkC;EACnE,OAAO;GACN,UAAU;GACV,OAAO,UACJ,UAAU,KAAK,OAAO,OAAO,GAAG,gCAAgC,YAAY,UAAU,oBAAoB,QAAQ,8BAClH,UAAU,KAAK,OAAO,OAAO,GAAG;GACnC,QACC;GAGD;GACA;EACD;CACD;CAIA,IAAI,IAAI,MAAM,mBAAmB,GAChC,OAAO;EACN,UAAU;EACV,OAAO,UAAU,KAAK,OAAO,OAAO,GAAG;EACvC,QACC;EAED;EACA;CACD;CAED,IAAI,IAAI,MAAM,gBAAgB,GAC7B,OAAO;EACN,UAAU;EACV,OAAO,UAAU,KAAK,OAAO,OAAO,GAAG;EACvC,QACC;EAED;EACA;CACD;CAED,IAAI,IAAI,MAAM,wBAAwB,KAAK,IAAI,MAAM,mBAAmB,GACvE,OAAO;EACN,UAAU;EACV,OAAO;EACP,QACC;EAED;EACA;CACD;CAID,IAAI,aAAa,GAAG;EAGnB,IAAI,IAAI,MAAM,gBAAgB,KAAK,IAAI,MAAM,eAAe,GAC3D,OAAO;GACN,UAAU;GACV,OAAO,qBAAqB,OAAO,KAAK,KAAK,KAAK,GAAG;GACrD,QAAQ;GACR;GACA;EACD;EAED,IAAI,QAAQ,MAAM,SAAS,IAC1B,OAAO;GACN,UAAU;GACV,OAAO,WAAW,KAAK,KAAK,GAAG;GAC/B;GACA;EACD;EAED,IAAI,IACH,OAAO;GACN,UAAU;GACV,OAAO,4BAA4B,GAAG;GACtC;GACA;EACD;EAED,OAAO;GACN,UAAU;GACV,OAAO;GACP;GACA;EACD;CACD;CAIA,OAAO;EACN,UAAU;EACV,OAAO,4BAA4B,SAAS;EAC5C,QACC;EAED;EACA;CACD;AACD"}
|
|
@@ -136,6 +136,12 @@ function writeChannel(channel) {
|
|
|
136
136
|
if (!isChannel(channel)) throw new Error(`Invalid release channel: ${channel}`);
|
|
137
137
|
writeFileSync(channelFilePath(), JSON.stringify({ channel }, null, 2) + "\n", "utf8");
|
|
138
138
|
}
|
|
139
|
+
// src/lib/server/dataFormat.server.ts
|
|
140
|
+
/** The format a published `package.json` declares. None means format 1. */
|
|
141
|
+
function declaredDataFormat(pkg) {
|
|
142
|
+
const value = pkg?.selva?.dataFormat;
|
|
143
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 1 ? value : 1;
|
|
144
|
+
}
|
|
139
145
|
// src/lib/server/updateCheck.server.ts
|
|
140
146
|
function readInstalledVersion() {
|
|
141
147
|
const dirs = [];
|
|
@@ -157,6 +163,11 @@ function readInstalledVersion() {
|
|
|
157
163
|
}
|
|
158
164
|
return null;
|
|
159
165
|
}
|
|
166
|
+
var UNREADABLE = {
|
|
167
|
+
version: null,
|
|
168
|
+
enginesNode: null,
|
|
169
|
+
dataFormat: null
|
|
170
|
+
};
|
|
160
171
|
async function fetchLatestManifest(fetchImpl, channel = "stable") {
|
|
161
172
|
const ctrl = new AbortController();
|
|
162
173
|
const timer = setTimeout(() => ctrl.abort(), 5e3);
|
|
@@ -165,27 +176,23 @@ async function fetchLatestManifest(fetchImpl, channel = "stable") {
|
|
|
165
176
|
headers: { Accept: "application/json" },
|
|
166
177
|
signal: ctrl.signal
|
|
167
178
|
});
|
|
168
|
-
if (!res.ok) return
|
|
169
|
-
version: null,
|
|
170
|
-
enginesNode: null
|
|
171
|
-
};
|
|
179
|
+
if (!res.ok) return UNREADABLE;
|
|
172
180
|
const body = await res.json();
|
|
181
|
+
const version = typeof body.version === "string" ? body.version : null;
|
|
173
182
|
return {
|
|
174
|
-
version
|
|
175
|
-
enginesNode: typeof body.engines?.node === "string" ? body.engines.node : null
|
|
183
|
+
version,
|
|
184
|
+
enginesNode: typeof body.engines?.node === "string" ? body.engines.node : null,
|
|
185
|
+
dataFormat: version ? declaredDataFormat(body) : null
|
|
176
186
|
};
|
|
177
187
|
} catch {
|
|
178
|
-
return
|
|
179
|
-
version: null,
|
|
180
|
-
enginesNode: null
|
|
181
|
-
};
|
|
188
|
+
return UNREADABLE;
|
|
182
189
|
} finally {
|
|
183
190
|
clearTimeout(timer);
|
|
184
191
|
}
|
|
185
192
|
}
|
|
186
193
|
async function checkForUpdate(fetchImpl, channel = "stable", runningNode = process.versions.node) {
|
|
187
194
|
const current = readInstalledVersion();
|
|
188
|
-
const { version: latest, enginesNode } = await fetchLatestManifest(fetchImpl, channel);
|
|
195
|
+
const { version: latest, enginesNode, dataFormat } = await fetchLatestManifest(fetchImpl, channel);
|
|
189
196
|
return {
|
|
190
197
|
channel,
|
|
191
198
|
current,
|
|
@@ -195,6 +202,11 @@ async function checkForUpdate(fetchImpl, channel = "stable", runningNode = proce
|
|
|
195
202
|
compatible: enginesNode ? satisfiesRange(runningNode, enginesNode) : null,
|
|
196
203
|
required: enginesNode,
|
|
197
204
|
running: runningNode
|
|
205
|
+
},
|
|
206
|
+
dataCompatibility: {
|
|
207
|
+
compatible: dataFormat === null ? null : dataFormat >= 2,
|
|
208
|
+
installed: 2,
|
|
209
|
+
target: dataFormat
|
|
198
210
|
}
|
|
199
211
|
};
|
|
200
212
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"updateCheck.server.js","names":[],"sources":["../../../../server/src/ops/semver.ts","../../../src/lib/server/releaseChannel.server.ts","../../../src/lib/server/updateCheck.server.ts"],"sourcesContent":["/**\n * Channel-aware semver comparison for update checks. Understands exactly the\n * two lines Selva publishes under: stable (`x.y.z`, npm `latest`) and beta\n * (`x.y.z-beta.N`, npm `beta`). Deliberately not general semver — no build\n * metadata, no arbitrary pre-release identifiers.\n */\n\n/** Which published line a deployment tracks. */\nexport type ReleaseChannel = 'stable' | 'beta';\n\n/**\n * Parse `x.y.z` plus an optional `-beta.N` counter. `beta` comes back separate\n * from the core so beta-channel comparisons can order successive betas of one\n * core. Null when the string doesn't lead with a numeric core.\n */\nexport function parseSemver(\n\tv: string\n): { core: [number, number, number]; beta: number | null } | null {\n\tconst m = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-beta\\.(\\d+))?/.exec(v.trim());\n\tif (!m) return null;\n\treturn {\n\t\tcore: [Number(m[1]), Number(m[2]), Number(m[3])],\n\t\tbeta: m[4] != null ? Number(m[4]) : null\n\t};\n}\n\n/**\n * Compare two `x.y.z` cores, ignoring pre-release tails. Callers that care\n * about those want `isNewer`, which layers the channel rules on top.\n */\nexport function compareCore(a: string, b: string): number {\n\tconst pa = parseSemver(a);\n\tconst pb = parseSemver(b);\n\tif (!pa || !pb) return 0;\n\tfor (let i = 0; i < 3; i++) {\n\t\tif (pa.core[i] > pb.core[i]) return 1;\n\t\tif (pa.core[i] < pb.core[i]) return -1;\n\t}\n\treturn 0;\n}\n\n/**\n * Does `version` satisfy an `engines.node` range?\n *\n * Deliberately narrow: handles the `>=`, `>`, `<=`, `<`, `^`, `~`, `=` and\n * bare-version forms Selva and its dependencies publish, plus `||` alternatives\n * and space-separated conjunctions (`>=18 <21`). Anything it can't parse\n * returns `null` for \"unknown\", never a false \"incompatible\" — a wrong block\n * would strand an operator with no way to override the bad parse.\n *\n * A full `semver` dependency would subsume this, but isn't warranted for the\n * handful of range forms in play.\n */\nexport function satisfiesRange(version: string, range: string): boolean | null {\n\tconst v = parseSemver(version);\n\tif (!v) return null;\n\n\tconst alternatives = range.split('||').map((r) => r.trim());\n\tlet anyParsed = false;\n\n\tfor (const alt of alternatives) {\n\t\tconst clauses = alt.split(/\\s+/).filter(Boolean);\n\t\tif (clauses.length === 0) continue;\n\n\t\tlet all = true;\n\t\tlet altParsed = true;\n\t\tfor (const clause of clauses) {\n\t\t\tconst m = /^(>=|<=|>|<|\\^|~|=)?\\s*v?(\\d+)(?:\\.(\\d+|x|\\*))?(?:\\.(\\d+|x|\\*))?/.exec(clause);\n\t\t\tif (!m) {\n\t\t\t\taltParsed = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst op = m[1] ?? '=';\n\t\t\tconst num = (s: string | undefined) => (s == null || s === 'x' || s === '*' ? 0 : Number(s));\n\t\t\tconst target: [number, number, number] = [Number(m[2]), num(m[3]), num(m[4])];\n\t\t\tconst cmp = (() => {\n\t\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\t\tif (v.core[i] > target[i]) return 1;\n\t\t\t\t\tif (v.core[i] < target[i]) return -1;\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t})();\n\n\t\t\tlet ok: boolean;\n\t\t\tswitch (op) {\n\t\t\t\tcase '>=':\n\t\t\t\t\tok = cmp >= 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '>':\n\t\t\t\t\tok = cmp > 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '<=':\n\t\t\t\t\tok = cmp <= 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '<':\n\t\t\t\t\tok = cmp < 0;\n\t\t\t\t\tbreak;\n\t\t\t\t// ^X.Y.Z allows anything up to the next major; ~X.Y.Z up to the next minor.\n\t\t\t\tcase '^':\n\t\t\t\t\tok = cmp >= 0 && v.core[0] === target[0];\n\t\t\t\t\tbreak;\n\t\t\t\tcase '~':\n\t\t\t\t\tok = cmp >= 0 && v.core[0] === target[0] && v.core[1] === target[1];\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t// A bare version means that exact release, but `18` / `18.x` mean the\n\t\t\t\t\t// whole line — treat omitted segments as wildcards.\n\t\t\t\t\tok =\n\t\t\t\t\t\tv.core[0] === target[0] &&\n\t\t\t\t\t\t(m[3] == null || m[3] === 'x' || m[3] === '*' || v.core[1] === target[1]) &&\n\t\t\t\t\t\t(m[4] == null || m[4] === 'x' || m[4] === '*' || v.core[2] === target[2]);\n\t\t\t}\n\t\t\tif (!ok) {\n\t\t\t\tall = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!altParsed) continue;\n\t\tanyParsed = true;\n\t\tif (all) return true;\n\t}\n\n\treturn anyParsed ? false : null;\n}\n\n/**\n * True when `latest` is strictly newer than `current`.\n *\n * Stable channel (default): pre-release suffixes are ignored, so only stable\n * core bumps surface.\n *\n * Beta channel: pre-releases participate. A higher core wins; on an equal core\n * a higher `-beta.N` wins, and a stable (no suffix) outranks any -beta of that\n * core (4.6.0 > 4.6.0-beta.9). An update UI can then show both \"beta.1 →\n * beta.2\" and the promotion of a beta line to stable.\n *\n * Unparseable versions fall back to inequality: different strings count as\n * newer, so an odd published version still surfaces; identical ones don't.\n */\nexport function isNewer(\n\tlatest: string,\n\tcurrent: string,\n\tchannel: ReleaseChannel = 'stable'\n): boolean {\n\tconst a = parseSemver(latest);\n\tconst b = parseSemver(current);\n\tif (!a || !b) return latest !== current;\n\tfor (let i = 0; i < 3; i++) {\n\t\tif (a.core[i] > b.core[i]) return true;\n\t\tif (a.core[i] < b.core[i]) return false;\n\t}\n\tif (channel !== 'beta') return false;\n\t// Stable (beta == null) ranks above any pre-release of the same core.\n\tconst rank = (beta: number | null) => (beta == null ? Infinity : beta);\n\treturn rank(a.beta) > rank(b.beta);\n}\n","// ============================================================================\n// Release channel\n// ============================================================================\n//\n// Which published line of @selvajs/* this deployment tracks: \"stable\" (npm\n// `latest` dist-tag) or \"beta\" (npm `beta` dist-tag). Persisted as a tiny\n// JSON file in the deployment dir (next to package.json / ecosystem.config.cjs)\n// — not a provider store — because both the SvelteKit process and the bash\n// update runner must read it, and the runner can't reach a DB. The file is\n// the single source of truth; absent/invalid resolves to \"stable\".\n//\n// The deployment dir is found the same way the update runner detects it: the\n// dir holding node_modules/@selvajs/selva (probed from cwd upward, or pinned\n// via INSTALL_DIR), so the channel file travels with the deployment and is\n// reachable from the runner's cwd.\n\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport { join } from 'path';\nimport { env } from '#lib/server/env.js';\nimport type { ReleaseChannel } from '@selvajs/server/ops';\n\nexport type { ReleaseChannel };\n\nconst CHANNEL_FILE = 'selva-channel.json';\n\nexport function channelTag(channel: ReleaseChannel): string {\n\treturn channel === 'beta' ? 'beta' : 'latest';\n}\n\nexport function channelRegistryUrl(channel: ReleaseChannel): string {\n\treturn `https://registry.npmjs.org/@selvajs%2Fselva/${channelTag(channel)}`;\n}\n\nfunction isChannel(v: unknown): v is ReleaseChannel {\n\treturn v === 'stable' || v === 'beta';\n}\n\n// Mirrors detectUpdatePlan / readInstalledVersion so the channel file lands\n// where all three agree.\nfunction deploymentDir(): string | null {\n\tconst candidates: string[] = [];\n\tif (env.INSTALL_DIR) candidates.push(env.INSTALL_DIR);\n\tlet dir = process.cwd();\n\tfor (let i = 0; i < 6; i++) {\n\t\tcandidates.push(dir);\n\t\tconst parent = join(dir, '..');\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\tfor (const d of candidates) {\n\t\tif (existsSync(join(d, 'node_modules', '@selvajs', 'selva', 'package.json'))) return d;\n\t}\n\treturn null;\n}\n\n// Falls back to cwd outside a recognizable deployment (dev, tests) so\n// writeChannel never throws for lack of a target.\nfunction channelFilePath(): string {\n\treturn join(deploymentDir() ?? process.cwd(), CHANNEL_FILE);\n}\n\nexport function readChannel(): ReleaseChannel {\n\tconst path = channelFilePath();\n\tif (!existsSync(path)) return 'stable';\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, 'utf8')) as { channel?: unknown };\n\t\treturn isChannel(parsed.channel) ? parsed.channel : 'stable';\n\t} catch {\n\t\treturn 'stable';\n\t}\n}\n\nexport function writeChannel(channel: ReleaseChannel): void {\n\tif (!isChannel(channel)) throw new Error(`Invalid release channel: ${channel}`);\n\twriteFileSync(channelFilePath(), JSON.stringify({ channel }, null, 2) + '\\n', 'utf8');\n}\n","// ============================================================================\n// Update availability check\n// ============================================================================\n//\n// Queries the npm registry for the published @selvajs/selva version on the\n// deployment's channel and compares it to the installed version, so the\n// admin System page can show an \"update available\" badge. The registry fetch\n// is injected so it's testable, and every failure path degrades to \"no\n// update available\" rather than throwing — the admin page must never break\n// because npm is slow or unreachable.\n\nimport { existsSync, readFileSync } from 'fs';\nimport { join } from 'path';\nimport { env } from '#lib/server/env.js';\nimport { isNewer, satisfiesRange } from '@selvajs/server/ops';\nimport { channelRegistryUrl, type ReleaseChannel } from './releaseChannel.server';\n\nexport { isNewer };\n\n/**\n * Whether the host's Node satisfies the target release's `engines.node`.\n *\n * `compatible: null` means we couldn't tell (registry down, no engines field,\n * unparseable range) — the UI must treat that as \"proceed\", not as a block.\n * npm only enforces engines with `engine-strict=true`, which no deployment\n * sets, so a mismatch installs cleanly and `/api/health` still returns 200\n * (it exercises no Node-version-specific path) — hence this pre-flight.\n */\nexport interface NodeCompatibility {\n\tcompatible: boolean | null;\n\t/** The target's `engines.node` range, when the registry reported one. */\n\trequired: string | null;\n\t/** The Node version this deployment is running. */\n\trunning: string;\n}\n\nexport interface UpdateAvailability {\n\tchannel: ReleaseChannel;\n\t/** Installed @selvajs/selva version, or null if it couldn't be read. */\n\tcurrent: string | null;\n\t/** Latest published version on the channel, or null if the registry was unreachable. */\n\tlatest: string | null;\n\t/** True when both versions are known and differ — a forward update OR a stable revert target. */\n\tupdateAvailable: boolean;\n\tnodeCompatibility: NodeCompatibility;\n}\n\n// Probes cwd upward (and an explicit INSTALL_DIR) the same way the update\n// runner detects the deployment dir.\nexport function readInstalledVersion(): string | null {\n\tconst dirs: string[] = [];\n\tif (env.INSTALL_DIR) dirs.push(env.INSTALL_DIR);\n\tlet dir = process.cwd();\n\tfor (let i = 0; i < 6; i++) {\n\t\tdirs.push(dir);\n\t\tconst parent = join(dir, '..');\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\tfor (const d of dirs) {\n\t\tconst pkgPath = join(d, 'node_modules', '@selvajs', 'selva', 'package.json');\n\t\tif (!existsSync(pkgPath)) continue;\n\t\ttry {\n\t\t\tconst pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));\n\t\t\tif (typeof pkg.version === 'string') return pkg.version;\n\t\t} catch {\n\t\t\t// fall through to the next candidate\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * The registry's per-tag manifest carries `engines` alongside `version`, so\n * the Node pre-flight costs no extra request. Uses a short timeout so a slow\n * registry can't hang the caller; returns nulls on any failure.\n */\nexport interface PublishedManifest {\n\tversion: string | null;\n\tenginesNode: string | null;\n}\n\nexport async function fetchLatestManifest(\n\tfetchImpl: typeof fetch,\n\tchannel: ReleaseChannel = 'stable'\n): Promise<PublishedManifest> {\n\tconst ctrl = new AbortController();\n\tconst timer = setTimeout(() => ctrl.abort(), 5000);\n\ttry {\n\t\tconst res = await fetchImpl(channelRegistryUrl(channel), {\n\t\t\theaders: { Accept: 'application/json' },\n\t\t\tsignal: ctrl.signal\n\t\t});\n\t\tif (!res.ok) return { version: null, enginesNode: null };\n\t\tconst body = (await res.json()) as { version?: unknown; engines?: { node?: unknown } };\n\t\treturn {\n\t\t\tversion: typeof body.version === 'string' ? body.version : null,\n\t\t\tenginesNode: typeof body.engines?.node === 'string' ? body.engines.node : null\n\t\t};\n\t} catch {\n\t\treturn { version: null, enginesNode: null };\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\nexport async function fetchLatestVersion(\n\tfetchImpl: typeof fetch,\n\tchannel: ReleaseChannel = 'stable'\n): Promise<string | null> {\n\treturn (await fetchLatestManifest(fetchImpl, channel)).version;\n}\n\nexport async function checkForUpdate(\n\tfetchImpl: typeof fetch,\n\tchannel: ReleaseChannel = 'stable',\n\trunningNode: string = process.versions.node\n): Promise<UpdateAvailability> {\n\tconst current = readInstalledVersion();\n\tconst { version: latest, enginesNode } = await fetchLatestManifest(fetchImpl, channel);\n\t// Any difference between installed and the channel's published version is\n\t// actionable: a forward update (stable→newer, beta→newer beta) OR a revert\n\t// (beta→stable lands on an OLDER stable version, but switching channel is\n\t// exactly what the operator asked for). Same version means nothing to do.\n\tconst updateAvailable = !!(current && latest && latest !== current);\n\treturn {\n\t\tchannel,\n\t\tcurrent,\n\t\tlatest,\n\t\tupdateAvailable,\n\t\tnodeCompatibility: {\n\t\t\tcompatible: enginesNode ? satisfiesRange(runningNode, enginesNode) : null,\n\t\t\trequired: enginesNode,\n\t\t\trunning: running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CACjD,IAAI;EACH,MAAM,MAAM,MAAM,UAAU,mBAAmB,OAAO,GAAG;GACxD,SAAS,EAAE,QAAQ,mBAAmB;GACtC,QAAQ,KAAK;EACd,CAAC;EACD,IAAI,CAAC,IAAI,IAAI,OAAO;GAAE,SAAS;GAAM,aAAa;EAAK;EACvD,MAAM,OAAQ,MAAM,IAAI,KAAK;EAC7B,OAAO;GACN,SAAS,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU;GAC3D,aAAa,OAAO,KAAK,SAAS,SAAS,WAAW,KAAK,QAAQ,OAAO;EAC3E;CACD,QAAQ;EACP,OAAO;GAAE,SAAS;GAAM,aAAa;EAAK;CAC3C,UAAU;EACT,aAAa,KAAK;CACnB;AACD;AASA,eAAsB,eACrB,WACA,UAA0B,UAC1B,cAAsB,QAAQ,SAAS,MACT;CAC9B,MAAM,UAAU,qBAAqB;CACrC,MAAM,EAAE,SAAS,QAAQ,gBAAgB,MAAM,oBAAoB,WAAW,OAAO;CAMrF,OAAO;EACN;EACA;EACA;EACA,iBAAA,CALwB,EAAE,WAAW,UAAU,WAAW;EAM1D,mBAAmB;GAClB,YAAY,cAAc,eAAe,aAAa,WAAW,IAAI;GACrE,UAAU;GACV,SAAS;EACV;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"updateCheck.server.js","names":[],"sources":["../../../../server/src/ops/semver.ts","../../../src/lib/server/releaseChannel.server.ts","../../../src/lib/server/dataFormat.server.ts","../../../src/lib/server/updateCheck.server.ts"],"sourcesContent":["/**\n * Channel-aware semver comparison for update checks. Understands exactly the\n * two lines Selva publishes under: stable (`x.y.z`, npm `latest`) and beta\n * (`x.y.z-beta.N`, npm `beta`). Deliberately not general semver — no build\n * metadata, no arbitrary pre-release identifiers.\n */\n\n/** Which published line a deployment tracks. */\nexport type ReleaseChannel = 'stable' | 'beta';\n\n/**\n * Parse `x.y.z` plus an optional `-beta.N` counter. `beta` comes back separate\n * from the core so beta-channel comparisons can order successive betas of one\n * core. Null when the string doesn't lead with a numeric core.\n */\nexport function parseSemver(\n\tv: string\n): { core: [number, number, number]; beta: number | null } | null {\n\tconst m = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-beta\\.(\\d+))?/.exec(v.trim());\n\tif (!m) return null;\n\treturn {\n\t\tcore: [Number(m[1]), Number(m[2]), Number(m[3])],\n\t\tbeta: m[4] != null ? Number(m[4]) : null\n\t};\n}\n\n/**\n * Compare two `x.y.z` cores, ignoring pre-release tails. Callers that care\n * about those want `isNewer`, which layers the channel rules on top.\n */\nexport function compareCore(a: string, b: string): number {\n\tconst pa = parseSemver(a);\n\tconst pb = parseSemver(b);\n\tif (!pa || !pb) return 0;\n\tfor (let i = 0; i < 3; i++) {\n\t\tif (pa.core[i] > pb.core[i]) return 1;\n\t\tif (pa.core[i] < pb.core[i]) return -1;\n\t}\n\treturn 0;\n}\n\n/**\n * Does `version` satisfy an `engines.node` range?\n *\n * Deliberately narrow: handles the `>=`, `>`, `<=`, `<`, `^`, `~`, `=` and\n * bare-version forms Selva and its dependencies publish, plus `||` alternatives\n * and space-separated conjunctions (`>=18 <21`). Anything it can't parse\n * returns `null` for \"unknown\", never a false \"incompatible\" — a wrong block\n * would strand an operator with no way to override the bad parse.\n *\n * A full `semver` dependency would subsume this, but isn't warranted for the\n * handful of range forms in play.\n */\nexport function satisfiesRange(version: string, range: string): boolean | null {\n\tconst v = parseSemver(version);\n\tif (!v) return null;\n\n\tconst alternatives = range.split('||').map((r) => r.trim());\n\tlet anyParsed = false;\n\n\tfor (const alt of alternatives) {\n\t\tconst clauses = alt.split(/\\s+/).filter(Boolean);\n\t\tif (clauses.length === 0) continue;\n\n\t\tlet all = true;\n\t\tlet altParsed = true;\n\t\tfor (const clause of clauses) {\n\t\t\tconst m = /^(>=|<=|>|<|\\^|~|=)?\\s*v?(\\d+)(?:\\.(\\d+|x|\\*))?(?:\\.(\\d+|x|\\*))?/.exec(clause);\n\t\t\tif (!m) {\n\t\t\t\taltParsed = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst op = m[1] ?? '=';\n\t\t\tconst num = (s: string | undefined) => (s == null || s === 'x' || s === '*' ? 0 : Number(s));\n\t\t\tconst target: [number, number, number] = [Number(m[2]), num(m[3]), num(m[4])];\n\t\t\tconst cmp = (() => {\n\t\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\t\tif (v.core[i] > target[i]) return 1;\n\t\t\t\t\tif (v.core[i] < target[i]) return -1;\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t})();\n\n\t\t\tlet ok: boolean;\n\t\t\tswitch (op) {\n\t\t\t\tcase '>=':\n\t\t\t\t\tok = cmp >= 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '>':\n\t\t\t\t\tok = cmp > 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '<=':\n\t\t\t\t\tok = cmp <= 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '<':\n\t\t\t\t\tok = cmp < 0;\n\t\t\t\t\tbreak;\n\t\t\t\t// ^X.Y.Z allows anything up to the next major; ~X.Y.Z up to the next minor.\n\t\t\t\tcase '^':\n\t\t\t\t\tok = cmp >= 0 && v.core[0] === target[0];\n\t\t\t\t\tbreak;\n\t\t\t\tcase '~':\n\t\t\t\t\tok = cmp >= 0 && v.core[0] === target[0] && v.core[1] === target[1];\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t// A bare version means that exact release, but `18` / `18.x` mean the\n\t\t\t\t\t// whole line — treat omitted segments as wildcards.\n\t\t\t\t\tok =\n\t\t\t\t\t\tv.core[0] === target[0] &&\n\t\t\t\t\t\t(m[3] == null || m[3] === 'x' || m[3] === '*' || v.core[1] === target[1]) &&\n\t\t\t\t\t\t(m[4] == null || m[4] === 'x' || m[4] === '*' || v.core[2] === target[2]);\n\t\t\t}\n\t\t\tif (!ok) {\n\t\t\t\tall = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!altParsed) continue;\n\t\tanyParsed = true;\n\t\tif (all) return true;\n\t}\n\n\treturn anyParsed ? false : null;\n}\n\n/**\n * True when `latest` is strictly newer than `current`.\n *\n * Stable channel (default): pre-release suffixes are ignored, so only stable\n * core bumps surface.\n *\n * Beta channel: pre-releases participate. A higher core wins; on an equal core\n * a higher `-beta.N` wins, and a stable (no suffix) outranks any -beta of that\n * core (4.6.0 > 4.6.0-beta.9). An update UI can then show both \"beta.1 →\n * beta.2\" and the promotion of a beta line to stable.\n *\n * Unparseable versions fall back to inequality: different strings count as\n * newer, so an odd published version still surfaces; identical ones don't.\n */\nexport function isNewer(\n\tlatest: string,\n\tcurrent: string,\n\tchannel: ReleaseChannel = 'stable'\n): boolean {\n\tconst a = parseSemver(latest);\n\tconst b = parseSemver(current);\n\tif (!a || !b) return latest !== current;\n\tfor (let i = 0; i < 3; i++) {\n\t\tif (a.core[i] > b.core[i]) return true;\n\t\tif (a.core[i] < b.core[i]) return false;\n\t}\n\tif (channel !== 'beta') return false;\n\t// Stable (beta == null) ranks above any pre-release of the same core.\n\tconst rank = (beta: number | null) => (beta == null ? Infinity : beta);\n\treturn rank(a.beta) > rank(b.beta);\n}\n","// ============================================================================\n// Release channel\n// ============================================================================\n//\n// Which published line of @selvajs/* this deployment tracks: \"stable\" (npm\n// `latest` dist-tag) or \"beta\" (npm `beta` dist-tag). Persisted as a tiny\n// JSON file in the deployment dir (next to package.json / ecosystem.config.cjs)\n// — not a provider store — because both the SvelteKit process and the bash\n// update runner must read it, and the runner can't reach a DB. The file is\n// the single source of truth; absent/invalid resolves to \"stable\".\n//\n// The deployment dir is found the same way the update runner detects it: the\n// dir holding node_modules/@selvajs/selva (probed from cwd upward, or pinned\n// via INSTALL_DIR), so the channel file travels with the deployment and is\n// reachable from the runner's cwd.\n\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport { join } from 'path';\nimport { env } from '#lib/server/env.js';\nimport type { ReleaseChannel } from '@selvajs/server/ops';\n\nexport type { ReleaseChannel };\n\nconst CHANNEL_FILE = 'selva-channel.json';\n\nexport function channelTag(channel: ReleaseChannel): string {\n\treturn channel === 'beta' ? 'beta' : 'latest';\n}\n\nexport function channelRegistryUrl(channel: ReleaseChannel): string {\n\treturn `https://registry.npmjs.org/@selvajs%2Fselva/${channelTag(channel)}`;\n}\n\nfunction isChannel(v: unknown): v is ReleaseChannel {\n\treturn v === 'stable' || v === 'beta';\n}\n\n// Mirrors detectUpdatePlan / readInstalledVersion so the channel file lands\n// where all three agree.\nfunction deploymentDir(): string | null {\n\tconst candidates: string[] = [];\n\tif (env.INSTALL_DIR) candidates.push(env.INSTALL_DIR);\n\tlet dir = process.cwd();\n\tfor (let i = 0; i < 6; i++) {\n\t\tcandidates.push(dir);\n\t\tconst parent = join(dir, '..');\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\tfor (const d of candidates) {\n\t\tif (existsSync(join(d, 'node_modules', '@selvajs', 'selva', 'package.json'))) return d;\n\t}\n\treturn null;\n}\n\n// Falls back to cwd outside a recognizable deployment (dev, tests) so\n// writeChannel never throws for lack of a target.\nfunction channelFilePath(): string {\n\treturn join(deploymentDir() ?? process.cwd(), CHANNEL_FILE);\n}\n\nexport function readChannel(): ReleaseChannel {\n\tconst path = channelFilePath();\n\tif (!existsSync(path)) return 'stable';\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, 'utf8')) as { channel?: unknown };\n\t\treturn isChannel(parsed.channel) ? parsed.channel : 'stable';\n\t} catch {\n\t\treturn 'stable';\n\t}\n}\n\nexport function writeChannel(channel: ReleaseChannel): void {\n\tif (!isChannel(channel)) throw new Error(`Invalid release channel: ${channel}`);\n\twriteFileSync(channelFilePath(), JSON.stringify({ channel }, null, 2) + '\\n', 'utf8');\n}\n","// ============================================================================\n// Data format\n// ============================================================================\n//\n// One number for everything this app persists: data files, database rows,\n// at-rest envelopes. A build with format N writes data that only builds with\n// format >= N can read, so the updater refuses to install a lower one.\n//\n// Bump it in the change that makes an older release unable to read what this\n// one writes, and add a line below. `selva.dataFormat` in package.json must\n// match: the updater reads the target's number from the npm registry, before\n// the target's code is on the host. `pnpm check:downgrade` fails a release\n// that breaks the latest stable's reads without a bump.\n//\n// 1 Through 4.20.0, which declares no number.\n// 2 4.21.0. Boot re-seals Compute API keys as `enc:v3:`, which format 1\n// reports as plaintext and refuses to use.\n\nexport const DATA_FORMAT = 2;\n\n/** The format a published `package.json` declares. None means format 1. */\nexport function declaredDataFormat(pkg: unknown): number {\n\tconst value = (pkg as { selva?: { dataFormat?: unknown } } | null)?.selva?.dataFormat;\n\treturn typeof value === 'number' && Number.isInteger(value) && value >= 1 ? value : 1;\n}\n","// ============================================================================\n// Update availability check\n// ============================================================================\n//\n// Queries the npm registry for the published @selvajs/selva version on the\n// deployment's channel and compares it to the installed version, so the\n// admin System page can show an \"update available\" badge. The registry fetch\n// is injected so it's testable, and every failure path degrades to \"no\n// update available\" rather than throwing — the admin page must never break\n// because npm is slow or unreachable.\n\nimport { existsSync, readFileSync } from 'fs';\nimport { join } from 'path';\nimport { env } from '#lib/server/env.js';\nimport { isNewer, satisfiesRange } from '@selvajs/server/ops';\nimport { channelRegistryUrl, type ReleaseChannel } from './releaseChannel.server';\nimport { DATA_FORMAT, declaredDataFormat } from './dataFormat.server';\n\nexport { isNewer };\n\n/**\n * Whether the host's Node satisfies the target release's `engines.node`.\n *\n * `compatible: null` means we couldn't tell (registry down, no engines field,\n * unparseable range) — the UI must treat that as \"proceed\", not as a block.\n * npm only enforces engines with `engine-strict=true`, which no deployment\n * sets, so a mismatch installs cleanly and `/api/health` still returns 200\n * (it exercises no Node-version-specific path) — hence this pre-flight.\n */\nexport interface NodeCompatibility {\n\tcompatible: boolean | null;\n\t/** The target's `engines.node` range, when the registry reported one. */\n\trequired: string | null;\n\t/** The Node version this deployment is running. */\n\trunning: string;\n}\n\n/**\n * Whether the target release can read what this deployment has stored. Only a\n * lower target format blocks; `compatible: null` means the registry gave no\n * answer, which the UI treats as \"proceed\" (the runner checks again).\n */\nexport interface DataCompatibility {\n\tcompatible: boolean | null;\n\t/** This build's data format. */\n\tinstalled: number;\n\t/** The target's, or null when the registry was unreachable. */\n\ttarget: number | null;\n}\n\nexport interface UpdateAvailability {\n\tchannel: ReleaseChannel;\n\t/** Installed @selvajs/selva version, or null if it couldn't be read. */\n\tcurrent: string | null;\n\t/** Latest published version on the channel, or null if the registry was unreachable. */\n\tlatest: string | null;\n\t/** True when both versions are known and differ — a forward update OR a stable revert target. */\n\tupdateAvailable: boolean;\n\tnodeCompatibility: NodeCompatibility;\n\tdataCompatibility: DataCompatibility;\n}\n\n// Probes cwd upward (and an explicit INSTALL_DIR) the same way the update\n// runner detects the deployment dir.\nexport function readInstalledVersion(): string | null {\n\tconst dirs: string[] = [];\n\tif (env.INSTALL_DIR) dirs.push(env.INSTALL_DIR);\n\tlet dir = process.cwd();\n\tfor (let i = 0; i < 6; i++) {\n\t\tdirs.push(dir);\n\t\tconst parent = join(dir, '..');\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\tfor (const d of dirs) {\n\t\tconst pkgPath = join(d, 'node_modules', '@selvajs', 'selva', 'package.json');\n\t\tif (!existsSync(pkgPath)) continue;\n\t\ttry {\n\t\t\tconst pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));\n\t\t\tif (typeof pkg.version === 'string') return pkg.version;\n\t\t} catch {\n\t\t\t// fall through to the next candidate\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * The registry's per-tag manifest carries `engines` alongside `version`, so\n * the Node pre-flight costs no extra request. Uses a short timeout so a slow\n * registry can't hang the caller; returns nulls on any failure.\n */\nexport interface PublishedManifest {\n\tversion: string | null;\n\tenginesNode: string | null;\n\t/** Null when the manifest could not be read; a manifest that declares none is format 1. */\n\tdataFormat: number | null;\n}\n\nconst UNREADABLE: PublishedManifest = { version: null, enginesNode: null, dataFormat: null };\n\nexport async function fetchLatestManifest(\n\tfetchImpl: typeof fetch,\n\tchannel: ReleaseChannel = 'stable'\n): Promise<PublishedManifest> {\n\tconst ctrl = new AbortController();\n\tconst timer = setTimeout(() => ctrl.abort(), 5000);\n\ttry {\n\t\tconst res = await fetchImpl(channelRegistryUrl(channel), {\n\t\t\theaders: { Accept: 'application/json' },\n\t\t\tsignal: ctrl.signal\n\t\t});\n\t\tif (!res.ok) return UNREADABLE;\n\t\tconst body = (await res.json()) as { version?: unknown; engines?: { node?: unknown } };\n\t\tconst version = typeof body.version === 'string' ? body.version : null;\n\t\treturn {\n\t\t\tversion,\n\t\t\tenginesNode: typeof body.engines?.node === 'string' ? body.engines.node : null,\n\t\t\tdataFormat: version ? declaredDataFormat(body) : null\n\t\t};\n\t} catch {\n\t\treturn UNREADABLE;\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\nexport async function fetchLatestVersion(\n\tfetchImpl: typeof fetch,\n\tchannel: ReleaseChannel = 'stable'\n): Promise<string | null> {\n\treturn (await fetchLatestManifest(fetchImpl, channel)).version;\n}\n\nexport async function checkForUpdate(\n\tfetchImpl: typeof fetch,\n\tchannel: ReleaseChannel = 'stable',\n\trunningNode: string = process.versions.node\n): Promise<UpdateAvailability> {\n\tconst current = readInstalledVersion();\n\tconst {\n\t\tversion: latest,\n\t\tenginesNode,\n\t\tdataFormat\n\t} = await fetchLatestManifest(fetchImpl, channel);\n\t// Any difference between installed and the channel's published version is\n\t// actionable: a forward update (stable→newer, beta→newer beta) OR a revert\n\t// (beta→stable lands on an OLDER stable version, but switching channel is\n\t// exactly what the operator asked for). Same version means nothing to do.\n\tconst updateAvailable = !!(current && latest && latest !== current);\n\treturn {\n\t\tchannel,\n\t\tcurrent,\n\t\tlatest,\n\t\tupdateAvailable,\n\t\tnodeCompatibility: {\n\t\t\tcompatible: enginesNode ? satisfiesRange(runningNode, enginesNode) : null,\n\t\t\trequired: enginesNode,\n\t\t\trunning: runningNode\n\t\t},\n\t\tdataCompatibility: {\n\t\t\tcompatible: dataFormat === null ? null : dataFormat >= DATA_FORMAT,\n\t\t\tinstalled: DATA_FORMAT,\n\t\t\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AAQ,CAER;CACD;CACA,OAAO;AACR;AAcA,IAAM,aAAgC;CAAE,SAAS;CAAM,aAAa;CAAM,YAAY;AAAK;AAE3F,eAAsB,oBACrB,WACA,UAA0B,UACG;CAC7B,MAAM,OAAO,IAAI,gBAAgB;CACjC,MAAM,QAAQ,iBAAiB,KAAK,MAAM,GAAG,GAAI;CACjD,IAAI;EACH,MAAM,MAAM,MAAM,UAAU,mBAAmB,OAAO,GAAG;GACxD,SAAS,EAAE,QAAQ,mBAAmB;GACtC,QAAQ,KAAK;EACd,CAAC;EACD,IAAI,CAAC,IAAI,IAAI,OAAO;EACpB,MAAM,OAAQ,MAAM,IAAI,KAAK;EAC7B,MAAM,UAAU,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU;EAClE,OAAO;GACN;GACA,aAAa,OAAO,KAAK,SAAS,SAAS,WAAW,KAAK,QAAQ,OAAO;GAC1E,YAAY,UAAU,mBAAmB,IAAI,IAAI;EAClD;CACD,QAAQ;EACP,OAAO;CACR,UAAU;EACT,aAAa,KAAK;CACnB;AACD;AASA,eAAsB,eACrB,WACA,UAA0B,UAC1B,cAAsB,QAAQ,SAAS,MACT;CAC9B,MAAM,UAAU,qBAAqB;CACrC,MAAM,EACL,SAAS,QACT,aACA,eACG,MAAM,oBAAoB,WAAW,OAAO;CAMhD,OAAO;EACN;EACA;EACA;EACA,iBAAA,CALwB,EAAE,WAAW,UAAU,WAAW;EAM1D,mBAAmB;GAClB,YAAY,cAAc,eAAe,aAAa,WAAW,IAAI;GACrE,UAAU;GACV,SAAS;EACV;EACA,mBAAmB;GAClB,YAAY,eAAe,OAAO,OAAO,cAAA;GACzC,WAAA;GACA,QAAQ;EACT;CACD;AACD"}
|
|
@@ -27,11 +27,12 @@ function atRestSecretsCheck(report) {
|
|
|
27
27
|
};
|
|
28
28
|
const failed = report.failures.map((f) => `"${f.serverLabel}" (${f.reason}${f.cause ? `: ${f.cause}` : ""})`).join(", ");
|
|
29
29
|
const plaintext = report.plaintextFound;
|
|
30
|
+
const newerFormat = report.failures.some((f) => f.reason === "unknown_envelope");
|
|
30
31
|
return {
|
|
31
32
|
...base,
|
|
32
33
|
status: "degraded",
|
|
33
34
|
summary: `${report.failures.length} compute server key(s) could not be loaded: ${failed}.`,
|
|
34
|
-
remediation: plaintext ? "A key is stored in plaintext on disk — re-enter it via /admin/compute so it is encrypted." : "The stored ciphertext does not match the current SELVA_AT_REST_KEY (rotated key or restored backup). Re-enter the affected keys via /admin/compute, or restore the original SELVA_AT_REST_KEY, then run this check again."
|
|
35
|
+
remediation: plaintext ? "A key is stored in plaintext on disk — re-enter it via /admin/compute so it is encrypted." : newerFormat ? "A key was sealed by a newer Selva version than the one running. Upgrade Selva again, or re-enter the affected keys via /admin/compute, then run this check again." : "The stored ciphertext does not match the current SELVA_AT_REST_KEY (rotated key or restored backup). Re-enter the affected keys via /admin/compute, or restore the original SELVA_AT_REST_KEY, then run this check again."
|
|
35
36
|
};
|
|
36
37
|
}
|
|
37
38
|
function schemaVersionCheck(report) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_server.ts.js","names":["privateEnv"],"sources":["../../../../../../../../src/routes/api/admin/system/health/+server.ts"],"sourcesContent":["import { json } from '@sveltejs/kit';\nimport type { RequestHandler } from './$types';\nimport { randomUUID } from 'node:crypto';\nimport { writeFile, unlink, mkdir } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { env as privateEnv } from '#lib/server/env.js';\nimport { LocalComputeServerStore } from '@selvajs/local-provider';\nimport { openServerStats } from '#lib/server/compute/serverStats.server.js';\nimport {\n\tfindServerById,\n\ttype SchemaVersionReport,\n\ttype SecretVerificationReport\n} from '@selvajs/platform';\nimport { checkDeploymentConfig, type ConfigFinding } from '@selvajs/server/ops';\nimport { providers, getComputeServerConfigStore } from '#lib/server/providers.server.js';\nimport { requirePermission } from '#lib/server/access.server.js';\n\n/**\n * On-demand admin health check. Unlike `/api/health` (which serves the cached\n * BOOT snapshot for load balancers), this re-runs the integrity checks LIVE so\n * the result reflects the current state — an operator who just re-entered a\n * compute apiKey via /admin/compute sees \"ok\" immediately, without restarting.\n *\n * Checks (each reports `not_applicable` rather than a misleading green when\n * it can't run against the active provider):\n * 1. At-rest secret decryption — stored compute API keys decrypt under the\n * current SELVA_AT_REST_KEY (local provider only; the compute-key state\n * that otherwise surfaces as opaque 401/403s from Rhino.Compute).\n * 2. Compute reachability — the default platform server answers its\n * liveness probe. Catches \"key decrypts fine but the server is down\", a\n * gap check #1 can't see: a healthy at-rest key with an unreachable\n * server still fails every solve.\n * 3. Data path writable — for the local provider, a temp file can be\n * written + deleted under DATA_PATH. Catches disk-full / permission\n * regressions before they corrupt a JSON store mid-write.\n * 4. Deployment config — the reverse-proxy and upload-limit vars adapter-node\n * reads. These break a running deployment without failing anything at\n * boot, so a panel that omits them reads as \"all clear\" while every user\n * shares one login rate-limit bucket. Same rules `selva doctor` applies.\n * 5. API token sessions — on Supabase, whether the configured signing key\n * is one the project accepts. A bad key turns API tokens off silently\n * otherwise: they answer 503 while browser sign-in keeps working.\n *\n * Deliberately NOT covered, because the running process cannot answer them\n * honestly — `selva doctor` owns these, and the panel says so:\n * - Host filesystem state (`.env` present, interrupted migration, pm2 boot\n * unit). The app sees its own resolved env, not the files behind it, so a\n * green here would only mean \"something booted me\".\n * - Secret strength (SELVA_HMAC_KEY / SELVA_AT_REST_KEY still the shipped\n * placeholder). Checkable, but it means handling raw signing keys in a\n * request handler to report a fact that cannot change without a restart.\n *\n * `instance_admin` only — this reveals which compute servers failed and why.\n */\n\ntype CheckStatus = 'ok' | 'degraded' | 'not_applicable' | 'error';\n\ninterface HealthCheck {\n\tid: string;\n\tlabel: string;\n\tstatus: CheckStatus;\n\t/** Operator-facing summary. Always set. */\n\tsummary: string;\n\t/** Concrete next step when not ok. */\n\tremediation?: string;\n}\n\nfunction atRestSecretsCheck(report: SecretVerificationReport | null): HealthCheck {\n\tconst base = { id: 'at-rest-secrets', label: 'Compute server secrets' };\n\n\tif (report === null) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'not_applicable',\n\t\t\tsummary:\n\t\t\t\t'The active data provider does not encrypt secrets at this layer — nothing to verify.'\n\t\t};\n\t}\n\n\tif (report.ok) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'ok',\n\t\t\tsummary: 'All stored compute server API keys decrypt under the current SELVA_AT_REST_KEY.'\n\t\t};\n\t}\n\n\tconst failed = report.failures\n\t\t.map((f) => `\"${f.serverLabel}\" (${f.reason}${f.cause ? `: ${f.cause}` : ''})`)\n\t\t.join(', ');\n\tconst plaintext = report.plaintextFound;\n\treturn {\n\t\t...base,\n\t\tstatus: 'degraded',\n\t\tsummary: `${report.failures.length} compute server key(s) could not be loaded: ${failed}.`,\n\t\tremediation: plaintext\n\t\t\t? 'A key is stored in plaintext on disk — re-enter it via /admin/compute so it is encrypted.'\n\t\t\t: 'The stored ciphertext does not match the current SELVA_AT_REST_KEY (rotated key or ' +\n\t\t\t\t'restored backup). Re-enter the affected keys via /admin/compute, or restore the ' +\n\t\t\t\t'original SELVA_AT_REST_KEY, then run this check again.'\n\t};\n}\n\nfunction schemaVersionCheck(report: SchemaVersionReport | null): HealthCheck {\n\tconst base = { id: 'schema-version', label: 'Database schema' };\n\n\tif (report === null) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'not_applicable',\n\t\t\tsummary:\n\t\t\t\t'The active data provider migrates with the app — there is no separate schema to verify.'\n\t\t};\n\t}\n\n\tif (report.ok) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'ok',\n\t\t\tsummary: `Database migration head ${report.actual} satisfies the app's expected ${report.expected}.`\n\t\t};\n\t}\n\n\treturn {\n\t\t...base,\n\t\tstatus: 'degraded',\n\t\tsummary:\n\t\t\treport.message ??\n\t\t\t`Database migration head ${report.actual ?? 'unavailable'} is behind the app's expected ${report.expected}.`,\n\t\tremediation:\n\t\t\t'Sync the provider migrations into your Supabase project and run `npx supabase db push`, ' +\n\t\t\t'then restart the app. `selva doctor` runs the same check from the CLI.'\n\t};\n}\n\n/** API tokens on a provider with row security need a signing key Supabase trusts. */\nasync function delegatedSessionCheck(): Promise<HealthCheck> {\n\tconst base = { id: 'api-token-sessions', label: 'API token sessions' };\n\tconst delegated = providers.auth.delegatedSession;\n\tif (!delegated) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'not_applicable',\n\t\t\tsummary: 'The active auth provider needs no signed sessions for API tokens.'\n\t\t};\n\t}\n\tconst status = await delegated.status();\n\tif (status.ok) {\n\t\treturn { ...base, status: 'ok', summary: 'API tokens can act as their owners.' };\n\t}\n\treturn {\n\t\t...base,\n\t\tstatus: 'degraded',\n\t\tsummary: `API tokens are off: ${status.message}`,\n\t\tremediation:\n\t\t\t'Set SUPABASE_JWT_SIGNING_KEY to the private ES256 JWK your Supabase project signs with ' +\n\t\t\t'(see the Supabase provider docs), then restart. Browser sign-in is unaffected.'\n\t};\n}\n\nconst COMPUTE_PING_TIMEOUT_MS = 8000;\n\n/**\n * Ping the global default compute server's liveness root (`GET /` — the\n * rhino.compute proxy has no `/healthcheck` route). We probe the default\n * specifically because that's the server every solve falls back to;\n * a degraded default breaks the baseline for all orgs. Org-private and\n * non-default platform servers are out of scope here — they have their own\n * per-server status probe at /api/admin/compute/status.\n */\nasync function computeReachabilityCheck(locals: App.Locals): Promise<HealthCheck> {\n\tconst base = { id: 'compute-reachable', label: 'Default compute server' };\n\n\tlet config;\n\ttry {\n\t\tconfig = await getComputeServerConfigStore().getConfig(locals.ctx!);\n\t} catch (err) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'error',\n\t\t\tsummary: `Could not read compute config: ${err instanceof Error ? err.message : String(err)}`\n\t\t};\n\t}\n\n\tconst server = config.defaultServerId\n\t\t? findServerById(config, config.defaultServerId)\n\t\t: undefined;\n\tif (!server) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'not_applicable',\n\t\t\tsummary: 'No default compute server is configured — nothing to reach.',\n\t\t\tremediation: 'Add a server and set it as default in /admin/compute.'\n\t\t};\n\t}\n\n\tconst apiKey = server.hasApiKey\n\t\t? await getComputeServerConfigStore().getServerApiKey(locals.ctx!, server.id)\n\t\t: undefined;\n\tconst { stats, misconfigured } = openServerStats(server.serverUrl, apiKey ?? undefined);\n\tif (!stats) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'error',\n\t\t\tsummary: `\"${server.label}\" can't be used: ${misconfigured}`,\n\t\t\tremediation: 'Fix the server URL or API key in /admin/compute.'\n\t\t};\n\t}\n\ttry {\n\t\tconst online = await stats.isServerOnline(COMPUTE_PING_TIMEOUT_MS);\n\t\tif (online) {\n\t\t\treturn { ...base, status: 'ok', summary: `\"${server.label}\" is reachable.` };\n\t\t}\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'degraded',\n\t\t\tsummary: `\"${server.label}\" did not respond within ${COMPUTE_PING_TIMEOUT_MS / 1000}s or answered with an error.`,\n\t\t\tremediation: `Confirm the Rhino.Compute host is running, ${server.serverUrl} is correct, and the API key in /admin/compute is valid.`\n\t\t};\n\t} finally {\n\t\tawait stats.dispose();\n\t}\n}\n\n/**\n * Write + delete a temp file under DATA_PATH to prove the local provider can\n * still persist. The JSON stores read-modify-write without a fallback, so a\n * full disk or a permission change (e.g. ownership drift after a restore)\n * corrupts data on the next write — catch it here while it's still just a\n * failed health check.\n */\nasync function dataPathWritableCheck(): Promise<HealthCheck> {\n\tconst base = { id: 'data-path-writable', label: 'Data path writable' };\n\n\t// Only meaningful when a local store is actually backing the deployment.\n\tif (!(providers.data.computeServer instanceof LocalComputeServerStore)) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'not_applicable',\n\t\t\tsummary: 'The active data provider does not persist to a local DATA_PATH.'\n\t\t};\n\t}\n\n\tconst dataPath = privateEnv.DATA_PATH;\n\tif (!dataPath) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'error',\n\t\t\tsummary: 'DATA_PATH is unset but the local provider is active.',\n\t\t\tremediation: 'Set DATA_PATH in .env and restart.'\n\t\t};\n\t}\n\n\tconst absolute = resolve(dataPath);\n\tconst probe = join(absolute, `.health-probe-${randomUUID()}`);\n\ttry {\n\t\tawait mkdir(absolute, { recursive: true });\n\t\tawait writeFile(probe, 'ok');\n\t\tawait unlink(probe);\n\t\treturn { ...base, status: 'ok', summary: `DATA_PATH (${dataPath}) is writable.` };\n\t} catch (err) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'degraded',\n\t\t\tsummary: `DATA_PATH (${dataPath}) is not writable: ${err instanceof Error ? err.message : String(err)}.`,\n\t\t\tremediation:\n\t\t\t\t'Check free disk space and that the directory is owned by the user running the app ' +\n\t\t\t\t'(`df -h`, `ls -la`).'\n\t\t};\n\t}\n}\n\n/**\n * Deployment-config rules run against the live process env, which is what\n * adapter-node itself read at boot — not a re-parse of `.env`, so a var\n * overridden by the service manager is judged as it actually applies.\n *\n * A `fail` maps to `error` rather than `degraded`: these are the same verdicts\n * that exit `selva doctor` non-zero, and the panel should not soften them.\n */\nfunction deploymentConfigChecks(): HealthCheck[] {\n\treturn checkDeploymentConfig(privateEnv).map((finding: ConfigFinding) => ({\n\t\tid: finding.id,\n\t\tlabel: finding.label,\n\t\tstatus: finding.verdict === 'fail' ? 'error' : finding.verdict === 'warn' ? 'degraded' : 'ok',\n\t\tsummary: finding.summary,\n\t\tremediation: finding.remediation\n\t}));\n}\n\nexport const GET: RequestHandler = async ({ locals }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tconst checks: HealthCheck[] = [];\n\n\tconst store = providers.data.computeServer;\n\tif (typeof store.verifySecrets === 'function') {\n\t\ttry {\n\t\t\tchecks.push(atRestSecretsCheck(await store.verifySecrets()));\n\t\t} catch (err) {\n\t\t\tchecks.push({\n\t\t\t\tid: 'at-rest-secrets',\n\t\t\t\tlabel: 'Compute server secrets',\n\t\t\t\tstatus: 'error',\n\t\t\t\tsummary: `Verification threw: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\tremediation: 'Check server logs (`pm2 logs selva-compute`) for the underlying error.'\n\t\t\t});\n\t\t}\n\t} else {\n\t\tchecks.push(atRestSecretsCheck(null));\n\t}\n\n\t// Live app↔DB schema handshake (audit O3) — unlike boot health this re-runs\n\t// on every request, so an operator sees green right after `db push` without\n\t// restarting first (the boot report itself stays stale by design).\n\tconst data = providers.data;\n\tif (typeof data.verifySchemaVersion === 'function') {\n\t\tchecks.push(schemaVersionCheck(await data.verifySchemaVersion()));\n\t} else {\n\t\tchecks.push(schemaVersionCheck(null));\n\t}\n\n\t// Reachability + writability run in parallel — independent of each other\n\t// and of the at-rest check above. Each self-contains its error handling.\n\tchecks.push(\n\t\t...(await Promise.all([\n\t\t\tcomputeReachabilityCheck(locals),\n\t\t\tdataPathWritableCheck(),\n\t\t\tdelegatedSessionCheck()\n\t\t]))\n\t);\n\n\tchecks.push(...deploymentConfigChecks());\n\n\t// Worst status wins for the overall verdict. `not_applicable` never\n\t// degrades the overall result.\n\tconst rank: Record<CheckStatus, number> = {\n\t\tok: 0,\n\t\tnot_applicable: 0,\n\t\tdegraded: 2,\n\t\terror: 3\n\t};\n\tconst overall = checks.reduce<CheckStatus>(\n\t\t(worst, c) => (rank[c.status] > rank[worst] ? c.status : worst),\n\t\t'ok'\n\t);\n\n\treturn json({ overall, checkedAt: new Date().toISOString(), checks });\n};\n"],"mappings":";;;;;;;;;;;;AAmEA,SAAS,mBAAmB,QAAsD;CACjF,MAAM,OAAO;EAAE,IAAI;EAAmB,OAAO;CAAyB;CAEtE,IAAI,WAAW,MACd,OAAO;EACN,GAAG;EACH,QAAQ;EACR,SACC;CACF;CAGD,IAAI,OAAO,IACV,OAAO;EACN,GAAG;EACH,QAAQ;EACR,SAAS;CACV;CAGD,MAAM,SAAS,OAAO,SACpB,KAAK,MAAM,IAAI,EAAE,YAAY,KAAK,EAAE,SAAS,EAAE,QAAQ,KAAK,EAAE,UAAU,GAAG,EAAE,CAAC,CAC9E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AO,QACrB,OAAO,MAAO,KAAK,EAAE,UAAU,KAAK,SAAS,EAAE,SAAS,OACzD,IACD;CAEA,OAAO,KAAK;EAAE;EAAS,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;EAAG;CAAO,CAAC;AACrE"}
|
|
1
|
+
{"version":3,"file":"_server.ts.js","names":["privateEnv"],"sources":["../../../../../../../../src/routes/api/admin/system/health/+server.ts"],"sourcesContent":["import { json } from '@sveltejs/kit';\nimport type { RequestHandler } from './$types';\nimport { randomUUID } from 'node:crypto';\nimport { writeFile, unlink, mkdir } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { env as privateEnv } from '#lib/server/env.js';\nimport { LocalComputeServerStore } from '@selvajs/local-provider';\nimport { openServerStats } from '#lib/server/compute/serverStats.server.js';\nimport {\n\tfindServerById,\n\ttype SchemaVersionReport,\n\ttype SecretVerificationReport\n} from '@selvajs/platform';\nimport { checkDeploymentConfig, type ConfigFinding } from '@selvajs/server/ops';\nimport { providers, getComputeServerConfigStore } from '#lib/server/providers.server.js';\nimport { requirePermission } from '#lib/server/access.server.js';\n\n/**\n * On-demand admin health check. Unlike `/api/health` (which serves the cached\n * BOOT snapshot for load balancers), this re-runs the integrity checks LIVE so\n * the result reflects the current state — an operator who just re-entered a\n * compute apiKey via /admin/compute sees \"ok\" immediately, without restarting.\n *\n * Checks (each reports `not_applicable` rather than a misleading green when\n * it can't run against the active provider):\n * 1. At-rest secret decryption — stored compute API keys decrypt under the\n * current SELVA_AT_REST_KEY (local provider only; the compute-key state\n * that otherwise surfaces as opaque 401/403s from Rhino.Compute).\n * 2. Compute reachability — the default platform server answers its\n * liveness probe. Catches \"key decrypts fine but the server is down\", a\n * gap check #1 can't see: a healthy at-rest key with an unreachable\n * server still fails every solve.\n * 3. Data path writable — for the local provider, a temp file can be\n * written + deleted under DATA_PATH. Catches disk-full / permission\n * regressions before they corrupt a JSON store mid-write.\n * 4. Deployment config — the reverse-proxy and upload-limit vars adapter-node\n * reads. These break a running deployment without failing anything at\n * boot, so a panel that omits them reads as \"all clear\" while every user\n * shares one login rate-limit bucket. Same rules `selva doctor` applies.\n * 5. API token sessions — on Supabase, whether the configured signing key\n * is one the project accepts. A bad key turns API tokens off silently\n * otherwise: they answer 503 while browser sign-in keeps working.\n *\n * Deliberately NOT covered, because the running process cannot answer them\n * honestly — `selva doctor` owns these, and the panel says so:\n * - Host filesystem state (`.env` present, interrupted migration, pm2 boot\n * unit). The app sees its own resolved env, not the files behind it, so a\n * green here would only mean \"something booted me\".\n * - Secret strength (SELVA_HMAC_KEY / SELVA_AT_REST_KEY still the shipped\n * placeholder). Checkable, but it means handling raw signing keys in a\n * request handler to report a fact that cannot change without a restart.\n *\n * `instance_admin` only — this reveals which compute servers failed and why.\n */\n\ntype CheckStatus = 'ok' | 'degraded' | 'not_applicable' | 'error';\n\ninterface HealthCheck {\n\tid: string;\n\tlabel: string;\n\tstatus: CheckStatus;\n\t/** Operator-facing summary. Always set. */\n\tsummary: string;\n\t/** Concrete next step when not ok. */\n\tremediation?: string;\n}\n\nfunction atRestSecretsCheck(report: SecretVerificationReport | null): HealthCheck {\n\tconst base = { id: 'at-rest-secrets', label: 'Compute server secrets' };\n\n\tif (report === null) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'not_applicable',\n\t\t\tsummary:\n\t\t\t\t'The active data provider does not encrypt secrets at this layer — nothing to verify.'\n\t\t};\n\t}\n\n\tif (report.ok) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'ok',\n\t\t\tsummary: 'All stored compute server API keys decrypt under the current SELVA_AT_REST_KEY.'\n\t\t};\n\t}\n\n\tconst failed = report.failures\n\t\t.map((f) => `\"${f.serverLabel}\" (${f.reason}${f.cause ? `: ${f.cause}` : ''})`)\n\t\t.join(', ');\n\tconst plaintext = report.plaintextFound;\n\tconst newerFormat = report.failures.some((f) => f.reason === 'unknown_envelope');\n\treturn {\n\t\t...base,\n\t\tstatus: 'degraded',\n\t\tsummary: `${report.failures.length} compute server key(s) could not be loaded: ${failed}.`,\n\t\tremediation: plaintext\n\t\t\t? 'A key is stored in plaintext on disk — re-enter it via /admin/compute so it is encrypted.'\n\t\t\t: newerFormat\n\t\t\t\t? 'A key was sealed by a newer Selva version than the one running. Upgrade Selva ' +\n\t\t\t\t\t'again, or re-enter the affected keys via /admin/compute, then run this check again.'\n\t\t\t\t: 'The stored ciphertext does not match the current SELVA_AT_REST_KEY (rotated key or ' +\n\t\t\t\t\t'restored backup). Re-enter the affected keys via /admin/compute, or restore the ' +\n\t\t\t\t\t'original SELVA_AT_REST_KEY, then run this check again.'\n\t};\n}\n\nfunction schemaVersionCheck(report: SchemaVersionReport | null): HealthCheck {\n\tconst base = { id: 'schema-version', label: 'Database schema' };\n\n\tif (report === null) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'not_applicable',\n\t\t\tsummary:\n\t\t\t\t'The active data provider migrates with the app — there is no separate schema to verify.'\n\t\t};\n\t}\n\n\tif (report.ok) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'ok',\n\t\t\tsummary: `Database migration head ${report.actual} satisfies the app's expected ${report.expected}.`\n\t\t};\n\t}\n\n\treturn {\n\t\t...base,\n\t\tstatus: 'degraded',\n\t\tsummary:\n\t\t\treport.message ??\n\t\t\t`Database migration head ${report.actual ?? 'unavailable'} is behind the app's expected ${report.expected}.`,\n\t\tremediation:\n\t\t\t'Sync the provider migrations into your Supabase project and run `npx supabase db push`, ' +\n\t\t\t'then restart the app. `selva doctor` runs the same check from the CLI.'\n\t};\n}\n\n/** API tokens on a provider with row security need a signing key Supabase trusts. */\nasync function delegatedSessionCheck(): Promise<HealthCheck> {\n\tconst base = { id: 'api-token-sessions', label: 'API token sessions' };\n\tconst delegated = providers.auth.delegatedSession;\n\tif (!delegated) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'not_applicable',\n\t\t\tsummary: 'The active auth provider needs no signed sessions for API tokens.'\n\t\t};\n\t}\n\tconst status = await delegated.status();\n\tif (status.ok) {\n\t\treturn { ...base, status: 'ok', summary: 'API tokens can act as their owners.' };\n\t}\n\treturn {\n\t\t...base,\n\t\tstatus: 'degraded',\n\t\tsummary: `API tokens are off: ${status.message}`,\n\t\tremediation:\n\t\t\t'Set SUPABASE_JWT_SIGNING_KEY to the private ES256 JWK your Supabase project signs with ' +\n\t\t\t'(see the Supabase provider docs), then restart. Browser sign-in is unaffected.'\n\t};\n}\n\nconst COMPUTE_PING_TIMEOUT_MS = 8000;\n\n/**\n * Ping the global default compute server's liveness root (`GET /` — the\n * rhino.compute proxy has no `/healthcheck` route). We probe the default\n * specifically because that's the server every solve falls back to;\n * a degraded default breaks the baseline for all orgs. Org-private and\n * non-default platform servers are out of scope here — they have their own\n * per-server status probe at /api/admin/compute/status.\n */\nasync function computeReachabilityCheck(locals: App.Locals): Promise<HealthCheck> {\n\tconst base = { id: 'compute-reachable', label: 'Default compute server' };\n\n\tlet config;\n\ttry {\n\t\tconfig = await getComputeServerConfigStore().getConfig(locals.ctx!);\n\t} catch (err) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'error',\n\t\t\tsummary: `Could not read compute config: ${err instanceof Error ? err.message : String(err)}`\n\t\t};\n\t}\n\n\tconst server = config.defaultServerId\n\t\t? findServerById(config, config.defaultServerId)\n\t\t: undefined;\n\tif (!server) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'not_applicable',\n\t\t\tsummary: 'No default compute server is configured — nothing to reach.',\n\t\t\tremediation: 'Add a server and set it as default in /admin/compute.'\n\t\t};\n\t}\n\n\tconst apiKey = server.hasApiKey\n\t\t? await getComputeServerConfigStore().getServerApiKey(locals.ctx!, server.id)\n\t\t: undefined;\n\tconst { stats, misconfigured } = openServerStats(server.serverUrl, apiKey ?? undefined);\n\tif (!stats) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'error',\n\t\t\tsummary: `\"${server.label}\" can't be used: ${misconfigured}`,\n\t\t\tremediation: 'Fix the server URL or API key in /admin/compute.'\n\t\t};\n\t}\n\ttry {\n\t\tconst online = await stats.isServerOnline(COMPUTE_PING_TIMEOUT_MS);\n\t\tif (online) {\n\t\t\treturn { ...base, status: 'ok', summary: `\"${server.label}\" is reachable.` };\n\t\t}\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'degraded',\n\t\t\tsummary: `\"${server.label}\" did not respond within ${COMPUTE_PING_TIMEOUT_MS / 1000}s or answered with an error.`,\n\t\t\tremediation: `Confirm the Rhino.Compute host is running, ${server.serverUrl} is correct, and the API key in /admin/compute is valid.`\n\t\t};\n\t} finally {\n\t\tawait stats.dispose();\n\t}\n}\n\n/**\n * Write + delete a temp file under DATA_PATH to prove the local provider can\n * still persist. The JSON stores read-modify-write without a fallback, so a\n * full disk or a permission change (e.g. ownership drift after a restore)\n * corrupts data on the next write — catch it here while it's still just a\n * failed health check.\n */\nasync function dataPathWritableCheck(): Promise<HealthCheck> {\n\tconst base = { id: 'data-path-writable', label: 'Data path writable' };\n\n\t// Only meaningful when a local store is actually backing the deployment.\n\tif (!(providers.data.computeServer instanceof LocalComputeServerStore)) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'not_applicable',\n\t\t\tsummary: 'The active data provider does not persist to a local DATA_PATH.'\n\t\t};\n\t}\n\n\tconst dataPath = privateEnv.DATA_PATH;\n\tif (!dataPath) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'error',\n\t\t\tsummary: 'DATA_PATH is unset but the local provider is active.',\n\t\t\tremediation: 'Set DATA_PATH in .env and restart.'\n\t\t};\n\t}\n\n\tconst absolute = resolve(dataPath);\n\tconst probe = join(absolute, `.health-probe-${randomUUID()}`);\n\ttry {\n\t\tawait mkdir(absolute, { recursive: true });\n\t\tawait writeFile(probe, 'ok');\n\t\tawait unlink(probe);\n\t\treturn { ...base, status: 'ok', summary: `DATA_PATH (${dataPath}) is writable.` };\n\t} catch (err) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstatus: 'degraded',\n\t\t\tsummary: `DATA_PATH (${dataPath}) is not writable: ${err instanceof Error ? err.message : String(err)}.`,\n\t\t\tremediation:\n\t\t\t\t'Check free disk space and that the directory is owned by the user running the app ' +\n\t\t\t\t'(`df -h`, `ls -la`).'\n\t\t};\n\t}\n}\n\n/**\n * Deployment-config rules run against the live process env, which is what\n * adapter-node itself read at boot — not a re-parse of `.env`, so a var\n * overridden by the service manager is judged as it actually applies.\n *\n * A `fail` maps to `error` rather than `degraded`: these are the same verdicts\n * that exit `selva doctor` non-zero, and the panel should not soften them.\n */\nfunction deploymentConfigChecks(): HealthCheck[] {\n\treturn checkDeploymentConfig(privateEnv).map((finding: ConfigFinding) => ({\n\t\tid: finding.id,\n\t\tlabel: finding.label,\n\t\tstatus: finding.verdict === 'fail' ? 'error' : finding.verdict === 'warn' ? 'degraded' : 'ok',\n\t\tsummary: finding.summary,\n\t\tremediation: finding.remediation\n\t}));\n}\n\nexport const GET: RequestHandler = async ({ locals }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tconst checks: HealthCheck[] = [];\n\n\tconst store = providers.data.computeServer;\n\tif (typeof store.verifySecrets === 'function') {\n\t\ttry {\n\t\t\tchecks.push(atRestSecretsCheck(await store.verifySecrets()));\n\t\t} catch (err) {\n\t\t\tchecks.push({\n\t\t\t\tid: 'at-rest-secrets',\n\t\t\t\tlabel: 'Compute server secrets',\n\t\t\t\tstatus: 'error',\n\t\t\t\tsummary: `Verification threw: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\tremediation: 'Check server logs (`pm2 logs selva-compute`) for the underlying error.'\n\t\t\t});\n\t\t}\n\t} else {\n\t\tchecks.push(atRestSecretsCheck(null));\n\t}\n\n\t// Live app↔DB schema handshake (audit O3) — unlike boot health this re-runs\n\t// on every request, so an operator sees green right after `db push` without\n\t// restarting first (the boot report itself stays stale by design).\n\tconst data = providers.data;\n\tif (typeof data.verifySchemaVersion === 'function') {\n\t\tchecks.push(schemaVersionCheck(await data.verifySchemaVersion()));\n\t} else {\n\t\tchecks.push(schemaVersionCheck(null));\n\t}\n\n\t// Reachability + writability run in parallel — independent of each other\n\t// and of the at-rest check above. Each self-contains its error handling.\n\tchecks.push(\n\t\t...(await Promise.all([\n\t\t\tcomputeReachabilityCheck(locals),\n\t\t\tdataPathWritableCheck(),\n\t\t\tdelegatedSessionCheck()\n\t\t]))\n\t);\n\n\tchecks.push(...deploymentConfigChecks());\n\n\t// Worst status wins for the overall verdict. `not_applicable` never\n\t// degrades the overall result.\n\tconst rank: Record<CheckStatus, number> = {\n\t\tok: 0,\n\t\tnot_applicable: 0,\n\t\tdegraded: 2,\n\t\terror: 3\n\t};\n\tconst overall = checks.reduce<CheckStatus>(\n\t\t(worst, c) => (rank[c.status] > rank[worst] ? c.status : worst),\n\t\t'ok'\n\t);\n\n\treturn json({ overall, checkedAt: new Date().toISOString(), checks });\n};\n"],"mappings":";;;;;;;;;;;;AAmEA,SAAS,mBAAmB,QAAsD;CACjF,MAAM,OAAO;EAAE,IAAI;EAAmB,OAAO;CAAyB;CAEtE,IAAI,WAAW,MACd,OAAO;EACN,GAAG;EACH,QAAQ;EACR,SACC;CACF;CAGD,IAAI,OAAO,IACV,OAAO;EACN,GAAG;EACH,QAAQ;EACR,SAAS;CACV;CAGD,MAAM,SAAS,OAAO,SACpB,KAAK,MAAM,IAAI,EAAE,YAAY,KAAK,EAAE,SAAS,EAAE,QAAQ,KAAK,EAAE,UAAU,GAAG,EAAE,CAAC,CAC9E,KAAK,IAAI;CACX,MAAM,YAAY,OAAO;CACzB,MAAM,cAAc,OAAO,SAAS,MAAM,MAAM,EAAE,WAAW,kBAAkB;CAC/E,OAAO;EACN,GAAG;EACH,QAAQ;EACR,SAAS,GAAG,OAAO,SAAS,OAAO,8CAA8C,OAAO;EACxF,aAAa,YACV,8FACA,cACC,sKAEA;CAGL;AACD;AAEA,SAAS,mBAAmB,QAAiD;CAC5E,MAAM,OAAO;EAAE,IAAI;EAAkB,OAAO;CAAkB;CAE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]; then
|
|
|
228
228
|
fi
|
|
229
229
|
fi
|
|
230
230
|
|
|
231
|
+
# ---------------------------------------------------------------------------
|
|
232
|
+
# 1c. Data format pre-flight — BEFORE any downtime.
|
|
233
|
+
# ---------------------------------------------------------------------------
|
|
234
|
+
# A release with a lower data format than the installed one cannot read what
|
|
235
|
+
# this deployment has already stored (dataFormat.server.ts). It would boot, fail
|
|
236
|
+
# its health check and roll back: two outages for nothing. Installed by hand it
|
|
237
|
+
# leaves stored Compute API keys unreadable. A release that declares no format
|
|
238
|
+
# is format 1. Skipped when the registry gave no answer: the target is unknown.
|
|
239
|
+
INSTALLED_FORMAT=$(node -p "require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1" 2>/dev/null)
|
|
240
|
+
case "$INSTALLED_FORMAT" in ''|*[!0-9]*) INSTALLED_FORMAT=1 ;; esac
|
|
241
|
+
if [ -n "$LATEST" ] && TARGET_FORMAT=$(npm view "@selvajs/selva@$TAG" selva.dataFormat --silent 2>/dev/null); then
|
|
242
|
+
TARGET_FORMAT=$(echo "$TARGET_FORMAT" | tr -d '"' | tr -d "'" | tr -d '[:space:]')
|
|
243
|
+
case "$TARGET_FORMAT" in ''|*[!0-9]*) TARGET_FORMAT=1 ;; esac
|
|
244
|
+
if [ "$TARGET_FORMAT" -lt "$INSTALLED_FORMAT" ]; then
|
|
245
|
+
echo "[FATAL] DATA_FORMAT: @selvajs/selva@$LATEST reads data format $TARGET_FORMAT, but this deployment is on format $INSTALLED_FORMAT."
|
|
246
|
+
echo "[FATAL] It could not read what the installed version has stored, such as Compute API keys."
|
|
247
|
+
echo "[FATAL] Aborting WITHOUT stopping the app — it is still running."
|
|
248
|
+
echo "[FATAL] To go back anyway: docs/self-hosting/deployment/admin.md, 'Going back to an older release'."
|
|
249
|
+
exit 10
|
|
250
|
+
fi
|
|
251
|
+
fi
|
|
252
|
+
|
|
231
253
|
# ---------------------------------------------------------------------------
|
|
232
254
|
# 2. Resync PM2 daemon if its in-memory version drifted from the CLI on disk.
|
|
233
255
|
# ---------------------------------------------------------------------------
|
|
@@ -451,6 +473,15 @@ if [ -z "$BEFORE" ]; then
|
|
|
451
473
|
exit 3
|
|
452
474
|
fi
|
|
453
475
|
|
|
476
|
+
# The failed version has already booted, so it may have rewritten stored data in
|
|
477
|
+
# a format $BEFORE cannot read. Rolling back is still the better outcome; say so.
|
|
478
|
+
AFTER_FORMAT=$(node -p "require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1" 2>/dev/null)
|
|
479
|
+
case "$AFTER_FORMAT" in ''|*[!0-9]*) AFTER_FORMAT=1 ;; esac
|
|
480
|
+
if [ "$AFTER_FORMAT" -gt "$INSTALLED_FORMAT" ]; then
|
|
481
|
+
echo "[WARN] DATA_FORMAT_ROLLBACK: the failed version stores data format $AFTER_FORMAT; $BEFORE reads format $INSTALLED_FORMAT."
|
|
482
|
+
echo "[WARN] If Compute API keys fail to load after this rollback, re-enter them at /admin/compute."
|
|
483
|
+
fi
|
|
484
|
+
|
|
454
485
|
echo "[STEP] Rolling back @selvajs/selva to $BEFORE"
|
|
455
486
|
"$PM2" stop selva-compute >/dev/null 2>&1 || true
|
|
456
487
|
wait_until_stopped >/dev/null 2>&1
|