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(install): make one-line bootstrap atomic

Rahman83413ca90fe4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 32a04b04..e95727f1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -40,7 +40,7 @@ jobs:
run: node -e "require('node-pty')"
- name: Validate installer syntax
- run: bash -n scripts/install.sh
+ run: bash -n scripts/install.sh && bash -n scripts/install-core.sh
- name: Typecheck
run: bun run typecheck
diff --git a/CLAUDE.md b/CLAUDE.md
index 4c345106..c0876483 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -238,7 +238,7 @@ to `resources/` (rr) and drive any project from one manifest:
in THIS repo** (it used to live untracked under `~/.openclaw/workspace/`, so a fresh
clone could not start the Browser at all and the `-nopw` → `-rfbauth` hardening had no
version control). The script refuses to start without a VNC password file. Two further
- host-side facts that `scripts/install.sh` NOW CARRIES ITSELF, and that the feature dies
+ host-side facts that the installer flow (`scripts/install.sh` → verified `scripts/install-core.sh`) NOW CARRIES, and that the feature dies
quietly without: (1) `loginctl enable-linger <user>`, or the unit stops at
logout and never starts at boot; (2) `Environment=XDG_RUNTIME_DIR=/run/user/<uid>` in
mso.service — a system unit running as `User=` gets NO user-bus address, so without it
@@ -246,7 +246,7 @@ to `resources/` (rr) and drive any project from one manifest:
`lib/camoufox/service.ts` reports that as an error rather than as "not installed", so the
panel tells you which one it is.
Treating these as un-carryable host lore was itself the bug: a host set up by
- `scripts/install.sh` alone had neither, so the Browser app looked uninstalled and every
+ the installer flow had neither, so the Browser app looked uninstalled and every
managed-app install died at the step that registers its user service. The installer sets
both now, and `lib/managed-apps/user-bus.ts` re-derives the bus address at call time so a
cockpit installed BEFORE this change is not left broken until someone re-runs the
@@ -365,7 +365,7 @@ the real runtime and working analogue before changing a tool or skill contract.
## CLI (`bin/mso`) — the web UI is only one frontend
`bin/mso` reaches the same `/api` surface from a shell — every route has a named verb
(enforced by a test in `bin/mso.test.ts`), plus `doctor`, `completion` and `--base`.
-`scripts/install.sh` symlinks
+`scripts/install.sh` verifies and launches `scripts/install-core.sh`; the core symlinks
it to `~/.local/bin/mso` and symlinks `claude-skills/*` into `~/.claude/skills/`
(every committed directory under `claude-skills/`, including `/mso-skill-authoring`).
`mso -h` lists every verb; `mso api <METHOD> <path> [json]` is
diff --git a/README.md b/README.md
index bf55001e..492b5a15 100644
--- a/README.md
+++ b/README.md
@@ -108,9 +108,15 @@ Run one command on the Linux server as your normal user, **not root**:
curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash
```
+That URL is now a **small bootstrap, not the 30 KB installer body**. It downloads
+`scripts/install-core.sh` to a private temporary file, retries transient transfers, requires
+the complete EOF marker, verifies the committed SHA-256 and `bash -n`, and only then executes
+the core. This prevents a truncated `curl | bash` response from stopping after a few preflight
+lines while incorrectly returning success. The command stays the same; the execution boundary is safer.
+
A fresh install now finishes with a **guided terminal onboarding** when a controlling
-terminal is available. `curl | bash` uses stdin for the downloaded script, so the
-installer deliberately opens `/dev/tty` for the prompts instead of silently skipping them.
+terminal is available. The public bootstrap itself arrives on stdin, so the verified core
+still opens `/dev/tty` for prompts instead of depending on pipeline stdin.
The flow lets you choose:
- **Alfa AI provider** — OpenAI ChatGPT/Codex device OAuth, or an API-key provider such
@@ -330,7 +336,7 @@ bun run verify # typecheck + lint + test + checks + audit
node scripts/check-docs.mjs # docs links/toolset/slice drift
node scripts/gen-comparison.mjs --check # comparison evidence + 90-day freshness
bash scripts/verify-build.sh # build HEAD out-of-tree — safe on the prod checkout
-bash -n scripts/install.sh
+bash -n scripts/install.sh && bash -n scripts/install-core.sh
```
The package manager is **bun** (`bun.lock` is committed); the **runtime stays Node 22** — `next`, `tsc`, `eslint` and `vitest` all carry a `#!/usr/bin/env node` shebang and bun honours it, and production runs `npm run start`. Use bun so the lockfile and the native `node-pty` build path stay predictable: `node-pty` has no Linux prebuild and is listed under `trustedDependencies`, without which its postinstall is skipped and the whole `/api/v1` surface fails to load.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index cd57fe44..7ac80129 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Fixed**
+- `install` make one-line bootstrap atomic
- `install` bind readiness to runtime instance
- `install` preserve caller path semantics
- `install` prove stable-id service takeover
diff --git a/docs/CLI.md b/docs/CLI.md
index 81e650f9..d07df50a 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -5,7 +5,7 @@
The browser UI at your instance's domain is one frontend, not the product. `mso`
reaches the same `/api` surface from a shell, so every feature is scriptable.
-`scripts/install.sh` symlinks `bin/mso` to `~/.local/bin/mso`. To install it by
+`scripts/install.sh` verifies and launches `scripts/install-core.sh`, which symlinks `bin/mso` to `~/.local/bin/mso`. To install it by
hand from a checkout:
```bash
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 080dfd84..1f9b648a 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -26,7 +26,12 @@ Run as the normal server user, not root:
curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash
```
-The installer:
+`scripts/install.sh` is intentionally a tiny bootstrap. It downloads `scripts/install-core.sh`
+completely into a private temporary file, retries transient transfers, checks a committed SHA-256,
+requires the exact EOF marker, runs `bash -n`, and only then executes the payload. The large
+installer is therefore never executed while bytes are still arriving over the network.
+
+The installer core:
1. resolves/creates the checkout and records whether this is a fresh install;
2. installs Bun/dependencies as needed;
@@ -56,8 +61,8 @@ Useful flags:
--uninstall remove the system unit; keep code + ~/.mso
```
-`curl | bash` cannot use stdin for questions because stdin carries the script itself. The
-installer therefore prompts through `/dev/tty`. If there is no controlling terminal it
+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.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 0dbc901b..96336b74 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -49,6 +49,30 @@ CodeQL/dependency/Gitleaks/Trivy/OSV/Semgrep checks.
> [`docs/README.md`](./README.md) and [`docs/ARCHITECTURE.md`](./ARCHITECTURE.md); keep old
> entries intact as historical evidence even when their commands/counts have been superseded.
+## 2026-08-30 — atomic installer bootstrap for WSL / partial-transfer safety (SHIPPED)
+
+A real WSL run of the documented one-liner exposed a gap the earlier isolated tests missed: the
+large `scripts/install.sh` was executed directly from the network stream. Replaying only the first
+11,981 bytes of that file reproduced the report exactly — Node and Bun printed as healthy, Bash
+reached a syntactically complete EOF and returned **0**, but checkout/CLI installation never ran.
+A partial HTTP response could therefore look like a successful install even though `mso -h` did
+not exist.
+
+The public `scripts/install.sh` is now an intentionally small bootstrap. It downloads the complete
+`scripts/install-core.sh` to an owner-private temporary file first, retries the transfer, requires
+a minimum payload size and exact EOF marker, verifies the committed SHA-256, runs `bash -n`, and
+only then executes the core with the original arguments. The core carries phase-only error
+reporting (no raw command/secret echo). A second clean-image reproduction found that `bin/mso` also
+requires `jq`: Node and Bun alone were not enough, and the old installer never installed that CLI
+runtime dependency. The core now verifies/installs `curl`, `jq` and the required coreutils before
+creating the launcher, then separately proves the target is executable and that `mso -h` succeeds.
+
+The existing WSL contracts remain intact: CLI setup precedes service setup, PID 1—not the presence
+of `systemctl`—decides service availability, caller PATH/cwd semantics are preserved, custom bin
+paths are reported honestly, and installer-driven service readiness is tied to a fresh runtime
+instance ID. Contract tests execute the local bootstrap/core pair and prove that a syntactically
+complete truncated payload is rejected.
+
## 2026-08-29 — evidence-backed comparison, delegated roles and Service Center (SHIPPED)
The old README comparison mixed unrelated tools into one hand-written scorecard. It is now generated
diff --git a/lib/install-contract.test.ts b/lib/install-contract.test.ts
index 3c843020..f7c6bb80 100644
--- a/lib/install-contract.test.ts
+++ b/lib/install-contract.test.ts
@@ -1,21 +1,60 @@
-import { execFileSync } from "node:child_process";
+import { execFileSync, spawnSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
+import os from "node:os";
+import crypto from "node:crypto";
import { describe, expect, it } from "vitest";
-const INSTALL = path.join(__dirname, "../scripts/install.sh");
+const BOOTSTRAP = path.join(__dirname, "../scripts/install.sh");
+const CORE = path.join(__dirname, "../scripts/install-core.sh");
describe("one-line installer contract", () => {
it("is valid bash and documents onboarding controls", () => {
- expect(() => execFileSync("bash", ["-n", INSTALL])).not.toThrow();
- const help = execFileSync("bash", [INSTALL, "--help"], { encoding: "utf8" });
+ expect(() => execFileSync("bash", ["-n", BOOTSTRAP])).not.toThrow();
+ expect(() => execFileSync("bash", ["-n", CORE])).not.toThrow();
+ const help = execFileSync("bash", [CORE, "--help"], { encoding: "utf8" });
expect(help).toContain("--onboard");
expect(help).toContain("--no-onboard");
expect(help).toContain("-y, --yes");
});
+ it("downloads and verifies the complete installer core before executing any payload bytes", () => {
+ const bootstrap = fs.readFileSync(BOOTSTRAP, "utf8");
+ const core = fs.readFileSync(CORE);
+ expect(Buffer.byteLength(bootstrap)).toBeLessThan(4096);
+ expect(bootstrap).toContain("scripts/install-core.sh");
+ expect(bootstrap).toContain("installer payload is unexpectedly short");
+ expect(bootstrap).toContain("EOF marker missing");
+ expect(bootstrap).toContain('bash -n "$TMP_INSTALLER"');
+ expect(bootstrap).toContain('bash "$TMP_INSTALLER" "$@"');
+ const declared = bootstrap.match(/CORE_SHA256="([0-9a-f]{64})"/)?.[1];
+ expect(declared).toBe(crypto.createHash("sha256").update(core).digest("hex"));
+ expect(core.toString("utf8").trimEnd().endsWith("# MSO_INSTALLER_CORE_EOF")).toBe(true);
+ });
+
+ it("runs the verified local core and rejects a syntactically complete truncated payload", () => {
+ const env = { ...process.env, MSO_INSTALL_CORE_URL: `file://${CORE}` };
+ const help = execFileSync("bash", [BOOTSTRAP, "--help"], { encoding: "utf8", env });
+ expect(help).toContain("mso installer");
+
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-installer-truncated-"));
+ try {
+ const truncated = path.join(dir, "install-core.sh");
+ const source = fs.readFileSync(CORE);
+ fs.writeFileSync(truncated, source.subarray(0, Math.min(22000, source.length - 1)));
+ const result = spawnSync("bash", [BOOTSTRAP, "--help"], {
+ encoding: "utf8",
+ env: { ...process.env, MSO_INSTALL_CORE_URL: `file://${truncated}` },
+ });
+ expect(result.status).not.toBe(0);
+ expect(result.stderr).toMatch(/incomplete|hash mismatch|unexpectedly short/);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
it("uses the controlling tty after curl|bash and never stdin for onboarding", () => {
- const src = fs.readFileSync(INSTALL, "utf8");
+ const src = fs.readFileSync(CORE, "utf8");
expect(src).toContain("[ -r /dev/tty ] && [ -w /dev/tty ]");
expect(src).toContain('onboard </dev/tty >/dev/tty 2>/dev/tty');
expect(src).toContain('ONBOARD_MODE=auto');
@@ -23,7 +62,7 @@ describe("one-line installer contract", () => {
});
it("installs the CLI before service setup and proves it against the invoking PATH", () => {
- const src = fs.readFileSync(INSTALL, "utf8");
+ const src = fs.readFileSync(CORE, "utf8");
expect(src.indexOf("# ---- CLI on PATH")).toBeLessThan(src.indexOf("# ---- systemd unit ----"));
expect(src).toContain('PARENT_PATH="${PATH:-}"');
expect(src).toContain('PARENT_CWD="$PWD"');
@@ -35,10 +74,14 @@ describe("one-line installer contract", () => {
expect(src).toContain("# >>> mso cli >>>");
expect(src).toContain('export PATH="$BIN_DIR:$PATH"');
expect(src).toContain('custom MSO_BIN_DIR is not persisted automatically');
+ expect(src).toContain("ensure_cli_tools()");
+ expect(src).toContain("curl jq coreutils");
+ expect(src).toContain('[ -x "$BIN_DIR/mso" ]');
+ expect(src).toContain('CLI launcher self-check failed');
});
it("requires systemd as PID 1 before service setup and gates onboarding on verified health", () => {
- const src = fs.readFileSync(INSTALL, "utf8");
+ const src = fs.readFileSync(CORE, "utf8");
expect(src).toContain("systemd_ready()");
expect(src).toContain("/proc/1/comm");
expect(src).toContain('= "systemd"');
@@ -54,7 +97,7 @@ describe("one-line installer contract", () => {
});
it("verifies a commit-pinned Bun bootstrap before execution", () => {
- const src = fs.readFileSync(INSTALL, "utf8");
+ const src = fs.readFileSync(CORE, "utf8");
expect(src).toMatch(/BUN_BOOTSTRAP_COMMIT="[0-9a-f]{40}"/);
expect(src).toMatch(/BUN_BOOTSTRAP_SHA256="[0-9a-f]{64}"/);
expect(src).toContain('raw.githubusercontent.com/oven-sh/bun/$BUN_BOOTSTRAP_COMMIT/src/cli/install.sh');
diff --git a/scripts/gen-cli-docs.mjs b/scripts/gen-cli-docs.mjs
index 2ae1b645..c7086fbf 100644
--- a/scripts/gen-cli-docs.mjs
+++ b/scripts/gen-cli-docs.mjs
@@ -26,7 +26,7 @@ const doc = `<!-- GENERATED by scripts/gen-cli-docs.mjs — edit the header of b
The browser UI at your instance's domain is one frontend, not the product. \`mso\`
reaches the same \`/api\` surface from a shell, so every feature is scriptable.
-\`scripts/install.sh\` symlinks \`bin/mso\` to \`~/.local/bin/mso\`. To install it by
+\`scripts/install.sh\` verifies and launches \`scripts/install-core.sh\`, which symlinks \`bin/mso\` to \`~/.local/bin/mso\`. To install it by
hand from a checkout:
\`\`\`bash
diff --git a/scripts/install-core.sh b/scripts/install-core.sh
new file mode 100755
index 00000000..d9444c2f
--- /dev/null
+++ b/scripts/install-core.sh
@@ -0,0 +1,691 @@
+#!/usr/bin/env bash
+# mso (Manef Shell OS) installer core — fetched and verified by scripts/install.sh.
+#
+# curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash
+#
+# Idempotent: re-running updates the checkout, rebuilds, and restarts the
+# service. The bootstrap never needs stdin, so curl|bash stays safe. After a
+# FRESH install it uses /dev/tty (when present) for guided onboarding; CI/headless
+# installs never hang and can run `mso onboard` later. Existing .env.local is preserved.
+set -Eeuo pipefail
+
+# ---- config: env override > flag > default ----
+REPO_URL="${MSO_REPO:-https://github.com/rahmanef63/mso.git}"
+DIR="${MSO_DIR:-$HOME/mso}"
+DIR_EXPLICIT=0
+REF="${MSO_REF:-main}"
+PORT="${MSO_PORT:-4005}"
+# Address the server listens on. Loopback by DEFAULT, for two reasons that point
+# the same way:
+# 1. It cannot log in otherwise. sessionCookieAttrs() sets `secure: true`
+# (lib/auth/session-cookie.ts), and a browser only accepts a Secure cookie
+# over plain http on a trustworthy origin — localhost / 127.0.0.1 / ::1. So
+# http://<lan-or-public-ip>:PORT returns 200 on login and then silently
+# drops the cookie: an endless login loop. A 0.0.0.0 bind buys no working
+# access it did not already have.
+# 2. It is a shell. An authenticated session runs commands as this user, and a
+# fresh VPS has ufw installed but disabled — so the old default published
+# that shell to the whole internet about two minutes into a curl|bash.
+# Reach it over an SSH tunnel, `tailscale serve`, or a reverse proxy on this host
+# (all three land the browser on a trustworthy origin, so the cookie sticks).
+BIND="${MSO_BIND:-127.0.0.1}"
+SERVICE="mso.service"
+DO_SERVICE=1
+DO_UNINSTALL=0
+YES=0
+ONBOARD_MODE=auto
+FRESH_INSTALL=0
+# bun is the package manager; the RUNTIME stays node (see ensure_bun below).
+export BUN_INSTALL="${BUN_INSTALL:-$HOME/.bun}"
+# Capture the INVOKING shell PATH before Bun or the installer changes it. A child
+# curl|bash process cannot export back into its parent, so this is the only PATH
+# that matters when proving `mso -h` will resolve immediately after we return.
+PARENT_PATH="${PATH:-}"
+PARENT_CWD="$PWD"
+SERVICE_READY=0
+SERVICE_ATTEMPTED=0
+# Reproducible bootstrap: this is Bun v1.3.14's installer source, pinned by
+# immutable Git commit and verified before execution. Update both values together.
+BUN_BOOTSTRAP_COMMIT="0d9b296af33f2b851fcbf4df3e9ec89751734ba4"
+BUN_BOOTSTRAP_SHA256="bab8acfb046aac8c72407bdcce903957665d655d7acaa3e11c7c4616beae68dd"
+
+# ---- pretty output (tty + NO_COLOR aware) ----
+if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
+ C_OK=$'\033[32m'; C_WARN=$'\033[33m'; C_ERR=$'\033[31m'; C_DIM=$'\033[2m'; C_RST=$'\033[0m'
+else
+ C_OK=; C_WARN=; C_ERR=; C_DIM=; C_RST=
+fi
+info() { printf '%s·%s %s\n' "$C_DIM" "$C_RST" "$*"; }
+ok() { printf '%s✓%s %s\n' "$C_OK" "$C_RST" "$*"; }
+warn() { printf '%s!%s %s\n' "$C_WARN" "$C_RST" "$*" >&2; }
+die() { printf '%s✗%s %s\n' "$C_ERR" "$C_RST" "$*" >&2; exit 1; }
+
+# `curl | bash` historically allowed a truncated stream to end at a syntactically
+# complete line and look successful. The public bootstrap now downloads + hashes
+# this complete file first. This phase-only ERR trap handles genuine runtime
+# failures without echoing commands that may contain credentials.
+INSTALL_PHASE=arguments
+trap 'rc=$?; printf "%s✗%s mso installer failed during %s (line %s, exit %s)\n" "$C_ERR" "$C_RST" "$INSTALL_PHASE" "$LINENO" "$rc" >&2' ERR
+
+usage() {
+ cat <<EOF
+mso installer
+ --dir PATH install dir (default: \$HOME/mso, or an existing service's dir)
+ --ref REF git ref/branch/tag to check out (default: main)
+ --port N listen port (default: 4005)
+ --bind ADDR listen address (default: 127.0.0.1). 0.0.0.0 publishes a shell
+ to every network this host is on — see the note in this file.
+ --no-service build only; skip the systemd unit
+ --onboard run guided onboarding even on an existing install
+ --no-onboard never start onboarding automatically
+ -y, --yes safe non-interactive defaults (no external accounts/apps/skills)
+ --uninstall stop+disable+remove the systemd unit (keeps code + ~/.mso)
+ -h, --help this help
+Env: MSO_DIR MSO_REF MSO_PORT MSO_BIND MSO_REPO
+EOF
+}
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --dir) DIR="$2"; DIR_EXPLICIT=1; shift 2 ;;
+ --ref) REF="$2"; shift 2 ;;
+ --port) PORT="$2"; shift 2 ;;
+ --bind) BIND="$2"; shift 2 ;;
+ --no-service) DO_SERVICE=0; shift ;;
+ --onboard) ONBOARD_MODE=always; shift ;;
+ --no-onboard) ONBOARD_MODE=never; shift ;;
+ -y|--yes) YES=1; shift ;;
+ --uninstall) DO_UNINSTALL=1; shift ;;
+ -h|--help) usage; exit 0 ;;
+ *) die "unknown arg: $1 (see --help)" ;;
+ esac
+done
+
+INSTALL_PHASE=preflight
+# ---- never as root: an authed session gets shell as this user ----
+[ "$(id -u)" -ne 0 ] || die "run as your normal NON-root user, not root (mso runs shell as the process user)."
+
+sudo_do() { if command -v sudo >/dev/null 2>&1; then sudo "$@"; else die "need root for: $* (install sudo or run the step by hand)"; fi; }
+
+is_wsl() {
+ grep -qi microsoft /proc/sys/kernel/osrelease 2>/dev/null || grep -qi microsoft /proc/version 2>/dev/null
+}
+
+systemd_ready() {
+ command -v systemctl >/dev/null 2>&1 || return 1
+ [ -r /proc/1/comm ] || return 1
+ [ "$(tr -d '\n' </proc/1/comm 2>/dev/null)" = "systemd" ]
+}
+
+path_has_dir() {
+ case ":$1:" in *":$2:"*) return 0 ;; *) return 1 ;; esac
+}
+
+# PATH entries are resolved by the caller relative to the caller's cwd. The
+# installer later cd's into the checkout, so replaying a raw relative PATH there
+# would prove the wrong shell. Convert each entry to the directory the parent
+# shell will actually search after this child returns. Empty entries mean cwd.
+normalize_parent_path() {
+ local raw="$1" cwd="$2" out="" entry last=0
+ while [ "$last" -eq 0 ]; do
+ case "$raw" in
+ *:*) entry="${raw%%:*}"; raw="${raw#*:}" ;;
+ *) entry="$raw"; raw=""; last=1 ;;
+ esac
+ case "$entry" in
+ "") entry="$cwd" ;;
+ /*) ;;
+ *) entry="$cwd/$entry" ;;
+ esac
+ if [ -n "$out" ]; then out="$out:$entry"; else out="$entry"; fi
+ done
+ printf '%s' "$out"
+}
+
+# Create/update one CLI symlink without ever replacing an unrelated command.
+# Returns nonzero when the destination is unavailable; callers decide whether that
+# is fatal (the user-local launcher is) or only affects current-shell discovery.
+link_cli_guarded() {
+ local link="$1" target="$2" current dir
+ dir="$(dirname "$link")"
+ [ -d "$dir" ] || return 1
+ if [ -e "$link" ] && [ ! -L "$link" ]; then
+ warn "$link already exists and is not a symlink — left untouched"
+ return 1
+ fi
+ if [ -L "$link" ]; then
+ current="$(readlink "$link")"
+ case "$current" in
+ "$DIR/"*) ;;
+ *) warn "$link already points elsewhere ($current) — left untouched"; return 1 ;;
+ esac
+ fi
+ if [ -w "$dir" ]; then
+ ln -sfn "$target" "$link"
+ elif command -v sudo >/dev/null 2>&1; then
+ sudo ln -sfn "$target" "$link" || return 1
+ else
+ return 1
+ fi
+}
+
+# If a service already exists, update IT in place (unless --dir was given) — so a
+# re-run never spins up a divergent second copy next to a working install.
+if [ "$DIR_EXPLICIT" -eq 0 ] && systemd_ready; then
+ existing="$(systemctl show -p WorkingDirectory --value "$SERVICE" 2>/dev/null || true)"
+ [ -n "$existing" ] && [ -d "$existing/.git" ] && DIR="$existing" && info "found existing service → updating $DIR"
+fi
+[ -d "$DIR/.git" ] || FRESH_INSTALL=1
+
+# ---- uninstall ----
+if [ "$DO_UNINSTALL" -eq 1 ]; then
+ # Guarded: without this, --uninstall on a box that never had the unit still
+ # asks for a sudo password and then claims to have removed something.
+ if command -v systemctl >/dev/null 2>&1 && [ -f "/etc/systemd/system/$SERVICE" ]; then
+ sudo_do systemctl disable --now "$SERVICE" 2>/dev/null || true
+ sudo_do rm -f "/etc/systemd/system/$SERVICE"
+ sudo_do systemctl daemon-reload
+ ok "removed $SERVICE"
+ else
+ info "no $SERVICE installed — nothing to remove"
+ fi
+
+ # Take back the symlinks this script created. Both are resolved and compared
+ # against $DIR first, so a hand-made `mso` on PATH or a third-party skill of
+ # the same name is never touched.
+ UNINST_BIN="${MSO_BIN_DIR:-$HOME/.local/bin}/mso"
+ if [ -L "$UNINST_BIN" ] && case "$(readlink "$UNINST_BIN")" in "$DIR/"*) true ;; *) false ;; esac; then
+ rm -f "$UNINST_BIN"; ok "removed cli symlink $UNINST_BIN"
+ fi
+ UNINST_SYSTEM_CLI="${MSO_SYSTEM_BIN_DIR:-/usr/local/bin}/mso"
+ if [ -L "$UNINST_SYSTEM_CLI" ] && case "$(readlink "$UNINST_SYSTEM_CLI")" in "$DIR/"*) true ;; *) false ;; esac; then
+ if [ -w "$(dirname "$UNINST_SYSTEM_CLI")" ]; then rm -f "$UNINST_SYSTEM_CLI"
+ else sudo_do rm -f "$UNINST_SYSTEM_CLI"; fi
+ ok "removed cli symlink $UNINST_SYSTEM_CLI"
+ fi
+ UNINST_SKILLS="${MSO_SKILL_DIR:-$HOME/.claude/skills}"
+ if [ -d "$UNINST_SKILLS" ]; then
+ for l in "$UNINST_SKILLS"/*; do
+ [ -L "$l" ] || continue
+ case "$(readlink "$l")" in "$DIR/claude-skills/"*) rm -f "$l"; info "removed skill $(basename "$l")" ;; esac
+ done
+ fi
+
+ info "code left at $DIR and data at ~/.mso — delete by hand if you want them gone."
+ exit 0
+fi
+
+INSTALL_PHASE=prerequisites
+# ---- prereqs ----
+ensure_git() {
+ command -v git >/dev/null 2>&1 && return
+ info "installing git…"
+ if command -v apt-get >/dev/null 2>&1; then sudo_do apt-get update -qq && sudo_do apt-get install -y -qq git
+ elif command -v dnf >/dev/null 2>&1; then sudo_do dnf install -y -q git
+ elif command -v pacman >/dev/null 2>&1; then sudo_do pacman -Sy --noconfirm git
+ else die "git missing and no known package manager — install git and re-run."; fi
+}
+
+node_ok() {
+ command -v node >/dev/null 2>&1 || return 1
+ node -e 'const[a,b]=process.versions.node.split(".").map(Number);process.exit(a>20||(a===20&&b>=9)?0:1)'
+}
+ensure_node() {
+ node_ok && { info "node $(node -v) ok"; return; }
+ warn "Node >=20.9 not found"
+ if command -v apt-get >/dev/null 2>&1; then
+ info "installing Node 22 via NodeSource…"
+ curl -fsSL https://deb.nodesource.com/setup_22.x | sudo_do -E bash -
+ sudo_do apt-get install -y -qq nodejs
+ else
+ die "install Node >=20.9 (22 recommended) from https://nodejs.org or your distro, then re-run."
+ fi
+ node_ok || die "Node still <20.9 after install."
+}
+
+# bun installs dependencies; it does NOT run the app. `next start` stays on node
+# (see the unit's ExecStart below) because node-pty's binding is built against
+# node's ABI and the whole /api/v1 surface imports it.
+ensure_bun() {
+ command -v bun >/dev/null 2>&1 && { info "bun $(bun -v) ok"; return; }
+ command -v sha256sum >/dev/null 2>&1 || die "sha256sum is required to verify the Bun bootstrap."
+ info "installing Bun from a pinned, verified bootstrap…"
+ local bootstrap actual url
+ bootstrap="$(mktemp)"
+ url="https://raw.githubusercontent.com/oven-sh/bun/$BUN_BOOTSTRAP_COMMIT/src/cli/install.sh"
+ curl -fsSL "$url" -o "$bootstrap" || { rm -f "$bootstrap"; die "Bun bootstrap download failed."; }
+ actual="$(sha256sum "$bootstrap" | awk '{print $1}')"
+ [ "$actual" = "$BUN_BOOTSTRAP_SHA256" ] || {
+ rm -f "$bootstrap"
+ die "Bun bootstrap integrity check failed."
+ }
+ bash "$bootstrap" >/dev/null 2>&1 || { rm -f "$bootstrap"; die "bun install failed."; }
+ rm -f "$bootstrap"
+ export PATH="$BUN_INSTALL/bin:$PATH"
+ command -v bun >/dev/null 2>&1 || die "bun installed but not on PATH — add $BUN_INSTALL/bin."
+}
+
+ensure_buildtools() {
+ # node-pty is a native addon with no linux prebuild → needs a C/C++ toolchain +
+ # python3 to compile at install time, under bun exactly as under pnpm.
+ # This is the single most likely install failure on a minimal box.
+ command -v cc >/dev/null 2>&1 && command -v python3 >/dev/null 2>&1 && return
+ info "installing build toolchain (for node-pty)…"
+ if command -v apt-get >/dev/null 2>&1; then sudo_do apt-get update -qq && sudo_do apt-get install -y -qq build-essential python3
+ elif command -v dnf >/dev/null 2>&1; then sudo_do dnf install -y -q gcc-c++ make python3
+ elif command -v pacman >/dev/null 2>&1; then sudo_do pacman -Sy --noconfirm base-devel python
+ else warn "no known package manager — if 'bun install' fails on node-pty, install a C++ toolchain + python3 by hand."; fi
+}
+
+ensure_cli_tools() {
+ # bin/mso uses jq for JSON shaping and coreutils for guarded file identity.
+ # A pristine WSL/Ubuntu image may have Node+Bun but no jq. Install these before
+ # creating the launcher so `mso -h` is a real installer postcondition.
+ local missing=0 tool
+ for tool in curl jq realpath stat mktemp sha256sum; do
+ command -v "$tool" >/dev/null 2>&1 || { missing=1; break; }
+ done
+ [ "$missing" -eq 0 ] && return
+ info "installing CLI runtime tools (curl, jq, coreutils)…"
+ if command -v apt-get >/dev/null 2>&1; then sudo_do apt-get update -qq && sudo_do apt-get install -y -qq curl jq coreutils
+ elif command -v dnf >/dev/null 2>&1; then sudo_do dnf install -y -q curl jq coreutils
+ elif command -v pacman >/dev/null 2>&1; then sudo_do pacman -Sy --noconfirm curl jq coreutils
+ else die "mso CLI needs curl, jq, realpath, stat, mktemp and sha256sum; install the missing tools, then rerun."; fi
+ for tool in curl jq realpath stat mktemp sha256sum; do
+ command -v "$tool" >/dev/null 2>&1 || die "CLI runtime dependency still missing after package install: $tool"
+ done
+}
+
+ensure_git; ensure_node; ensure_bun; ensure_buildtools; ensure_cli_tools
+
+# portable 32-byte hex RNG (node is guaranteed present by now)
+rand_hex() {
+ if command -v openssl >/dev/null 2>&1; then openssl rand -hex "$1"
+ else node -e "process.stdout.write(require('crypto').randomBytes($1).toString('hex'))"; fi
+}
+
+rand_password() {
+ node -e 'const c="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";const b=require("crypto").randomBytes(24);let s="";for(const x of b)s+=c[x%c.length];process.stdout.write(s)'
+}
+
+INSTALL_PHASE=checkout
+# ---- clone or update (idempotent, resilient to a dirty tree) ----
+if [ -d "$DIR/.git" ]; then
+ info "updating existing checkout at $DIR"
+ old_commit="$(git -C "$DIR" rev-parse --short HEAD)"
+ if [ -n "$(git -C "$DIR" status --porcelain)" ]; then
+ die "checkout has uncommitted changes at $DIR. Commit/stash them, or install into another --dir. Current commit: $old_commit"
+ fi
+ info "current commit: $old_commit"
+ git -C "$DIR" fetch --quiet origin "$REF" || die "could not fetch origin $REF"
+ target_commit="$(git -C "$DIR" rev-parse --short FETCH_HEAD)" || die "could not resolve fetched ref $REF"
+ info "target commit: $target_commit"
+ git -C "$DIR" checkout --quiet FETCH_HEAD || die "could not check out $target_commit"
+ ok "updated checkout $old_commit → $(git -C "$DIR" rev-parse --short HEAD)"
+else
+ info "cloning $REPO_URL → $DIR"
+ git clone --quiet --branch "$REF" "$REPO_URL" "$DIR" 2>/dev/null || git clone --quiet "$REPO_URL" "$DIR"
+fi
+cd "$DIR"
+
+INSTALL_PHASE=dependencies
+# ---- deps (compiles node-pty) ----
+info "installing dependencies…"
+bun install --frozen-lockfile || bun install
+
+INSTALL_PHASE=configuration
+# ---- data dir + secrets (write .env.local only if absent) ----
+mkdir -p "$HOME/.mso" && chmod 700 "$HOME/.mso"
+
+GEN_PW=""
+if [ ! -f .env.local ]; then
+ SECRET="$(rand_hex 32)"
+ GEN_PW="$(rand_password)"
+ ( umask 077
+ cat > .env.local <<EOF
+# mso — generated by install.sh. Private; NEVER commit.
+OS_LOGIN_PASSWORD=$GEN_PW
+OS_SESSION_SECRET=$SECRET
+# SESSION_EXPIRY_HOURS=24
+# OS_FS_READ_ROOTS=~:~/projects
+# OS_FS_WRITE_ROOTS=~:~/projects
+# OS_AUDIT_LOG=~/.mso/audit.log
+EOF
+ )
+ chmod 600 .env.local
+ ok "wrote .env.local (login password + session secret generated)"
+else
+ info ".env.local exists — left untouched (existing secrets preserved)"
+fi
+
+INSTALL_PHASE=build
+# ---- build ----
+info "building (next build)…"
+bun run build
+
+INSTALL_PHASE=cli
+# ---- CLI on PATH (before service setup so WSL/no-systemd still gets a CLI) ----
+# The web UI is one frontend; bin/mso reaches the same /api surface from a shell.
+BIN_DIR="${MSO_BIN_DIR:-$HOME/.local/bin}"
+mkdir -p "$BIN_DIR"
+ln -sfn "$DIR/bin/mso" "$BIN_DIR/mso"
+ok "cli → $BIN_DIR/mso"
+
+# A fresh distro/WSL home often omits ~/.local/bin from the current PATH. Persist
+# one small idempotent block for future shells. Default to bash when SHELL is not
+# exported (common in curl|bash/cloud-init); zsh gets its own rc instead.
+path_block() {
+ local rc="$1"
+ [ -e "$rc" ] || : > "$rc"
+ grep -q '^# >>> mso cli >>>$' "$rc" 2>/dev/null && return
+ cat >> "$rc" <<'EOF'
+
+# >>> mso cli >>>
+case ":$PATH:" in
+ *":$HOME/.local/bin:"*) ;;
+ *) export PATH="$HOME/.local/bin:$PATH" ;;
+esac
+# <<< mso cli <<<
+EOF
+ info "added ~/.local/bin to PATH in $rc"
+}
+if [ "$BIN_DIR" = "$HOME/.local/bin" ]; then
+ path_block "$HOME/.profile"
+ case "${SHELL:-/bin/bash}" in
+ */zsh) path_block "$HOME/.zshrc" ;;
+ *) path_block "$HOME/.bashrc" ;;
+ esac
+else
+ warn "custom MSO_BIN_DIR=$BIN_DIR is not written into shell profiles; add it to PATH yourself"
+fi
+
+# Prove discoverability from the PARENT shell's original PATH. If the user-local
+# directory was already there, nothing else is needed. Otherwise use a guarded
+# launcher in /usr/local/bin (or MSO_SYSTEM_BIN_DIR) only when that directory is
+# already on the invoking PATH. This also makes `--no-service` useful on WSL.
+PARENT_PATH_RESOLVED="$(normalize_parent_path "$PARENT_PATH" "$PARENT_CWD")"
+SYSTEM_BIN_DIR="${MSO_SYSTEM_BIN_DIR:-/usr/local/bin}"
+case "$SYSTEM_BIN_DIR" in /*) ;; *) SYSTEM_BIN_DIR="$PARENT_CWD/$SYSTEM_BIN_DIR" ;; esac
+SYSTEM_CLI="$SYSTEM_BIN_DIR/mso"
+TARGET_CLI_REAL="$(readlink -f "$DIR/bin/mso")"
+CLI_IMMEDIATE=0
+parent_cli="$(PATH="$PARENT_PATH_RESOLVED" command -v mso 2>/dev/null || true)"
+if [ -n "$parent_cli" ] && [ "$(readlink -f "$parent_cli" 2>/dev/null || true)" = "$TARGET_CLI_REAL" ]; then
+ CLI_IMMEDIATE=1
+elif path_has_dir "$PARENT_PATH_RESOLVED" "$SYSTEM_BIN_DIR"; then
+ if link_cli_guarded "$SYSTEM_CLI" "$DIR/bin/mso"; then
+ ok "current-PATH cli → $SYSTEM_CLI"
+ parent_cli="$(PATH="$PARENT_PATH_RESOLVED" command -v mso 2>/dev/null || true)"
+ if [ -n "$parent_cli" ] && [ "$(readlink -f "$parent_cli" 2>/dev/null || true)" = "$TARGET_CLI_REAL" ]; then
+ CLI_IMMEDIATE=1
+ fi
+ else
+ warn "could not install $SYSTEM_CLI; the user CLI is still installed at $BIN_DIR/mso"
+ fi
+else
+ info "$SYSTEM_BIN_DIR is not on the invoking PATH — skipped the extra launcher"
+fi
+
+# Validate the actual launcher independently of PATH. The child installer may use
+# its own exported PATH for onboarding, but that is NOT treated as proof that the
+# parent shell can see the command.
+[ -x "$BIN_DIR/mso" ] || die "CLI launcher target is not executable: $BIN_DIR/mso"
+"$BIN_DIR/mso" -h >/dev/null 2>&1 || die "CLI launcher self-check failed: $BIN_DIR/mso (verify curl/jq/coreutils and rerun)"
+export PATH="$BIN_DIR:$PATH"
+if [ "$CLI_IMMEDIATE" -eq 1 ]; then
+ ok "mso -h will resolve immediately after the installer returns ($parent_cli)"
+else
+ warn "mso is installed, but this shell's existing PATH cannot see it yet"
+ warn "for this shell run: export PATH=\"$BIN_DIR:\$PATH\""
+ if [ "$BIN_DIR" = "$HOME/.local/bin" ]; then
+ info "future shells will load the persisted ~/.local/bin PATH block"
+ else
+ warn "custom MSO_BIN_DIR is not persisted automatically; add $BIN_DIR to your shell profile"
+ fi
+fi
+
+INSTALL_PHASE=service
+# ---- systemd unit ----
+if [ "$DO_SERVICE" -eq 1 ] && systemd_ready; then
+ SERVICE_ATTEMPTED=1
+ # Start via npm (always on PATH, ships with node) to match the proven prod unit;
+ # PORT/HOSTNAME are set as env too so `next start` binds correctly regardless.
+ NPM_BIN="$(command -v npm)"
+ RUNTIME_INSTANCE_ID="$(rand_hex 16)"
+ info "installing $SERVICE (needs sudo)…"
+ sudo_do tee "/etc/systemd/system/$SERVICE" >/dev/null <<EOF
+[Unit]
+Description=Manef Shell OS — browser-based visual shell for a Linux server
+After=network.target
+
+[Service]
+Type=simple
+User=$(id -un)
+WorkingDirectory=$DIR
+EnvironmentFile=$DIR/.env.local
+Environment=PORT=$PORT
+Environment=HOSTNAME=$BIND
+# Fresh on every installer-driven restart. /api/health echoes this non-secret nonce
+# so readiness proves the HTTP response came from THIS restarted unit, not a stale
+# process that happened to keep answering on the configured port.
+Environment=MSO_RUNTIME_INSTANCE_ID=$RUNTIME_INSTANCE_ID
+# A system unit with User= inherits no login session, so it gets no user-bus
+# address and every \`systemctl --user\` it runs answers "Failed to connect to bus:
+# No medium found". That silently broke the managed-app installs (which create
+# systemd USER units) and made installed apps read as "not installed". Paired with
+# the \`loginctl enable-linger\` below, without which /run/user/<uid> is destroyed
+# at logout.
+#
+# The UID IS WRITTEN OUT, NOT the %U specifier. Do not "tidy" this back to %U — it
+# was tried and it FAILS: with User=antinrml and UID=1000, systemd 255 expanded %U
+# to 0, so the unit got XDG_RUNTIME_DIR=/run/user/0 and every systemctl --user
+# answered "No such file or directory" — the original bug wearing a new message.
+# Specifiers are expanded while the unit is parsed, before the NAME in User= has
+# been resolved to a uid, so %U falls back to the manager's own uid (root).
+Environment=XDG_RUNTIME_DIR=/run/user/$(id -u)
+# systemd would otherwise give this unit only
+# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin. Both managed-app CLIs install
+# themselves into ~/.local/bin, so without this \`which hermes\` fails inside the
+# service on a host where it plainly works in a terminal.
+Environment=PATH=$HOME/.local/bin:$HOME/.bun/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
+ExecStart=$NPM_BIN run start -- --hostname $BIND --port $PORT
+Restart=always
+RestartSec=5
+KillSignal=SIGTERM
+TimeoutStopSec=20
+MemoryMax=3G
+StandardOutput=journal
+StandardError=journal
+SyslogIdentifier=mso
+
+[Install]
+WantedBy=multi-user.target
+EOF
+ # A wildcard bind is not an address you can dial; probe loopback instead.
+ HEALTH_HOST="$BIND"
+ case "$BIND" in 0.0.0.0|::|"") HEALTH_HOST=127.0.0.1 ;; esac
+
+ # Makes /run/user/<uid> — where the user bus lives — exist without a login
+ # session and survive logout. The XDG_RUNTIME_DIR above names that directory, so
+ # without linger it would point at nothing after the installing shell exits.
+ # Idempotent; failure is not fatal, it only means managed-app installs will say
+ # so plainly when they preflight the bus.
+ sudo_do loginctl enable-linger "$(id -un)" >/dev/null 2>&1 \
+ || warn "could not enable linger for $(id -un) — self-update and managed-app user services may stop after logout"
+ # `enable-linger` makes the manager persistent, but some minimal images do not
+ # start [email protected] until the next login. Start it now so the first update
+ # button works immediately, then prove the bus MSO will use actually answers.
+ sudo_do systemctl start "user@$(id -u).service" >/dev/null 2>&1 \
+ || warn "could not start the per-user systemd manager — self-update may be unavailable"
+ if ! XDG_RUNTIME_DIR="/run/user/$(id -u)" systemctl --user show-environment >/dev/null 2>&1; then
+ warn "per-user systemd bus is unavailable — self-update and managed-app services will not work until user@$(id -u).service is running"
+ fi
+
+ sudo_do systemctl daemon-reload
+ sudo_do systemctl enable "$SERVICE"
+ # restart, NOT `enable --now`. `--now` only *starts*, and a start on a unit
+ # that is already running is a no-op — so re-running this installer used to
+ # fetch, rebuild and then leave the OLD process serving a .next that had been
+ # replaced underneath it. Every chunk 404s and nosniff makes that fatal
+ # (docs/TROUBLESHOOTING.md). `restart` starts an inactive unit just as well,
+ # so this is also correct on a first install.
+ sudo_do systemctl restart "$SERVICE"
+ ok "$SERVICE enabled + restarted"
+
+ info "waiting for http://$HEALTH_HOST:$PORT/api/health …"
+ up=0
+ for _ in $(seq 1 30); do
+ body="$(curl -fsS --max-time 3 "http://$HEALTH_HOST:$PORT/api/health" 2>/dev/null || true)"
+ if [ -n "$body" ]; then
+ now_build="$(printf '%s' "$body" | sed -n 's/.*"buildId":"\([^"]*\)".*/\1/p')"
+ now_instance="$(printf '%s' "$body" | sed -n 's/.*"runtimeInstanceId":"\([^"]*\)".*/\1/p')"
+ # A healthy response is accepted only when it carries the nonce injected into
+ # THIS service unit before restart. This remains correct when NEXT_DEPLOYMENT_ID
+ # intentionally keeps buildId stable and cannot be satisfied by a stale or
+ # unrelated process still listening on the same port.
+ if [ "$now_instance" = "$RUNTIME_INSTANCE_ID" ]; then
+ up=1; SERVICE_READY=1
+ ok "health OK (build ${now_build:-unknown}, runtime instance verified)"
+ break
+ fi
+ fi
+ sleep 2
+ done
+ if [ "$up" -ne 1 ]; then
+ # is-active needs no privileges — do not spend a sudo prompt on the sad path.
+ if systemctl is-active --quiet "$SERVICE"; then
+ warn "service is running but /api/health did not prove the restarted runtime instance — check: journalctl -u mso -e"
+ else
+ warn "$SERVICE is not running — check: journalctl -u mso -e"
+ fi
+ fi
+elif [ "$DO_SERVICE" -eq 1 ]; then
+ if is_wsl; then
+ warn "WSL detected without systemd as PID 1 — service install skipped; the mso CLI is still installed"
+ info "for the full service: enable systemd in /etc/wsl.conf, run 'wsl --shutdown' from Windows, reopen WSL, then re-run this installer --onboard"
+ else
+ warn "systemd is not available as PID 1 — service install skipped; run manually: PORT=$PORT bun run start"
+ fi
+fi
+
+INSTALL_PHASE=integrations
+# ---- optional Claude Code integration ----
+# MSO catalogs $DIR/claude-skills directly, so these symlinks are NOT required by MSO.
+# They only expose the same official playbooks to Claude Code when its home exists.
+SKILL_DIR="${MSO_SKILL_DIR:-$HOME/.claude/skills}"
+if [ -d "$DIR/claude-skills" ] && [ -d "$(dirname "$SKILL_DIR")" ]; then
+ mkdir -p "$SKILL_DIR"
+ for s in "$DIR"/claude-skills/*/; do
+ name="$(basename "$s")"
+ if [ -e "$SKILL_DIR/$name" ] && [ ! -L "$SKILL_DIR/$name" ]; then
+ warn "skill $name exists and is not a symlink — left alone"
+ continue
+ fi
+ ln -sfn "${s%/}" "$SKILL_DIR/$name"
+ done
+ # Prune ours that no longer exist. Only symlinks POINTING INTO this repo's
+ # claude-skills are touched, so a hand-made or third-party skill is never
+ # removed. Without this a deleted skill kept a dangling entry forever and the
+ # agent still saw it listed (mso-browser-list did exactly that).
+ for l in "$SKILL_DIR"/*; do
+ [ -L "$l" ] || continue
+ tgt="$(readlink "$l")"
+ case "$tgt" in "$DIR/claude-skills/"*) [ -d "$tgt" ] || { rm -f "$l"; info "pruned stale skill $(basename "$l")"; } ;; esac
+ done
+ ok "skills → $SKILL_DIR (/mso, /mso-camoufox, /mso-apps, /mso-list, …)"
+fi
+
+INSTALL_PHASE=summary
+# ---- next steps ----
+# How to reach it depends on the bind AND on the Secure session cookie: a
+# browser only keeps that cookie over plain http on localhost/127.0.0.1/::1, so
+# any address that is not one of those needs TLS or a tunnel to log in at all.
+WHOAMI="$(id -un)"
+case "$BIND" in
+ 127.0.0.1|::1|localhost)
+ REACH="tunnel from your own machine:
+ ssh -N -L $PORT:127.0.0.1:$PORT $WHOAMI@<this-host>
+ then open http://localhost:$PORT
+ (or \`tailscale serve $PORT\`, or a TLS reverse proxy → 127.0.0.1:$PORT)" ;;
+ 0.0.0.0|::)
+ REACH="http://<this-host>:$PORT
+ !! bound on EVERY interface. An authenticated session runs commands as
+ $WHOAMI — firewall it, or re-run with --bind 127.0.0.1.
+ Plain http to an IP also cannot log in: the session cookie is Secure." ;;
+ *)
+ REACH="http://$BIND:$PORT
+ (plain http to a non-loopback address cannot complete a login — the
+ session cookie is Secure. Put TLS in front, or tunnel to loopback.)" ;;
+esac
+
+if [ "$SERVICE_READY" -eq 1 ]; then
+ OPEN_STATUS="$REACH"
+ LOG_STATUS="journalctl -u mso -f"
+elif [ "$DO_SERVICE" -eq 0 ]; then
+ OPEN_STATUS="not running (--no-service). Start manually: cd $DIR && PORT=$PORT bun run start"
+ LOG_STATUS="no system service installed"
+elif [ "$SERVICE_ATTEMPTED" -eq 1 ]; then
+ OPEN_STATUS="service was installed/restarted but did not pass health verification; inspect the journal before opening the UI"
+ LOG_STATUS="journalctl -u mso -e"
+elif is_wsl; then
+ OPEN_STATUS="not running (WSL systemd is unavailable). Enable systemd or start manually from $DIR"
+ LOG_STATUS="no system service installed"
+else
+ OPEN_STATUS="systemd is unavailable; start manually from $DIR"
+ LOG_STATUS="no system service installed"
+fi
+
+ok "mso installed at $DIR"
+cat <<EOF
+
+ Runtime: $OPEN_STATUS
+ Env: $DIR/.env.local
+EOF
+[ -n "$GEN_PW" ] && printf ' Password: %s (shown once — save it now; edit OS_LOGIN_PASSWORD in .env.local + service refresh to change)\n' "$GEN_PW"
+cat <<EOF
+
+ Pair your first device after the API is running (device approval is a browser allowlist, not standards-based 2FA):
+ 1. Open the URL, enter the password — the browser lands PENDING and shows a device id.
+ 2. On this server:
+ node $DIR/scripts/approve-device.js --list # see the pending id
+ node $DIR/scripts/approve-device.js <deviceId> "my phone" # approve it
+ 3. Reload + log in. Approve later devices from Settings → Devices.
+
+ Logs: $LOG_STATUS
+ Update: re-run this installer (pull + verify + build + service refresh), or --uninstall to remove
+ Listen: $BIND:$PORT (change with --bind / MSO_BIND)
+ Security: verify from OUTSIDE the box — \`curl -m5 http://<public-ip>:$PORT/api/health\`
+ run on your laptop is the only test that proves what is reachable.
+ Review ~/.mso/audit.log.
+EOF
+
+INSTALL_PHASE=onboarding
+# A successful fresh install should lead directly into a usable product. curl|bash
+# owns stdin, so interactive setup uses the controlling terminal explicitly.
+RUN_ONBOARD=0
+case "$ONBOARD_MODE" in
+ always) RUN_ONBOARD=1 ;;
+ never) RUN_ONBOARD=0 ;;
+ auto) [ "$FRESH_INSTALL" -eq 1 ] && RUN_ONBOARD=1 ;;
+esac
+if [ "$RUN_ONBOARD" -eq 1 ] && [ "$SERVICE_READY" -eq 1 ]; then
+ if [ "$YES" -eq 1 ]; then
+ echo
+ info "running minimal non-interactive onboarding (-y)…"
+ "$BIN_DIR/mso" onboard -y || warn "onboarding did not finish — rerun: mso onboard"
+ elif [ -r /dev/tty ] && [ -w /dev/tty ]; then
+ echo
+ info "starting guided onboarding…"
+ if ! "$BIN_DIR/mso" onboard </dev/tty >/dev/tty 2>/dev/tty; then
+ warn "onboarding stopped early — resume anytime with: mso onboard"
+ fi
+ else
+ echo
+ warn "no interactive terminal detected — onboarding skipped. Run: mso onboard"
+ fi
+elif [ "$RUN_ONBOARD" -eq 1 ]; then
+ warn "no verified running MSO API is available for onboarding — start/enable the service, then run 'mso onboard'"
+fi
+
+INSTALL_PHASE=complete
+# MSO_INSTALLER_CORE_EOF
diff --git a/scripts/install.sh b/scripts/install.sh
index 19e3df6a..924fcf38 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -1,650 +1,50 @@
#!/usr/bin/env bash
-# mso (Manef Shell OS) one-command installer — fresh single-owner Linux VPS.
+# MSO one-line installer bootstrap.
#
# curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash
#
-# Idempotent: re-running updates the checkout, rebuilds, and restarts the
-# service. The bootstrap never needs stdin, so curl|bash stays safe. After a
-# FRESH install it uses /dev/tty (when present) for guided onboarding; CI/headless
-# installs never hang and can run `mso onboard` later. Existing .env.local is preserved.
-set -euo pipefail
-
-# ---- config: env override > flag > default ----
-REPO_URL="${MSO_REPO:-https://github.com/rahmanef63/mso.git}"
-DIR="${MSO_DIR:-$HOME/mso}"
-DIR_EXPLICIT=0
-REF="${MSO_REF:-main}"
-PORT="${MSO_PORT:-4005}"
-# Address the server listens on. Loopback by DEFAULT, for two reasons that point
-# the same way:
-# 1. It cannot log in otherwise. sessionCookieAttrs() sets `secure: true`
-# (lib/auth/session-cookie.ts), and a browser only accepts a Secure cookie
-# over plain http on a trustworthy origin — localhost / 127.0.0.1 / ::1. So
-# http://<lan-or-public-ip>:PORT returns 200 on login and then silently
-# drops the cookie: an endless login loop. A 0.0.0.0 bind buys no working
-# access it did not already have.
-# 2. It is a shell. An authenticated session runs commands as this user, and a
-# fresh VPS has ufw installed but disabled — so the old default published
-# that shell to the whole internet about two minutes into a curl|bash.
-# Reach it over an SSH tunnel, `tailscale serve`, or a reverse proxy on this host
-# (all three land the browser on a trustworthy origin, so the cookie sticks).
-BIND="${MSO_BIND:-127.0.0.1}"
-SERVICE="mso.service"
-DO_SERVICE=1
-DO_UNINSTALL=0
-YES=0
-ONBOARD_MODE=auto
-FRESH_INSTALL=0
-# bun is the package manager; the RUNTIME stays node (see ensure_bun below).
-export BUN_INSTALL="${BUN_INSTALL:-$HOME/.bun}"
-# Capture the INVOKING shell PATH before Bun or the installer changes it. A child
-# curl|bash process cannot export back into its parent, so this is the only PATH
-# that matters when proving `mso -h` will resolve immediately after we return.
-PARENT_PATH="${PATH:-}"
-PARENT_CWD="$PWD"
-SERVICE_READY=0
-SERVICE_ATTEMPTED=0
-# Reproducible bootstrap: this is Bun v1.3.14's installer source, pinned by
-# immutable Git commit and verified before execution. Update both values together.
-BUN_BOOTSTRAP_COMMIT="0d9b296af33f2b851fcbf4df3e9ec89751734ba4"
-BUN_BOOTSTRAP_SHA256="bab8acfb046aac8c72407bdcce903957665d655d7acaa3e11c7c4616beae68dd"
-
-# ---- pretty output (tty + NO_COLOR aware) ----
-if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
- C_OK=$'\033[32m'; C_WARN=$'\033[33m'; C_ERR=$'\033[31m'; C_DIM=$'\033[2m'; C_RST=$'\033[0m'
-else
- C_OK=; C_WARN=; C_ERR=; C_DIM=; C_RST=
-fi
-info() { printf '%s·%s %s\n' "$C_DIM" "$C_RST" "$*"; }
-ok() { printf '%s✓%s %s\n' "$C_OK" "$C_RST" "$*"; }
-warn() { printf '%s!%s %s\n' "$C_WARN" "$C_RST" "$*" >&2; }
-die() { printf '%s✗%s %s\n' "$C_ERR" "$C_RST" "$*" >&2; exit 1; }
-
-usage() {
- cat <<EOF
-mso installer
- --dir PATH install dir (default: \$HOME/mso, or an existing service's dir)
- --ref REF git ref/branch/tag to check out (default: main)
- --port N listen port (default: 4005)
- --bind ADDR listen address (default: 127.0.0.1). 0.0.0.0 publishes a shell
- to every network this host is on — see the note in this file.
- --no-service build only; skip the systemd unit
- --onboard run guided onboarding even on an existing install
- --no-onboard never start onboarding automatically
- -y, --yes safe non-interactive defaults (no external accounts/apps/skills)
- --uninstall stop+disable+remove the systemd unit (keeps code + ~/.mso)
- -h, --help this help
-Env: MSO_DIR MSO_REF MSO_PORT MSO_BIND MSO_REPO
-EOF
-}
-
-while [ $# -gt 0 ]; do
- case "$1" in
- --dir) DIR="$2"; DIR_EXPLICIT=1; shift 2 ;;
- --ref) REF="$2"; shift 2 ;;
- --port) PORT="$2"; shift 2 ;;
- --bind) BIND="$2"; shift 2 ;;
- --no-service) DO_SERVICE=0; shift ;;
- --onboard) ONBOARD_MODE=always; shift ;;
- --no-onboard) ONBOARD_MODE=never; shift ;;
- -y|--yes) YES=1; shift ;;
- --uninstall) DO_UNINSTALL=1; shift ;;
- -h|--help) usage; exit 0 ;;
- *) die "unknown arg: $1 (see --help)" ;;
- esac
-done
-
-# ---- never as root: an authed session gets shell as this user ----
-[ "$(id -u)" -ne 0 ] || die "run as your normal NON-root user, not root (mso runs shell as the process user)."
-
-sudo_do() { if command -v sudo >/dev/null 2>&1; then sudo "$@"; else die "need root for: $* (install sudo or run the step by hand)"; fi; }
-
-is_wsl() {
- grep -qi microsoft /proc/sys/kernel/osrelease 2>/dev/null || grep -qi microsoft /proc/version 2>/dev/null
-}
-
-systemd_ready() {
- command -v systemctl >/dev/null 2>&1 || return 1
- [ -r /proc/1/comm ] || return 1
- [ "$(tr -d '\n' </proc/1/comm 2>/dev/null)" = "systemd" ]
-}
-
-path_has_dir() {
- case ":$1:" in *":$2:"*) return 0 ;; *) return 1 ;; esac
-}
-
-# PATH entries are resolved by the caller relative to the caller's cwd. The
-# installer later cd's into the checkout, so replaying a raw relative PATH there
-# would prove the wrong shell. Convert each entry to the directory the parent
-# shell will actually search after this child returns. Empty entries mean cwd.
-normalize_parent_path() {
- local raw="$1" cwd="$2" out="" entry last=0
- while [ "$last" -eq 0 ]; do
- case "$raw" in
- *:*) entry="${raw%%:*}"; raw="${raw#*:}" ;;
- *) entry="$raw"; raw=""; last=1 ;;
- esac
- case "$entry" in
- "") entry="$cwd" ;;
- /*) ;;
- *) entry="$cwd/$entry" ;;
- esac
- if [ -n "$out" ]; then out="$out:$entry"; else out="$entry"; fi
- done
- printf '%s' "$out"
-}
-
-# Create/update one CLI symlink without ever replacing an unrelated command.
-# Returns nonzero when the destination is unavailable; callers decide whether that
-# is fatal (the user-local launcher is) or only affects current-shell discovery.
-link_cli_guarded() {
- local link="$1" target="$2" current dir
- dir="$(dirname "$link")"
- [ -d "$dir" ] || return 1
- if [ -e "$link" ] && [ ! -L "$link" ]; then
- warn "$link already exists and is not a symlink — left untouched"
- return 1
- fi
- if [ -L "$link" ]; then
- current="$(readlink "$link")"
- case "$current" in
- "$DIR/"*) ;;
- *) warn "$link already points elsewhere ($current) — left untouched"; return 1 ;;
- esac
- fi
- if [ -w "$dir" ]; then
- ln -sfn "$target" "$link"
- elif command -v sudo >/dev/null 2>&1; then
- sudo ln -sfn "$target" "$link" || return 1
- else
- return 1
- fi
-}
-
-# If a service already exists, update IT in place (unless --dir was given) — so a
-# re-run never spins up a divergent second copy next to a working install.
-if [ "$DIR_EXPLICIT" -eq 0 ] && systemd_ready; then
- existing="$(systemctl show -p WorkingDirectory --value "$SERVICE" 2>/dev/null || true)"
- [ -n "$existing" ] && [ -d "$existing/.git" ] && DIR="$existing" && info "found existing service → updating $DIR"
-fi
-[ -d "$DIR/.git" ] || FRESH_INSTALL=1
-
-# ---- uninstall ----
-if [ "$DO_UNINSTALL" -eq 1 ]; then
- # Guarded: without this, --uninstall on a box that never had the unit still
- # asks for a sudo password and then claims to have removed something.
- if command -v systemctl >/dev/null 2>&1 && [ -f "/etc/systemd/system/$SERVICE" ]; then
- sudo_do systemctl disable --now "$SERVICE" 2>/dev/null || true
- sudo_do rm -f "/etc/systemd/system/$SERVICE"
- sudo_do systemctl daemon-reload
- ok "removed $SERVICE"
- else
- info "no $SERVICE installed — nothing to remove"
- fi
-
- # Take back the symlinks this script created. Both are resolved and compared
- # against $DIR first, so a hand-made `mso` on PATH or a third-party skill of
- # the same name is never touched.
- UNINST_BIN="${MSO_BIN_DIR:-$HOME/.local/bin}/mso"
- if [ -L "$UNINST_BIN" ] && case "$(readlink "$UNINST_BIN")" in "$DIR/"*) true ;; *) false ;; esac; then
- rm -f "$UNINST_BIN"; ok "removed cli symlink $UNINST_BIN"
- fi
- UNINST_SYSTEM_CLI="${MSO_SYSTEM_BIN_DIR:-/usr/local/bin}/mso"
- if [ -L "$UNINST_SYSTEM_CLI" ] && case "$(readlink "$UNINST_SYSTEM_CLI")" in "$DIR/"*) true ;; *) false ;; esac; then
- if [ -w "$(dirname "$UNINST_SYSTEM_CLI")" ]; then rm -f "$UNINST_SYSTEM_CLI"
- else sudo_do rm -f "$UNINST_SYSTEM_CLI"; fi
- ok "removed cli symlink $UNINST_SYSTEM_CLI"
- fi
- UNINST_SKILLS="${MSO_SKILL_DIR:-$HOME/.claude/skills}"
- if [ -d "$UNINST_SKILLS" ]; then
- for l in "$UNINST_SKILLS"/*; do
- [ -L "$l" ] || continue
- case "$(readlink "$l")" in "$DIR/claude-skills/"*) rm -f "$l"; info "removed skill $(basename "$l")" ;; esac
- done
- fi
-
- info "code left at $DIR and data at ~/.mso — delete by hand if you want them gone."
- exit 0
-fi
-
-# ---- prereqs ----
-ensure_git() {
- command -v git >/dev/null 2>&1 && return
- info "installing git…"
- if command -v apt-get >/dev/null 2>&1; then sudo_do apt-get update -qq && sudo_do apt-get install -y -qq git
- elif command -v dnf >/dev/null 2>&1; then sudo_do dnf install -y -q git
- elif command -v pacman >/dev/null 2>&1; then sudo_do pacman -Sy --noconfirm git
- else die "git missing and no known package manager — install git and re-run."; fi
-}
-
-node_ok() {
- command -v node >/dev/null 2>&1 || return 1
- node -e 'const[a,b]=process.versions.node.split(".").map(Number);process.exit(a>20||(a===20&&b>=9)?0:1)'
-}
-ensure_node() {
- node_ok && { info "node $(node -v) ok"; return; }
- warn "Node >=20.9 not found"
- if command -v apt-get >/dev/null 2>&1; then
- info "installing Node 22 via NodeSource…"
- curl -fsSL https://deb.nodesource.com/setup_22.x | sudo_do -E bash -
- sudo_do apt-get install -y -qq nodejs
- else
- die "install Node >=20.9 (22 recommended) from https://nodejs.org or your distro, then re-run."
- fi
- node_ok || die "Node still <20.9 after install."
-}
-
-# bun installs dependencies; it does NOT run the app. `next start` stays on node
-# (see the unit's ExecStart below) because node-pty's binding is built against
-# node's ABI and the whole /api/v1 surface imports it.
-ensure_bun() {
- command -v bun >/dev/null 2>&1 && { info "bun $(bun -v) ok"; return; }
- command -v sha256sum >/dev/null 2>&1 || die "sha256sum is required to verify the Bun bootstrap."
- info "installing Bun from a pinned, verified bootstrap…"
- local bootstrap actual url
- bootstrap="$(mktemp)"
- url="https://raw.githubusercontent.com/oven-sh/bun/$BUN_BOOTSTRAP_COMMIT/src/cli/install.sh"
- curl -fsSL "$url" -o "$bootstrap" || { rm -f "$bootstrap"; die "Bun bootstrap download failed."; }
- actual="$(sha256sum "$bootstrap" | awk '{print $1}')"
- [ "$actual" = "$BUN_BOOTSTRAP_SHA256" ] || {
- rm -f "$bootstrap"
- die "Bun bootstrap integrity check failed."
- }
- bash "$bootstrap" >/dev/null 2>&1 || { rm -f "$bootstrap"; die "bun install failed."; }
- rm -f "$bootstrap"
- export PATH="$BUN_INSTALL/bin:$PATH"
- command -v bun >/dev/null 2>&1 || die "bun installed but not on PATH — add $BUN_INSTALL/bin."
-}
-
-ensure_buildtools() {
- # node-pty is a native addon with no linux prebuild → needs a C/C++ toolchain +
- # python3 to compile at install time, under bun exactly as under pnpm.
- # This is the single most likely install failure on a minimal box.
- command -v cc >/dev/null 2>&1 && command -v python3 >/dev/null 2>&1 && return
- info "installing build toolchain (for node-pty)…"
- if command -v apt-get >/dev/null 2>&1; then sudo_do apt-get update -qq && sudo_do apt-get install -y -qq build-essential python3
- elif command -v dnf >/dev/null 2>&1; then sudo_do dnf install -y -q gcc-c++ make python3
- elif command -v pacman >/dev/null 2>&1; then sudo_do pacman -Sy --noconfirm base-devel python
- else warn "no known package manager — if 'bun install' fails on node-pty, install a C++ toolchain + python3 by hand."; fi
-}
-
-ensure_git; ensure_node; ensure_bun; ensure_buildtools
-
-# portable 32-byte hex RNG (node is guaranteed present by now)
-rand_hex() {
- if command -v openssl >/dev/null 2>&1; then openssl rand -hex "$1"
- else node -e "process.stdout.write(require('crypto').randomBytes($1).toString('hex'))"; fi
-}
-
-rand_password() {
- node -e 'const c="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";const b=require("crypto").randomBytes(24);let s="";for(const x of b)s+=c[x%c.length];process.stdout.write(s)'
-}
-
-# ---- clone or update (idempotent, resilient to a dirty tree) ----
-if [ -d "$DIR/.git" ]; then
- info "updating existing checkout at $DIR"
- old_commit="$(git -C "$DIR" rev-parse --short HEAD)"
- if [ -n "$(git -C "$DIR" status --porcelain)" ]; then
- die "checkout has uncommitted changes at $DIR. Commit/stash them, or install into another --dir. Current commit: $old_commit"
- fi
- info "current commit: $old_commit"
- git -C "$DIR" fetch --quiet origin "$REF" || die "could not fetch origin $REF"
- target_commit="$(git -C "$DIR" rev-parse --short FETCH_HEAD)" || die "could not resolve fetched ref $REF"
- info "target commit: $target_commit"
- git -C "$DIR" checkout --quiet FETCH_HEAD || die "could not check out $target_commit"
- ok "updated checkout $old_commit → $(git -C "$DIR" rev-parse --short HEAD)"
-else
- info "cloning $REPO_URL → $DIR"
- git clone --quiet --branch "$REF" "$REPO_URL" "$DIR" 2>/dev/null || git clone --quiet "$REPO_URL" "$DIR"
-fi
-cd "$DIR"
-
-# ---- deps (compiles node-pty) ----
-info "installing dependencies…"
-bun install --frozen-lockfile || bun install
-
-# ---- data dir + secrets (write .env.local only if absent) ----
-mkdir -p "$HOME/.mso" && chmod 700 "$HOME/.mso"
-
-GEN_PW=""
-if [ ! -f .env.local ]; then
- SECRET="$(rand_hex 32)"
- GEN_PW="$(rand_password)"
- ( umask 077
- cat > .env.local <<EOF
-# mso — generated by install.sh. Private; NEVER commit.
-OS_LOGIN_PASSWORD=$GEN_PW
-OS_SESSION_SECRET=$SECRET
-# SESSION_EXPIRY_HOURS=24
-# OS_FS_READ_ROOTS=~:~/projects
-# OS_FS_WRITE_ROOTS=~:~/projects
-# OS_AUDIT_LOG=~/.mso/audit.log
-EOF
- )
- chmod 600 .env.local
- ok "wrote .env.local (login password + session secret generated)"
-else
- info ".env.local exists — left untouched (existing secrets preserved)"
-fi
-
-# ---- build ----
-info "building (next build)…"
-bun run build
-
-# ---- CLI on PATH (before service setup so WSL/no-systemd still gets a CLI) ----
-# The web UI is one frontend; bin/mso reaches the same /api surface from a shell.
-BIN_DIR="${MSO_BIN_DIR:-$HOME/.local/bin}"
-mkdir -p "$BIN_DIR"
-ln -sfn "$DIR/bin/mso" "$BIN_DIR/mso"
-ok "cli → $BIN_DIR/mso"
-
-# A fresh distro/WSL home often omits ~/.local/bin from the current PATH. Persist
-# one small idempotent block for future shells. Default to bash when SHELL is not
-# exported (common in curl|bash/cloud-init); zsh gets its own rc instead.
-path_block() {
- local rc="$1"
- [ -e "$rc" ] || : > "$rc"
- grep -q '^# >>> mso cli >>>$' "$rc" 2>/dev/null && return
- cat >> "$rc" <<'EOF'
-
-# >>> mso cli >>>
-case ":$PATH:" in
- *":$HOME/.local/bin:"*) ;;
- *) export PATH="$HOME/.local/bin:$PATH" ;;
-esac
-# <<< mso cli <<<
-EOF
- info "added ~/.local/bin to PATH in $rc"
-}
-if [ "$BIN_DIR" = "$HOME/.local/bin" ]; then
- path_block "$HOME/.profile"
- case "${SHELL:-/bin/bash}" in
- */zsh) path_block "$HOME/.zshrc" ;;
- *) path_block "$HOME/.bashrc" ;;
- esac
-else
- warn "custom MSO_BIN_DIR=$BIN_DIR is not written into shell profiles; add it to PATH yourself"
-fi
-
-# Prove discoverability from the PARENT shell's original PATH. If the user-local
-# directory was already there, nothing else is needed. Otherwise use a guarded
-# launcher in /usr/local/bin (or MSO_SYSTEM_BIN_DIR) only when that directory is
-# already on the invoking PATH. This also makes `--no-service` useful on WSL.
-PARENT_PATH_RESOLVED="$(normalize_parent_path "$PARENT_PATH" "$PARENT_CWD")"
-SYSTEM_BIN_DIR="${MSO_SYSTEM_BIN_DIR:-/usr/local/bin}"
-case "$SYSTEM_BIN_DIR" in /*) ;; *) SYSTEM_BIN_DIR="$PARENT_CWD/$SYSTEM_BIN_DIR" ;; esac
-SYSTEM_CLI="$SYSTEM_BIN_DIR/mso"
-TARGET_CLI_REAL="$(readlink -f "$DIR/bin/mso")"
-CLI_IMMEDIATE=0
-parent_cli="$(PATH="$PARENT_PATH_RESOLVED" command -v mso 2>/dev/null || true)"
-if [ -n "$parent_cli" ] && [ "$(readlink -f "$parent_cli" 2>/dev/null || true)" = "$TARGET_CLI_REAL" ]; then
- CLI_IMMEDIATE=1
-elif path_has_dir "$PARENT_PATH_RESOLVED" "$SYSTEM_BIN_DIR"; then
- if link_cli_guarded "$SYSTEM_CLI" "$DIR/bin/mso"; then
- ok "current-PATH cli → $SYSTEM_CLI"
- parent_cli="$(PATH="$PARENT_PATH_RESOLVED" command -v mso 2>/dev/null || true)"
- if [ -n "$parent_cli" ] && [ "$(readlink -f "$parent_cli" 2>/dev/null || true)" = "$TARGET_CLI_REAL" ]; then
- CLI_IMMEDIATE=1
- fi
- else
- warn "could not install $SYSTEM_CLI; the user CLI is still installed at $BIN_DIR/mso"
- fi
-else
- info "$SYSTEM_BIN_DIR is not on the invoking PATH — skipped the extra launcher"
-fi
-
-# Validate the actual launcher independently of PATH. The child installer may use
-# its own exported PATH for onboarding, but that is NOT treated as proof that the
-# parent shell can see the command.
-"$BIN_DIR/mso" -h >/dev/null 2>&1 || die "CLI launcher is not executable: $BIN_DIR/mso"
-export PATH="$BIN_DIR:$PATH"
-if [ "$CLI_IMMEDIATE" -eq 1 ]; then
- ok "mso -h will resolve immediately after the installer returns ($parent_cli)"
-else
- warn "mso is installed, but this shell's existing PATH cannot see it yet"
- warn "for this shell run: export PATH=\"$BIN_DIR:\$PATH\""
- if [ "$BIN_DIR" = "$HOME/.local/bin" ]; then
- info "future shells will load the persisted ~/.local/bin PATH block"
- else
- warn "custom MSO_BIN_DIR is not persisted automatically; add $BIN_DIR to your shell profile"
- fi
-fi
-
-# ---- systemd unit ----
-if [ "$DO_SERVICE" -eq 1 ] && systemd_ready; then
- SERVICE_ATTEMPTED=1
- # Start via npm (always on PATH, ships with node) to match the proven prod unit;
- # PORT/HOSTNAME are set as env too so `next start` binds correctly regardless.
- NPM_BIN="$(command -v npm)"
- RUNTIME_INSTANCE_ID="$(rand_hex 16)"
- info "installing $SERVICE (needs sudo)…"
- sudo_do tee "/etc/systemd/system/$SERVICE" >/dev/null <<EOF
-[Unit]
-Description=Manef Shell OS — browser-based visual shell for a Linux server
-After=network.target
-
-[Service]
-Type=simple
-User=$(id -un)
-WorkingDirectory=$DIR
-EnvironmentFile=$DIR/.env.local
-Environment=PORT=$PORT
-Environment=HOSTNAME=$BIND
-# Fresh on every installer-driven restart. /api/health echoes this non-secret nonce
-# so readiness proves the HTTP response came from THIS restarted unit, not a stale
-# process that happened to keep answering on the configured port.
-Environment=MSO_RUNTIME_INSTANCE_ID=$RUNTIME_INSTANCE_ID
-# A system unit with User= inherits no login session, so it gets no user-bus
-# address and every \`systemctl --user\` it runs answers "Failed to connect to bus:
-# No medium found". That silently broke the managed-app installs (which create
-# systemd USER units) and made installed apps read as "not installed". Paired with
-# the \`loginctl enable-linger\` below, without which /run/user/<uid> is destroyed
-# at logout.
-#
-# The UID IS WRITTEN OUT, NOT the %U specifier. Do not "tidy" this back to %U — it
-# was tried and it FAILS: with User=antinrml and UID=1000, systemd 255 expanded %U
-# to 0, so the unit got XDG_RUNTIME_DIR=/run/user/0 and every systemctl --user
-# answered "No such file or directory" — the original bug wearing a new message.
-# Specifiers are expanded while the unit is parsed, before the NAME in User= has
-# been resolved to a uid, so %U falls back to the manager's own uid (root).
-Environment=XDG_RUNTIME_DIR=/run/user/$(id -u)
-# systemd would otherwise give this unit only
-# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin. Both managed-app CLIs install
-# themselves into ~/.local/bin, so without this \`which hermes\` fails inside the
-# service on a host where it plainly works in a terminal.
-Environment=PATH=$HOME/.local/bin:$HOME/.bun/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
-ExecStart=$NPM_BIN run start -- --hostname $BIND --port $PORT
-Restart=always
-RestartSec=5
-KillSignal=SIGTERM
-TimeoutStopSec=20
-MemoryMax=3G
-StandardOutput=journal
-StandardError=journal
-SyslogIdentifier=mso
-
-[Install]
-WantedBy=multi-user.target
-EOF
- # A wildcard bind is not an address you can dial; probe loopback instead.
- HEALTH_HOST="$BIND"
- case "$BIND" in 0.0.0.0|::|"") HEALTH_HOST=127.0.0.1 ;; esac
-
- # Makes /run/user/<uid> — where the user bus lives — exist without a login
- # session and survive logout. The XDG_RUNTIME_DIR above names that directory, so
- # without linger it would point at nothing after the installing shell exits.
- # Idempotent; failure is not fatal, it only means managed-app installs will say
- # so plainly when they preflight the bus.
- sudo_do loginctl enable-linger "$(id -un)" >/dev/null 2>&1 \
- || warn "could not enable linger for $(id -un) — self-update and managed-app user services may stop after logout"
- # `enable-linger` makes the manager persistent, but some minimal images do not
- # start [email protected] until the next login. Start it now so the first update
- # button works immediately, then prove the bus MSO will use actually answers.
- sudo_do systemctl start "user@$(id -u).service" >/dev/null 2>&1 \
- || warn "could not start the per-user systemd manager — self-update may be unavailable"
- if ! XDG_RUNTIME_DIR="/run/user/$(id -u)" systemctl --user show-environment >/dev/null 2>&1; then
- warn "per-user systemd bus is unavailable — self-update and managed-app services will not work until user@$(id -u).service is running"
- fi
-
- sudo_do systemctl daemon-reload
- sudo_do systemctl enable "$SERVICE"
- # restart, NOT `enable --now`. `--now` only *starts*, and a start on a unit
- # that is already running is a no-op — so re-running this installer used to
- # fetch, rebuild and then leave the OLD process serving a .next that had been
- # replaced underneath it. Every chunk 404s and nosniff makes that fatal
- # (docs/TROUBLESHOOTING.md). `restart` starts an inactive unit just as well,
- # so this is also correct on a first install.
- sudo_do systemctl restart "$SERVICE"
- ok "$SERVICE enabled + restarted"
-
- info "waiting for http://$HEALTH_HOST:$PORT/api/health …"
- up=0
- for _ in $(seq 1 30); do
- body="$(curl -fsS --max-time 3 "http://$HEALTH_HOST:$PORT/api/health" 2>/dev/null || true)"
- if [ -n "$body" ]; then
- now_build="$(printf '%s' "$body" | sed -n 's/.*"buildId":"\([^"]*\)".*/\1/p')"
- now_instance="$(printf '%s' "$body" | sed -n 's/.*"runtimeInstanceId":"\([^"]*\)".*/\1/p')"
- # A healthy response is accepted only when it carries the nonce injected into
- # THIS service unit before restart. This remains correct when NEXT_DEPLOYMENT_ID
- # intentionally keeps buildId stable and cannot be satisfied by a stale or
- # unrelated process still listening on the same port.
- if [ "$now_instance" = "$RUNTIME_INSTANCE_ID" ]; then
- up=1; SERVICE_READY=1
- ok "health OK (build ${now_build:-unknown}, runtime instance verified)"
- break
- fi
- fi
- sleep 2
- done
- if [ "$up" -ne 1 ]; then
- # is-active needs no privileges — do not spend a sudo prompt on the sad path.
- if systemctl is-active --quiet "$SERVICE"; then
- warn "service is running but /api/health did not prove the restarted runtime instance — check: journalctl -u mso -e"
- else
- warn "$SERVICE is not running — check: journalctl -u mso -e"
- fi
- fi
-elif [ "$DO_SERVICE" -eq 1 ]; then
- if is_wsl; then
- warn "WSL detected without systemd as PID 1 — service install skipped; the mso CLI is still installed"
- info "for the full service: enable systemd in /etc/wsl.conf, run 'wsl --shutdown' from Windows, reopen WSL, then re-run this installer --onboard"
- else
- warn "systemd is not available as PID 1 — service install skipped; run manually: PORT=$PORT bun run start"
- fi
-fi
-
-# ---- optional Claude Code integration ----
-# MSO catalogs $DIR/claude-skills directly, so these symlinks are NOT required by MSO.
-# They only expose the same official playbooks to Claude Code when its home exists.
-SKILL_DIR="${MSO_SKILL_DIR:-$HOME/.claude/skills}"
-if [ -d "$DIR/claude-skills" ] && [ -d "$(dirname "$SKILL_DIR")" ]; then
- mkdir -p "$SKILL_DIR"
- for s in "$DIR"/claude-skills/*/; do
- name="$(basename "$s")"
- if [ -e "$SKILL_DIR/$name" ] && [ ! -L "$SKILL_DIR/$name" ]; then
- warn "skill $name exists and is not a symlink — left alone"
- continue
- fi
- ln -sfn "${s%/}" "$SKILL_DIR/$name"
- done
- # Prune ours that no longer exist. Only symlinks POINTING INTO this repo's
- # claude-skills are touched, so a hand-made or third-party skill is never
- # removed. Without this a deleted skill kept a dangling entry forever and the
- # agent still saw it listed (mso-browser-list did exactly that).
- for l in "$SKILL_DIR"/*; do
- [ -L "$l" ] || continue
- tgt="$(readlink "$l")"
- case "$tgt" in "$DIR/claude-skills/"*) [ -d "$tgt" ] || { rm -f "$l"; info "pruned stale skill $(basename "$l")"; } ;; esac
- done
- ok "skills → $SKILL_DIR (/mso, /mso-camoufox, /mso-apps, /mso-list, …)"
-fi
-
-# ---- next steps ----
-# How to reach it depends on the bind AND on the Secure session cookie: a
-# browser only keeps that cookie over plain http on localhost/127.0.0.1/::1, so
-# any address that is not one of those needs TLS or a tunnel to log in at all.
-WHOAMI="$(id -un)"
-case "$BIND" in
- 127.0.0.1|::1|localhost)
- REACH="tunnel from your own machine:
- ssh -N -L $PORT:127.0.0.1:$PORT $WHOAMI@<this-host>
- then open http://localhost:$PORT
- (or \`tailscale serve $PORT\`, or a TLS reverse proxy → 127.0.0.1:$PORT)" ;;
- 0.0.0.0|::)
- REACH="http://<this-host>:$PORT
- !! bound on EVERY interface. An authenticated session runs commands as
- $WHOAMI — firewall it, or re-run with --bind 127.0.0.1.
- Plain http to an IP also cannot log in: the session cookie is Secure." ;;
- *)
- REACH="http://$BIND:$PORT
- (plain http to a non-loopback address cannot complete a login — the
- session cookie is Secure. Put TLS in front, or tunnel to loopback.)" ;;
-esac
-
-if [ "$SERVICE_READY" -eq 1 ]; then
- OPEN_STATUS="$REACH"
- LOG_STATUS="journalctl -u mso -f"
-elif [ "$DO_SERVICE" -eq 0 ]; then
- OPEN_STATUS="not running (--no-service). Start manually: cd $DIR && PORT=$PORT bun run start"
- LOG_STATUS="no system service installed"
-elif [ "$SERVICE_ATTEMPTED" -eq 1 ]; then
- OPEN_STATUS="service was installed/restarted but did not pass health verification; inspect the journal before opening the UI"
- LOG_STATUS="journalctl -u mso -e"
-elif is_wsl; then
- OPEN_STATUS="not running (WSL systemd is unavailable). Enable systemd or start manually from $DIR"
- LOG_STATUS="no system service installed"
-else
- OPEN_STATUS="systemd is unavailable; start manually from $DIR"
- LOG_STATUS="no system service installed"
-fi
-
-ok "mso installed at $DIR"
-cat <<EOF
-
- Runtime: $OPEN_STATUS
- Env: $DIR/.env.local
-EOF
-[ -n "$GEN_PW" ] && printf ' Password: %s (shown once — save it now; edit OS_LOGIN_PASSWORD in .env.local + service refresh to change)\n' "$GEN_PW"
-cat <<EOF
-
- Pair your first device after the API is running (device approval is a browser allowlist, not standards-based 2FA):
- 1. Open the URL, enter the password — the browser lands PENDING and shows a device id.
- 2. On this server:
- node $DIR/scripts/approve-device.js --list # see the pending id
- node $DIR/scripts/approve-device.js <deviceId> "my phone" # approve it
- 3. Reload + log in. Approve later devices from Settings → Devices.
-
- Logs: $LOG_STATUS
- Update: re-run this installer (pull + verify + build + service refresh), or --uninstall to remove
- Listen: $BIND:$PORT (change with --bind / MSO_BIND)
- Security: verify from OUTSIDE the box — \`curl -m5 http://<public-ip>:$PORT/api/health\`
- run on your laptop is the only test that proves what is reachable.
- Review ~/.mso/audit.log.
-EOF
-
-# A successful fresh install should lead directly into a usable product. curl|bash
-# owns stdin, so interactive setup uses the controlling terminal explicitly.
-RUN_ONBOARD=0
-case "$ONBOARD_MODE" in
- always) RUN_ONBOARD=1 ;;
- never) RUN_ONBOARD=0 ;;
- auto) [ "$FRESH_INSTALL" -eq 1 ] && RUN_ONBOARD=1 ;;
-esac
-if [ "$RUN_ONBOARD" -eq 1 ] && [ "$SERVICE_READY" -eq 1 ]; then
- if [ "$YES" -eq 1 ]; then
- echo
- info "running minimal non-interactive onboarding (-y)…"
- "$BIN_DIR/mso" onboard -y || warn "onboarding did not finish — rerun: mso onboard"
- elif [ -r /dev/tty ] && [ -w /dev/tty ]; then
- echo
- info "starting guided onboarding…"
- if ! "$BIN_DIR/mso" onboard </dev/tty >/dev/tty 2>/dev/tty; then
- warn "onboarding stopped early — resume anytime with: mso onboard"
- fi
- else
- echo
- warn "no interactive terminal detected — onboarding skipped. Run: mso onboard"
- fi
-elif [ "$RUN_ONBOARD" -eq 1 ]; then
- warn "no verified running MSO API is available for onboarding — start/enable the service, then run 'mso onboard'"
-fi
+# Keep this file intentionally tiny. Streaming a large shell script directly into
+# bash can produce a false success if an intermediary closes the response at a
+# syntactically complete line. This bootstrap downloads the real installer to a
+# private temporary file, proves completeness + SHA-256 + syntax, then executes it.
+set -Eeuo pipefail
+umask 077
+
+CORE_URL="${MSO_INSTALL_CORE_URL:-https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install-core.sh}"
+CORE_SHA256="913350997e568a279c6582e752d38151f20798cb1f1e471b557aba06b71821ad"
+CORE_EOF='# MSO_INSTALLER_CORE_EOF'
+BOOTSTRAP_DONE=0
+TMP_INSTALLER=''
+
+bootstrap_exit() {
+ rc=$?
+ trap - EXIT
+ [ -z "$TMP_INSTALLER" ] || rm -f "$TMP_INSTALLER"
+ if [ "$rc" -eq 0 ] && [ "$BOOTSTRAP_DONE" -ne 1 ]; then
+ printf 'mso installer bootstrap ended before verification completed; retry the download.\n' >&2
+ rc=97
+ fi
+ exit "$rc"
+}
+trap bootstrap_exit EXIT
+
+fail() { printf 'mso installer bootstrap: %s\n' "$*" >&2; exit 1; }
+command -v curl >/dev/null 2>&1 || fail 'curl is required.'
+command -v sha256sum >/dev/null 2>&1 || fail 'sha256sum is required to verify the installer payload.'
+
+TMP_INSTALLER="$(mktemp "${TMPDIR:-/tmp}/mso-install-core.XXXXXX")"
+# Download FIRST; never execute bytes while they are still arriving.
+curl -fsSL --retry 3 --retry-delay 1 --connect-timeout 15 --max-time 180 "$CORE_URL" -o "$TMP_INSTALLER" || fail 'installer payload download failed.'
+
+[ "$(wc -c <"$TMP_INSTALLER")" -ge 20000 ] || fail 'installer payload is unexpectedly short; refusing partial execution.'
+[ "$(tail -n 1 "$TMP_INSTALLER")" = "$CORE_EOF" ] || fail 'installer payload is incomplete; EOF marker missing.'
+ACTUAL_SHA="$(sha256sum "$TMP_INSTALLER" | awk '{print $1}')"
+[ "$ACTUAL_SHA" = "$CORE_SHA256" ] || fail 'installer payload hash mismatch (main may have changed during download); retry.'
+bash -n "$TMP_INSTALLER" || fail 'installer payload failed shell syntax validation.'
+
+BOOTSTRAP_DONE=1
+set +e
+bash "$TMP_INSTALLER" "$@"
+rc=$?
+set -e
+exit "$rc"
diff --git a/scripts/security-ultimate.sh b/scripts/security-ultimate.sh
index ba4ca346..c4589276 100755
--- a/scripts/security-ultimate.sh
+++ b/scripts/security-ultimate.sh
@@ -56,7 +56,7 @@ run_capture() {
}
run_capture "repository verify" bun run verify
-run_capture "installer syntax" bash -n scripts/install.sh
+run_capture "installer syntax" bash -c 'bash -n scripts/install.sh && bash -n scripts/install-core.sh'
run_capture "Trivy high/critical" docker run --rm -v "$SRC:/src:ro" "$TRIVY_IMAGE" \
fs --scanners vuln,misconfig,secret --severity HIGH,CRITICAL --exit-code 1 /src
run_capture "OSV dependencies" docker run --rm -v "$SRC:/src:ro" "$OSV_IMAGE" \