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): close update authority and stop races

Rahman024940b69cde
diff --git a/bin/mso-update-offline.test.ts b/bin/mso-update-offline.test.ts
index 0bcd30dd..066297bc 100644
--- a/bin/mso-update-offline.test.ts
+++ b/bin/mso-update-offline.test.ts
@@ -34,6 +34,7 @@ function fixture() {
"scripts/lib/update-state.sh",
"scripts/lib/runtime-exclusion.sh",
"scripts/lib/update-gateway-runtimes.sh",
+ "scripts/lib/update-git-authority.sh",
]) copy(repo, rel);
fs.writeFileSync(
path.join(fakebin, "curl"),
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 746300a8..11747547 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` close update authority and stop races
- `runtime` preserve installer and env lifecycles
- `runtime` serialize deploy and service starts
- `gateway` recheck web state under lock
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index c9ed1612..820fbd83 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -171,7 +171,7 @@ never changes the application bind to `0.0.0.0`. The tool cache is user-local an
with Cloudflare auto-update disabled. The tunnel process also receives a scrubbed environment rather
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
+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. User-facing `gateway stop` also takes the checkout update transaction lock before the gateway lifecycle lock, so an in-flight update/installer must finish its runtime restore first; the operator's later stop is therefore final instead of being undone by stale restore inventory. Internal updater `runtime-stop` deliberately does not reacquire that transaction lock. Private state and logs are owner-only and scoped by the canonical checkout plus selected loopback
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
@@ -452,7 +452,7 @@ mso update # preferred: update safely even if :4005 is down
mso update log
```
-The updater verifies the incoming checkout/build before replacing the service. With an active
+The updater verifies the incoming checkout/build before replacing the service. A normal `mso update` treats fetched `origin/main` as the release authority: after any fast-forward, local `main` must equal that remote commit exactly. A clean branch that is locally ahead or diverged is refused before dependency/build mutation instead of deploying unpushed code. `mso update status` reports that state explicitly. `mso update --rebuild` is different by design: it rebuilds the already-selected clean checkout without changing Git history. With an active
`mso.service` it first canonicalizes the unit's `WorkingDirectory` and requires it to equal the checkout
that invoked `mso update`; a secondary clone is never allowed to restart an unrelated live service.
The updater then runs outside that service cgroup so it survives the restart. With no active
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 172311c9..145b58a7 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.
+### `mso update` says local main is ahead/diverged from `origin/main`
+
+This is an authority refusal, not an updater failure. Normal update may deploy only the fetched `origin/main`
+release. Push the intended commit to `origin/main`, or reconcile/reset the checkout, then rerun `mso update`.
+MSO will not silently build a clean but unpushed local commit. If Git source is intentionally already correct
+and only the production build needs repair, `mso update --rebuild` rebuilds that selected clean checkout
+without fetching or rewriting Git history.
+
### 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
@@ -110,7 +118,9 @@ for full Terminal behavior. `mso gateway status` labels a Quick Tunnel as tempor
Expected. The gateway only stops a Next runtime when it launched that exact loopback process and
recorded it as gateway-owned. An existing systemd/manual runtime is outside the gateway lifecycle.
-This prevents `stop` from terminating an unrelated or pre-existing process.
+This prevents `stop` from terminating an unrelated or pre-existing process. If an update/installer is in
+flight, user-facing `mso gateway stop` waits for that checkout transaction to finish restoring its recorded
+fallbacks, then applies the stop under the gateway lifecycle lock; the updater cannot restart it afterward.
### Login returns success but the browser is logged out immediately
diff --git a/scripts/lib/update-git-authority.sh b/scripts/lib/update-git-authority.sh
new file mode 100755
index 00000000..bb965805
--- /dev/null
+++ b/scripts/lib/update-git-authority.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+# Classify one checkout against its fetched origin/main without mutating history.
+# Output: <exact|behind|ahead|diverged> <ahead-count> <behind-count>
+
+update_git_relation() {
+ local root="$1" head remote ahead behind relation
+ head="$(git -C "$root" rev-parse HEAD 2>/dev/null || true)"
+ remote="$(git -C "$root" rev-parse origin/main 2>/dev/null || true)"
+ [[ "$head" =~ ^[0-9a-f]{40}$ ]] && [[ "$remote" =~ ^[0-9a-f]{40}$ ]] || return 1
+ ahead="$(git -C "$root" rev-list --count origin/main..HEAD 2>/dev/null || true)"
+ behind="$(git -C "$root" rev-list --count HEAD..origin/main 2>/dev/null || true)"
+ [[ "$ahead" =~ ^[0-9]+$ ]] && [[ "$behind" =~ ^[0-9]+$ ]] || return 1
+ if [ "$ahead" -eq 0 ] && [ "$behind" -eq 0 ]; then relation=exact
+ elif [ "$ahead" -eq 0 ]; then relation=behind
+ elif [ "$behind" -eq 0 ]; then relation=ahead
+ else relation=diverged
+ fi
+ printf '%s %s %s\n' "$relation" "$ahead" "$behind"
+}
diff --git a/scripts/lib/update-state.sh b/scripts/lib/update-state.sh
index a38d44c0..ff2c3230 100755
--- a/scripts/lib/update-state.sh
+++ b/scripts/lib/update-state.sh
@@ -67,10 +67,12 @@ clear_restart_pending() {
}
update_lock_acquire() {
+ local timeout="${MSO_UPDATE_LOCK_TIMEOUT_SECONDS:-900}"
+ [[ "$timeout" =~ ^[0-9]+([.][0-9]+)?$ ]] || fail "invalid update transaction lock timeout"
init_update_state
mso_private_state_ensure_file "$UPDATE_LOCK_DIR" >/dev/null || fail "unsafe offline update transaction lock"
exec {UPDATE_LOCK_FD}<>"$UPDATE_LOCK_DIR" || fail "cannot open offline update transaction lock"
- if ! flock -x -w 900 "$UPDATE_LOCK_FD"; then
+ if ! flock -x -w "$timeout" "$UPDATE_LOCK_FD"; then
exec {UPDATE_LOCK_FD}>&- || true
UPDATE_LOCK_FD=''
fail "another offline update transaction is still running"
diff --git a/scripts/mso-gateway b/scripts/mso-gateway
index e02e7658..a7ffa352 100755
--- a/scripts/mso-gateway
+++ b/scripts/mso-gateway
@@ -9,6 +9,7 @@ ENVF="${MSO_GATEWAY_ENV:-$ROOT/.env.local}"
LOCAL_URL_OVERRIDE="${MSO_GATEWAY_LOCAL_URL:-}"
LOCAL_URL=""
STATE_ROOT_OVERRIDE="${MSO_GATEWAY_STATE_DIR:-}"
+UPDATE_STATE_DIR_REQUESTED="${MSO_UPDATE_STATE_DIR:-$HOME/.mso/private/update-state}"
STATE_ROOT=''
GATEWAY_CANONICAL_ROOT=''
GATEWAY_SCOPE_ID=''
@@ -26,6 +27,10 @@ for dep in node jq sha256sum realpath stat mktemp flock; do command -v "$dep" >/
# Source config early because it owns the single env-file safety validator.
# shellcheck source=scripts/lib/gateway-config.sh
. "$ROOT/scripts/lib/gateway-config.sh"
+# update-state uses the caller's fail() boundary; bridge it to the gateway error prefix.
+fail() { gateway_fail "$@"; }
+# shellcheck source=scripts/lib/update-state.sh
+. "$ROOT/scripts/lib/update-state.sh"
# Direct `scripts/mso-gateway` calls and `mso gateway` must have the same runtime
# environment. Persist only the validated file identity — never env contents.
@@ -81,9 +86,20 @@ gateway_with_runtime_shared() {
runtime_exclusion_release
}
+gateway_stop_serialized() {
+ local rc=0
+ # User stop is an operator intent that must be ordered AFTER any in-flight
+ # update/install transaction restores its fallback inventory. Internal
+ # runtime-stop intentionally does not take this lock (the updater already owns it).
+ update_lock_acquire
+ gateway_with_lock gateway_cmd_stop_locked || rc=$?
+ update_lock_release
+ return "$rc"
+}
+
case "${1:-status}" in
start) gateway_parse_start_args "$@"; gateway_with_lock gateway_with_runtime_shared gateway_cmd_start_locked ;;
- stop) gateway_with_lock gateway_cmd_stop_locked ;;
+ stop) gateway_stop_serialized ;;
status) gateway_cmd_status ;;
url) gateway_cmd_url ;;
doctor) gateway_cmd_doctor ;;
diff --git a/scripts/mso-gateway-stop-update-lock.test.ts b/scripts/mso-gateway-stop-update-lock.test.ts
new file mode 100644
index 00000000..27f30865
--- /dev/null
+++ b/scripts/mso-gateway-stop-update-lock.test.ts
@@ -0,0 +1,46 @@
+import { spawn, spawnSync } from "node:child_process";
+import crypto from "node:crypto";
+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";
+
+function transactionLock(base: string) {
+ const canonical = fs.realpathSync(process.cwd());
+ const key = crypto.createHash("sha256").update(canonical).digest("hex");
+ const scope = path.join(base, key); fs.mkdirSync(scope, { recursive: true, mode: 0o700 });
+ fs.chmodSync(base, 0o700); fs.chmodSync(scope, 0o700);
+ const lock = path.join(scope, "transaction.lock"); fs.writeFileSync(lock, "", { mode: 0o600 });
+ return lock;
+}
+
+describe("gateway stop vs update restore", () => {
+ it("waits for the checkout update transaction, then makes stop final", async () => {
+ const f = fixture(), updateState = path.join(f.dir, "update-state"), lock = transactionLock(updateState);
+ const env = { ...f.baseEnv, MSO_UPDATE_STATE_DIR: updateState, MSO_UPDATE_LOCK_TIMEOUT_SECONDS: "3" };
+ runGateway(["start"], env); expect(fs.existsSync(path.join(f.state, "state.json"))).toBe(true);
+ const holder = spawn("flock", ["-x", lock, "-c", "sleep 0.8"], { stdio: "ignore" });
+ await new Promise((r) => setTimeout(r, 80));
+ const stop = spawn(GATEWAY, ["stop"], { env, stdio: ["ignore", "pipe", "pipe"] });
+ let closed = false;
+ const done = new Promise<number | null>((resolve) => stop.once("close", (code) => { closed = true; resolve(code); }));
+ await new Promise((r) => setTimeout(r, 180));
+ expect(closed).toBe(false); expect(fs.existsSync(path.join(f.state, "state.json"))).toBe(true);
+ await new Promise<void>((resolve) => holder.once("close", () => resolve()));
+ expect(await done).toBe(0); expect(fs.existsSync(path.join(f.state, "state.json"))).toBe(false);
+ });
+
+ it("keeps internal runtime-stop independent of the transaction lock", async () => {
+ const f = fixture(), updateState = path.join(f.dir, "update-state"), lock = transactionLock(updateState);
+ const marker = path.join(f.dir, "restart-runtime");
+ const env = { ...f.baseEnv, MSO_UPDATE_STATE_DIR: updateState, MSO_UPDATE_LOCK_TIMEOUT_SECONDS: "0.1", MSO_GATEWAY_RECOVERY_MARKER: marker };
+ runGateway(["start"], env);
+ fs.writeFileSync(f.curl, "#!/bin/sh\nexit 1\n", { mode: 0o700 });
+ const holder = spawn("flock", ["-x", lock, "-c", "sleep 0.7"], { stdio: "ignore" });
+ await new Promise((r) => setTimeout(r, 80));
+ const out = spawnSync(GATEWAY, ["runtime-stop"], { env, encoding: "utf8" });
+ expect(out.status).toBe(0); expect(out.stdout).toContain("runtime: already-down");
+ holder.kill(); await new Promise<void>((resolve) => holder.once("close", () => resolve()));
+ runGateway(["stop"], { ...env, MSO_UPDATE_LOCK_TIMEOUT_SECONDS: "2" });
+ });
+});
diff --git a/scripts/mso-update b/scripts/mso-update
index c3f94f49..420e900e 100755
--- a/scripts/mso-update
+++ b/scripts/mso-update
@@ -16,23 +16,19 @@ GATEWAY="$ROOT/scripts/mso-gateway"
. "$ROOT/scripts/lib/runtime-exclusion.sh"
# shellcheck source=scripts/lib/update-gateway-runtimes.sh
. "$ROOT/scripts/lib/update-gateway-runtimes.sh"
-
+# shellcheck source=scripts/lib/update-git-authority.sh
+. "$ROOT/scripts/lib/update-git-authority.sh"
fail() { printf 'mso update: %s\n' "$*" >&2; exit 1; }
git_root() { [ "$(git -C "$ROOT" rev-parse --show-toplevel 2>/dev/null || true)" = "$ROOT" ]; }
current_version() { sed -n 's/^VERSION="\([^"]*\)".*/\1/p' "$ROOT/bin/mso" | head -1; }
remote_version() { git -C "$ROOT" show origin/main:bin/mso 2>/dev/null | sed -n 's/^VERSION="\([^"]*\)".*/\1/p' | head -1; }
-behind() { git -C "$ROOT" rev-list --count HEAD..origin/main 2>/dev/null || printf 0; }
-
require_checkout() {
git_root || fail "$ROOT is not a Git checkout; reinstall from the official repository"
[ "$(git -C "$ROOT" branch --show-current)" = main ] || fail "updates require the installed checkout to be on main"
[ -z "$(git -C "$ROOT" status --porcelain)" ] || fail "checkout has local changes; refusing to overwrite them"
}
-
fetch_main() { git -C "$ROOT" fetch --quiet origin main || fail "could not reach origin/main"; }
-
service_is_active() { command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet mso.service; }
-
service_port() {
local raw port
raw="$(systemctl show -p Environment --value mso.service 2>/dev/null || true)"
@@ -40,7 +36,6 @@ service_port() {
if ! [[ "$port" =~ ^[0-9]+$ ]] || [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then port=4005; fi
printf '%s' "$port"
}
-
service_build_sha() {
local timeout="${1:-3}" port body sha
port="$(service_port)"
@@ -52,7 +47,6 @@ service_build_sha() {
' 2>/dev/null)" || return 1
printf '%s' "$sha"
}
-
require_service_checkout() {
local configured canonical_root canonical_service
configured="$(systemctl show -p WorkingDirectory --value mso.service 2>/dev/null || true)"
@@ -64,10 +58,19 @@ require_service_checkout() {
[ "$canonical_service" = "$canonical_root" ] \
|| fail "active mso.service belongs to $canonical_service, not this checkout $canonical_root; run update from the service checkout"
}
-
print_status() {
- local n local_v remote_v head receipt=''
- require_checkout; fetch_main; n="$(behind)"; local_v="$(current_version)"; remote_v="$(remote_version)"; head="$(git -C "$ROOT" rev-parse HEAD)"
+ local relation ahead n local_v remote_v head receipt=''
+ require_checkout; fetch_main
+ read -r relation ahead n < <(update_git_relation "$ROOT") || fail "could not compare HEAD with origin/main"
+ local_v="$(current_version)"; remote_v="$(remote_version)"; head="$(git -C "$ROOT" rev-parse HEAD)"
+ if [ "$relation" = ahead ]; then
+ printf 'local main is ahead of origin/main by %s commit%s; refusing to deploy unpushed code. push/reset the checkout first.\n' "$ahead" "$([ "$ahead" = 1 ] || printf s)"
+ return
+ fi
+ if [ "$relation" = diverged ]; then
+ printf 'local main has diverged from origin/main (ahead %s, behind %s); refusing update. reconcile the checkout first.\n' "$ahead" "$n"
+ return
+ fi
if [ "$n" -gt 0 ]; then
printf 'update available: mso %s -> %s (%s commit%s)\n' "${local_v:-unknown}" "${remote_v:-newer}" "$n" "$([ "$n" = 1 ] || printf s)"
git -C "$ROOT" log --format=' %h %s' -5 HEAD..origin/main
@@ -96,9 +99,8 @@ print_status() {
printf 'mso %s is up to date (%s)\n' "${local_v:-unknown}" "${head:0:7}"
fi
}
-
notice() {
- local dir stamp now last=0 n local_v remote_v
+ local dir stamp now last=0 relation ahead n local_v remote_v
git_root || return 0
[ "$(git -C "$ROOT" branch --show-current 2>/dev/null || true)" = main ] || return 0
dir="$(mso_private_state_dir "$NOTICE_DIR")" || return 0; stamp="$dir/last-fetch"; now="$(date +%s)"
@@ -107,7 +109,12 @@ notice() {
printf '%s\n' "$now" | mso_private_state_atomic_write "$stamp" >/dev/null 2>&1 || true
(cd "$ROOT" && nohup git fetch --quiet origin main >/dev/null 2>&1 </dev/null &) || true
fi
- n="$(behind)"
+ read -r relation ahead n < <(update_git_relation "$ROOT") || return 0
+ if [ "$relation" = ahead ] || [ "$relation" = diverged ]; then
+ printf 'MSO update refused: local main is %s origin/main (ahead %s, behind %s). Reconcile/push the checkout first.\n' \
+ "$relation" "$ahead" "$n" >&2
+ return 0
+ fi
if [ "$n" -gt 0 ]; then
local_v="$(current_version)"; remote_v="$(remote_version)"
printf 'MSO update available: %s -> %s (%s commit%s). Run: mso update\n' \
@@ -137,9 +144,18 @@ offline_build_locked() {
service_is_active && fail "mso.service became active while waiting for the offline update lock; rerun mso update"
init_update_state
if [ "$rebuild_only" != 1 ]; then
+ local relation ahead
fetch_main
- n="$(behind)"
- [ "$n" -eq 0 ] || git -C "$ROOT" merge --ff-only origin/main || fail "cannot fast-forward to origin/main"
+ read -r relation ahead n < <(update_git_relation "$ROOT") || fail "could not compare HEAD with origin/main"
+ case "$relation" in
+ exact) ;;
+ behind) git -C "$ROOT" merge --ff-only origin/main || fail "cannot fast-forward to origin/main" ;;
+ ahead) fail "local main is ahead of origin/main by $ahead commit(s); refusing to deploy unpushed code" ;;
+ diverged) fail "local main has diverged from origin/main (ahead $ahead, behind $n); reconcile it before update" ;;
+ *) fail "unknown Git authority state" ;;
+ esac
+ read -r relation ahead n < <(update_git_relation "$ROOT") || fail "could not re-check origin/main after fast-forward"
+ [ "$relation" = exact ] || fail "checkout does not exactly match origin/main after update; refusing deployment"
fi
head="$(git -C "$ROOT" rev-parse HEAD)"
if [ -e "$DEPLOY_RECEIPT" ] || [ -L "$DEPLOY_RECEIPT" ]; then receipt="$(read_receipt)"; fi
diff --git a/scripts/mso-update-authority.test.ts b/scripts/mso-update-authority.test.ts
new file mode 100644
index 00000000..e5b1ebbb
--- /dev/null
+++ b/scripts/mso-update-authority.test.ts
@@ -0,0 +1,59 @@
+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 UPDATE = path.join(ROOT, "scripts/mso-update");
+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 git(cwd: string, ...args: string[]) { return execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); }
+
+function fixture() {
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), "mso-update-authority-")); roots.push(base);
+ const repo = path.join(base, "repo"), remote = path.join(base, "remote.git"), fakebin = path.join(base, "bin"), capture = path.join(base, "capture");
+ fs.mkdirSync(path.join(repo, "scripts/lib"), { recursive: true }); fs.mkdirSync(path.join(repo, "bin")); fs.mkdirSync(fakebin);
+ for (const rel of ["scripts/lib/private-state.sh", "scripts/lib/update-state.sh", "scripts/lib/runtime-exclusion.sh", "scripts/lib/update-gateway-runtimes.sh", "scripts/lib/update-git-authority.sh", "scripts/self-update.sh"]) copy(path.join(ROOT, rel), path.join(repo, rel));
+ fs.writeFileSync(path.join(repo, "bin/mso"), '#!/bin/sh\nVERSION="1.0.0"\n', { mode: 0o755 });
+ git(repo, "init", "-q", "-b", "main"); git(repo, "config", "user.name", "MSO Test"); git(repo, "config", "user.email", "[email protected]");
+ git(repo, "add", "."); git(repo, "commit", "-q", "-m", "remote base");
+ git(base, "init", "--bare", "-q", remote); git(repo, "remote", "add", "origin", remote); git(repo, "push", "-q", "-u", "origin", "main");
+ fs.writeFileSync(path.join(repo, "local-only.txt"), "not pushed\n"); git(repo, "add", "."); git(repo, "commit", "-q", "-m", "local only");
+ fs.writeFileSync(path.join(fakebin, "systemctl"), "#!/bin/sh\nexit 3\n", { mode: 0o755 });
+ fs.writeFileSync(path.join(fakebin, "bun"), `#!/bin/sh\nprintf 'bun %s\\n' "$*" >> ${JSON.stringify(capture)}\n`, { mode: 0o755 });
+ const env = { ...process.env, HOME: path.join(base, "home"), PATH: `${fakebin}:${process.env.PATH}`, MSO_UPDATE_ROOT: repo,
+ MSO_UPDATE_STATE_DIR: path.join(base, "update-state"), MSO_RUNTIME_EXCLUSION_DIR: path.join(base, "runtime-exclusion"), MSO_UPDATE_NOTICE_DIR: path.join(base, "notice") };
+ fs.mkdirSync(env.HOME, { recursive: true });
+ return { base, repo, capture, env };
+}
+
+afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
+
+describe("origin/main deployment authority", () => {
+ it("reports local-ahead main instead of calling it up to date", () => {
+ const f = fixture(); const out = execFileSync(UPDATE, ["status"], { env: f.env, encoding: "utf8" });
+ expect(out).toContain("ahead of origin/main by 1 commit"); expect(out).toContain("refusing to deploy unpushed code");
+ expect(out).not.toContain("is up to date");
+ });
+
+ it("normal offline update refuses local-only commits before install/build", () => {
+ const f = fixture(); const before = git(f.repo, "rev-parse", "HEAD");
+ const out = spawnSync(UPDATE, [], { env: f.env, encoding: "utf8" });
+ expect(out.status).not.toBe(0); expect(out.stderr).toContain("ahead of origin/main");
+ expect(git(f.repo, "rev-parse", "HEAD")).toBe(before);
+ expect(fs.existsSync(f.capture) ? fs.readFileSync(f.capture, "utf8") : "").not.toContain("bun");
+ });
+
+ it("active-service inner normal update enforces the same remote authority", () => {
+ const f = fixture(), log = path.join(f.base, "self-update.log");
+ const out = spawnSync(path.join(f.repo, "scripts/self-update.sh"), [], { env: { ...f.env, MSO_UPDATE_LOG: log }, encoding: "utf8" });
+ expect(out.status).not.toBe(0);
+ expect(fs.readFileSync(log, "utf8")).toContain("ahead of origin/main");
+ expect(fs.existsSync(f.capture) ? fs.readFileSync(f.capture, "utf8") : "").not.toContain("bun");
+ });
+});
diff --git a/scripts/mso-update-service-status.test.ts b/scripts/mso-update-service-status.test.ts
index 202c2d07..cafc8b4f 100644
--- a/scripts/mso-update-service-status.test.ts
+++ b/scripts/mso-update-service-status.test.ts
@@ -5,7 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
const SCRIPT = path.join(process.cwd(), "scripts/mso-update");
-const LIBS = ["private-state.sh", "update-state.sh", "runtime-exclusion.sh", "update-gateway-runtimes.sh"];
+const LIBS = ["private-state.sh", "update-state.sh", "runtime-exclusion.sh", "update-gateway-runtimes.sh", "update-git-authority.sh"];
const roots: string[] = [];
function git(cwd: string, ...args: string[]) {
diff --git a/scripts/mso-update.test.ts b/scripts/mso-update.test.ts
index 55393851..35c5bc1a 100644
--- a/scripts/mso-update.test.ts
+++ b/scripts/mso-update.test.ts
@@ -20,6 +20,7 @@ function fixture(options: { failInstallOnce?: boolean; activeService?: "same" |
fs.copyFileSync(UPDATE_STATE, path.join(repo, "scripts/lib/update-state.sh"));
fs.copyFileSync(RUNTIME_EXCLUSION, path.join(repo, "scripts/lib/runtime-exclusion.sh"));
fs.copyFileSync(UPDATE_GATEWAYS, path.join(repo, "scripts/lib/update-gateway-runtimes.sh"));
+ fs.copyFileSync(path.join(process.cwd(), "scripts/lib/update-git-authority.sh"), path.join(repo, "scripts/lib/update-git-authority.sh"));
fs.copyFileSync(SERVICE_UPDATE, path.join(repo, "scripts/mso-service-update")); fs.chmodSync(path.join(repo, "scripts/mso-service-update"), 0o755);
fs.writeFileSync(path.join(repo, "scripts/self-update.sh"), `#!/bin/sh\nprintf 'self-update %s\\n' "$*" >> "${capture}"\n`, { mode: 0o755 });
fs.writeFileSync(path.join(repo, "scripts/verify-build.sh"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
@@ -76,7 +77,6 @@ if [ "${options.failInstallOnce ? "1" : "0"}" = 1 ] && [ "$1" = install ] && [ !
MSO_RUNTIME_EXCLUSION_DIR: path.join(root, "runtime-exclusion"), MSO_UPDATE_LOCAL_URL: "http://127.0.0.1:4555" };
return { root, repo, remote, old, newer, capture, env, home };
}
-
function receipts(base: string) {
if (!fs.existsSync(base)) return [] as Array<{ path: string; root: string; sha: string }>;
return fs.readdirSync(base, { withFileTypes: true }).filter((e) => e.isDirectory()).flatMap((e) => {
diff --git a/scripts/self-update.sh b/scripts/self-update.sh
index 2913641e..18970f60 100755
--- a/scripts/self-update.sh
+++ b/scripts/self-update.sh
@@ -16,6 +16,8 @@ set -uo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" || exit 1
cd "$ROOT" || exit 1
+# shellcheck source=scripts/lib/update-git-authority.sh
+. "$ROOT/scripts/lib/update-git-authority.sh"
LOG="${MSO_UPDATE_LOG:-$HOME/.mso/self-update.log}"
mkdir -p "$(dirname "$LOG")"
@@ -60,11 +62,19 @@ fi
if [ "$REBUILD_ONLY" -eq 0 ]; then
step "fetching origin/main"
git fetch --quiet origin main || die "could not reach the remote"
- step "fast-forwarding"
- # --ff-only, never a merge: this checkout must stay a mirror of main. A refusal
- # here means someone committed on the host, and silently merging their work into
- # a deploy is worse than stopping.
- git merge --ff-only origin/main || die "cannot fast-forward — the checkout has diverged from origin/main"
+ step "verifying remote authority / fast-forwarding"
+ read -r RELATION AHEAD_COUNT BEHIND_COUNT < <(update_git_relation "$ROOT") \
+ || die "could not compare checkout with origin/main"
+ case "$RELATION" in
+ exact) ;;
+ behind) git merge --ff-only origin/main || die "cannot fast-forward — the checkout has diverged from origin/main" ;;
+ ahead) die "local main is ahead of origin/main by $AHEAD_COUNT commit(s); refusing to deploy unpushed code" ;;
+ diverged) die "local main has diverged from origin/main (ahead $AHEAD_COUNT, behind $BEHIND_COUNT)" ;;
+ *) die "unknown Git authority state" ;;
+ esac
+ read -r RELATION AHEAD_COUNT BEHIND_COUNT < <(update_git_relation "$ROOT") \
+ || die "could not re-check origin/main after fast-forward"
+ [ "$RELATION" = exact ] || die "checkout does not exactly match origin/main after update"
git log -1 --format='now at %h — %s'
step "installing dependencies"