Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(runtime): preserve installer and env lifecycles

Rahman6ae50a79a39a
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 9568141d..746300a8 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -13,6 +13,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Fixed**
+- `runtime` preserve installer and env lifecycles
- `runtime` serialize deploy and service starts
- `gateway` recheck web state under lock
- `update` reject unowned live runtimes
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 46783146..c9ed1612 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -40,16 +40,19 @@ The installer core:
shell's PATH;
3. verifies whether the invoking shell will actually resolve `mso` after the child installer
returns, and persists an idempotent `~/.local/bin` PATH fallback for future shells;
-4. installs Bun/dependencies as needed;
-5. creates private owner auth configuration when missing;
-6. runs the production build through `node node_modules/next/dist/bin/next build`, bypassing Bun's
+4. before dependency or `.next` mutation, acquires the same checkout transaction/runtime exclusion used by
+ self-update, validates every owned gateway fallback, quiesces an active service only when it belongs to
+ this checkout, then quiesces gateway-owned fallback runtimes while preserving their public tunnels;
+5. installs Bun/dependencies as needed;
+6. creates private owner auth configuration when missing;
+7. runs the production build through `node node_modules/next/dist/bin/next build`, bypassing Bun's
package-bin remapper; if the Next package payload itself is absent, it performs one bounded
`bun install --force` repair before failing;
-7. installs the `mso.service` system unit only when systemd is really PID 1 (not merely when a
+8. installs the `mso.service` system unit only when systemd is really PID 1 (not merely when a
`systemctl` executable exists);
-8. enables the owner's lingering user manager needed by self-update/managed-app user units;
-9. activates the service only after a successful build;
-10. on a fresh interactive install with a verified running service, opens `/dev/tty` and launches `mso onboard`.
+9. enables the owner's lingering user manager needed by self-update/managed-app user units;
+10. activates the service only after a successful build;
+11. on a fresh interactive install with a verified running service, opens `/dev/tty` and launches `mso onboard`.
Useful flags:
@@ -68,8 +71,11 @@ Useful flags:
The public bootstrap is delivered through pipeline stdin, and the core deliberately does not
make interactive setup depend on that stream. It prompts through `/dev/tty`. If there is no controlling terminal it
never waits for input and tells the operator to run `mso onboard` later. Re-running the
-installer updates an existing installation with the same build-before-replace safety rule
-and does not repeat onboarding unless `--onboard` is requested.
+installer updates an existing installation under the same checkout-wide runtime lifecycle: a WSL/no-systemd
+fallback is stopped before dependency/build mutation and restored afterward, and an existing system service
+must belong to the same checkout before the installer may quiesce it. `--no-service` refuses to rebuild a
+checkout that is already serving through its system service. Onboarding is not repeated unless `--onboard`
+is requested.
### Guided onboarding
@@ -166,7 +172,11 @@ with Cloudflare auto-update disabled. The tunnel process also receives a scrubbe
than inheriting MSO login/session/BYOK secrets from the application shell. If systemd is unavailable (common on WSL), it may start the
already-built Next production runtime itself, still on `127.0.0.1`, and records whether that process
is gateway-owned. `gateway stop` terminates only recorded identities: Cloudflared is matched by PID/start-time/executable/exact argv, while the Next fallback uses PID/start-time/Node executable plus a random runtime-instance nonce echoed by `/api/health` so Next's mutable process title cannot confuse ownership. After TERM/SIGKILL, MSO re-verifies that the exact recorded process identity disappeared before deleting lifecycle state; an unverified survivor leaves state intact and the stop fails closed. Private state and logs are owner-only and scoped by the canonical checkout plus selected loopback
-origin. The fallback Next process uses the same held-child release handshake as Cloudflared, so neither
+origin. When a fallback is launched through a custom `mso --env /path/file web`, state stores only the
+validated env-file identity (canonical path, device and inode), never its secret contents. Update/installer
+restore revalidates that same owner/private non-symlink file and identity before sourcing it; a replacement
+or moved file fails closed while restore intent remains persisted instead of silently switching to
+`.env.local`. The fallback Next process uses the same held-child release handshake as Cloudflared, so neither
child may execute before the parent records PID + kernel start-ticks. Gateway/update lifecycle
transactions use kernel `flock`, which is released automatically when a process exits instead of
trying to reclaim stale lock directories. A second checkout-wide shared/exclusive runtime lock blocks
@@ -450,7 +460,7 @@ service (including WSL without systemd), it performs the clean fast-forward/depe
path locally. Before an offline build mutates dependencies or `.next`, MSO also verifies the selected
loopback origin is either down or represented by gateway-owned lifecycle state; a manually started or
otherwise unowned healthy MSO runtime is refused and must be stopped first. Before either the
-service-active or offline in-place build, update inventories every gateway state for the canonical checkout, quiesces each verified owned fallback runtime, leaves active tunnel identities intact, rebuilds, then restores every previously-owned origin. A
+service-active or offline in-place build, update inventories every gateway state for the canonical checkout, quiesces each verified owned fallback runtime, leaves active tunnel identities intact, rebuilds, then restores every previously-owned origin with the exact env-file identity recorded for that fallback. Older owned state that predates env identity is refused before the runtime is stopped; run the same `mso --env ... web`/gateway path once to migrate it safely. A
checkout-scoped private deployment receipt and restart marker mean a dependency/build failure after
Git already reached `origin/main` is retried by the next ordinary `mso update` instead of being
mislabeled "already up to date". The state is keyed by canonical checkout path, so two clones at the
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 32969809..172311c9 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -41,6 +41,14 @@ a gateway-owned runtime is quiesced, so an interrupted state update remains safe
When `mso.service` is active, status also compares the commit baked into the live loopback `/api/health`
response with source `HEAD`; source equality alone is not treated as proof that deployment finished.
+### Re-running the installer while MSO is already running
+
+Supported reruns now use the same checkout-wide mutation boundary as self-update before dependency install
+or `.next` build. A same-checkout service is quiesced and refreshed as part of the installer lifecycle;
+gateway-owned WSL/no-systemd fallbacks are inventoried, stopped and restored afterward with their original
+env-file identities. A service from another checkout, an unowned loopback runtime, or `--no-service` against
+an active same-checkout service is refused before mutation.
+
### `mso update` says the active service belongs to another checkout
This is a safety refusal. A machine may contain multiple MSO clones, but an active `mso.service` has
@@ -54,6 +62,15 @@ recorded as a gateway-owned fallback runtime. This is commonly a manual `bun run
Stop that manual runtime first, then rerun `mso update`. MSO refuses here before dependency or `.next`
mutation rather than rebuilding underneath a process that is actively serving the old build.
+### `mso update` says a gateway-owned runtime predates env identity
+
+The fallback was created by an older MSO version that did not record which env file launched it. MSO
+refuses before stopping that runtime because guessing `.env.local` could restart it with different auth,
+provider or public-origin configuration. Re-run the same local launcher once with the env file that runtime
+uses (for example `mso --env /same/private.env web`), then retry the update. This rewrites only the owner-only
+gateway lifecycle state with the env file's canonical path/device/inode; env contents are never copied into
+state. Do not delete the private restore/update state to bypass this check.
+
### `mso gateway start` says an offline update is mutating this checkout
This is an intentional safety exclusion. Every in-place `mso update` (service-active or offline) holds the checkout-wide runtime lock while `.next` can change, so `mso web`, onboarding fallback, gateway runtime recovery, and `mso service start/restart` cannot start
diff --git a/lib/install-contract.test.ts b/lib/install-contract.test.ts
index f6c0a751..b56f41be 100644
--- a/lib/install-contract.test.ts
+++ b/lib/install-contract.test.ts
@@ -124,6 +124,22 @@ describe("one-line installer contract", () => {
expect(src).toContain('CLI launcher self-check failed');
});
+ it("holds the checkout runtime lifecycle across dependency/build and service refresh", () => {
+ const src = fs.readFileSync(CORE, "utf8");
+ const begin = src.indexOf("install_runtime_lifecycle_begin");
+ const deps = src.indexOf("INSTALL_PHASE=dependencies");
+ const build = src.indexOf('node "$NEXT_BIN" build');
+ const service = src.indexOf("# ---- systemd unit ----");
+ const finish = src.indexOf("install_runtime_lifecycle_finish");
+ expect(begin).toBeGreaterThan(0);
+ expect(begin).toBeLessThan(deps);
+ expect(deps).toBeLessThan(build);
+ expect(build).toBeLessThan(service);
+ expect(service).toBeLessThan(finish);
+ expect(src).toContain('trap install_runtime_lifecycle_cleanup EXIT');
+ expect(src).toContain('scripts/lib/install-runtime-lifecycle.sh');
+ });
+
it("bypasses Bun bin remapping for production build and repairs only a missing package payload", () => {
const src = fs.readFileSync(CORE, "utf8");
expect(src).toContain('NEXT_BIN="$DIR/node_modules/next/dist/bin/next"');
diff --git a/scripts/install-core.sh b/scripts/install-core.sh
index 603b1499..f44500ad 100755
--- a/scripts/install-core.sh
+++ b/scripts/install-core.sh
@@ -411,6 +411,16 @@ else
fi
+INSTALL_PHASE=runtime-safety
+# ---- freeze every runtime that can read this checkout before dependency/build mutation ----
+# The lifecycle remains open through service refresh. On failure, EXIT releases locks
+# but intentionally keeps gateway restore intent so a broken build is never served.
+# shellcheck source=scripts/lib/install-runtime-lifecycle.sh
+. "$DIR/scripts/lib/install-runtime-lifecycle.sh"
+trap install_runtime_lifecycle_cleanup EXIT
+trap 'exit 129' HUP; trap 'exit 130' INT; trap 'exit 143' TERM
+install_runtime_lifecycle_begin
+
INSTALL_PHASE=dependencies
# ---- deps (compiles node-pty) ----
info "installing dependencies…"
@@ -581,6 +591,13 @@ elif [ "$DO_SERVICE" -eq 1 ]; then
fi
fi
+INSTALL_PHASE=runtime-restore
+# `.next` and service state are stable. Release the exclusive mutation lock before
+# local-start takes its shared side, then restore every previously-owned fallback
+# using the exact env-file identity persisted with that runtime.
+install_runtime_lifecycle_finish
+trap - EXIT HUP INT TERM
+
INSTALL_PHASE=integrations
# ---- optional Claude Code integration ----
# MSO catalogs $DIR/claude-skills directly, so these symlinks are NOT required by MSO.
diff --git a/scripts/install-runtime-lifecycle.test.ts b/scripts/install-runtime-lifecycle.test.ts
new file mode 100644
index 00000000..1bb47510
--- /dev/null
+++ b/scripts/install-runtime-lifecycle.test.ts
@@ -0,0 +1,84 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+const ROOT = process.cwd();
+const LIBS = ["private-state.sh", "update-state.sh", "runtime-exclusion.sh", "update-gateway-runtimes.sh", "install-runtime-lifecycle.sh"];
+const roots: string[] = [];
+
+function copy(src: string, dst: string) { fs.mkdirSync(path.dirname(dst), { recursive: true }); fs.copyFileSync(src, dst); fs.chmodSync(dst, 0o755); }
+function envIdentity(file: string) { const st = fs.statSync(file); return { path: fs.realpathSync(file), dev: String(st.dev), ino: String(st.ino) }; }
+
+function fixture(systemd = false, doService = 1) {
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), "mso-install-runtime-")); roots.push(base);
+ const repo = path.join(base, "repo"), home = path.join(base, "home"), bin = path.join(base, "bin"), capture = path.join(base, "capture");
+ fs.mkdirSync(home); fs.mkdirSync(bin); fs.mkdirSync(path.join(repo, "scripts/lib"), { recursive: true });
+ for (const lib of LIBS) copy(path.join(ROOT, "scripts/lib", lib), path.join(repo, "scripts/lib", lib));
+ const customEnv = path.join(base, "custom.env"); fs.writeFileSync(customEnv, "OS_SESSION_SECRET=fixture\n", { mode: 0o600 });
+ fs.writeFileSync(path.join(repo, "scripts/mso-gateway"), `#!/bin/sh
+printf '%s url=%s env=%s expected=%s\n' "$1" "\${MSO_GATEWAY_LOCAL_URL:-}" "\${MSO_GATEWAY_ENV:-}" "\${MSO_GATEWAY_EXPECT_ENV_IDENTITY:-}" >> ${JSON.stringify(capture)}
+case "$1" in
+ runtime-assert-update-safe) echo 'runtime: update-owned' ;;
+ runtime-stop) printf '1\n' > "$MSO_GATEWAY_RECOVERY_MARKER"; chmod 600 "$MSO_GATEWAY_RECOVERY_MARKER"; echo 'runtime: stopped-owned' ;;
+ local-start) echo 'runtime: healthy MSO at fixture' ;;
+ *) exit 2 ;;
+esac
+`, { mode: 0o755 });
+ const canonical = fs.realpathSync(repo), stateDir = path.join(home, ".mso/private/gateway/scope");
+ fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
+ for (const dir of [path.join(home, ".mso"), path.join(home, ".mso/private"), path.join(home, ".mso/private/gateway")]) fs.chmodSync(dir, 0o700);
+ fs.writeFileSync(path.join(stateDir, "state.json"), `${JSON.stringify({ root: canonical, localUrl: "http://127.0.0.1:4555", runtimeOwned: true, envFile: envIdentity(customEnv) })}\n`, { mode: 0o600 });
+ const systemctl = path.join(bin, "systemctl");
+ fs.writeFileSync(systemctl, `#!/bin/sh
+printf 'systemctl %s\n' "$*" >> ${JSON.stringify(capture)}
+case "$*" in
+ 'is-active --quiet mso.service') exit ${systemd ? 0 : 3} ;;
+ 'show -p WorkingDirectory --value mso.service') printf '%s\n' ${JSON.stringify(canonical)} ;;
+esac
+`, { mode: 0o755 });
+ const runner = path.join(base, "runner.sh");
+ fs.writeFileSync(runner, `#!/bin/bash
+set -euo pipefail
+DIR=${JSON.stringify(repo)}; PORT=4005; DO_SERVICE=${doService}; SERVICE=mso.service
+export HOME=${JSON.stringify(home)} PATH=${JSON.stringify(`${bin}:${process.env.PATH}`)} MSO_UPDATE_STATE_DIR=${JSON.stringify(path.join(base, "update-state"))} MSO_RUNTIME_EXCLUSION_DIR=${JSON.stringify(path.join(base, "runtime-exclusion"))}
+die(){ echo "installer: $*" >&2; exit 1; }
+sudo_do(){ "$@"; }
+systemd_ready(){ ${systemd ? "return 0" : "return 1"}; }
+. "$DIR/scripts/lib/install-runtime-lifecycle.sh"
+trap install_runtime_lifecycle_cleanup EXIT
+install_runtime_lifecycle_begin
+printf 'MUTATE\n' >> ${JSON.stringify(capture)}
+install_runtime_lifecycle_finish
+trap - EXIT
+`, { mode: 0o755 });
+ return { base, capture, customEnv, runner };
+}
+
+afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
+
+describe("installer runtime lifecycle", () => {
+ it("quiesces and restores a no-systemd fallback around installer mutation with its custom env", () => {
+ const f = fixture(false, 1); execFileSync(f.runner, [], { encoding: "utf8" });
+ const calls = fs.readFileSync(f.capture, "utf8");
+ expect(calls.indexOf("runtime-stop")).toBeLessThan(calls.indexOf("MUTATE"));
+ expect(calls.lastIndexOf("local-start")).toBeGreaterThan(calls.indexOf("MUTATE"));
+ expect(calls).toContain(`env=${fs.realpathSync(f.customEnv)}`);
+ });
+
+ it("refuses --no-service before mutation when this checkout already owns an active service", () => {
+ const f = fixture(true, 0); const out = spawnSync(f.runner, [], { encoding: "utf8" });
+ expect(out.status).not.toBe(0); expect(out.stderr).toContain("--no-service cannot rebuild its live .next tree");
+ const calls = fs.existsSync(f.capture) ? fs.readFileSync(f.capture, "utf8") : "";
+ expect(calls).not.toContain("MUTATE"); expect(calls).not.toContain("runtime-stop");
+ });
+
+ it("stops the owned service before mutation and restores fallbacks afterward", () => {
+ const f = fixture(true, 1); execFileSync(f.runner, [], { encoding: "utf8" });
+ const calls = fs.readFileSync(f.capture, "utf8");
+ expect(calls.indexOf("systemctl stop mso.service")).toBeLessThan(calls.indexOf("MUTATE"));
+ expect(calls.indexOf("runtime-stop")).toBeLessThan(calls.indexOf("MUTATE"));
+ expect(calls.lastIndexOf("local-start")).toBeGreaterThan(calls.indexOf("MUTATE"));
+ });
+});
diff --git a/scripts/install.sh b/scripts/install.sh
index 7152fe5c..82196c78 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -12,7 +12,7 @@ set -Eeuo pipefail
umask 077
CORE_URL="${MSO_INSTALL_CORE_URL:-https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install-core.sh}"
-CORE_SHA256="c21f72acd477edd2a60062efbe3b735f24ddcd0b46a7db60f0cd0900428fbc5d"
+CORE_SHA256="19f9e0ebde506c356c7b93c1b8afad5ea1d2a130719790f5b3d5a35c45fcd8ee"
CORE_EOF='# MSO_INSTALLER_CORE_EOF'
TMP_INSTALLER=''
diff --git a/scripts/lib/gateway-config.sh b/scripts/lib/gateway-config.sh
index 8d26d03f..3e40944e 100644
--- a/scripts/lib/gateway-config.sh
+++ b/scripts/lib/gateway-config.sh
@@ -10,6 +10,35 @@ gateway_safe_env_file() {
|| gateway_fail "env file contains secrets and must not be group/world-accessible (got mode $mode)"
}
+gateway_env_identity() {
+ local canonical dev ino
+ # Missing/default env and explicit /dev/null are the same runtime contract: no
+ # file is sourced. Persist /dev/null so a later restore cannot accidentally pick
+ # up a newly-created .env.local with different credentials.
+ if [ "$ENVF" = /dev/null ] || { [ ! -e "$ENVF" ] && [ ! -L "$ENVF" ]; }; then
+ jq -nc '{path:"/dev/null",dev:null,ino:null}'
+ return 0
+ fi
+ gateway_safe_env_file
+ canonical="$(realpath -e -- "$ENVF" 2>/dev/null || true)"
+ [ -n "$canonical" ] || gateway_fail "cannot canonicalize env file: $ENVF"
+ dev="$(stat -c '%d' -- "$ENVF")"; ino="$(stat -c '%i' -- "$ENVF")"
+ [[ "$dev" =~ ^[0-9]+$ && "$ino" =~ ^[0-9]+$ ]] || gateway_fail "cannot identify env file: $ENVF"
+ jq -nc --arg path "$canonical" --arg dev "$dev" --arg ino "$ino" '{path:$path,dev:$dev,ino:$ino}'
+}
+
+gateway_assert_expected_env_identity() {
+ local current="$1" expected="${MSO_GATEWAY_EXPECT_ENV_IDENTITY:-}"
+ [ -n "$expected" ] || return 0
+ jq -e 'type=="object" and (.path|type=="string") and
+ ((.path=="/dev/null" and .dev==null and .ino==null) or
+ ((.path|startswith("/")) and .path!="/dev/null" and
+ (.dev|type=="string" and test("^[0-9]+$")) and (.ino|type=="string" and test("^[0-9]+$"))))' <<<"$expected" >/dev/null 2>&1 \
+ || gateway_fail "invalid expected env-file identity"
+ [ "$(jq -cS . <<<"$current")" = "$(jq -cS . <<<"$expected")" ] \
+ || gateway_fail "env file identity changed while runtime was quiesced; restore state was preserved"
+}
+
gateway_env_origin() {
gateway_safe_env_file
sed -n 's/^OS_PUBLIC_ORIGIN=//p' "$ENVF" | tail -1
diff --git a/scripts/lib/gateway-runtime.sh b/scripts/lib/gateway-runtime.sh
index b4eb84ba..472751d9 100644
--- a/scripts/lib/gateway-runtime.sh
+++ b/scripts/lib/gateway-runtime.sh
@@ -4,14 +4,19 @@
GATEWAY_EXPECTED_VERSION="$(node -p "require('$ROOT/package.json').version")" || gateway_fail "cannot read MSO version"
gateway_runtime_from_state() {
- local state="$1" identity owned instance
+ local state="$1" identity owned instance stored_env
RUNTIME_IDENTITY='null'; RUNTIME_INSTANCE_ID=''; RUNTIME_OWNED=false; RUNTIME_STARTED_NOW=false
owned="$(jq -r '.runtimeOwned // false' <<<"$state")"
identity="$(jq -c '.runtimeIdentity // null' <<<"$state")"
instance="$(jq -r '.runtimeIdentity.instanceId // empty' <<<"$state")"
- if [ "$owned" = true ] && [ "$identity" != null ] && [ -n "$instance" ] \
- && gateway_runtime_identity_matches "$identity"; then
- RUNTIME_IDENTITY="$identity"; RUNTIME_INSTANCE_ID="$instance"; RUNTIME_OWNED=true
+ stored_env="$(jq -c '.envFile // null' <<<"$state")"
+ if [ "$owned" = true ] && [ "$identity" != null ] && [ -n "$instance" ]; then
+ # Legacy state may be migrated by one explicit local-start using the same env.
+ [ "$stored_env" = null ] || [ "$(jq -cS . <<<"$stored_env")" = "$(jq -cS . <<<"$GATEWAY_ENV_IDENTITY")" ] \
+ || gateway_fail "recorded runtime belongs to another env-file identity; use its original --env or stop it first"
+ if gateway_runtime_identity_matches "$identity"; then
+ RUNTIME_IDENTITY="$identity"; RUNTIME_INSTANCE_ID="$instance"; RUNTIME_OWNED=true
+ fi
fi
}
gateway_start_runtime_if_needed() {
@@ -74,13 +79,13 @@ gateway_write_state() {
local provider="$1" mode="$2" url="$3" tunnel_identity="$4"
jq -nc --arg scopeId "$GATEWAY_SCOPE_ID" --arg root "$GATEWAY_CANONICAL_ROOT" \
--arg provider "$provider" --arg mode "$mode" --arg url "$url" --arg local "$LOCAL_URL" \
- --argjson tunnelIdentity "$tunnel_identity" --argjson runtimeIdentity "$RUNTIME_IDENTITY" \
- --argjson runtimeOwned "$RUNTIME_OWNED" --arg startedAt "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
- '{scopeId:$scopeId,root:$root,provider:$provider,mode:$mode,url:$url,localUrl:$local,tunnelIdentity:$tunnelIdentity,
- runtimeIdentity:$runtimeIdentity,runtimeOwned:$runtimeOwned,startedAt:$startedAt}' \
+ --argjson envFile "$GATEWAY_ENV_IDENTITY" --argjson tunnelIdentity "$tunnel_identity" \
+ --argjson runtimeIdentity "$RUNTIME_IDENTITY" --argjson runtimeOwned "$RUNTIME_OWNED" \
+ --arg startedAt "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
+ '{scopeId:$scopeId,root:$root,provider:$provider,mode:$mode,url:$url,localUrl:$local,envFile:$envFile,
+ tunnelIdentity:$tunnelIdentity,runtimeIdentity:$runtimeIdentity,runtimeOwned:$runtimeOwned,startedAt:$startedAt}' \
| mso_private_state_atomic_write "$STATE_FILE" >/dev/null
}
-
gateway_active_state() {
local state identity rc
if state="$(gateway_state_read)"; then :; else rc=$?; return "$rc"; fi
@@ -127,8 +132,6 @@ gateway_cmd_runtime_assert_update_safe_locked() {
state="$(gateway_state_read)"
runtime="$(jq -c '.runtimeIdentity // null' <<<"$state")"
owned="$(jq -r '.runtimeOwned // false' <<<"$state")"
- # A recorded owned runtime is handled by the subsequent checkout-wide quiesce
- # inventory. Do not stop anything here: this command is intentionally read-only.
if [ "$owned" = true ] && [ "$runtime" != null ]; then
gateway_info "runtime: update-owned"
return 0
@@ -158,9 +161,6 @@ gateway_cmd_runtime_stop_locked() {
gateway_info "runtime: stopped-owned"
return 0
fi
- # A prior attempt may have killed the verified runtime and then lost the
- # state write. Reconcile only when durable intent exists, the recorded
- # process identity is gone, and no other MSO responder owns the local port.
if gateway_recovery_pending && ! gateway_runtime_process_matches "$runtime" && ! gateway_health_ok; then
gateway_persist_quiesced_state "$state" \
|| gateway_fail "could not reconcile stale owned runtime; recovery marker preserved"
diff --git a/scripts/lib/install-runtime-lifecycle.sh b/scripts/lib/install-runtime-lifecycle.sh
new file mode 100644
index 00000000..277a2509
--- /dev/null
+++ b/scripts/lib/install-runtime-lifecycle.sh
@@ -0,0 +1,76 @@
+#!/usr/bin/env bash
+# Installer-side checkout lifecycle around dependency + in-place Next build work.
+# Expected globals/functions: DIR, PORT, DO_SERVICE, SERVICE, die, sudo_do,
+# systemd_ready. The installer keeps this lifecycle open through service refresh.
+
+INSTALL_RUNTIME_LIFECYCLE=0
+INSTALL_RUNTIME_SERVICE_STOPPED=0
+
+install_runtime_lifecycle_init() {
+ ROOT="$DIR"
+ UPDATE_STATE_DIR_REQUESTED="${MSO_UPDATE_STATE_DIR:-$HOME/.mso/private/update-state}"
+ LOCAL_URL="${MSO_GATEWAY_LOCAL_URL:-http://127.0.0.1:${PORT:-4005}}"
+ GATEWAY="$ROOT/scripts/mso-gateway"
+ fail() { die "$@"; }
+
+ # shellcheck source=scripts/lib/private-state.sh
+ . "$ROOT/scripts/lib/private-state.sh"
+ # shellcheck source=scripts/lib/update-state.sh
+ . "$ROOT/scripts/lib/update-state.sh"
+ # shellcheck source=scripts/lib/runtime-exclusion.sh
+ . "$ROOT/scripts/lib/runtime-exclusion.sh"
+ # shellcheck source=scripts/lib/update-gateway-runtimes.sh
+ . "$ROOT/scripts/lib/update-gateway-runtimes.sh"
+}
+
+install_runtime_lifecycle_cleanup() {
+ [ "$INSTALL_RUNTIME_LIFECYCLE" = 1 ] || return 0
+ runtime_exclusion_release >/dev/null 2>&1 || true
+ update_lock_release >/dev/null 2>&1 || true
+}
+
+install_runtime_active_service_preflight() {
+ local configured canonical_service
+ systemd_ready || return 0
+ systemctl is-active --quiet "$SERVICE" || return 0
+ configured="$(systemctl show -p WorkingDirectory --value "$SERVICE" 2>/dev/null || true)"
+ [ -n "$configured" ] || die "$SERVICE is active but its WorkingDirectory is unreadable; refusing in-place installer build"
+ canonical_service="$(realpath -e -- "$configured" 2>/dev/null || true)"
+ [ -n "$canonical_service" ] || die "cannot canonicalize active $SERVICE WorkingDirectory"
+ [ "$canonical_service" = "$UPDATE_CANONICAL_ROOT" ] \
+ || die "$SERVICE belongs to $canonical_service, not installer checkout $UPDATE_CANONICAL_ROOT; stop it or rerun against that checkout"
+ [ "$DO_SERVICE" -eq 1 ] \
+ || die "$SERVICE is active on this checkout; --no-service cannot rebuild its live .next tree"
+ INSTALL_RUNTIME_SERVICE_STOPPED=1
+}
+
+install_runtime_lifecycle_begin() {
+ install_runtime_lifecycle_init
+ update_lock_acquire
+ INSTALL_RUNTIME_LIFECYCLE=1
+ runtime_exclusion_acquire_exclusive \
+ || die "could not acquire checkout runtime exclusion before installer build"
+
+ # Validate pending + owned gateway inventory before stopping a system service.
+ # A legacy owned runtime with no env identity fails here while everything is live.
+ update_gateway_collect_entries >/dev/null \
+ || die "could not validate gateway runtime inventory before installer build"
+ install_runtime_active_service_preflight
+ if [ "$INSTALL_RUNTIME_SERVICE_STOPPED" = 1 ]; then
+ sudo_do systemctl stop "$SERVICE" || die "could not quiesce $SERVICE before installer build"
+ fi
+
+ # After any owned service is down, no unowned selected loopback runtime may still
+ # be serving the tree. Then persist restore intent before stopping fallbacks.
+ update_gateway_assert_offline_selected_origin_safe
+ update_gateway_quiesce_all
+}
+
+install_runtime_lifecycle_finish() {
+ [ "$INSTALL_RUNTIME_LIFECYCLE" = 1 ] || return 0
+ runtime_exclusion_release
+ update_gateway_restore_all
+ update_lock_release
+ INSTALL_RUNTIME_LIFECYCLE=0
+ INSTALL_RUNTIME_SERVICE_STOPPED=0
+}
diff --git a/scripts/lib/update-gateway-runtimes.sh b/scripts/lib/update-gateway-runtimes.sh
index 28c62e81..052706a8 100755
--- a/scripts/lib/update-gateway-runtimes.sh
+++ b/scripts/lib/update-gateway-runtimes.sh
@@ -5,62 +5,97 @@ update_gateway_restore_pending() {
init_update_state
if [ -e "$GATEWAY_RESTORE_FILE" ] || [ -L "$GATEWAY_RESTORE_FILE" ]; then
mso_private_state_validate_file "$GATEWAY_RESTORE_FILE" >/dev/null || fail "unsafe gateway runtime restore inventory"
- jq -e 'type == "array" and all(.[]; type == "string" and length > 0)' "$GATEWAY_RESTORE_FILE" >/dev/null 2>&1 \
- || fail "invalid gateway runtime restore inventory"
+ jq -e '
+ def envok: type=="object" and (.path|type=="string") and
+ ((.path=="/dev/null" and .dev==null and .ino==null) or
+ ((.path|startswith("/")) and .path!="/dev/null" and
+ (.dev|type=="string" and test("^[0-9]+$")) and (.ino|type=="string" and test("^[0-9]+$"))));
+ type=="array" and all(.[];
+ (type=="string" and length>0) or
+ (type=="object" and (.url|type=="string" and length>0) and ((.envFile==null) or (.envFile|envok))))
+ ' "$GATEWAY_RESTORE_FILE" >/dev/null 2>&1 || fail "invalid gateway runtime restore inventory"
[ "$(jq 'length' "$GATEWAY_RESTORE_FILE")" -gt 0 ] && return 0
fi
restart_pending
}
-update_gateway_restore_urls() {
+update_gateway_restore_entries() {
init_update_state
if [ -e "$GATEWAY_RESTORE_FILE" ] || [ -L "$GATEWAY_RESTORE_FILE" ]; then
mso_private_state_validate_file "$GATEWAY_RESTORE_FILE" >/dev/null || fail "unsafe gateway runtime restore inventory"
- jq -er 'if type == "array" and all(.[]; type == "string" and length > 0) then .[] else error("invalid") end' \
- "$GATEWAY_RESTORE_FILE" 2>/dev/null || fail "invalid gateway runtime restore inventory"
+ jq -cer '
+ def envok: type=="object" and (.path|type=="string") and
+ ((.path=="/dev/null" and .dev==null and .ino==null) or
+ ((.path|startswith("/")) and .path!="/dev/null" and
+ (.dev|type=="string" and test("^[0-9]+$")) and (.ino|type=="string" and test("^[0-9]+$"))));
+ if type!="array" then error("invalid")
+ elif all(.[]; type=="string" and length>0) then .[] | {url:.,envFile:null}
+ elif all(.[]; type=="object" and (.url|type=="string" and length>0) and ((.envFile==null) or (.envFile|envok))) then .[]
+ else error("invalid") end
+ ' "$GATEWAY_RESTORE_FILE" 2>/dev/null || fail "invalid gateway runtime restore inventory"
elif restart_pending; then
- # Backward compatibility with the single-runtime marker used by older MSO.
- printf '%s\n' "${LOCAL_URL:-${MSO_GATEWAY_LOCAL_URL:-http://127.0.0.1:${MSO_PORT:-4005}}}"
+ # Backward compatibility with the old single-runtime marker. It predated env
+ # identity, so only this legacy recovery path falls back to the checkout env.
+ jq -nc --arg url "${LOCAL_URL:-${MSO_GATEWAY_LOCAL_URL:-http://127.0.0.1:${MSO_PORT:-4005}}}" '{url:$url,envFile:null}'
fi
}
-update_gateway_owned_urls() {
- local base dir file state root owned url
+update_gateway_owned_entries() {
+ local base dir file state root owned url env_file
init_update_state
- base="$(mso_private_state_dir "${MSO_GATEWAY_STATE_BASE:-$HOME/.mso/private/gateway}")" \
- || fail "unsafe gateway state base"
+ base="$(mso_private_state_dir "${MSO_GATEWAY_STATE_BASE:-$HOME/.mso/private/gateway}")" || fail "unsafe gateway state base"
shopt -s nullglob
for dir in "$base"/*; do
[ -d "$dir" ] && [ ! -L "$dir" ] || continue
- file="$dir/state.json"
- [ -e "$file" ] || [ -L "$file" ] || continue
+ file="$dir/state.json"; [ -e "$file" ] || [ -L "$file" ] || continue
mso_private_state_validate_file "$file" >/dev/null || fail "unsafe gateway state while preparing update"
state="$(jq -ce . "$file" 2>/dev/null)" || fail "corrupt gateway state while preparing update"
root="$(jq -er '.root | select(type=="string")' <<<"$state" 2>/dev/null || true)"
[ "$root" = "$UPDATE_CANONICAL_ROOT" ] || continue
- owned="$(jq -r '.runtimeOwned // false' <<<"$state")"
- [ "$owned" = true ] || continue
+ owned="$(jq -r '.runtimeOwned // false' <<<"$state")"; [ "$owned" = true ] || continue
url="$(jq -er '.localUrl | select(type=="string" and length>0)' <<<"$state" 2>/dev/null || true)"
[ -n "$url" ] || fail "gateway-owned runtime is missing its loopback origin"
- printf '%s\n' "$url"
+ env_file="$(jq -c '.envFile // null' <<<"$state")"
+ [ "$env_file" != null ] || fail "gateway-owned runtime predates env identity; rerun mso web/gateway once with its original --env before updating"
+ jq -e 'type=="object" and (.path|type=="string") and
+ ((.path=="/dev/null" and .dev==null and .ino==null) or
+ ((.path|startswith("/")) and .path!="/dev/null" and
+ (.dev|type=="string" and test("^[0-9]+$")) and (.ino|type=="string" and test("^[0-9]+$"))))' \
+ <<<"$env_file" >/dev/null 2>&1 || fail "gateway-owned runtime has invalid env identity"
+ jq -nc --arg url "$url" --argjson envFile "$env_file" '{url:$url,envFile:$envFile}'
done
shopt -u nullglob
}
-update_gateway_collect_urls() {
+update_gateway_collect_entries() {
local restored owned
- restored="$(update_gateway_restore_urls)" || return 1
- owned="$(update_gateway_owned_urls)" || return 1
- printf '%s\n%s\n' "$restored" "$owned" | awk 'NF && !seen[$0]++'
+ restored="$(update_gateway_restore_entries)" || return 1
+ owned="$(update_gateway_owned_entries)" || return 1
+ printf '%s\n%s\n' "$restored" "$owned" | awk 'NF' | jq -cs 'unique_by(.url)[]'
}
-update_gateway_write_restore_urls() {
+update_gateway_write_restore_entries() {
local payload
- payload="$(cat | jq -Rsc 'split("\n") | map(select(length > 0)) | unique')" || fail "could not encode gateway restore inventory"
+ payload="$(jq -cs 'unique_by(.url)')" || fail "could not encode gateway restore inventory"
printf '%s\n' "$payload" | mso_private_state_atomic_write "$GATEWAY_RESTORE_FILE" >/dev/null \
|| fail "could not persist gateway restore inventory"
}
+update_gateway_entry_call() {
+ local action="$1" entry="$2" url env_file env_path
+ url="$(jq -er '.url' <<<"$entry")" || return 1
+ env_file="$(jq -c '.envFile // null' <<<"$entry")"
+ if [ "$env_file" = null ]; then
+ MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ROOT/.env.local" MSO_GATEWAY_LOCAL_URL="$url" \
+ MSO_GATEWAY_RECOVERY_MARKER="${RESTART_MARKER:-}" "$GATEWAY" "$action"
+ return
+ fi
+ env_path="$(jq -er '.path' <<<"$env_file")" || return 1
+ MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$env_path" MSO_GATEWAY_LOCAL_URL="$url" \
+ MSO_GATEWAY_EXPECT_ENV_IDENTITY="$env_file" MSO_GATEWAY_RECOVERY_MARKER="${RESTART_MARKER:-}" \
+ "$GATEWAY" "$action"
+}
+
update_gateway_assert_offline_selected_origin_safe() {
local selected
selected="${LOCAL_URL:-${MSO_GATEWAY_LOCAL_URL:-http://127.0.0.1:${MSO_PORT:-4005}}}"
@@ -70,34 +105,32 @@ update_gateway_assert_offline_selected_origin_safe() {
}
update_gateway_quiesce_all() {
- local url out collected
- local -a urls=()
+ local entry out collected
+ local -a entries=()
init_update_state
- collected="$(update_gateway_collect_urls)" || fail "could not inventory checkout gateway runtimes"
+ collected="$(update_gateway_collect_entries)" || fail "could not inventory checkout gateway runtimes"
[ -n "$collected" ] || return 0
- mapfile -t urls <<<"$collected"
- printf '%s\n' "${urls[@]}" | update_gateway_write_restore_urls
- for url in "${urls[@]}"; do
- out="$(MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ROOT/.env.local" MSO_GATEWAY_LOCAL_URL="$url" \
- MSO_GATEWAY_RECOVERY_MARKER="$RESTART_MARKER" "$GATEWAY" runtime-stop)" \
- || fail "could not safely quiesce gateway runtime at $url"
+ mapfile -t entries <<<"$collected"
+ printf '%s\n' "${entries[@]}" | update_gateway_write_restore_entries
+ for entry in "${entries[@]}"; do
+ out="$(update_gateway_entry_call runtime-stop "$entry")" || fail "could not safely quiesce gateway runtime at $(jq -r .url <<<"$entry")"
case "$out" in
*'runtime: stopped-owned'*|*'runtime: recovered-stale-owned'*|*'runtime: recovery-pending'*|*'runtime: already-down'*) ;;
- *) fail "unexpected gateway runtime-stop result for $url" ;;
+ *) fail "unexpected gateway runtime-stop result for $(jq -r .url <<<"$entry")" ;;
esac
done
}
update_gateway_restore_all() {
- local url restored
- local -a urls=()
+ local entry restored
+ local -a entries=()
init_update_state
- restored="$(update_gateway_restore_urls)" || fail "could not read gateway runtime restore inventory"
+ restored="$(update_gateway_restore_entries)" || fail "could not read gateway runtime restore inventory"
[ -n "$restored" ] || { clear_restart_pending; return 0; }
- mapfile -t urls <<<"$restored"
- for url in "${urls[@]}"; do
- MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ROOT/.env.local" MSO_GATEWAY_LOCAL_URL="$url" \
- "$GATEWAY" local-start >/dev/null || fail "updated build is healthy, but fallback runtime restore failed at $url"
+ mapfile -t entries <<<"$restored"
+ for entry in "${entries[@]}"; do
+ update_gateway_entry_call local-start "$entry" >/dev/null \
+ || fail "updated build is healthy, but fallback runtime restore failed at $(jq -r .url <<<"$entry")"
done
clear_restart_pending
mso_private_state_remove_file "$GATEWAY_RESTORE_FILE" >/dev/null 2>&1 || true
diff --git a/scripts/mso-gateway b/scripts/mso-gateway
index d318f19d..e02e7658 100755
--- a/scripts/mso-gateway
+++ b/scripts/mso-gateway
@@ -12,6 +12,7 @@ STATE_ROOT_OVERRIDE="${MSO_GATEWAY_STATE_DIR:-}"
STATE_ROOT=''
GATEWAY_CANONICAL_ROOT=''
GATEWAY_SCOPE_ID=''
+GATEWAY_ENV_IDENTITY=''
CLOUDFLARED=""
CURL="${MSO_GATEWAY_CURL:-$(command -v curl 2>/dev/null || true)}"
@@ -27,10 +28,10 @@ for dep in node jq sha256sum realpath stat mktemp flock; do command -v "$dep" >/
. "$ROOT/scripts/lib/gateway-config.sh"
# Direct `scripts/mso-gateway` calls and `mso gateway` must have the same runtime
-# environment. The file is owner/private checked before sourcing. cloudflared is
-# spawned later with a scrubbed environment so these secrets never reach it.
+# environment. Persist only the validated file identity — never env contents.
+GATEWAY_ENV_IDENTITY="$(gateway_env_identity)"
+gateway_assert_expected_env_identity "$GATEWAY_ENV_IDENTITY"
if [ "$ENVF" != /dev/null ] && { [ -e "$ENVF" ] || [ -L "$ENVF" ]; }; then
- gateway_safe_env_file
# shellcheck disable=SC1090
set -a; . "$ENVF"; set +a
fi
diff --git a/scripts/mso-gateway-env.test.ts b/scripts/mso-gateway-env.test.ts
new file mode 100644
index 00000000..0dbd874a
--- /dev/null
+++ b/scripts/mso-gateway-env.test.ts
@@ -0,0 +1,32 @@
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { GATEWAY, fixture, runGateway } from "./mso-gateway-test-fixture";
+
+describe("gateway env-file identity", () => {
+ it("persists only canonical path/device/inode and never env contents", () => {
+ const f = fixture(); runGateway(["start"], f.baseEnv);
+ const raw = fs.readFileSync(path.join(f.state, "state.json"), "utf8");
+ const state = JSON.parse(raw) as { envFile: { path: string; dev: string; ino: string } };
+ const stat = fs.statSync(f.envFile);
+ expect(state.envFile).toEqual({ path: fs.realpathSync(f.envFile), dev: String(stat.dev), ino: String(stat.ino) });
+ expect(raw).not.toContain("fixture-only-not-a-real-secret");
+ runGateway(["stop"], f.baseEnv);
+ });
+
+ it("refuses a restore expectation after the env file is atomically replaced", () => {
+ const f = fixture(); runGateway(["start"], f.baseEnv);
+ const state = JSON.parse(fs.readFileSync(path.join(f.state, "state.json"), "utf8")) as { envFile: unknown };
+ runGateway(["stop"], f.baseEnv);
+ const replacement = path.join(f.dir, "replacement.env");
+ fs.writeFileSync(replacement, "OS_SESSION_SECRET=replaced\n", { mode: 0o600 });
+ fs.renameSync(replacement, f.envFile);
+ const out = spawnSync(GATEWAY, ["status"], {
+ encoding: "utf8",
+ env: { ...f.baseEnv, MSO_GATEWAY_EXPECT_ENV_IDENTITY: JSON.stringify(state.envFile) },
+ });
+ expect(out.status).not.toBe(0);
+ expect(out.stderr).toContain("env file identity changed while runtime was quiesced");
+ });
+});
diff --git a/scripts/mso-service-update.test.ts b/scripts/mso-service-update.test.ts
index aee3d714..a15735e2 100644
--- a/scripts/mso-service-update.test.ts
+++ b/scripts/mso-service-update.test.ts
@@ -17,11 +17,16 @@ function copy(root: string, rel: string, source: string) {
fs.copyFileSync(source, dst); fs.chmodSync(dst, 0o755);
}
-function state(home: string, name: string, root: string, localUrl: string, runtimeOwned = true) {
+function envIdentity(file: string) {
+ const stat = fs.statSync(file);
+ return { path: fs.realpathSync(file), dev: String(stat.dev), ino: String(stat.ino) };
+}
+
+function state(home: string, name: string, root: string, localUrl: string, envFile: string, runtimeOwned = true) {
const dir = path.join(home, ".mso/private/gateway", name);
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
for (const p of [path.join(home, ".mso"), path.join(home, ".mso/private"), path.join(home, ".mso/private/gateway")]) fs.chmodSync(p, 0o700);
- fs.writeFileSync(path.join(dir, "state.json"), `${JSON.stringify({ root, localUrl, runtimeOwned })}\n`, { mode: 0o600 });
+ fs.writeFileSync(path.join(dir, "state.json"), `${JSON.stringify({ root, localUrl, runtimeOwned, envFile: envIdentity(envFile) })}\n`, { mode: 0o600 });
}
function fixture(delayMs = 0, failRestoreUrl = "") {
@@ -31,7 +36,7 @@ function fixture(delayMs = 0, failRestoreUrl = "") {
copy(repo, "scripts/lib/private-state.sh", PRIVATE); copy(repo, "scripts/lib/update-state.sh", UPDATE_STATE);
copy(repo, "scripts/lib/runtime-exclusion.sh", RUNTIME_EXCLUSION); copy(repo, "scripts/lib/update-gateway-runtimes.sh", UPDATE_GATEWAYS);
fs.writeFileSync(path.join(repo, "scripts/mso-gateway"), `#!/bin/sh
-printf '%s %s\n' "$1" "\${MSO_GATEWAY_LOCAL_URL:-}" >> ${JSON.stringify(capture)}
+printf '%s %s env=%s expected=%s\n' "$1" "\${MSO_GATEWAY_LOCAL_URL:-}" "\${MSO_GATEWAY_ENV:-}" "\${MSO_GATEWAY_EXPECT_ENV_IDENTITY:-}" >> ${JSON.stringify(capture)}
if [ "$1" = runtime-stop ]; then printf '1\n' > "$MSO_GATEWAY_RECOVERY_MARKER"; chmod 600 "$MSO_GATEWAY_RECOVERY_MARKER"; echo 'runtime: stopped-owned'; exit 0; fi
[ "$1" = local-start ] && { [ "${failRestoreUrl}" = "\${MSO_GATEWAY_LOCAL_URL:-}" ] && exit 31; exit 0; }
exit 2
@@ -42,12 +47,14 @@ sleep ${Math.max(0, delayMs) / 1000}
printf 'self-end\n' >> ${JSON.stringify(capture)}
`, { mode: 0o755 });
const canonical = fs.realpathSync(repo);
- state(home, "one", canonical, "http://127.0.0.1:4555");
- state(home, "two", canonical, "http://127.0.0.1:4666");
- state(home, "other", path.join(base, "other-checkout"), "http://127.0.0.1:4777");
+ const envOne = path.join(base, "one.env"), envTwo = path.join(base, "two.env"), envOther = path.join(base, "other.env");
+ for (const file of [envOne, envTwo, envOther]) fs.writeFileSync(file, "OS_SESSION_SECRET=fixture\n", { mode: 0o600 });
+ state(home, "one", canonical, "http://127.0.0.1:4555", envOne);
+ state(home, "two", canonical, "http://127.0.0.1:4666", envTwo);
+ state(home, "other", path.join(base, "other-checkout"), "http://127.0.0.1:4777", envOther);
const env = { ...process.env, HOME: home, MSO_UPDATE_ROOT: repo,
MSO_UPDATE_STATE_DIR: path.join(base, "update-state"), MSO_RUNTIME_EXCLUSION_DIR: path.join(base, "runtime-exclusion") };
- return { base, repo, capture, env };
+ return { base, repo, capture, env, envOne, envTwo };
}
function runAsync(env: NodeJS.ProcessEnv) {
@@ -73,6 +80,27 @@ describe("service-active update lifecycle", () => {
expect(calls.lastIndexOf("local-start")).toBeGreaterThan(calls.indexOf("self-end"));
});
+
+ it("restores each fallback with the exact env-file identity it was launched with", () => {
+ const f = fixture(); execFileSync(WRAPPER, [], { env: f.env, encoding: "utf8" });
+ const calls = fs.readFileSync(f.capture, "utf8");
+ expect(calls).toContain(`local-start http://127.0.0.1:4555 env=${fs.realpathSync(f.envOne)} expected={`);
+ expect(calls).toContain(`local-start http://127.0.0.1:4666 env=${fs.realpathSync(f.envTwo)} expected={`);
+ expect(calls).toContain(`\"path\":\"${fs.realpathSync(f.envOne)}\"`);
+ expect(calls).toContain(`\"path\":\"${fs.realpathSync(f.envTwo)}\"`);
+ });
+
+ it("refuses to stop a legacy owned runtime before its env identity is migrated", () => {
+ const f = fixture();
+ const file = path.join(f.env.HOME as string, ".mso/private/gateway/one/state.json");
+ const legacy = JSON.parse(fs.readFileSync(file, "utf8")); delete legacy.envFile;
+ fs.writeFileSync(file, `${JSON.stringify(legacy)}\n`, { mode: 0o600 });
+ const out = spawnSync(WRAPPER, [], { env: f.env, encoding: "utf8" });
+ expect(out.status).not.toBe(0);
+ expect(out.stderr).toContain("predates env identity");
+ expect(fs.existsSync(f.capture) ? fs.readFileSync(f.capture, "utf8") : "").not.toContain("runtime-stop");
+ });
+
it("writes UPDATE OK only after every fallback runtime has been restored", () => {
const f = fixture(); execFileSync(WRAPPER, [], { env: f.env, encoding: "utf8" });
const log = fs.readFileSync(path.join(f.env.HOME as string, ".mso/self-update.log"), "utf8");
diff --git a/scripts/mso-update.test.ts b/scripts/mso-update.test.ts
index 4ccf91a9..55393851 100644
--- a/scripts/mso-update.test.ts
+++ b/scripts/mso-update.test.ts
@@ -70,7 +70,7 @@ if [ "${options.failInstallOnce ? "1" : "0"}" = 1 ] && [ "$1" = install ] && [ !
const gatewayScope = path.join(home, ".mso/private/gateway/default-scope");
fs.mkdirSync(gatewayScope, { recursive: true, mode: 0o700 }); fs.chmodSync(path.join(home, ".mso"), 0o700);
fs.chmodSync(path.join(home, ".mso/private"), 0o700); fs.chmodSync(path.join(home, ".mso/private/gateway"), 0o700);
- fs.writeFileSync(path.join(gatewayScope, "state.json"), JSON.stringify({ root: fs.realpathSync(repo), localUrl: "http://127.0.0.1:4555", runtimeOwned: true }) + "\n", { mode: 0o600 });
+ fs.writeFileSync(path.join(gatewayScope, "state.json"), JSON.stringify({ root: fs.realpathSync(repo), localUrl: "http://127.0.0.1:4555", runtimeOwned: true, envFile: { path: "/dev/null", dev: null, ino: null } }) + "\n", { mode: 0o600 });
const env = { ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}`, MSO_UPDATE_ROOT: repo,
MSO_UPDATE_NOTICE_DIR: path.join(root, "notice"), MSO_UPDATE_STATE_DIR: path.join(root, "update-state"),
MSO_RUNTIME_EXCLUSION_DIR: path.join(root, "runtime-exclusion"), MSO_UPDATE_LOCAL_URL: "http://127.0.0.1:4555" };