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(cli): diagnose HTTPS login and add doctor --fix

Rahmanf35d261bae79
diff --git a/README.md b/README.md
index ff6043dd..48724c50 100644
--- a/README.md
+++ b/README.md
@@ -259,9 +259,12 @@ curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install
curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash -s -- --uninstall
```
-There is also a no-login install guide at **<https://mso.rahmanef.com/install>**. Full
-production setup, TLS/VPN notes, filesystem roots, update/rollback and onboarding details
-live in [docs/INSTALL.md](./docs/INSTALL.md).
+There is also a no-login install guide at **<https://mso.rahmanef.com/install>**. **Browser
+sign-in requires HTTPS**, except when you access MSO through a loopback URL such as
+`http://localhost:4005`. Do not pair/approve a browser on plain `http://<server-ip>:4005`:
+the session cookie is `Secure`, so the browser cannot keep the login there. Full production setup,
+TLS/VPN notes, filesystem roots, update/rollback and onboarding details live in
+[docs/INSTALL.md](./docs/INSTALL.md).
## CLI
@@ -271,7 +274,8 @@ covers anything without one.
```bash
mso -h # grouped command list; `mso <command> --help` per command
-mso doctor # deps, env, service, session, device — names what broke
+mso doctor # includes HTTPS/login-origin diagnosis
+mso doctor --fix # safe local repairs; never changes DNS/TLS/firewall/credentials
mso onboard # guided AI/app/skill setup
mso skills available # curated installable skills
mso skills install ponytail caveman rtk -y
diff --git a/app/install/page.tsx b/app/install/page.tsx
index d7f4e7d4..6d20b975 100644
--- a/app/install/page.tsx
+++ b/app/install/page.tsx
@@ -39,7 +39,7 @@ const STEPS = [
{
n: 3,
title: "Reach it",
- body: "The installer binds 127.0.0.1, so :4005 is closed to other machines by default. Tunnel in from whatever you browse on. The session cookie is Secure, so ordinary plain-http IP addresses are not a valid permanent login origin.",
+ body: "The installer binds 127.0.0.1, so :4005 is closed to other machines by default. Tunnel in from whatever you browse on. Pair the device only after you are on HTTPS or http://localhost: a plain-http server IP cannot store MSO's Secure session cookie, and changing hostnames creates a different browser device ID.",
code: "ssh -N -L 4005:127.0.0.1:4005 you@your-server",
note: "Then open http://localhost:4005. For something permanent use `tailscale serve 4005`, or a TLS reverse proxy pointed at 127.0.0.1:4005.",
},
@@ -47,7 +47,7 @@ const STEPS = [
n: 4,
title: "Pair your browser",
body: "Open the app and enter the password. Your browser lands PENDING and shows a device id. Terminal onboarding approves only the local CLI device; browser devices remain explicit owner approvals.",
- code: "mso device pending\nmso device approve <deviceId> \"my laptop\"",
+ code: "mso device pending\nmso device approve <deviceId> \"my laptop\"\n# back in the SAME HTTPS/localhost browser: click Check again",
note: "Device approval is a browser allowlist, not standards-based 2FA. Approve only devices you own.",
},
{
diff --git a/bin/mso b/bin/mso
index 39400ce3..7b4c86b1 100755
--- a/bin/mso
+++ b/bin/mso
@@ -41,7 +41,7 @@
# cleanup [--run] Reclaimable junk; --run actually deletes it
# status Public service status (no session needed)
# health Is this CLI's session valid?
-# doctor Check deps, env, service, session, device — and say what broke
+# doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues
# onboard [-y] Guided first-run setup: AI, response style, managed apps, skills
# gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
# web Open the MSO browser UI (active gateway first, else loopback)
@@ -452,7 +452,7 @@ ensure_local_cli_device() {
http://127.0.0.1:*|http://localhost:*|http://[::1]:*) ;;
*) return 0 ;;
esac
- if ! dev_script --list 2>/dev/null | grep -q "$d"; then
+ if ! dev_script --is-approved "$d" >/dev/null 2>&1; then
dev_script "$d" "mso cli" >/dev/null
echo " ✓ approved this local CLI device"
fi
@@ -653,6 +653,7 @@ verbs() {
# you're wrong.
U_camoufox="camoufox status|start|stop|session"
U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"
+U_doctor="doctor [--fix]"
U_mapp="mapp list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"
U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows>|stream <id>|close <id>"
U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner]|role <id> <role>|revoke <id>|revoke all --yes"
@@ -738,20 +739,49 @@ case "$cmd" in
# Layer-by-layer, cheapest first, so the FIRST failure names the real cause
# instead of the symptom three layers up ("login failed" when node is missing).
doctor)
+ fix=0
+ case "${1-}" in
+ "") ;;
+ --fix) fix=1 ;;
+ *) die "usage: mso $U_doctor" ;;
+ esac
fails=0
chk() { if eval "$2" >/dev/null 2>&1; then printf ' ok %s\n' "$1"; else printf ' FAIL %s — %s\n' "$1" "$3"; fails=$((fails+1)); fi; }
- echo "mso doctor (base $B)"
+ fixed() { printf ' FIXED %s\n' "$1"; }
+ browser_origin_ok() {
+ case "$1" in
+ https://*) return 0 ;;
+ http://127.*:*|http://localhost:*|http://\[::1\]:*) return 0 ;;
+ *) return 1 ;;
+ esac
+ }
+ doctor_label="mso doctor"; [ "$fix" = 1 ] && doctor_label="$doctor_label --fix"
+ echo "$doctor_label (base $B)"
chk "curl" "command -v curl" "install curl"
chk "jq" "command -v jq" "install jq"
chk "node" "command -v node" "install Node >=20.9"
chk "env file" "[ -f '$ENVF' ]" "no $ENVF — copy .env.example and fill it"
chk "login password" "[ -n '$PASS' ]" "OS_LOGIN_PASSWORD unset in $ENVF"
chk "session secret" "[ -n \"\${OS_SESSION_SECRET-}\" ]" "OS_SESSION_SECRET unset in $ENVF"
- # Not a chk with a pass/fail: serving NO managed-app dashboards is a supported
- # deployment, not a fault — but it is the reason a Hermes/OpenClaw window opens on a
- # terminal, and nothing else anywhere says so out loud. Half-configured IS a fault,
- # and a security one: a cookie domain without the host template hands the session to
- # every host under that name while each still serves a whole cockpit.
+
+ # Browser login is stricter than CLI reachability: the session cookie is
+ # always Secure. Plain HTTP on a server/LAN IP can answer /api/health and even
+ # accept the password, but the browser cannot retain the session. Loopback is
+ # the development exception. Never auto-create a public tunnel in --fix.
+ if browser_origin_ok "$B"; then
+ echo " ok login transport — browser must use HTTPS or http://localhost (never plain http://server-ip)"
+ else
+ printf ' FAIL login transport — browser login requires HTTPS or a loopback URL; use a TLS proxy/gateway, or SSH -L and open http://localhost\n'
+ fails=$((fails+1))
+ fi
+ if [ -n "${OS_PUBLIC_ORIGIN-}" ] && ! browser_origin_ok "$OS_PUBLIC_ORIGIN"; then
+ printf ' FAIL public origin — OS_PUBLIC_ORIGIN=%s is not a valid browser login origin; use https://...\n' "$OS_PUBLIC_ORIGIN"
+ fails=$((fails+1))
+ elif [ -n "${OS_PUBLIC_ORIGIN-}" ]; then
+ printf ' ok public origin (%s)\n' "$OS_PUBLIC_ORIGIN"
+ fi
+
+ # Not a chk with a pass/fail: serving NO managed-app dashboards is supported.
tpl="${NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE-}"; dom="${OS_SESSION_COOKIE_DOMAIN-}"
if [ -n "$tpl" ] && [ -n "$dom" ]; then
echo " ok app dashboards ($tpl) — after changing this, REBUILD and sign in again"
@@ -761,23 +791,55 @@ case "$cmd" in
printf ' FAIL app dashboards — set BOTH NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE and OS_SESSION_COOKIE_DOMAIN, or neither\n'
fails=$((fails+1))
fi
- chk "service unit" "systemctl is-active --quiet mso.service" "mso.service not active — mso service start"
+
+ if ! service_manager_read is-active --quiet mso.service 2>/dev/null; then
+ if [ "$fix" = 1 ] && service_manager_read show -p WorkingDirectory --value mso.service 2>/dev/null | grep -q .; then
+ if ( service_start_safe >/dev/null 2>&1 ); then fixed "service unit started"; else printf ' FAIL service unit — automatic start failed; run: mso service logs\n'; fails=$((fails+1)); fi
+ else
+ printf ' FAIL service unit — mso.service not active%s\n' "$([ "$fix" = 1 ] && printf '; no existing unit could be safely started' || printf ' — run: mso doctor --fix or mso service start')"
+ fails=$((fails+1))
+ fi
+ else
+ echo " ok service unit"
+ fi
chk "reachable" "curl -fsS --max-time 5 '$B/api/health'" "nothing answering at $B"
- d=$(cli_device)
- # Only meaningful against a local base — the allowlist lives on the host, and
- # dev_script now refuses a remote one rather than reading the wrong file.
+
+ d=$(cli_device); device_ready=0
case "$B" in
http://127.0.0.1:*|http://localhost:*|http://[::1]:*)
- chk "device known" "dev_script --list | grep -q '$d'" "this CLI device is not approved — mso device approve $d 'mso cli'" ;;
- *) echo " -- device known (skipped: --base is remote; check it on that host)" ;;
+ if dev_script --is-approved "$d" >/dev/null 2>&1; then
+ echo " ok device known"; device_ready=1
+ elif [ "$fix" = 1 ]; then
+ if dev_script "$d" "mso cli" >/dev/null 2>&1; then fixed "local CLI device approved"; device_ready=1
+ else printf ' FAIL device known — could not approve the local CLI device; inspect: mso device list\n'; fails=$((fails+1)); fi
+ else
+ printf ' FAIL device known — this CLI device is not approved; run: mso doctor --fix (or mso device approve %s "mso cli")\n' "$d"
+ fails=$((fails+1))
+ fi ;;
+ *) echo " -- device known (skipped: --base is remote; check it on that host)"; device_ready=1 ;;
esac
+
fresh_session_check() {
mso_private_state_remove_file "$JAR" || return 1
JAR=$(mso_private_state_ensure_file "$JAR") || return 1
[ "$(jget /api/auth/me | jq -r .authenticated)" = true ]
}
- chk "session" "fresh_session_check" "cannot sign in — see the checks above"
+ if [ "$device_ready" = 1 ]; then
+ if ( fresh_session_check >/dev/null 2>&1 ); then
+ [ "$fix" = 1 ] && fixed "session refreshed" || echo " ok session"
+ else
+ printf ' FAIL session — cannot sign in; verify password, approved device, and browser/CLI origin above\n'
+ fails=$((fails+1))
+ fi
+ else
+ printf ' FAIL session — skipped until the local CLI device is approved\n'
+ fails=$((fails+1))
+ fi
echo
+ if [ "$fix" = 1 ]; then
+ echo "--fix only changes safe local state: existing service start, this host's CLI approval, and its cookie jar."
+ echo "It never changes DNS, TLS certificates, firewall rules, public exposure, or credentials."
+ fi
[ "$fails" -eq 0 ] && echo "all good." || echo "$fails check(s) failed."
exit $(( fails > 0 ? 1 : 0 )) ;;
diff --git a/bin/mso-doctor.test.ts b/bin/mso-doctor.test.ts
new file mode 100644
index 00000000..904c603d
--- /dev/null
+++ b/bin/mso-doctor.test.ts
@@ -0,0 +1,67 @@
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+const CLI = path.join(__dirname, "mso");
+
+function fixture() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-doctor-"));
+ const bin = path.join(root, "bin");
+ const envFile = path.join(root, ".env.local");
+ const store = path.join(root, "devices.json");
+ const devFile = path.join(root, "cli.device.id");
+ const device = "d".repeat(32);
+ fs.mkdirSync(bin, { mode: 0o700 });
+ fs.writeFileSync(devFile, device, { mode: 0o600 });
+ fs.writeFileSync(envFile, "OS_LOGIN_PASSWORD=fixture-password\nOS_SESSION_SECRET=fixture-session-secret-long-enough\n", { mode: 0o600 });
+ fs.writeFileSync(store, JSON.stringify({ approved: {}, pending: { [device]: { label: "mso cli", firstSeen: 1, lastSeen: 1, ip: "127.0.0.1", attempts: 1 } } }));
+ fs.writeFileSync(path.join(bin, "curl"), `#!/bin/sh
+case "$*" in
+ *api/auth/login*) body='{"success":true}' ;;
+ *api/auth/me*) body='{"authenticated":true,"role":"owner"}' ;;
+ *) body='{"status":"ok","service":"mso"}' ;;
+esac
+case "$*" in *'-w '*) printf '%s\n200' "$body" ;; *) printf '%s' "$body" ;; esac
+`, { mode: 0o700 });
+ fs.writeFileSync(path.join(bin, "systemctl"), `#!/bin/sh
+case "$*" in
+ *'show -p WorkingDirectory --value mso.service'*) printf '%s\n' '${path.dirname(CLI)}' ;;
+ *'show -p Environment --value mso.service'*) printf 'PORT=4005\n' ;;
+ *) exit 0 ;;
+esac
+`, { mode: 0o700 });
+ const env = { ...process.env, HOME: root, PATH: `${bin}:${process.env.PATH}`, MSO_ENV: envFile,
+ OS_DEVICE_STORE: store, MSO_DEVICE_FILE: devFile, MSO_SYSTEMCTL_BIN: path.join(bin, "systemctl"),
+ NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE: "", OS_SESSION_COOKIE_DOMAIN: "", OS_PUBLIC_ORIGIN: "" };
+ return { root, store, device, env };
+}
+
+describe("mso doctor", () => {
+ it("explains that plain HTTP on a server IP cannot keep a browser session", () => {
+ const fx = fixture();
+ try {
+ const result = spawnSync(CLI, ["--base", "http://192.0.2.10:4005", "doctor"], { encoding: "utf8", env: fx.env });
+ expect(result.status).toBe(1);
+ expect(result.stdout).toContain("FAIL login transport");
+ expect(result.stdout).toContain("browser login requires HTTPS or a loopback URL");
+ expect(result.stdout).toContain("http://localhost");
+ } finally { fs.rmSync(fx.root, { recursive: true, force: true }); }
+ });
+
+ it("--fix promotes this host's pending CLI device and refreshes its session without changing TLS/network state", () => {
+ const fx = fixture();
+ try {
+ const result = spawnSync(CLI, ["--base", "http://127.0.0.1:4005", "doctor", "--fix"], { encoding: "utf8", env: fx.env });
+ expect(result.status).toBe(0);
+ expect(result.stdout).toContain("mso doctor --fix");
+ expect(result.stdout).toContain("FIXED local CLI device approved");
+ expect(result.stdout).toContain("FIXED session refreshed");
+ expect(result.stdout).toContain("never changes DNS, TLS certificates, firewall rules, public exposure, or credentials");
+ const parsed = JSON.parse(fs.readFileSync(fx.store, "utf8"));
+ expect(parsed.approved[fx.device]).toMatchObject({ label: "mso cli", role: "owner" });
+ expect(parsed.pending[fx.device]).toBeUndefined();
+ } finally { fs.rmSync(fx.root, { recursive: true, force: true }); }
+ });
+});
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 569b20d1..5b502d51 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -12,10 +12,29 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Fixed**
+- `cli` diagnose HTTPS login and add doctor --fix
- `mcp` validate browser origins
+- `security` avoid recovery guard fsync convoy
+- `runtime` verify service readiness before handoff
+- `jobs` finish retention before releasing runtime
+- `runtime` preserve fallback recovery readiness
+- `runtime` keep service starts on shared exclusion
- `settings` hide premature update warning
- `update` enforce main and raise MCP daily limit
- `mcp` raise daily token call limit
+- `gateway` canonicalize public origin assignment
+- `git` restore executable script modes
+- `runtime` close service installer and notice races
+- `install` hold update lock across checkout refresh
+- `install` restore service after pre-mutation abort
+
+**Tests**
+
+- `security` remove recovery marker TOCTOU
+- `gateway` assert one live tunnel after concurrent start
+- `install` read abort capture by descriptor
+- `install` align bootstrap and abort harness
+- `install` make abort recovery harness static
**Docs**
diff --git a/docs/CLI.md b/docs/CLI.md
index 2cbe6a74..6ac1ed5d 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -16,7 +16,8 @@ eval "$(mso completion bash)" # optional: tab completion
## First run
```bash
-mso doctor # deps, env, service, session, device — names what broke
+mso doctor # deps, HTTPS/login origin, service, session, device — names what broke
+mso doctor --fix # safe local repairs; never changes DNS/TLS/firewall/credentials
mso device pending # after a browser tries to log in, approve it from here
```
@@ -27,6 +28,11 @@ device id (`~/.mso/cli.device.id`), which you approve once:
mso device approve "$(cat ~/.mso/cli.device.id)" "mso cli"
```
+Browser sign-in must use **HTTPS**, except for loopback development/access such as
+`http://localhost:4005`. Plain `http://<server-ip>:4005` may answer health/API requests,
+but the browser cannot retain MSO's `Secure` session cookie there. Pair the device on its final
+HTTPS/localhost origin; `mso doctor` reports this explicitly.
+
Device and service commands work even while the service is down — that is on
purpose, because those are exactly the commands you need when it is.
@@ -75,7 +81,7 @@ Commands:
cleanup [--run] Reclaimable junk; --run actually deletes it
status Public service status (no session needed)
health Is this CLI's session valid?
- doctor Check deps, env, service, session, device — and say what broke
+ doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues
onboard [-y] Guided first-run setup: AI, response style, managed apps, skills
gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
web Open the MSO browser UI (active gateway first, else loopback)
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 9450f1cf..55eb83b9 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -247,6 +247,11 @@ OS_LOGIN_PASSWORD=choose-a-strong-owner-password
OS_SESSION_SECRET=<stable random 32+ byte secret>
```
+Open the browser on its final login origin **before** pairing: HTTPS in production, or
+`http://localhost:<port>` through an SSH tunnel. Do not approve a device ID obtained on a plain-HTTP
+server IP and then switch to an HTTPS hostname; the Secure session cookie cannot persist on the first
+origin, and the hostname change has a different browser-scoped device identity.
+
The first correct login from a browser creates a **pending device**. Bootstrap an Owner from the
server, then approve additional devices from Settings → Devices or the CLI:
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 8698acd9..26aa4f74 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -2,6 +2,33 @@
Running log of what shipped each phase. Newest at top.
+## 2026-08-31 — Login-origin diagnosis + `mso doctor --fix` + runtime hardening (SHIPPED)
+
+A real install report confirmed the confusing post-approval login case was transport, not a broken
+device store: the browser was opening MSO on plain `http://<server-ip>:4005`. MSO's session cookie is
+always `Secure`, so that address can answer health/API requests and accept the password while the
+browser still cannot retain the authenticated session. Pairing on that IP and later moving to an HTTPS
+hostname is also a different browser origin, so the device ID shown there is not the final-origin ID.
+
+The supported guidance is now explicit in the installer summary, `/install`, README, CLI reference,
+Install and Troubleshooting docs: browser sign-in uses HTTPS, or loopback via `http://localhost` (for
+example through SSH port forwarding). `mso doctor` prints the same login-transport rule even when its
+own loopback CLI base is healthy, and fails clearly when `--base` / `OS_PUBLIC_ORIGIN` points at a
+plain-HTTP non-loopback address. `mso doctor --fix` was added for bounded local recovery: it may start
+an existing MSO service, approve this host's own CLI device, and refresh its session jar; it never
+changes DNS, certificates, firewall rules, public exposure, or login credentials.
+
+The screenshot also exposed a separate onboarding bug: `ensure_local_cli_device` previously searched
+`device --list`, which contains both APPROVED and PENDING rows. A CLI ID already in PENDING was
+therefore mistaken for approved, onboarding skipped promotion, then its first authenticated request
+failed. The device helper now has an exact approval-status probe; onboarding and doctor promote that
+local CLI ID correctly and regression tests cover the pending-to-approved case.
+
+The remaining changes from PR #28 were not discarded as stale. Its installer/update-lock recovery,
+service/fallback readiness handoff, gateway public-origin canonicalization, job-retention ordering and
+security-store contention fixes were integrated on top of the current MCP work and independently
+exercised before release.
+
## 2026-08-31 — Guided multi-client MCP setup in Settings (SHIPPED)
Settings → MCP now treats connection as an onboarding workflow instead of a developer-only list of
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 835cee80..811e28a9 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -18,7 +18,20 @@ forward the real client IP consistently so every user does not share the proxy a
### Correct password but "pending approval"
Expected for a new browser. Approve the shown device id from an already-approved browser
-(Settings → Devices) or from the server using the approval script.
+(Settings → Devices) or from the server using the approval script. Pair and re-check from the
+**same browser origin**. Device identity is browser-origin scoped, so approving an ID from
+`http://server-ip:4005` and then switching to `https://mso.example.com` creates a different ID.
+
+### Device was approved but login still does not stick
+
+Do not use plain HTTP on a non-loopback hostname/IP. MSO's session cookie is always `Secure`;
+a browser can reach `http://server-ip:4005` and submit the password, but it cannot retain the session
+cookie there, so the next authenticated probe stays signed out. Use HTTPS, or tunnel the service and
+open `http://localhost:4005`, then approve the device ID shown on that final origin and click
+**Check again**. `mso doctor` now calls out this transport mismatch; `mso doctor --fix` repairs safe
+local issues such as a pending CLI device/session, but deliberately does **not** change DNS, TLS,
+firewall rules or public exposure. If you approved the wrong-origin browser ID, revoke it only after
+the final-origin device is working.
### `mso onboard` approved the CLI device, then says port 4005 is unreachable
diff --git a/lib/onboard-contract.test.ts b/lib/onboard-contract.test.ts
index daec132f..3229073f 100644
--- a/lib/onboard-contract.test.ts
+++ b/lib/onboard-contract.test.ts
@@ -59,6 +59,39 @@ esac
} finally { fs.rmSync(root, { recursive: true, force: true }); }
});
+ it("promotes a CLI id that is present in pending instead of mistaking it for approved", () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-onboard-pending-cli-"));
+ const bin = path.join(root, "bin");
+ const envFile = path.join(root, ".env.local");
+ const store = path.join(root, "devices.json");
+ const devFile = path.join(root, "cli.device.id");
+ const fakeCurl = path.join(bin, "curl");
+ const device = "c".repeat(32);
+ fs.mkdirSync(bin, { mode: 0o700 });
+ fs.writeFileSync(devFile, device, { mode: 0o600 });
+ fs.writeFileSync(envFile, "OS_LOGIN_PASSWORD=fixture-password\nOS_SESSION_SECRET=fixture-session-secret-long-enough\n", { mode: 0o600 });
+ fs.writeFileSync(store, JSON.stringify({ approved: {}, pending: { [device]: { label: "mso cli", firstSeen: 1, lastSeen: 1, ip: "127.0.0.1", attempts: 1 } } }));
+ fs.writeFileSync(fakeCurl, `#!/bin/sh
+case "$*" in
+ *api/auth/login*) body='{"success":true}' ;;
+ *api/auth/me*) body='{"authenticated":true,"role":"owner"}' ;;
+ *) body='{"status":"ok","service":"mso","buildId":"fixture","buildSha":"abcdef1","runtimeInstanceId":"fixture","version":"0.2.1"}' ;;
+esac
+case "$*" in *'-w '*) printf '%s\n200' "$body" ;; *) printf '%s' "$body" ;; esac
+`, { mode: 0o700 });
+ try {
+ const out = execFileSync(path.join(__dirname, "../bin/mso"), ["--base", "http://127.0.0.1:4555", "onboard", "-y"], {
+ encoding: "utf8",
+ env: { ...process.env, HOME: root, PATH: `${bin}:${process.env.PATH}`, MSO_ENV: envFile, OS_DEVICE_STORE: store,
+ MSO_DEVICE_FILE: devFile, MSO_GATEWAY_CURL: fakeCurl, MSO_GATEWAY_STATE_DIR: path.join(root, "gateway-state") },
+ });
+ expect(out).toContain("approved this local CLI device");
+ const parsed = JSON.parse(fs.readFileSync(store, "utf8"));
+ expect(parsed.approved[device]).toMatchObject({ label: "mso cli", role: "owner" });
+ expect(parsed.pending[device]).toBeUndefined();
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
+ });
+
it("reports a down runtime instead of falsely asking an already-approved device to approve again", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-login-down-"));
const bin = path.join(root, "bin");
diff --git a/scripts/approve-device.js b/scripts/approve-device.js
index 4fd97c21..c5a95885 100755
--- a/scripts/approve-device.js
+++ b/scripts/approve-device.js
@@ -1,20 +1,15 @@
#!/usr/bin/env node
-// Seed / list / revoke trusted login devices for mso (no Convex — flat JSON,
-// same model as the VPS Control Room).
-//
-// node scripts/approve-device.js <deviceId> [label] [--role viewer|operator|owner]
-// node scripts/approve-device.js --list # show approved + pending
-// node scripts/approve-device.js --revoke <deviceId> # un-trust a device
-//
-// Store path = ~/.mso/auth-devices.json unless OS_DEVICE_STORE is set (must
-// match what the mso service sees).
+// Seed/list/revoke trusted login devices (flat JSON, no Convex).
+// Usage: approve-device.js <deviceId> [label] [--role ...] | --list | --revoke <id>
+// Store = ~/.mso/auth-devices.json unless OS_DEVICE_STORE overrides it; this must
+// match the path used by the running MSO service.
const fs = require("fs");
const os = require("os");
const path = require("path");
const { randomUUID } = require("crypto");
const { spawnSync } = require("child_process");
-const { DEVICE_ROLES, normalizeApproved, parseApprovalArgs, roleOf, setRoleResult } = require("./lib/device-role-cli");
+const { approvedExitCode, DEVICE_ROLES, normalizeApproved, parseApprovalArgs, roleOf, setRoleResult } = require("./lib/device-role-cli");
const STORE =
process.env.OS_DEVICE_STORE || path.join(os.homedir(), ".mso", "auth-devices.json");
@@ -37,10 +32,8 @@ function write(store) {
fs.renameSync(tmp, STORE);
}
-// The web process edits the same allowlist. Lock the full read-modify-write so a
-// local revoke cannot be overwritten by a concurrent login `lastSeen` touch. The
-// lock owner is recorded so a crashed helper/server is recoverable without turning
-// a stale file into a permanent authentication outage.
+// Serialize the full read-modify-write shared with the web process; lock-owner
+// metadata lets a crashed writer be recovered without losing a revocation.
const LOCK = `${STORE}.lock`;
const RECOVERY = `${LOCK}.recovery`;
const LOCK_WAIT_MS = 25;
@@ -190,6 +183,8 @@ if (args[0] === "--pending") {
process.exit(0);
}
+// Exact approval probe for onboard/doctor; --list also contains PENDING ids.
+if (args[0] === "--is-approved") process.exit(approvedExitCode({ args, deviceIdRe: DEVICE_ID_RE, read }));
if (args[0] === "--set-role") {
const result = setRoleResult({ args, deviceIdRe: DEVICE_ID_RE, withMutation, read, write });
diff --git a/scripts/gen-cli-docs.mjs b/scripts/gen-cli-docs.mjs
index c7086fbf..b7269855 100644
--- a/scripts/gen-cli-docs.mjs
+++ b/scripts/gen-cli-docs.mjs
@@ -37,7 +37,8 @@ eval "$(mso completion bash)" # optional: tab completion
## First run
\`\`\`bash
-mso doctor # deps, env, service, session, device — names what broke
+mso doctor # deps, HTTPS/login origin, service, session, device — names what broke
+mso doctor --fix # safe local repairs; never changes DNS/TLS/firewall/credentials
mso device pending # after a browser tries to log in, approve it from here
\`\`\`
@@ -48,6 +49,11 @@ device id (\`~/.mso/cli.device.id\`), which you approve once:
mso device approve "$(cat ~/.mso/cli.device.id)" "mso cli"
\`\`\`
+Browser sign-in must use **HTTPS**, except for loopback development/access such as
+\`http://localhost:4005\`. Plain \`http://<server-ip>:4005\` may answer health/API requests,
+but the browser cannot retain MSO's \`Secure\` session cookie there. Pair the device on its final
+HTTPS/localhost origin; \`mso doctor\` reports this explicitly.
+
Device and service commands work even while the service is down — that is on
purpose, because those are exactly the commands you need when it is.
diff --git a/scripts/install-core.sh b/scripts/install-core.sh
index f73dd603..833087f9 100755
--- a/scripts/install-core.sh
+++ b/scripts/install-core.sh
@@ -742,13 +742,16 @@ EOF
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:
+ 1. FIRST use HTTPS, or an SSH tunnel and http://localhost:$PORT. Do not pair on plain http://<server-ip>:$PORT:
+ the Secure session cookie cannot persist there, and changing to an HTTPS hostname creates a different browser device id.
+ 2. Enter the password — the browser lands PENDING and shows a device id.
+ 3. 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.
+ 4. In that SAME browser origin, click "Check again". Approve later devices from Settings → Devices.
Logs: $LOG_STATUS
+ Doctor: mso doctor (or: mso doctor --fix for safe local repairs)
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\`
@@ -769,12 +772,12 @@ 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"
+ "$BIN_DIR/mso" onboard -y || warn "onboarding did not finish — run: mso doctor --fix ; then: 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"
+ warn "onboarding stopped early — run: mso doctor --fix ; then resume: mso onboard"
fi
else
echo
diff --git a/scripts/install.sh b/scripts/install.sh
index b1111075..9919893c 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -12,7 +12,7 @@ set -Eeuo pipefail
umask 077
CORE_URL="${MSO_INSTALL_CORE_URL:-https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install-core.sh}"
-CORE_SHA256="9967738ca845c6ee462d2b98b5bde8bbb1ec79cce99316659d646d70e4fbc319"
+CORE_SHA256="6cb075743c17406dfde8d57a04ad2e48b6a792aab72284aeb93570f9103417a8"
CORE_EOF='# MSO_INSTALLER_CORE_EOF'
TMP_INSTALLER=''
diff --git a/scripts/lib/device-role-cli.js b/scripts/lib/device-role-cli.js
index a80b61c6..e4030556 100644
--- a/scripts/lib/device-role-cli.js
+++ b/scripts/lib/device-role-cli.js
@@ -29,6 +29,12 @@ function parseApprovalArgs(args) {
return { id, role, label: labelParts.join(" ") || "seeded device" };
}
+function approvedExitCode({ args, deviceIdRe, read }) {
+ const id = args[1];
+ if (!id || !deviceIdRe.test(id)) return 2;
+ return read().approved[id] ? 0 : 1;
+}
+
function setRoleResult({ args, deviceIdRe, withMutation, read, write }) {
const id = args[1];
const role = args[2];
@@ -52,4 +58,4 @@ function setRoleResult({ args, deviceIdRe, withMutation, read, write }) {
: { code: 1, error: true, lines: [`not approved: ${id}`] };
}
-module.exports = { DEVICE_ROLES, normalizeApproved, parseApprovalArgs, roleOf, setRoleResult };
+module.exports = { approvedExitCode, DEVICE_ROLES, normalizeApproved, parseApprovalArgs, roleOf, setRoleResult };