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.

feat(gateway): secure laptop public access lifecycle

Rahman6c4ef076fa44
diff --git a/.env.example b/.env.example
index 3ce149ee..9052d54f 100644
--- a/.env.example
+++ b/.env.example
@@ -134,6 +134,10 @@ OS_SESSION_SECRET=
# mso gateway domain set https://mso.example.com
# mso gateway domain clear
# Temporary `mso gateway start` Quick Tunnels deliberately do NOT write this value.
+# Optional CLI-only gateway controls (normally leave unset):
+# MSO_GATEWAY_LOCAL_URL=http://127.0.0.1:4005
+# MSO_GATEWAY_NO_AUTO_INSTALL=1 # require a pre-provisioned/reviewed cloudflared binary
+# MSO_GATEWAY_PUBLIC_READY_SECONDS=60 # bounded HTTPS edge propagation wait (10..120)
# --- Embedded managed-app dashboards: optional split-origin decision ---
# Unset (default) = MSO does not EMBED vendor web UIs. Managed-app lifecycle and
diff --git a/README.md b/README.md
index 81caf3e2..dd7fb3ca 100644
--- a/README.md
+++ b/README.md
@@ -59,7 +59,7 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
- **Inspect system health** — view live CPU, memory, disk, network, process, and uptime signals.
- **Operate services safely** — inventory system and user `systemd` units, read bounded journal output, and expose start/stop/restart only for exact owner-configured allowlist entries.
- **See pending package updates** — read the package manager’s existing local cache without refreshing repositories or applying an upgrade.
-- **Update itself** — Settings → About shows what is on `origin/main`, lists the incoming commits, and runs the whole deploy (pull → verify the build out-of-tree → build → restart) from a button. The verification runs first on purpose: a commit that does not compile becomes a refusal, not an outage. The updater runs in the owner's systemd user manager and does not require passwordless sudo. Same thing from a shell: `mso update run`.
+- **Update itself** — Settings → About shows what is on `origin/main`, lists the incoming commits, and runs the whole deploy (pull → verify the build out-of-tree → build → restart) from a button. The verification runs first on purpose: a commit that does not compile becomes a refusal, not an outage. The updater runs in the owner's systemd user manager and does not require passwordless sudo. Same thing from a shell: `mso update` (`mso update run` remains a compatibility alias). The CLI update path is Git-based and still works when the web runtime is down.
- **Manage other apps on the box** — detect, start/stop/restart, health, version, logs, and state backups for separate applications you already run (Hermes, OpenClaw, 9Router), driven through their own systemd/Docker/CLI contracts. 9Router uses its configured application domain or split-origin host as the in-shell dashboard; its Docker port is loopback-only unless public exposure is explicitly enabled. See [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md).
**Work** — code/text editor, browser, and media tools in the same workspace.
@@ -162,7 +162,9 @@ On the normal Ubuntu/WSL PATH (which includes `/usr/local/bin`) these work immed
```bash
mso -h
mso doctor
-mso onboard # run/re-run guided setup
+mso onboard # run/re-run guided setup; starts the built loopback runtime on WSL when needed
+mso web # open local UI; starts the built loopback runtime if no service is active
+mso update # fetch/verify/build safely; does not require :4005 to be alive
mso skills available # reviewed installable skill list
mso skills install ponytail caveman rtk -y
```
@@ -171,7 +173,9 @@ If it explicitly says the current shell cannot see the user launcher yet, run th
`export PATH="$HOME/.local/bin:$PATH"` it prints; new shells use the persisted profile entry.
**WSL2:** the CLI is supported even when systemd is not active. In that case the installer now
-finishes the CLI instead of failing in `systemctl`, but it skips `mso.service`. For the full
+finishes the CLI instead of failing in `systemctl`, but it skips `mso.service`. `mso onboard` and
+`mso web` can start the already-built production runtime detached on `127.0.0.1` and track ownership
+under private state; `mso update` can update/verify/build without a running API. For the full
background service, enable systemd in `/etc/wsl.conf`, exit all WSL sessions from Windows, reopen
the distro, then re-run the installer with `--onboard`.
@@ -192,7 +196,7 @@ On a laptop/WSL install, the supported public-preview path keeps that invariant
```bash
mso gateway doctor
-mso gateway start # temporary HTTPS URL; requires the official cloudflared client
+mso gateway start # temporary HTTPS URL; installs MSO's pinned cloudflared on first use
mso web # opens the active public URL, or loopback when no gateway is running
mso gateway status
mso gateway stop
@@ -202,9 +206,10 @@ Temporary mode uses a Cloudflare Quick Tunnel and does **not** change `OS_PUBLIC
MSO bind address, router/NAT rules, or the Windows firewall. The normal password + approved-device
gate, live device roles, Secure/HttpOnly/SameSite cookie, same-origin mutation gate, CSP and login
rate limits remain in front of the host APIs. Gateway state/logs live under owner-only
-`~/.mso/private/gateway`; `stop` validates process identity before terminating anything. MSO does
-not silently download an unpinned tunnel binary: install `cloudflared` from Cloudflare's official
-package/release channel first.
+`~/.mso/private/gateway`; `stop` validates process identity before terminating anything. On first use, MSO downloads the reviewed `cloudflared` release pinned in
+`security/gateway-artifacts.env` into user-local `~/.mso/tools`, verifies its SHA-256 before first
+execution and again before every reuse, and passes `--no-autoupdate`. No root package install,
+mutable `latest`, or `curl | sh` is involved. Use `mso gateway install` to prefetch it explicitly.
Quick Tunnels are a **preview/testing** surface, not the permanent deployment path. Cloudflare
documents a 200-concurrent-request limit and no Server-Sent Events support; MSO's live Terminal
@@ -222,8 +227,10 @@ mso web
```
`mso gateway domain set` updates `OS_PUBLIC_ORIGIN` atomically and prints a loopback-only ingress
-example. It does not create DNS credentials or put tunnel tokens on a command line. A permanent
-Cloudflare deployment can then add Cloudflare Access/WAF policy in front of MSO. If you prefer an
+example. Named mode accepts only a dedicated two-rule config (`your hostname → MSO loopback`, then
+`http_status:404`) and a private owner-owned credentials file. It does not put tunnel tokens on a
+command line. A permanent Cloudflare deployment can then add Cloudflare Access/WAF policy in front
+of MSO. If you prefer an
SSH-only connection instead, use:
```bash
diff --git a/SECURITY.md b/SECURITY.md
index 4c891aab..4174c5ad 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -26,11 +26,22 @@ application roles, but they still share the same deployment and underlying Unix
- Run MSO as a dedicated non-root user.
- Prefer Tailscale/VPN for a real deployment.
- Otherwise use HTTPS plus firewall/allowlist controls in front of the app.
-- Do not expose the raw app port directly to the public internet.
+- Do not expose the raw app port directly to the public internet. On laptop/WSL installs,
+ `mso gateway start` keeps MSO on loopback and creates an outbound HTTPS tunnel instead. The
+ temporary no-domain mode is preview-only; use a named tunnel/TLS reverse proxy plus an upstream
+ access policy for a permanent Internet-facing control plane.
- Keep `OS_FS_WRITE_ROOTS` narrow and review read roots deliberately.
- Do not commit `.env.local`, model credentials or data under `~/.mso`.
- Use `NEXT_PUBLIC_OS_DEMO=1` only in a separate mock-only public demo checkout.
+The core gateway client follows the same immutable-artifact rule as managed apps: MSO pins the
+official `cloudflared` release URL and SHA-256 per supported Linux architecture in
+`security/gateway-artifacts.env`, stores it user-locally, re-hashes before execution, and disables
+Cloudflare self-update. `MSO_GATEWAY_CLOUDFLARED` is an explicit operator override, not an automatic
+PATH fallback. The tunnel child starts from a scrubbed environment (HOME/PATH/LANG only); MSO login,
+session, provider and API-key environment variables stay with the application runtime and are not
+inherited by `cloudflared`.
+
## Authentication and sessions
The deployment login is password + device approval. A correct password on a new browser creates a
diff --git a/bin/mso b/bin/mso
index 1ff17781..14ae5b41 100755
--- a/bin/mso
+++ b/bin/mso
@@ -43,7 +43,7 @@
# health Is this CLI's session valid?
# doctor Check deps, env, service, session, device — and say what broke
# onboard [-y] Guided first-run setup: AI, response style, managed apps, skills
-# gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | domain
+# gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
# web Open the MSO browser UI (active gateway first, else loopback)
#
# Browser
@@ -81,7 +81,7 @@
# service * status | start | stop | restart | logs
# build Compile HEAD out-of-tree (safe against the live checkout)
# deploy next build, then restart the service
-# update [run] What is on origin/main; `run` pulls, verifies, builds, restarts
+# update [--rebuild] Update from origin/main safely; works even when the web runtime is down
#
# Escape hatches
# crud * Generic resource CRUD, incl. editor documents
@@ -119,7 +119,7 @@
# Docs: https://github.com/rahmanef63/mso
set -euo pipefail
-VERSION="1.3.0"
+VERSION="1.4.0"
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
die() { echo "mso: $*" >&2; exit 1; }
@@ -156,7 +156,7 @@ gateway_local_url() {
return
fi
case "$B" in
- http://127.*:*|http://localhost:*|http://[::1]:*) printf '%s' "$B"; return ;;
+ http://127.*:*|http://localhost:*|http://\[::1\]:*) printf '%s' "$B"; return ;;
esac
if command -v systemctl >/dev/null 2>&1; then
port=$(systemctl show -p Environment --value mso.service 2>/dev/null \
@@ -166,6 +166,14 @@ gateway_local_url() {
[[ "$port" =~ ^[0-9]{1,5}$ ]] || die "invalid MSO gateway port: $port"
printf 'http://127.0.0.1:%s' "$port"
}
+
+maybe_update_notice() {
+ local verb="$1"
+ [ -t 2 ] || return 0
+ case "$verb" in update|version|--version|-V|-v|help|-h|--help|completion) return 0 ;; esac
+ [ -x "$ROOT/scripts/mso-update" ] || return 0
+ MSO_UPDATE_ROOT="$ROOT" "$ROOT/scripts/mso-update" notice || true
+}
# shellcheck source=scripts/lib/private-state.sh
. "$ROOT/scripts/lib/private-state.sh"
@@ -210,18 +218,22 @@ JAR=$(mso_private_state_ensure_file "$JAR_REQUESTED") || die "refusing unsafe co
ORIGIN=(-H "origin: $B")
login() {
- local d code; d=$(cli_device)
+ local d out code body; d=$(cli_device)
[ -n "$PASS" ] || die "no OS_LOGIN_PASSWORD in $ENVF (or export MSO_PASSWORD)"
- # Revalidate immediately before curl writes a live bearer. The private-state helper
- # rejects symlinks, non-regular files, another owner, and any mode other than 0600.
JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
- # Body over stdin, never argv: a `-d "$(jq …)"` expansion puts the cleartext
- # password in curl's /proc/<pid>/cmdline for the life of the request.
- code=$(jq -n --arg p "$PASS" --arg d "$d" '{password:$p,deviceId:$d,deviceLabel:"mso cli"}' \
- | curl -sS -o /dev/null -w '%{http_code}' -c "$JAR" -X POST "$B/api/auth/login" \
- "${ORIGIN[@]}" -H 'content-type: application/json' -d @- || true)
- [ "$code" = "200" ] || die "login failed ($code) — run \`mso doctor\`, or approve this device:
- mso device approve $d \"mso cli\""
+ out=$(jq -n --arg p "$PASS" --arg d "$d" '{password:$p,deviceId:$d,deviceLabel:"mso cli"}' \
+ | curl -sS -w $'\n%{http_code}' -c "$JAR" -X POST "$B/api/auth/login" \
+ "${ORIGIN[@]}" -H 'content-type: application/json' -d @- 2>/dev/null || true)
+ code="${out##*$'\n'}"; body="${out%$'\n'*}"
+ [ "$code" = "200" ] && return 0
+ case "$code" in
+ 000|"") die "MSO runtime is not reachable at $B. Run: mso web (local UI) or mso gateway start (temporary public HTTPS)" ;;
+ 403) die "device is not approved by the running MSO instance. Check: mso device pending ; then approve the exact id with: mso device approve $d \"mso cli\"" ;;
+ 401) die "login password was rejected by the running MSO instance" ;;
+ 429) die "login is rate-limited; retry after the server window resets" ;;
+ 500) die "running MSO auth is not configured correctly; run: mso doctor" ;;
+ *) die "login failed ($code): ${body:-no response body}; run: mso doctor" ;;
+ esac
}
# Request with the cached cookie; on 401/403 (expired) log in once and retry.
@@ -306,6 +318,17 @@ ensure_local_cli_device() {
fi
}
+ensure_onboard_runtime() {
+ case "$B" in
+ http://127.*:*|http://localhost:*|http://\[::1\]:*)
+ MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$B" \
+ "$ROOT/scripts/mso-gateway" local-start >/dev/null \
+ || die "local MSO runtime is not ready. Run: mso update ; then: mso web"
+ echo " ✓ verified local MSO runtime at $B" ;;
+ *) return 0 ;;
+ esac
+}
+
onboard_ai() {
local yes="$1" choice provider key body response interval code url poll
if [ "$yes" = 1 ]; then
@@ -453,11 +476,11 @@ run_onboard() {
echo "MSO onboarding"
echo "=============="
ensure_local_cli_device
+ ensure_onboard_runtime
if [ "$yes" = 0 ] && ! tty_ok; then
die "interactive onboarding needs a terminal; use 'mso onboard -y' for safe minimal defaults"
fi
- # Prove the local service/auth path before asking for account credentials.
- jget "/api/health" >/dev/null
+ # Runtime liveness was verified without auth above; now prove the approved-device session.
jget "/api/auth/me" >/dev/null
onboard_ai "$yes"
onboard_style "$yes"
@@ -489,13 +512,13 @@ verbs() {
# so the help you get when you ask cannot disagree with the help you get when
# you're wrong.
U_camoufox="camoufox status|start|stop|session"
-U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|domain show|set <https://host>|clear"
+U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"
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"
U_service="service status|start|stop|restart|logs [n]"
U_unit="unit logs <system|user> <unit> [limit]|start|stop|restart <system|user> <unit>"
-U_update="update status|run [true]|log"
+U_update="update [--rebuild] | status | log"
U_threads="threads list|show <id>|save <json>|rm <id>"
U_memory="memory list|add <text>|rm <id>"
U_config="config show|set <json>|key <provider>|style <off|caveman|ponytail>|rm <provider>"
@@ -521,7 +544,7 @@ if [ $# -ge 2 ]; then
esac
fi
-cmd="${1:-help}"; shift || true
+cmd="${1:-help}"; maybe_update_notice "$cmd"; shift || true
case "$cmd" in
version|--version|-V|-v) echo "mso $VERSION (base $B, root $ROOT)"; exit 0 ;;
@@ -808,13 +831,7 @@ case "$cmd" in
# The same self-update Settings → About drives, so both surfaces get the same
# preflight and the same transient-unit handoff (a build spawned from the service
# would be killed by the restart it performs).
- update)
- case "${1:-status}" in
- status) jget "/api/v1/sys/update" ;;
- run) jpost "/api/v1/sys/update" "$(jq -n --argjson r "${2:-false}" '{rebuildOnly:$r}')" ;;
- log) jget "/api/v1/sys/update?check=0" | jq -r .log ;;
- *) die "usage: mso $U_update" ;;
- esac ;;
+ update) MSO_UPDATE_ROOT="$ROOT" "$ROOT/scripts/mso-update" "$@" ;;
# ── editor-document CRUD (one pattern, all editor features) ──────────────
crud)
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index bb46a99e..9fdd3150 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”.
**Added**
+- `gateway` secure laptop public access lifecycle
- `gateway` add loopback-only public web gateway
**Fixed**
diff --git a/docs/CLI.md b/docs/CLI.md
index 0412f895..e558bf76 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -77,7 +77,7 @@ Commands:
health Is this CLI's session valid?
doctor Check deps, env, service, session, device — and say what broke
onboard [-y] Guided first-run setup: AI, response style, managed apps, skills
- gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | domain
+ gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
web Open the MSO browser UI (active gateway first, else loopback)
Browser
@@ -115,7 +115,7 @@ Commands:
service * status | start | stop | restart | logs
build Compile HEAD out-of-tree (safe against the live checkout)
deploy next build, then restart the service
- update [run] What is on origin/main; `run` pulls, verifies, builds, restarts
+ update [--rebuild] Update from origin/main safely; works even when the web runtime is down
Escape hatches
crud * Generic resource CRUD, incl. editor documents
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index ac5c8e3c..362b6395 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -3,7 +3,7 @@
> **Current reference.** The one-command installer is the supported path for a normal
> deployment. Manual commands below explain the model and recovery boundaries; release
> developers should use `bun run ship`, while operators update through Settings → About or
-> `mso update run`.
+> `mso update` (`mso update run` remains accepted).
## 0. Requirements
@@ -79,8 +79,10 @@ mso onboard
```
It first approves the **local CLI device** as Owner in the device allowlist (a process already running
-as the owning Unix account has equivalent host authority), then verifies the local service
-and session before asking for provider credentials. API keys are read with terminal echo
+as the owning Unix account has equivalent host authority). On a loopback install it then verifies the
+MSO `/api/health` contract; when WSL has no active system service it can start the already-built Next
+production runtime itself, still bound to loopback, before proving the authenticated session. A dead
+runtime is reported as a runtime problem — it is not misreported as a device-approval failure. API keys are read with terminal echo
disabled and posted from stdin; they are not placed in the CLI/curl argv.
The current provider choices are OpenAI ChatGPT/Codex device OAuth, plus API-key providers
@@ -100,6 +102,12 @@ WSL can contain `systemctl` while still running a non-systemd PID 1. MSO treats
different capabilities: the CLI is installed normally, while the background service is skipped
with an explicit message. This prevents service setup from aborting before `mso` exists.
+Without systemd, `mso web` is the supported local UI path: it starts the existing production build on
+loopback when necessary. `mso gateway start` adds an outbound temporary HTTPS tunnel on top of that
+without publishing the app port. `mso update` also works without the web API: it fast-forwards a clean
+`main`, installs dependencies, verifies an out-of-tree build, and builds in place while no service is
+active.
+
For the full service on WSL2, enable systemd in `/etc/wsl.conf`:
```ini
@@ -138,10 +146,11 @@ plain-HTTP IP/hostnames will drop it.
### Public preview from a laptop / WSL (no custom domain)
-Keep MSO bound to loopback. With the official `cloudflared` client installed:
+Keep MSO bound to loopback. No system-wide tunnel package is required:
```bash
mso gateway doctor
+mso gateway install # optional prefetch; `start` does this automatically
mso gateway start
mso gateway url
mso web
@@ -149,8 +158,11 @@ mso web
mso gateway stop
```
-`gateway start` creates an outbound Cloudflare Quick Tunnel to `127.0.0.1:4005`; it never changes
-the application bind to `0.0.0.0`. If systemd is unavailable (common on WSL), it may start the
+`gateway start` installs only the reviewed Cloudflare binary pinned by exact release URL + SHA-256
+in `security/gateway-artifacts.env`, then creates an outbound Quick Tunnel to `127.0.0.1:4005`; it
+never changes the application bind to `0.0.0.0`. The tool cache is user-local and the tunnel is run
+with Cloudflare auto-update disabled. The tunnel process also receives a scrubbed environment rather
+than inheriting MSO login/session/BYOK secrets from the application shell. If systemd is unavailable (common on WSL), it may start the
already-built Next production runtime itself, still on `127.0.0.1`, and records whether that process
is gateway-owned. `gateway stop` only terminates a recorded process after its live command line
matches the expected MSO/cloudflared identity. Private state and logs are owner-only.
@@ -180,8 +192,12 @@ mso web
```
The config must be a regular file owned by the current user and must not be group/world-writable.
-For a permanent Internet-facing control plane, add Cloudflare Access/WAF policy (or equivalent) in
-front of MSO in addition to MSO's password + approved-device gate. Rebuild/restart MSO after
+MSO parses it before launch and requires exactly one ingress hostname matching `OS_PUBLIC_ORIGIN`
+that points to the configured MSO loopback port, followed by `http_status:404`; its
+`credentials-file` must be a private owner-owned regular file. This prevents a config intended for
+MSO from silently publishing other laptop services. For a permanent Internet-facing control plane,
+add Cloudflare Access/WAF policy (or equivalent) in front of MSO in addition to MSO's password +
+approved-device gate. Rebuild/restart MSO after
changing stable origin or split-host environment configuration.
### Tailscale (recommended)
@@ -408,18 +424,22 @@ no API-key storage. Do not toggle demo mode in the production owner checkout.
Use Settings → About or:
```bash
-mso update status
-mso update run
+mso update status # fetch + show incoming CLI version/commits
+mso update # preferred: update safely even if :4005 is down
mso update log
```
-The updater verifies the incoming checkout/build before replacing the service. A successful
-finalizer log ends with `UPDATE OK`.
+The updater verifies the incoming checkout/build before replacing the service. With an active
+`mso.service` it runs outside that service cgroup so the updater survives the restart. With no active
+service (including WSL without systemd), it performs the clean fast-forward/dependency/verify/build
+path locally and finishes by telling you to run `mso web`. Interactive CLI commands also show a
+throttled update notice when cached `origin/main` is ahead; the notice never depends on port 4005.
+A successful service finalizer log ends with `UPDATE OK`.
If the installed source is correct but the production build tree is inconsistent, use:
```bash
-mso update run --rebuild
+mso update --rebuild
```
### Developer release
@@ -443,7 +463,7 @@ Prefer an explicit known-good Git commit and the same verified rebuild/update ma
not ad-hoc partial `.next` changes. Keep the old running process alive if the candidate
build itself fails.
-For a live chunk mismatch after the source ref is already correct, `mso update run --rebuild`
+For a live chunk mismatch after the source ref is already correct, `mso update --rebuild`
is the supported recovery path. Verify `/api/health` and `scripts/post-deploy-smoke.sh`
afterward.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 6e6770cf..c6b319e7 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -2,22 +2,41 @@
Running log of what shipped each phase. Newest at top.
-## 2026-08-30 — Loopback-only public gateway + `mso web` (SHIPPED)
-
-MSO now has an explicit public-access lifecycle for laptop/WSL installs without weakening the
-application bind. `mso gateway start` keeps the Next server on `127.0.0.1`, launches an outbound
-HTTPS Cloudflare tunnel, stores process state/logs under owner-only private state, verifies process
-identity before stop, and can bootstrap the existing production build on WSL when systemd is
-unavailable. `mso web` opens the active gateway URL first and otherwise falls back to the stable
-public origin or loopback. Non-default loopback `--base` ports are preserved.
-
-Temporary Quick Tunnel mode is intentionally disclosed as preview-only because the provider does
-not support SSE, which MSO Terminal uses. Stable mode is configuration-driven:
-`mso gateway domain set https://…` atomically manages `OS_PUBLIC_ORIGIN`, and named-tunnel mode
-accepts only an owner-controlled, non-writable cloudflared config while keeping credentials out of
-argv. The global response policy also adds `X-Robots-Tag: noindex, nofollow, noarchive`. Regression
-tests exercise start/status/url/web/stop, private-state permissions, non-loopback refusal, custom
-ports, domain mutation, and unsafe config rejection.
+## 2026-08-30 — Loopback-only public gateway + resilient WSL CLI lifecycle (SHIPPED)
+
+MSO now has an explicit laptop/WSL public-access lifecycle without widening the application bind.
+`mso web` verifies the MSO health contract and can start the already-built production runtime on
+`127.0.0.1` when no service is active. `mso gateway start` adds an outbound HTTPS Cloudflare tunnel
+on top; temporary Quick Tunnel mode is disclosed as preview-only because the provider does not
+support SSE, while named/custom-domain mode remains driven by `OS_PUBLIC_ORIGIN`. `mso gateway
+domain set https://…` updates that stable origin atomically and prints loopback-only ingress config.
+
+The independent PR review found lifecycle failure modes before merge, so the gateway was hardened
+rather than those comments being dismissed. Gateway state now records a process fingerprint (PID,
+`/proc` start ticks, executable and command-line hash), startup first verifies the exact expected argv,
+`stop` refuses identity mismatches, start/stop share an owner-only lifecycle lock, concurrent starts
+produce one tunnel, state-write failure rolls newly launched processes back, stale tunnel state
+preserves a still-owned runtime, and both local/public probes require MSO's structured health
+contract rather than accepting any HTTP 2xx. The original 428-line script was split into bounded
+≤200-line single-responsibility modules. Regression tests cover rollback, PID reuse, concurrency,
+runtime ownership, non-loopback/hostname confusion, config permissions, domain mutation and browser
+selection.
+
+The WSL onboarding failure path is also repaired. `mso onboard` no longer turns a connection failure
+into the false advice to approve an already-approved device; loopback onboarding starts/verifies the
+fallback runtime first. Re-approving the same device+role is idempotent, while role changes still need
+`mso device role`. CLI version is now 1.4.0. `mso update` is API-independent and is the preferred
+operator command: it can fetch/fast-forward/verify/build even when port 4005 is down, and normal
+interactive CLI use emits a throttled Git-backed update notice when `origin/main` is ahead.
+`mso update run` remains accepted for compatibility.
+
+The global response policy additionally sends `X-Robots-Tag: noindex, nofollow, noarchive` because an
+MSO control plane should not be indexed merely because a temporary HTTPS endpoint exists. The
+Cloudflare client is now a core supply-chain lock too: release `2026.8.2` is pinned by exact official
+asset URL + SHA-256 for Linux amd64/arm64, installed user-locally on first gateway use, re-hashed
+before reuse, and launched with self-update disabled. Named configs are parsed before launch and are
+accepted only when dedicated to the configured MSO hostname/loopback port with a private credentials
+file and a terminal `http_status:404` fallback.
## 2026-08-30 — WSL Bun bin-metadata build resilience (SHIPPED)
diff --git a/docs/SECURITY-ASSURANCE.md b/docs/SECURITY-ASSURANCE.md
index b59f4d9a..00da4310 100644
--- a/docs/SECURITY-ASSURANCE.md
+++ b/docs/SECURITY-ASSURANCE.md
@@ -19,10 +19,11 @@ The standing baseline is informed by **OWASP ASVS 5.0.0**. MSO does not claim an
| AI-assisted code audit | OpenAI Codex Security `scan-components` | Twenty explicit component scans covering the tracked repository, followed by cross-component root-cause matching | Every component and matching must complete; High/Critical groups fail |
| Supply chain | OpenSSF Scorecard | Public repository security posture: pinned dependencies, branch protection, review process and related heuristics | Score is published as external evidence, not self-awarded |
| Managed-app artifact integrity | SHA-256/SHA-512 verification + OCI RepoDigest checks | Hermes release installer/checkout, exact OpenClaw tarball and 9Router multi-arch image are immutable execution identities | Any mismatch fails before installer/package/image execution |
+| Public-gateway artifact integrity | Release URL + SHA-256 verification | `cloudflared` Linux binaries are pinned per architecture, cached user-locally, re-hashed before reuse and run with auto-update disabled | Any mismatch fails before tunnel execution |
| Dependency changes | GitHub Dependency Review | Vulnerabilities newly introduced by pull requests | High/Critical introduced dependency fails |
| SBOM | Trivy CycloneDX | Machine-readable component inventory | Generated on Security Core workflow |
-All GitHub Actions referenced by the repository are pinned to immutable commit SHAs. Scanner containers used by the reproducible local gate are pinned to image digests. Managed-app release identities are separately recorded in `security/managed-app-artifacts.env`; moving tags are never accepted as installation identities.
+All GitHub Actions referenced by the repository are pinned to immutable commit SHAs. Scanner containers used by the reproducible local gate are pinned to image digests. Managed-app release identities are separately recorded in `security/managed-app-artifacts.env`, while the core public-gateway client is recorded in `security/gateway-artifacts.env`; moving tags are never accepted as execution identities.
## GitHub security controls
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 81eb3726..f5b8da43 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -20,12 +20,36 @@ forward the real client IP consistently so every user does not share the proxy a
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.
-### `mso gateway start` says cloudflared is missing
-
-MSO does not download a mutable/unpinned tunnel binary automatically. Install the official
-Cloudflare Tunnel client for this machine, then run `mso gateway doctor`. The MSO application must
-remain on loopback; do not work around a missing tunnel client by changing the service to
-`0.0.0.0:4005`.
+### `mso onboard` approved the CLI device, then says port 4005 is unreachable
+
+Device approval and runtime liveness are separate. Current MSO does not tell you to approve the same
+device again for a connection failure: on loopback, onboarding asks the gateway runtime helper to
+verify the MSO health contract and, on WSL/no-service installs, start the already-built production
+runtime on loopback. If the build is missing or stale, run `mso update`, then `mso web`, then resume
+`mso onboard`. Running `mso device approve <id>` again with the same role is idempotent; changing an
+existing device role still requires the explicit `mso device role` command.
+
+### How do I update when the web UI / port 4005 is down?
+
+Run `mso update`. The CLI updater reads/fetches `origin/main` directly and does not need the MSO API.
+On WSL without an active service it verifies and builds the clean updated checkout, then tells you to
+run `mso web`. Use `mso update status` to see the incoming CLI version/commits and `mso update log`
+for the service-updater transcript.
+
+### `mso gateway start` cannot install or verify cloudflared
+
+Current MSO installs a reviewed `cloudflared` release automatically into `~/.mso/tools` on first
+`mso gateway start`. The release URL and SHA-256 for supported Linux architectures are pinned in
+`security/gateway-artifacts.env`; the cached binary is re-hashed before reuse and auto-update is
+disabled. Run `mso gateway install` to retry the dependency step by itself. If outbound GitHub
+release downloads are blocked, fix that network policy or set `MSO_GATEWAY_CLOUDFLARED` to an
+explicit locally reviewed executable. Set `MSO_GATEWAY_NO_AUTO_INSTALL=1` when policy requires
+manual provisioning.
+A brand-new Quick Tunnel hostname may also take several seconds to become reachable. `mso gateway
+start` waits up to 60 seconds by default and still requires the exact MSO health/runtime-instance
+contract; this is readiness tolerance, not a weaker health check. A local resolver can cache the
+initial NXDOMAIN longer than the record creation itself; temporary mode therefore has a Cloudflare
+DoH fallback that still verifies HTTPS for the generated hostname and the exact runtime nonce.
### Temporary gateway opens, but Terminal does not stream
@@ -58,7 +82,7 @@ mutating the live `.next` tree manually. After any active updater/finalizer has
run the supported recovery rebuild:
```bash
-mso update run --rebuild
+mso update --rebuild
```
Then verify `/api/health` and run the post-deploy smoke check. Developer changes should be
@@ -81,7 +105,7 @@ lock remains, remove the stale lock, then use the normal update/release command.
Confirm Git `HEAD`, `origin/main`, `/api/health` build id and the deployment log all refer to
the expected release. If the deployment is correct but the build tree is inconsistent, use
-`mso update run --rebuild` rather than hand-restarting around a partial build.
+`mso update --rebuild` rather than hand-restarting around a partial build.
### Update button says a newer version exists forever
diff --git a/lib/onboard-contract.test.ts b/lib/onboard-contract.test.ts
index 65e98adb..daec132f 100644
--- a/lib/onboard-contract.test.ts
+++ b/lib/onboard-contract.test.ts
@@ -1,4 +1,6 @@
+import { execFileSync, 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";
@@ -29,4 +31,49 @@ describe("terminal onboarding contract", () => {
expect(cli).toContain("optional managed apps skipped (-y uses minimal defaults)");
expect(cli).toContain("none installed automatically; run: mso skills install ponytail caveman rtk -y");
});
+ it("bootstraps onboarding against a verified loopback runtime without asking for approval twice", () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-onboard-cli-"));
+ const bin = path.join(root, "bin");
+ const envFile = path.join(root, ".env.local");
+ const store = path.join(root, "devices.json");
+ const fakeCurl = path.join(bin, "curl");
+ fs.mkdirSync(bin, { mode: 0o700 });
+ fs.writeFileSync(envFile, "OS_LOGIN_PASSWORD=fixture-password\nOS_SESSION_SECRET=fixture-session-secret-long-enough\n", { mode: 0o600 });
+ fs.writeFileSync(fakeCurl, `#!/bin/sh
+case "$*" in
+ *api/auth/login*) printf '{"success":true}\n200' ;;
+ *api/auth/me*) printf '{"role":"owner"}\n200' ;;
+ *) printf '{"status":"ok","buildId":"fixture","runtimeInstanceId":"fixture","version":"0.2.1"}\n' ;;
+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_GATEWAY_CURL: fakeCurl, MSO_GATEWAY_STATE_DIR: path.join(root, "gateway-state") },
+ });
+ expect(out).toContain("approved this local CLI device");
+ expect(out).toContain("verified local MSO runtime at http://127.0.0.1:4555");
+ expect(out).toContain("Onboarding complete.");
+ expect(Object.keys(JSON.parse(fs.readFileSync(store, "utf8")).approved)).toHaveLength(1);
+ } 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");
+ const envFile = path.join(root, ".env.local");
+ fs.mkdirSync(bin, { mode: 0o700 });
+ fs.writeFileSync(envFile, "OS_LOGIN_PASSWORD=fixture-password\n", { mode: 0o600 });
+ fs.writeFileSync(path.join(bin, "curl"), "#!/bin/sh\nexit 7\n", { mode: 0o700 });
+ try {
+ const result = spawnSync(path.join(__dirname, "../bin/mso"), ["--base", "http://127.0.0.1:4555", "login"], {
+ encoding: "utf8", env: { ...process.env, HOME: root, PATH: `${bin}:${process.env.PATH}`, MSO_ENV: envFile },
+ });
+ expect(result.status).not.toBe(0);
+ expect(result.stderr).toContain("MSO runtime is not reachable");
+ expect(result.stderr).not.toContain("approve this device");
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
+ });
+
});
diff --git a/lib/security/gateway-supply-chain.test.ts b/lib/security/gateway-supply-chain.test.ts
new file mode 100644
index 00000000..cd9ac6ae
--- /dev/null
+++ b/lib/security/gateway-supply-chain.test.ts
@@ -0,0 +1,54 @@
+import { createHash } from "node:crypto";
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+const ROOT = path.resolve(__dirname, "../..");
+const GATEWAY = path.join(ROOT, "scripts/mso-gateway");
+const roots: string[] = [];
+const sha = (value: string) => createHash("sha256").update(value).digest("hex");
+
+afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
+
+describe("gateway supply chain", () => {
+ it("pins release-tagged official Cloudflare binaries for supported Linux architectures", () => {
+ const lock = fs.readFileSync(path.join(ROOT, "security/gateway-artifacts.env"), "utf8");
+ expect(lock).toContain("CLOUDFLARED_VERSION='2026.8.2'");
+ expect(lock).toMatch(/releases\/download\/2026\.8\.2\/cloudflared-linux-amd64/);
+ expect(lock).toMatch(/releases\/download\/2026\.8\.2\/cloudflared-linux-arm64/);
+ expect(lock.match(/CLOUDFLARED_LINUX_(?:AMD64|ARM64)_SHA256='[0-9a-f]{64}'/g)).toHaveLength(2);
+ expect(lock).not.toContain("latest");
+ });
+
+ it("downloads to user-local state, verifies SHA-256, and reuses only the verified cached binary", () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-gateway-pin-")); roots.push(root);
+ const bin = path.join(root, "bin"), state = path.join(root, "state"), tools = path.join(root, "tools");
+ fs.mkdirSync(bin, { mode: 0o700 });
+ const envFile = path.join(root, ".env.local"); fs.writeFileSync(envFile, "OS_SESSION_SECRET=fixture\n", { mode: 0o600 });
+ const binary = "#!/bin/sh\necho 'cloudflared version pinned-fixture'\n";
+ const digest = sha(binary), count = path.join(root, "downloads");
+ const lock = path.join(root, "gateway-artifacts.env");
+ fs.writeFileSync(lock, `CLOUDFLARED_VERSION='fixture'\nCLOUDFLARED_LINUX_AMD64_URL='https://example.invalid/cloudflared-amd64'\nCLOUDFLARED_LINUX_AMD64_SHA256='${digest}'\nCLOUDFLARED_LINUX_ARM64_URL='https://example.invalid/cloudflared-arm64'\nCLOUDFLARED_LINUX_ARM64_SHA256='${digest}'\n`, { mode: 0o600 });
+ const curl = path.join(bin, "curl");
+ fs.writeFileSync(curl, `#!/bin/sh\nout=''\nwhile [ $# -gt 0 ]; do case \"$1\" in -o) out=\"$2\"; shift 2;; *) shift;; esac; done\n[ -n \"$out\" ] || exit 2\nprintf x >> '${count}'\ncat >\"$out\" <<'EOF'\n${binary}EOF\n`, { mode: 0o700 });
+ const env = { ...process.env, HOME: root, PATH: `${bin}:${process.env.PATH}`, MSO_GATEWAY_ROOT: ROOT,
+ MSO_GATEWAY_ENV: envFile, MSO_GATEWAY_STATE_DIR: state, MSO_GATEWAY_CURL: curl,
+ MSO_GATEWAY_ARTIFACT_LOCK: lock, MSO_GATEWAY_TOOL_DIR: tools };
+
+ const first = execFileSync(GATEWAY, ["install"], { encoding: "utf8", env });
+ expect(first).toContain("pinned-fixture");
+ const installed = path.join(tools, "fixture", "cloudflared");
+ expect(fs.statSync(installed).mode & 0o777).toBe(0o700);
+ expect(sha(fs.readFileSync(installed, "utf8"))).toBe(digest);
+ expect(fs.readFileSync(count, "utf8")).toBe("x");
+
+ execFileSync(GATEWAY, ["install"], { encoding: "utf8", env });
+ expect(fs.readFileSync(count, "utf8")).toBe("x");
+ fs.appendFileSync(installed, "tamper\n");
+ execFileSync(GATEWAY, ["install"], { encoding: "utf8", env });
+ expect(fs.readFileSync(count, "utf8")).toBe("xx");
+ expect(sha(fs.readFileSync(installed, "utf8"))).toBe(digest);
+ });
+});
diff --git a/scripts/approve-device-lock.test.ts b/scripts/approve-device-lock.test.ts
index f50220d7..a70f303a 100644
--- a/scripts/approve-device-lock.test.ts
+++ b/scripts/approve-device-lock.test.ts
@@ -27,6 +27,9 @@ describe("approve-device cross-process lock protocol", () => {
});
try {
expect(run([device, "owner laptop", "--role", "owner"]).status).toBe(0);
+ const same = run([device, "same laptop", "--role", "owner"]);
+ expect(same.status).toBe(0);
+ expect(same.stdout).toContain("already approved");
const second = run([device, "same laptop", "--role", "viewer"]);
expect(second.status).not.toBe(0);
expect(second.stderr).toContain("already approved");
diff --git a/scripts/approve-device.js b/scripts/approve-device.js
index 86ece9ac..4fd97c21 100755
--- a/scripts/approve-device.js
+++ b/scripts/approve-device.js
@@ -259,18 +259,16 @@ if (!id || !DEVICE_ID_RE.test(id) || !DEVICE_ROLES.has(role)) {
console.error("deviceId must be 16-128 hex/uuid chars; role must be viewer, operator, or owner");
process.exit(1);
}
-const approved = withMutation(() => {
- const store = read();
- if (store.approved[id]) throw new Error("device is already approved; use --set-role");
+const result = withMutation(() => {
+ const store = read(), existing = store.approved[id];
+ if (existing && roleOf(existing) !== role) throw new Error(`device is already approved as role=${roleOf(existing)}; use --set-role to change privileges`);
+ if (existing) return { entry: existing, already: true };
const pending = store.pending[id];
store.approved[id] = {
- label: label !== "seeded device" ? label : (pending && pending.label) || label,
- approvedAt: Date.now(),
- role,
+ label: label !== "seeded device" ? label : (pending && pending.label) || label, approvedAt: Date.now(), role,
};
- delete store.pending[id];
- write(store);
- return store.approved[id];
+ delete store.pending[id]; write(store);
+ return { entry: store.approved[id], already: false };
});
-console.log(`approved ${id} "${approved.label}" role=${approved.role}`);
-console.log("-> that device can now sign in with the password.");
+console.log(`${result.already ? "already approved" : "approved"} ${id} "${result.entry.label}" role=${result.entry.role}`);
+if (!result.already) console.log("-> that device can now sign in with the password.");
diff --git a/scripts/lib/gateway-common.sh b/scripts/lib/gateway-common.sh
new file mode 100644
index 00000000..788d849f
--- /dev/null
+++ b/scripts/lib/gateway-common.sh
@@ -0,0 +1,217 @@
+#!/usr/bin/env bash
+# Shared validation, process identity, locking, and health checks for mso-gateway.
+
+gateway_fail() { printf 'mso gateway: %s\n' "$*" >&2; exit 1; }
+gateway_info() { printf '%s\n' "$*"; }
+
+gateway_validate_loopback_origin() {
+ node - "$1" <<'NODE'
+const raw = process.argv[2];
+try {
+ const u = new URL(raw), host = u.hostname.toLowerCase(), parts = host.split('.');
+ const v4 = parts.length === 4 && parts[0] === '127' && parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255);
+ const loopback = host === 'localhost' || host === '[::1]' || host === '::1' || v4;
+ const clean = u.protocol === 'http:' && loopback && !u.username && !u.password && u.pathname === '/' && !u.search && !u.hash;
+ if (!clean || !u.port) process.exit(1);
+ process.stdout.write(u.origin);
+} catch { process.exit(1); }
+NODE
+}
+
+gateway_validate_public_origin() {
+ node - "$1" <<'NODE'
+const raw = process.argv[2];
+try {
+ const u = new URL(raw);
+ if (u.protocol !== 'https:' || u.username || u.password || u.pathname !== '/' || u.search || u.hash) process.exit(1);
+ process.stdout.write(u.origin);
+} catch { process.exit(1); }
+NODE
+}
+
+gateway_loopback_host_port() {
+ node - "$LOCAL_URL" <<'NODE'
+const u = new URL(process.argv[2]);
+process.stdout.write(`${u.hostname.replace(/^\[|\]$/g, '')}\t${u.port}\n`);
+NODE
+}
+
+gateway_private_file() {
+ mso_private_state_ensure_file "$1" >/dev/null || gateway_fail "unsafe private state file: $1"
+}
+
+gateway_state_read() {
+ if [ -e "$STATE_FILE" ] || [ -L "$STATE_FILE" ]; then
+ if ! mso_private_state_validate_file "$STATE_FILE" >/dev/null; then
+ printf 'mso gateway: unsafe gateway state file\n' >&2; return 2
+ fi
+ if [ ! -s "$STATE_FILE" ]; then
+ printf 'mso gateway: gateway state is empty; inspect %s before removing it\n' "$STATE_FILE" >&2; return 2
+ fi
+ if ! jq -e . "$STATE_FILE" 2>/dev/null; then
+ printf 'mso gateway: gateway state is corrupt; inspect %s before removing it\n' "$STATE_FILE" >&2; return 2
+ fi
+ else
+ printf '{}\n'
+ fi
+}
+
+gateway_pid_alive() { [ "${1:-0}" -gt 1 ] 2>/dev/null && kill -0 "$1" 2>/dev/null; }
+
+gateway_proc_start_ticks() {
+ local pid="$1" line rest
+ gateway_pid_alive "$pid" || return 1
+ IFS= read -r line <"/proc/$pid/stat" || return 1
+ rest="${line##*) }"
+ set -- $rest
+ [ "$#" -ge 20 ] || return 1
+ printf '%s' "${20}"
+}
+
+gateway_capture_identity() {
+ local pid="$1" first second exe hash i
+ for i in 1 2 3 4; do
+ first="$(gateway_proc_start_ticks "$pid" 2>/dev/null || true)"
+ [ -n "$first" ] || return 1
+ exe="$(readlink -f -- "/proc/$pid/exe" 2>/dev/null || true)"
+ hash="$(sha256sum "/proc/$pid/cmdline" 2>/dev/null | awk '{print $1}' || true)"
+ second="$(gateway_proc_start_ticks "$pid" 2>/dev/null || true)"
+ if [ -n "$exe" ] && [ -n "$hash" ] && [ "$first" = "$second" ]; then
+ jq -nc --argjson pid "$pid" --arg start "$first" --arg exe "$exe" --arg cmdHash "$hash" \
+ '{pid:$pid,startTicks:$start,exe:$exe,cmdHash:$cmdHash}'
+ return 0
+ fi
+ sleep 0.02
+ done
+ return 1
+}
+
+gateway_identity_matches() {
+ local expected="$1" pid current
+ pid="$(jq -r '.pid // 0' <<<"$expected" 2>/dev/null || printf 0)"
+ [ "$pid" -gt 1 ] 2>/dev/null || return 1
+ current="$(gateway_capture_identity "$pid" 2>/dev/null || true)"
+ [ -n "$current" ] || return 1
+ jq -e --argjson current "$current" '
+ .pid == $current.pid and .startTicks == $current.startTicks and .exe == $current.exe and
+ (((.cmdHash // null) == null) or .cmdHash == $current.cmdHash)
+ ' <<<"$expected" >/dev/null 2>&1
+}
+
+gateway_identity_matches_retry() {
+ local expected="$1" attempts="${2:-4}" pid i
+ pid="$(jq -r '.pid // 0' <<<"$expected" 2>/dev/null || printf 0)"
+ [ "$pid" -gt 1 ] 2>/dev/null || return 1
+ for i in $(seq 1 "$attempts"); do
+ gateway_identity_matches "$expected" && return 0
+ gateway_pid_alive "$pid" || return 1
+ sleep 0.03
+ done
+ return 1
+}
+
+gateway_command_matches() {
+ local pid="$1" marker="$2" i j; shift 2
+ local -a argv expected=("$@")
+ gateway_pid_alive "$pid" || return 1
+ mapfile -d '' -t argv <"/proc/$pid/cmdline" 2>/dev/null || return 1
+ for ((i=0; i<${#argv[@]}; i++)); do
+ [ "${argv[$i]}" = "$marker" ] || continue
+ [ "$(( ${#argv[@]} - i - 1 ))" -eq "${#expected[@]}" ] || return 1
+ for ((j=0; j<${#expected[@]}; j++)); do
+ [ "${argv[$((i+j+1))]}" = "${expected[$j]}" ] || return 1
+ done
+ return 0
+ done
+ return 1
+}
+
+gateway_wait_spawn_identity() {
+ local pid="$1" marker="$2" i identity; shift 2
+ for i in $(seq 1 50); do
+ if gateway_command_matches "$pid" "$marker" "$@"; then
+ identity="$(gateway_capture_identity "$pid" 2>/dev/null || true)"
+ [ -n "$identity" ] && { printf '%s' "$identity"; return 0; }
+ fi
+ gateway_pid_alive "$pid" || return 1
+ sleep 0.05
+ done
+ return 1
+}
+
+gateway_stop_identity() {
+ local identity="$1" pid i
+ pid="$(jq -r '.pid // 0' <<<"$identity" 2>/dev/null || printf 0)"
+ gateway_identity_matches "$identity" || return 0
+ kill "$pid" 2>/dev/null || true
+ for i in $(seq 1 25); do
+ gateway_identity_matches "$identity" || return 0
+ sleep 0.1
+ done
+ gateway_identity_matches "$identity" && kill -KILL "$pid" 2>/dev/null || true
+}
+
+gateway_health_body_ok() {
+ local body="$1" expected_instance="${2-}"
+ [ -n "$body" ] || return 1
+ jq -e --arg version "$GATEWAY_EXPECTED_VERSION" --arg instance "$expected_instance" '
+ type == "object" and .status == "ok" and .version == $version and
+ (.buildId | type == "string") and (.buildId | length > 0) and
+ (if $instance == "" then has("runtimeInstanceId") else .runtimeInstanceId == $instance end)
+ ' <<<"$body" >/dev/null 2>&1
+}
+
+gateway_health_url_ok() {
+ local base="$1" expected_instance="${2-}" body
+ body="$("$CURL" -fsS --max-time 4 "$base/api/health" 2>/dev/null || true)"
+ gateway_health_body_ok "$body" "$expected_instance"
+}
+
+gateway_health_ok() { gateway_health_url_ok "$LOCAL_URL"; }
+
+gateway_wait_health() {
+ local expected_instance="${1-}" i
+ for i in $(seq 1 40); do gateway_health_url_ok "$LOCAL_URL" "$expected_instance" && return 0; sleep 0.25; done
+ return 1
+}
+
+gateway_lock_owner_valid() {
+ local owner="$LOCK_DIR/owner" pid ticks live
+ [ -f "$owner" ] && [ ! -L "$owner" ] || return 1
+ read -r pid ticks <"$owner" || return 1
+ [[ "$pid" =~ ^[0-9]+$ && "$ticks" =~ ^[0-9]+$ ]] || return 1
+ live="$(gateway_proc_start_ticks "$pid" 2>/dev/null || true)"
+ [ -n "$live" ] && [ "$live" = "$ticks" ]
+}
+
+gateway_lock_acquire() {
+ local self_ticks candidate stale i
+ self_ticks="$(gateway_proc_start_ticks $$)" || gateway_fail "cannot identify gateway process"
+ for i in $(seq 1 240); do
+ candidate="$STATE_ROOT/.lifecycle-lock.$$.$RANDOM"
+ mkdir -m 700 -- "$candidate"
+ printf '%s %s\n' "$$" "$self_ticks" >"$candidate/owner"; chmod 600 "$candidate/owner"
+ if mv -T -- "$candidate" "$LOCK_DIR" 2>/dev/null; then LOCK_HELD=1; return 0; fi
+ rm -rf -- "$candidate"
+ if [ -d "$LOCK_DIR" ] && [ ! -L "$LOCK_DIR" ] && ! gateway_lock_owner_valid; then
+ stale="$STATE_ROOT/.lifecycle-stale.$$.$RANDOM"
+ mv -T -- "$LOCK_DIR" "$stale" 2>/dev/null && rm -rf -- "$stale" || true
+ fi
+ sleep 0.05
+ done
+ gateway_fail "another gateway lifecycle operation is still running"
+}
+
+gateway_lock_release() {
+ [ "${LOCK_HELD:-0}" = 1 ] || return 0
+ if gateway_lock_owner_valid; then rm -f -- "$LOCK_DIR/owner"; rmdir -- "$LOCK_DIR" 2>/dev/null || true; fi
+ LOCK_HELD=0
+}
+
+gateway_with_lock() {
+ gateway_lock_acquire
+ trap gateway_lock_release EXIT
+ "$@"
+ gateway_lock_release
+ trap - EXIT
+}
diff --git a/scripts/lib/gateway-config.sh b/scripts/lib/gateway-config.sh
new file mode 100644
index 00000000..618a1564
--- /dev/null
+++ b/scripts/lib/gateway-config.sh
@@ -0,0 +1,124 @@
+#!/usr/bin/env bash
+# Stable-origin configuration, diagnostics, and browser launcher.
+
+gateway_safe_env_file() {
+ local mode
+ [ -e "$ENVF" ] || gateway_fail "env file not found: $ENVF"
+ [ -f "$ENVF" ] && [ ! -L "$ENVF" ] || gateway_fail "env file must be a regular non-symlink file"
+ [ "$(stat -c '%u' "$ENVF")" = "$(id -u)" ] || gateway_fail "env file must be owned by current user"
+ mode="$(stat -c '%a' "$ENVF")"; (( (8#$mode & 077) == 0 )) \
+ || gateway_fail "env file contains secrets and must not be group/world-accessible (got mode $mode)"
+}
+
+gateway_env_origin() {
+ gateway_safe_env_file
+ sed -n 's/^OS_PUBLIC_ORIGIN=//p' "$ENVF" | tail -1
+}
+
+gateway_rewrite_env_origin() {
+ local action="$1" value="${2-}"
+ gateway_safe_env_file
+ node - "$ENVF" "$action" "$value" <<'NODE'
+const fs = require('fs');
+const [file, action, value] = process.argv.slice(2);
+const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
+let st, text;
+try { st = fs.fstatSync(fd); text = fs.readFileSync(fd, 'utf8'); } finally { fs.closeSync(fd); }
+if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o077) !== 0) process.exit(2);
+if (action === 'set') {
+ const line = `OS_PUBLIC_ORIGIN=${value}`;
+ text = /^OS_PUBLIC_ORIGIN=.*$/m.test(text) ? text.replace(/^OS_PUBLIC_ORIGIN=.*$/m, line)
+ : text + `${text.endsWith('\n') || !text ? '' : '\n'}${line}\n`;
+} else if (action === 'clear') text = text.replace(/^OS_PUBLIC_ORIGIN=.*\n?/gm, '');
+else process.exit(2);
+const tmp = `${file}.mso-gateway-${process.pid}`;
+const out = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, st.mode & 0o777);
+try { fs.writeFileSync(out, text); fs.fsyncSync(out); } finally { fs.closeSync(out); }
+fs.renameSync(tmp, file);
+NODE
+}
+
+gateway_cmd_domain() {
+ local sub="${1:-show}" origin host
+ case "$sub" in
+ show) origin="$(gateway_env_origin)"; [ -n "$origin" ] && gateway_info "$origin" || gateway_info "OS_PUBLIC_ORIGIN is not set" ;;
+ set)
+ [ -n "${2-}" ] || gateway_fail "usage: mso gateway domain set https://mso.example.com"
+ origin="$(gateway_validate_public_origin "$2" 2>/dev/null || true)"
+ [ -n "$origin" ] || gateway_fail "public origin must be a clean HTTPS origin"
+ gateway_rewrite_env_origin set "$origin"; host="${origin#https://}"
+ gateway_info "saved OS_PUBLIC_ORIGIN=$origin in $ENVF"
+ gateway_info "MSO still binds only to $LOCAL_URL"
+ cat <<CFG
+named Cloudflare config example:
+ tunnel: <TUNNEL-UUID>
+ credentials-file: $HOME/.cloudflared/<TUNNEL-UUID>.json
+ ingress:
+ - hostname: $host
+ service: $LOCAL_URL
+ - service: http_status:404
+then: cloudflared tunnel route dns <TUNNEL-UUID-or-name> $host
+and: mso gateway start --config ~/.cloudflared/config.yml --tunnel <TUNNEL-UUID-or-name>
+CFG
+ gateway_info "rebuild/restart MSO after stable origin or split-host env changes" ;;
+ clear) gateway_rewrite_env_origin clear; gateway_info "removed OS_PUBLIC_ORIGIN" ;;
+ *) gateway_fail "usage: mso gateway domain show|set <https://host>|clear" ;;
+ esac
+}
+
+gateway_cmd_doctor() {
+ local fails=0 origin
+ gateway_info "mso gateway doctor"
+ gateway_health_ok && gateway_info " ok verified MSO runtime $LOCAL_URL" \
+ || gateway_info " -- no verified MSO runtime (mso web can start the built loopback fallback)"
+ if MSO_GATEWAY_NO_AUTO_INSTALL=1 gateway_resolve_cloudflared >/dev/null 2>&1; then
+ gateway_info " ok $("$CLOUDFLARED" --version 2>/dev/null | head -1) (pinned/explicit)"
+ else gateway_info " FAIL cloudflared unavailable — run: mso gateway install"; fails=$((fails+1)); fi
+ if gateway_port_exposure_state; then
+ gateway_info " FAIL raw MSO port has a non-loopback listener — reconfigure it to 127.0.0.1 before public tunneling"; fails=$((fails+1))
+ else
+ rc=$?
+ if [ "$rc" = 1 ]; then gateway_info " ok raw MSO port has no non-loopback listener"
+ else gateway_info " FAIL cannot verify kernel listener exposure"; fails=$((fails+1)); fi
+ fi
+ gateway_info " ok gateway upstream policy is loopback-only"
+ origin="$(gateway_env_origin 2>/dev/null || true)"
+ [ -n "$origin" ] && gateway_info " ok stable public origin: $origin" || gateway_info " -- no stable public origin (temporary mode available)"
+ local active_rc
+ if gateway_active_state >/dev/null; then gateway_info " ok public gateway running"
+ else active_rc=$?; if [ "$active_rc" = 1 ]; then gateway_info " -- public gateway stopped"
+ else gateway_info " FAIL gateway state is unsafe/corrupt"; fails=$((fails+1)); fi; fi
+ return "$fails"
+}
+
+gateway_cmd_web() {
+ local mode=auto print_only=0 url state opener
+ shift || true
+ while [ $# -gt 0 ]; do
+ case "$1" in --local) mode=local ;; --public) mode=public ;; --print) print_only=1 ;;
+ *) gateway_fail "usage: mso web [--local|--public] [--print]" ;; esac
+ shift
+ done
+ case "$mode" in
+ public)
+ if state="$(gateway_active_state)"; then url="$(jq -r .url <<<"$state")"
+ else rc=$?; [ "$rc" = 1 ] || return "$rc"; gateway_fail "public gateway is not running; run: mso gateway start"; fi ;;
+ local) gateway_health_ok || gateway_with_lock gateway_cmd_local_start_locked >/dev/null; url="$LOCAL_URL" ;;
+ auto)
+ if state="$(gateway_active_state)"; then url="$(jq -r .url <<<"$state")"
+ else rc=$?; [ "$rc" = 1 ] || return "$rc"
+ if [ -n "${OS_PUBLIC_ORIGIN:-}" ]; then url="$(gateway_validate_public_origin "$OS_PUBLIC_ORIGIN" 2>/dev/null || true)"
+ else gateway_health_ok || gateway_with_lock gateway_cmd_local_start_locked >/dev/null; url="$LOCAL_URL"; fi
+ fi ;;
+ esac
+ case "$url" in http:*) url="$(gateway_validate_loopback_origin "$url" 2>/dev/null || true)" ;;
+ https:*) url="$(gateway_validate_public_origin "$url" 2>/dev/null || true)" ;; *) url="" ;; esac
+ [ -n "$url" ] || gateway_fail "refusing unsafe browser URL"
+ [ "$print_only" = 1 ] && { printf '%s\n' "$url"; return; }
+ if command -v wslview >/dev/null 2>&1; then opener=wslview
+ elif command -v powershell.exe >/dev/null 2>&1; then powershell.exe -NoProfile -NonInteractive -Command 'Start-Process $args[0]' "$url" >/dev/null 2>&1 & gateway_info "opened $url"; return
+ elif command -v xdg-open >/dev/null 2>&1; then opener=xdg-open
+ elif command -v open >/dev/null 2>&1; then opener=open
+ else gateway_info "$url"; gateway_info "no browser opener found; open the URL above"; return; fi
+ "$opener" "$url" >/dev/null 2>&1 & gateway_info "opened $url"
+}
diff --git a/scripts/lib/gateway-network.sh b/scripts/lib/gateway-network.sh
new file mode 100755
index 00000000..00809777
--- /dev/null
+++ b/scripts/lib/gateway-network.sh
@@ -0,0 +1,46 @@
+#!/usr/bin/env bash
+# Prove that the MSO application port has no non-loopback listener before an
+# Internet tunnel is allowed. Reads kernel socket tables directly: no mutable
+# firewall assumption and no dependency on `ss`/net-tools.
+
+gateway_port_exposure_state() {
+ local port hex file line addr state seen=0 exposed=0
+ port="$(node - "$LOCAL_URL" <<'NODE'
+const u=new URL(process.argv[2]); process.stdout.write(u.port);
+NODE
+)"
+ [[ "$port" =~ ^[0-9]{1,5}$ ]] || return 2
+ printf -v hex '%04X' "$port"
+ for file in "${MSO_GATEWAY_PROC_NET_TCP:-/proc/net/tcp}" "${MSO_GATEWAY_PROC_NET_TCP6:-/proc/net/tcp6}"; do
+ [ -r "$file" ] || continue
+ seen=1
+ while read -r line; do
+ set -- $line; [ "$#" -ge 4 ] || continue
+ addr="${2:-}"; state="${4:-}"
+ [ "$state" = 0A ] || continue
+ case "$addr" in
+ *:"$hex") ;;
+ *) continue ;;
+ esac
+ case "$addr" in
+ # /proc/net/tcp stores IPv4 bytes little-endian. Every 127/8
+ # listener therefore ends in 7F. tcp6 renders ::1 as ...01000000.
+ ??????7F:"$hex"|00000000000000000000000001000000:"$hex") ;;
+ *) exposed=1 ;;
+ esac
+ done <"$file"
+ done
+ [ "$seen" = 1 ] || return 2
+ [ "$exposed" = 0 ] || return 0
+ return 1
+}
+
+gateway_assert_port_loopback_only() {
+ local rc
+ if gateway_port_exposure_state; then
+ gateway_fail "refusing public tunnel: the MSO port already has a non-loopback listener; reconfigure MSO to 127.0.0.1 first"
+ else
+ rc=$?
+ [ "$rc" = 1 ] || gateway_fail "cannot verify kernel listener exposure for the MSO port; refusing public tunnel"
+ fi
+}
diff --git a/scripts/lib/gateway-runtime.sh b/scripts/lib/gateway-runtime.sh
new file mode 100644
index 00000000..c44cbf0b
--- /dev/null
+++ b/scripts/lib/gateway-runtime.sh
@@ -0,0 +1,132 @@
+#!/usr/bin/env bash
+# Runtime/state lifecycle used by the public tunnel and local `mso web` fallback.
+
+GATEWAY_EXPECTED_VERSION="$(node -p "require('$ROOT/package.json').version")" || gateway_fail "cannot read MSO version"
+
+gateway_runtime_from_state() {
+ local state="$1" identity owned instance
+ RUNTIME_IDENTITY='null'; RUNTIME_INSTANCE_ID=''; RUNTIME_OWNED=false; RUNTIME_STARTED_NOW=false
+ owned="$(jq -r '.runtimeOwned // false' <<<"$state")"
+ identity="$(jq -c '.runtimeIdentity // null' <<<"$state")"
+ instance="$(jq -r '.runtimeIdentity.instanceId // empty' <<<"$state")"
+ if [ "$owned" = true ] && [ "$identity" != null ] && [ -n "$instance" ] && gateway_identity_matches_retry "$identity" && gateway_health_url_ok "$LOCAL_URL" "$instance"; then
+ RUNTIME_IDENTITY="$identity"; RUNTIME_INSTANCE_ID="$instance"; RUNTIME_OWNED=true
+ fi
+}
+
+gateway_start_runtime_if_needed() {
+ local next host port pid identity instance node_exe current_exe i
+ [ "$RUNTIME_OWNED" = true ] && gateway_health_url_ok "$LOCAL_URL" "$RUNTIME_INSTANCE_ID" && return 0
+ if gateway_health_ok; then
+ RUNTIME_IDENTITY='null'; RUNTIME_INSTANCE_ID=''; RUNTIME_OWNED=false; RUNTIME_STARTED_NOW=false
+ return 0
+ fi
+
+ next="$ROOT/node_modules/next/dist/bin/next"
+ [ -f "$next" ] || gateway_fail "MSO runtime is down and Next is missing; run: mso update"
+ [ -f "$ROOT/.next/BUILD_ID" ] || gateway_fail "MSO runtime is down and no production build exists; run: mso update"
+ IFS=$'\t' read -r host port < <(gateway_loopback_host_port)
+ [ "$host" = "127.0.0.1" ] || [ "$host" = "localhost" ] \
+ || gateway_fail "detached fallback supports 127.0.0.1/localhost; start MSO manually for $host"
+ [[ "$port" =~ ^[0-9]{1,5}$ ]] || gateway_fail "invalid local port: $port"
+
+ instance="$(node -e 'process.stdout.write(require("crypto").randomBytes(16).toString("hex"))')"
+ node_exe="$(readlink -f -- "$(command -v node)")"
+ gateway_private_file "$RUNTIME_LOG"; : >"$RUNTIME_LOG"
+ (
+ cd "$ROOT" || exit 1
+ nohup env MSO_RUNTIME_INSTANCE_ID="$instance" node "$next" start --hostname 127.0.0.1 --port "$port" >>"$RUNTIME_LOG" 2>&1 &
+ printf '%s\n' "$!"
+ ) >"$STATE_ROOT/.runtime-pid.$$"
+ pid="$(cat "$STATE_ROOT/.runtime-pid.$$")"; rm -f "$STATE_ROOT/.runtime-pid.$$"
+ identity=''
+ for i in $(seq 1 30); do
+ if gateway_pid_alive "$pid"; then
+ current_exe="$(readlink -f -- "/proc/$pid/exe" 2>/dev/null || true)"
+ if [ "$current_exe" = "$node_exe" ]; then
+ identity="$(gateway_capture_identity "$pid" 2>/dev/null || true)"
+ [ -n "$identity" ] && break
+ fi
+ else break; fi
+ sleep 0.05
+ done
+ if [ -z "$identity" ]; then kill "$pid" 2>/dev/null || true; gateway_fail "runtime did not start as the expected Node process"; fi
+ identity="$(jq -c --arg instance "$instance" '.cmdHash=null | .instanceId=$instance' <<<"$identity")"
+ if ! gateway_wait_health "$instance"; then
+ gateway_stop_identity "$identity"
+ gateway_fail "runtime did not become this launch's MSO health instance; see $RUNTIME_LOG"
+ fi
+ RUNTIME_IDENTITY="$identity"; RUNTIME_INSTANCE_ID="$instance"; RUNTIME_OWNED=true; RUNTIME_STARTED_NOW=true
+}
+
+gateway_write_state() {
+ local provider="$1" mode="$2" url="$3" tunnel_identity="$4"
+ jq -nc --arg provider "$provider" --arg mode "$mode" --arg url "$url" --arg local "$LOCAL_URL" \
+ --argjson tunnelIdentity "$tunnel_identity" --argjson runtimeIdentity "$RUNTIME_IDENTITY" \
+ --argjson runtimeOwned "$RUNTIME_OWNED" --arg startedAt "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
+ '{provider:$provider,mode:$mode,url:$url,localUrl:$local,tunnelIdentity:$tunnelIdentity,
+ runtimeIdentity:$runtimeIdentity,runtimeOwned:$runtimeOwned,startedAt:$startedAt}' \
+ | mso_private_state_atomic_write "$STATE_FILE" >/dev/null
+}
+
+gateway_active_state() {
+ local state identity rc
+ if state="$(gateway_state_read)"; then :; else rc=$?; return "$rc"; fi
+ identity="$(jq -c '.tunnelIdentity // null' <<<"$state")"
+ [ "$identity" != null ] && gateway_identity_matches "$identity" || return 1
+ printf '%s' "$state"
+}
+
+gateway_cmd_local_start_locked() {
+ local state
+ state="$(gateway_state_read)"
+ gateway_runtime_from_state "$state"
+ gateway_start_runtime_if_needed
+ if [ "$RUNTIME_STARTED_NOW" = true ] || [ "$RUNTIME_OWNED" = true ]; then
+ if ! gateway_write_state local local "$LOCAL_URL" null; then
+ [ "$RUNTIME_STARTED_NOW" = true ] && gateway_stop_identity "$RUNTIME_IDENTITY"
+ gateway_fail "could not persist local runtime state; newly started runtime was rolled back"
+ fi
+ fi
+ gateway_info "runtime: healthy MSO at $LOCAL_URL"
+}
+
+gateway_cmd_stop_locked() {
+ local state tunnel runtime owned
+ state="$(gateway_state_read)"
+ tunnel="$(jq -c '.tunnelIdentity // null' <<<"$state")"
+ runtime="$(jq -c '.runtimeIdentity // null' <<<"$state")"
+ owned="$(jq -r '.runtimeOwned // false' <<<"$state")"
+ [ "$tunnel" = null ] || gateway_stop_identity "$tunnel"
+ [ "$owned" != true ] || [ "$runtime" = null ] || gateway_stop_identity "$runtime"
+ mso_private_state_remove_file "$STATE_FILE" >/dev/null 2>&1 || true
+ gateway_info "gateway stopped; MSO remains loopback-only"
+}
+
+gateway_cmd_status() {
+ local state mode rc
+ if state="$(gateway_active_state)"; then
+ mode="$(jq -r .mode <<<"$state")"
+ gateway_info "gateway: running"
+ gateway_info "mode: $mode"
+ gateway_info "provider: $(jq -r .provider <<<"$state")"
+ gateway_info "public: $(jq -r .url <<<"$state")"
+ gateway_info "local: $(jq -r .localUrl <<<"$state")"
+ [ "$mode" != temporary ] || gateway_info "note: Quick Tunnel is preview-only; live Terminal SSE is not supported"
+ return 0
+ else
+ rc=$?
+ fi
+ [ "$rc" = 1 ] || return "$rc"
+ gateway_info "gateway: stopped"
+ gateway_info "local: $LOCAL_URL"
+ gateway_health_ok && gateway_info "runtime: healthy MSO (loopback)" || gateway_info "runtime: not a verified MSO endpoint"
+ return 1
+}
+
+gateway_cmd_url() {
+ local state rc
+ if state="$(gateway_active_state)"; then jq -r .url <<<"$state"; return 0; else rc=$?; fi
+ [ "$rc" = 1 ] || return "$rc"
+ gateway_fail "gateway is not running; run: mso gateway start"
+}
diff --git a/scripts/lib/gateway-tool.sh b/scripts/lib/gateway-tool.sh
new file mode 100755
index 00000000..90eb3a99
--- /dev/null
+++ b/scripts/lib/gateway-tool.sh
@@ -0,0 +1,71 @@
+#!/usr/bin/env bash
+# Pinned cloudflared resolver/installer. The public gateway never executes a mutable
+# `latest` artifact and needs no root package install.
+
+GATEWAY_ARTIFACT_LOCK="${MSO_GATEWAY_ARTIFACT_LOCK:-$ROOT/security/gateway-artifacts.env}"
+GATEWAY_TOOL_ROOT="${MSO_GATEWAY_TOOL_DIR:-$HOME/.mso/tools/cloudflared}"
+
+# shellcheck source=security/gateway-artifacts.env
+[ -r "$GATEWAY_ARTIFACT_LOCK" ] || gateway_fail "missing gateway artifact lock: $GATEWAY_ARTIFACT_LOCK"
+. "$GATEWAY_ARTIFACT_LOCK"
+
+_gateway_tool_expected() {
+ case "$(uname -m)" in
+ x86_64|amd64) printf '%s\t%s\n' "$CLOUDFLARED_LINUX_AMD64_URL" "$CLOUDFLARED_LINUX_AMD64_SHA256" ;;
+ aarch64|arm64) printf '%s\t%s\n' "$CLOUDFLARED_LINUX_ARM64_URL" "$CLOUDFLARED_LINUX_ARM64_SHA256" ;;
+ *) gateway_fail "unsupported architecture for automatic cloudflared install: $(uname -m). Set MSO_GATEWAY_CLOUDFLARED to a reviewed binary." ;;
+ esac
+}
+
+_gateway_tool_validate() {
+ local file="$1" expected="$2" owner mode actual
+ [ -f "$file" ] && [ ! -L "$file" ] || return 1
+ owner="$(stat -c '%u' -- "$file" 2>/dev/null || true)"; [ "$owner" = "$(id -u)" ] || return 1
+ mode="$(stat -c '%a' -- "$file" 2>/dev/null || true)"; [[ "$mode" =~ ^[0-7]{3,4}$ ]] || return 1
+ (( (8#$mode & 022) == 0 )) || return 1
+ actual="$(sha256sum "$file" 2>/dev/null | awk '{print $1}')"
+ [ "$actual" = "$expected" ] || return 1
+ [ -x "$file" ]
+}
+
+gateway_resolve_cloudflared() {
+ local override="${MSO_GATEWAY_CLOUDFLARED:-}" url expected dir dest tmp actual
+ if [ -n "$override" ]; then
+ case "$override" in /*) ;; *) gateway_fail "MSO_GATEWAY_CLOUDFLARED must be an absolute path" ;; esac
+ [ -f "$override" ] && [ ! -L "$override" ] && [ -x "$override" ] \
+ || gateway_fail "cloudflared override must be an executable regular non-symlink file: $override"
+ CLOUDFLARED="$(realpath -e -- "$override")"
+ return 0
+ fi
+
+ IFS=$'\t' read -r url expected < <(_gateway_tool_expected)
+ dir="$GATEWAY_TOOL_ROOT/$CLOUDFLARED_VERSION"
+ dir="$(mso_private_state_dir "$dir")" || gateway_fail "unsafe cloudflared tool directory"
+ dest="$dir/cloudflared"
+ if _gateway_tool_validate "$dest" "$expected"; then CLOUDFLARED="$dest"; return 0; fi
+ [ "${MSO_GATEWAY_NO_AUTO_INSTALL:-0}" != 1 ] \
+ || gateway_fail "pinned cloudflared $CLOUDFLARED_VERSION is not installed and auto-install is disabled"
+ if [ -e "$dest" ] || [ -L "$dest" ]; then
+ [ -L "$dest" ] && gateway_fail "refusing symlink at pinned cloudflared path: $dest"
+ rm -f -- "$dest"
+ fi
+
+ gateway_info "installing pinned cloudflared $CLOUDFLARED_VERSION for $(uname -m) (user-local, SHA-256 verified)…"
+ tmp="$(mktemp "$dir/.cloudflared.XXXXXX")"; chmod 600 "$tmp"
+ if ! "$CURL" --fail --silent --show-error --location --retry 3 --proto '=https' --tlsv1.2 -o "$tmp" "$url"; then
+ rm -f -- "$tmp"; gateway_fail "could not download pinned cloudflared from the official release"
+ fi
+ actual="$(sha256sum "$tmp" | awk '{print $1}')"
+ if [ "$actual" != "$expected" ]; then
+ rm -f -- "$tmp"; gateway_fail "cloudflared SHA-256 mismatch; refusing to execute downloaded artifact"
+ fi
+ chmod 700 "$tmp"; mv -fT -- "$tmp" "$dest"
+ _gateway_tool_validate "$dest" "$expected" || gateway_fail "installed cloudflared failed local identity verification"
+ CLOUDFLARED="$dest"
+}
+
+gateway_cmd_install_tool() {
+ gateway_resolve_cloudflared
+ gateway_info "cloudflared: $CLOUDFLARED"
+ "$CLOUDFLARED" --version | head -1
+}
diff --git a/scripts/lib/gateway-tunnel.sh b/scripts/lib/gateway-tunnel.sh
new file mode 100644
index 00000000..daa4f0a5
--- /dev/null
+++ b/scripts/lib/gateway-tunnel.sh
@@ -0,0 +1,185 @@
+#!/usr/bin/env bash
+# Cloudflare tunnel start path. The application port always remains loopback-only.
+
+gateway_parse_start_args() {
+ GATEWAY_CONFIG=""; GATEWAY_TUNNEL=""; GATEWAY_MODE=temporary; GATEWAY_PROVIDER=cloudflare-quick
+ shift || true
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --config) [ -n "${2-}" ] || gateway_fail "--config needs a path"; GATEWAY_CONFIG="$2"; shift 2 ;;
+ --tunnel) [ -n "${2-}" ] || gateway_fail "--tunnel needs a name or UUID"; GATEWAY_TUNNEL="$2"; shift 2 ;;
+ *) gateway_fail "usage: mso gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]" ;;
+ esac
+ done
+}
+
+gateway_validate_named_config() {
+ node - "$ROOT" "$GATEWAY_CONFIG" "$GATEWAY_PUBLIC_URL" "$LOCAL_URL" <<'NODE'
+const fs = require('fs');
+const path = require('path');
+const [root, file, publicOrigin, localOrigin] = process.argv.slice(2);
+let YAML;
+try { YAML = require(path.join(root, 'node_modules/yaml')); } catch { process.exit(10); }
+let cfg;
+try { cfg = YAML.parse(fs.readFileSync(file, 'utf8')); } catch { process.exit(11); }
+if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) process.exit(12);
+const ingress = cfg.ingress;
+if (!Array.isArray(ingress) || ingress.length !== 2) process.exit(13);
+const publicHost = new URL(publicOrigin).hostname.toLowerCase();
+const local = new URL(localOrigin);
+const loopback = (host) => host === 'localhost' || host === '::1' || host === '[::1]' || /^127(?:\.\d{1,3}){3}$/.test(host);
+const first = ingress[0], last = ingress[1];
+if (!first || typeof first !== 'object' || String(first.hostname || '').toLowerCase() !== publicHost) process.exit(14);
+let service;
+try { service = new URL(String(first.service || '')); } catch { process.exit(15); }
+if (service.protocol !== 'http:' || !loopback(service.hostname) || service.port !== local.port || service.pathname !== '/' || service.search || service.hash) process.exit(16);
+if (!last || typeof last !== 'object' || Object.keys(last).some((k) => k !== 'service') || last.service !== 'http_status:404') process.exit(17);
+const rawCred = cfg['credentials-file'];
+if (typeof rawCred !== 'string' || !rawCred.trim()) process.exit(18);
+let cred = rawCred.trim();
+if (cred.startsWith('~/')) cred = path.join(process.env.HOME || '', cred.slice(2));
+if (!path.isAbsolute(cred)) cred = path.resolve(path.dirname(file), cred);
+let st;
+try { st = fs.lstatSync(cred); } catch { process.exit(19); }
+if (!st.isFile() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077) !== 0) process.exit(20);
+NODE
+}
+
+gateway_validate_named_tunnel() {
+ local mode public
+ [ -n "$GATEWAY_CONFIG" ] && [ -n "$GATEWAY_TUNNEL" ] || gateway_fail "named mode requires BOTH --config and --tunnel"
+ [[ "$GATEWAY_TUNNEL" =~ ^[A-Za-z0-9_-]{1,80}$ ]] || gateway_fail "invalid tunnel name/UUID"
+ [ -f "$GATEWAY_CONFIG" ] && [ ! -L "$GATEWAY_CONFIG" ] || gateway_fail "config must be a regular non-symlink file"
+ [ "$(stat -c '%u' "$GATEWAY_CONFIG")" = "$(id -u)" ] || gateway_fail "cloudflared config must be owned by current user"
+ mode="$(stat -c '%a' "$GATEWAY_CONFIG")"; (( (8#$mode & 022) == 0 )) \
+ || gateway_fail "cloudflared config must not be group/world-writable (got mode $mode)"
+ public="$(gateway_validate_public_origin "${OS_PUBLIC_ORIGIN:-}" 2>/dev/null || true)"
+ [ -n "$public" ] || gateway_fail "named mode requires OS_PUBLIC_ORIGIN=https://your-domain (use: mso gateway domain set https://...)"
+ GATEWAY_MODE=named; GATEWAY_PROVIDER=cloudflare-named; GATEWAY_PUBLIC_URL="$public"
+ gateway_validate_named_config || gateway_fail "named config must be dedicated to OS_PUBLIC_ORIGIN -> the MSO loopback port, end in http_status:404, and reference a private owner-owned credentials-file"
+}
+
+gateway_spawn_tunnel() {
+ local pid identity safe_path safe_lang
+ local -a clean_env
+ gateway_private_file "$CF_LOG"; : >"$CF_LOG"
+ safe_path="${PATH:-/usr/local/bin:/usr/bin:/bin}"; safe_lang="${LANG:-C.UTF-8}"
+ # The parent intentionally has OS_LOGIN_PASSWORD, session secrets and BYOK keys
+ # for the Next runtime. cloudflared needs none of them. Start it from an empty
+ # environment so a tunnel/client compromise cannot read unrelated MSO secrets.
+ clean_env=(env -i "HOME=$HOME" "PATH=$safe_path" "LANG=$safe_lang")
+ if [ "$GATEWAY_MODE" = temporary ]; then
+ [ -z "${OS_PUBLIC_ORIGIN:-}" ] || gateway_info "warning: temporary gateway leaves existing OS_PUBLIC_ORIGIN unchanged"
+ nohup "${clean_env[@]}" "$CLOUDFLARED" tunnel --no-autoupdate --url "$LOCAL_URL" >>"$CF_LOG" 2>&1 & pid=$!
+ identity="$(gateway_wait_spawn_identity "$pid" "$CLOUDFLARED" tunnel --no-autoupdate --url "$LOCAL_URL" 2>/dev/null || true)"
+ else
+ nohup "${clean_env[@]}" "$CLOUDFLARED" tunnel --config "$GATEWAY_CONFIG" --no-autoupdate run "$GATEWAY_TUNNEL" >>"$CF_LOG" 2>&1 & pid=$!
+ identity="$(gateway_wait_spawn_identity "$pid" "$CLOUDFLARED" tunnel --config "$GATEWAY_CONFIG" --no-autoupdate run "$GATEWAY_TUNNEL" 2>/dev/null || true)"
+ fi
+ [ -n "$identity" ] || { kill "$pid" 2>/dev/null || true; return 1; }
+ TUNNEL_IDENTITY="$identity"
+}
+
+gateway_discover_quick_url() {
+ local pid i
+ pid="$(jq -r .pid <<<"$TUNNEL_IDENTITY")"
+ for i in $(seq 1 80); do
+ GATEWAY_PUBLIC_URL="$(grep -Eo 'https://[A-Za-z0-9-]+\.trycloudflare\.(com|app)' "$CF_LOG" | tail -1 || true)"
+ [ -n "$GATEWAY_PUBLIC_URL" ] && return 0
+ gateway_identity_matches_retry "$TUNNEL_IDENTITY" || return 1
+ sleep 0.25
+ done
+ return 1
+}
+
+gateway_quick_public_ipv4s() {
+ local host response
+ host="$(node - "$GATEWAY_PUBLIC_URL" <<'NODE'
+try {
+ const u = new URL(process.argv[2]);
+ if (u.protocol !== 'https:' || !/^[A-Za-z0-9-]+\.trycloudflare\.(?:com|app)$/.test(u.hostname)) process.exit(1);
+ process.stdout.write(u.hostname);
+} catch { process.exit(1); }
+NODE
+)" || return 1
+ response="$("$CURL" -fsS --max-time 5 -H 'accept: application/dns-json' \
+ "https://cloudflare-dns.com/dns-query?name=$host&type=A" 2>/dev/null || true)"
+ [ -n "$response" ] || return 1
+ jq -r '.Answer[]? | select(.type == 1) | .data' <<<"$response" 2>/dev/null \
+ | node -e '
+ const net=require("net"), readline=require("readline");
+ const blocked=(ip)=>{const p=ip.split(".").map(Number); return p[0]===0||p[0]===10||p[0]===127||p[0]>=224||
+ (p[0]===169&&p[1]===254)||(p[0]===172&&p[1]>=16&&p[1]<=31)||(p[0]===192&&p[1]===168)||
+ (p[0]===100&&p[1]>=64&&p[1]<=127)||(p[0]===198&&(p[1]===18||p[1]===19));};
+ const rl=readline.createInterface({input:process.stdin,crlfDelay:Infinity});
+ rl.on("line",ip=>{ip=ip.trim(); if(net.isIP(ip)===4&&!blocked(ip)) console.log(ip);});'
+}
+
+gateway_quick_edge_health_ok() {
+ local host ip body
+ [ "$GATEWAY_MODE" = temporary ] || return 1
+ host="${GATEWAY_PUBLIC_URL#https://}"
+ while IFS= read -r ip; do
+ [ -n "$ip" ] || continue
+ # --resolve bypasses only the caller's DNS cache. TLS still verifies the
+ # random trycloudflare hostname, and the body must match this launch's nonce.
+ body="$("$CURL" -fsS --max-time 5 --resolve "$host:443:$ip" \
+ "$GATEWAY_PUBLIC_URL/api/health" 2>/dev/null || true)"
+ gateway_health_body_ok "$body" "${RUNTIME_INSTANCE_ID:-}" && return 0
+ done < <(gateway_quick_public_ipv4s || true)
+ return 1
+}
+
+gateway_probe_public() {
+ local seconds="${MSO_GATEWAY_PUBLIC_READY_SECONDS:-60}" i
+ [ "${MSO_GATEWAY_SKIP_PUBLIC_PROBE:-0}" = 1 ] && return 0
+ [[ "$seconds" =~ ^[0-9]+$ ]] && [ "$seconds" -ge 10 ] && [ "$seconds" -le 120 ] \
+ || gateway_fail "MSO_GATEWAY_PUBLIC_READY_SECONDS must be an integer from 10 to 120"
+ # A newly allocated Quick Tunnel hostname can exist before the edge route has
+ # propagated. Do not weaken the MSO health/instance check; give the provider a
+ # bounded readiness window instead. Named tunnels usually pass on the first poll.
+ for i in $(seq 1 "$seconds"); do
+ gateway_health_url_ok "$GATEWAY_PUBLIC_URL" "${RUNTIME_INSTANCE_ID:-}" && return 0
+ gateway_quick_edge_health_ok && return 0
+ sleep 1
+ done
+ return 1
+}
+
+gateway_cleanup_failed_start() {
+ [ "${TUNNEL_IDENTITY:-null}" = null ] || gateway_stop_identity "$TUNNEL_IDENTITY"
+ [ "${RUNTIME_STARTED_NOW:-false}" != true ] || gateway_stop_identity "$RUNTIME_IDENTITY"
+}
+
+gateway_cmd_start_locked() {
+ local state active rc
+ if active="$(gateway_active_state)"; then gateway_cmd_status; return 0; else rc=$?; fi
+ [ "$rc" = 1 ] || return "$rc"
+ [ -z "$GATEWAY_CONFIG$GATEWAY_TUNNEL" ] || gateway_validate_named_tunnel
+ gateway_resolve_cloudflared
+
+ state="$(gateway_state_read)"
+ gateway_assert_port_loopback_only
+ gateway_runtime_from_state "$state"
+ gateway_start_runtime_if_needed
+ gateway_assert_port_loopback_only
+ TUNNEL_IDENTITY=null; GATEWAY_PUBLIC_URL="${GATEWAY_PUBLIC_URL:-}"
+ gateway_spawn_tunnel || { gateway_cleanup_failed_start; gateway_fail "cloudflared failed to start with the expected argv"; }
+ if [ "$GATEWAY_MODE" = temporary ]; then
+ gateway_discover_quick_url || { gateway_cleanup_failed_start; gateway_fail "Quick Tunnel did not return a public URL; see $CF_LOG"; }
+ fi
+ GATEWAY_PUBLIC_URL="$(gateway_validate_public_origin "$GATEWAY_PUBLIC_URL" 2>/dev/null || true)"
+ [ -n "$GATEWAY_PUBLIC_URL" ] || { gateway_cleanup_failed_start; gateway_fail "tunnel produced an invalid public origin"; }
+ gateway_probe_public || { gateway_cleanup_failed_start; gateway_fail "public endpoint did not return the MSO health contract; see $CF_LOG"; }
+ if ! gateway_write_state "$GATEWAY_PROVIDER" "$GATEWAY_MODE" "$GATEWAY_PUBLIC_URL" "$TUNNEL_IDENTITY"; then
+ gateway_cleanup_failed_start
+ gateway_fail "could not persist gateway state; newly launched processes were rolled back"
+ fi
+
+ gateway_info "gateway started"
+ gateway_info "public: $GATEWAY_PUBLIC_URL"
+ gateway_info "local: $LOCAL_URL (still loopback-only)"
+ [ "$GATEWAY_MODE" != temporary ] || gateway_info "warning: Quick Tunnel is preview-only; live Terminal SSE may not work"
+ gateway_info "open: mso web"
+ gateway_info "stop: mso gateway stop"
+}
diff --git a/scripts/mso-gateway b/scripts/mso-gateway
index c5a075a2..6b36217d 100755
--- a/scripts/mso-gateway
+++ b/scripts/mso-gateway
@@ -1,428 +1,63 @@
#!/usr/bin/env bash
-# Local/public gateway lifecycle for MSO.
-# The invariant is deliberate: MSO itself always stays on loopback. Public access
-# is an outbound HTTPS tunnel, never a 0.0.0.0 listener created by this script.
+# MSO local/public gateway dispatcher. Public access is always an outbound HTTPS
+# tunnel; the Next application itself remains on a validated loopback origin.
set -euo pipefail
umask 077
ROOT="${MSO_GATEWAY_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
ENVF="${MSO_GATEWAY_ENV:-$ROOT/.env.local}"
-LOCAL_URL="${MSO_GATEWAY_LOCAL_URL:-http://127.0.0.1:4005}"
+LOCAL_URL_OVERRIDE="${MSO_GATEWAY_LOCAL_URL:-}"
+LOCAL_URL=""
STATE_ROOT="${MSO_GATEWAY_STATE_DIR:-$HOME/.mso/private/gateway}"
-CLOUDFLARED="${MSO_GATEWAY_CLOUDFLARED:-$(command -v cloudflared 2>/dev/null || true)}"
+CLOUDFLARED=""
CURL="${MSO_GATEWAY_CURL:-$(command -v curl 2>/dev/null || true)}"
+for dep in node jq sha256sum realpath stat mktemp; do command -v "$dep" >/dev/null || { echo "mso gateway: missing dependency: $dep" >&2; exit 1; }; done
+[ -n "$CURL" ] || { echo "mso gateway: curl is required" >&2; exit 1; }
+
# shellcheck source=scripts/lib/private-state.sh
. "$ROOT/scripts/lib/private-state.sh"
-
-fail() { printf 'mso gateway: %s\n' "$*" >&2; exit 1; }
-info() { printf '%s\n' "$*"; }
-
-[ -n "$CURL" ] || fail "curl is required"
-
-validate_loopback_origin() {
- node - "$1" <<'NODE'
-const raw = process.argv[2];
-try {
- const u = new URL(raw);
- const host = u.hostname.toLowerCase();
- const parts = host.split('.');
- const ipv4Loopback = parts.length === 4 && parts[0] === '127' && parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255);
- const loopback = host === 'localhost' || host === '[::1]' || host === '::1' || ipv4Loopback;
- const clean = u.protocol === 'http:' && loopback && !u.username && !u.password && u.pathname === '/' && !u.search && !u.hash;
- if (!clean || !u.port) process.exit(1);
- process.stdout.write(u.origin);
-} catch { process.exit(1); }
-NODE
-}
-
-LOCAL_URL="$(validate_loopback_origin "$LOCAL_URL" 2>/dev/null || true)"
-[ -n "$LOCAL_URL" ] || fail "refusing non-loopback/invalid upstream (MSO gateway only accepts a clean http://127/8, localhost, or ::1 origin with an explicit port)"
-
-STATE_ROOT="$(mso_private_state_dir "$STATE_ROOT")" || fail "unsafe gateway state directory"
+# shellcheck source=scripts/lib/gateway-common.sh
+. "$ROOT/scripts/lib/gateway-common.sh"
+# Source config early because it owns the single env-file safety validator.
+# shellcheck source=scripts/lib/gateway-config.sh
+. "$ROOT/scripts/lib/gateway-config.sh"
+
+# Direct `scripts/mso-gateway` calls and `mso gateway` must have the same runtime
+# environment. The file is owner/private checked before sourcing. cloudflared is
+# spawned later with a scrubbed environment so these secrets never reach it.
+if [ "$ENVF" != /dev/null ] && { [ -e "$ENVF" ] || [ -L "$ENVF" ]; }; then
+ gateway_safe_env_file
+ # shellcheck disable=SC1090
+ set -a; . "$ENVF"; set +a
+fi
+LOCAL_URL="${LOCAL_URL_OVERRIDE:-${MSO_GATEWAY_LOCAL_URL:-http://127.0.0.1:${MSO_PORT:-4005}}}"
+LOCAL_URL="$(gateway_validate_loopback_origin "$LOCAL_URL" 2>/dev/null || true)"
+[ -n "$LOCAL_URL" ] || gateway_fail "refusing non-loopback/invalid upstream; use a clean http://127/8, localhost, or ::1 origin with an explicit port"
+STATE_ROOT="$(mso_private_state_dir "$STATE_ROOT")" || gateway_fail "unsafe gateway state directory"
STATE_FILE="$STATE_ROOT/state.json"
CF_LOG="$STATE_ROOT/cloudflared.log"
RUNTIME_LOG="$STATE_ROOT/runtime.log"
-
-private_file() {
- mso_private_state_ensure_file "$1" >/dev/null || fail "unsafe private state file: $1"
-}
-
-state_read() {
- if [ -s "$STATE_FILE" ]; then
- mso_private_state_validate_file "$STATE_FILE" >/dev/null || fail "unsafe gateway state file"
- jq -e . "$STATE_FILE" 2>/dev/null || fail "gateway state is corrupt; inspect $STATE_FILE before removing it"
- else
- printf '{}\n'
- fi
-}
-
-pid_alive() { [ "${1:-0}" -gt 1 ] 2>/dev/null && kill -0 "$1" 2>/dev/null; }
-cmdline() { tr '\0' ' ' <"/proc/$1/cmdline" 2>/dev/null || true; }
-
-is_our_tunnel_pid() {
- local pid="${1:-0}" line
- pid_alive "$pid" || return 1
- line="$(cmdline "$pid")"
- [[ "$line" == *cloudflared* && "$line" == *tunnel* ]]
-}
-
-is_our_runtime_pid() {
- local pid="${1:-0}" line
- pid_alive "$pid" || return 1
- line="$(cmdline "$pid")"
- [[ "$line" == *"$ROOT/node_modules/next/dist/bin/next"* && "$line" == *" start "* && "$line" == *"127.0.0.1"* ]]
-}
-
-# A forked child can exist for a few scheduler ticks before exec() replaces its
-# cmdline. Never weaken the identity check; wait briefly for the expected identity
-# instead. This also avoids treating a slow laptop as a failed gateway start.
-wait_identity() {
- local pid="$1" kind="$2" i
- for i in $(seq 1 40); do
- case "$kind" in
- tunnel) is_our_tunnel_pid "$pid" && return 0 ;;
- runtime) is_our_runtime_pid "$pid" && return 0 ;;
- *) return 1 ;;
- esac
- pid_alive "$pid" || return 1
- sleep 0.05
- done
- return 1
-}
-
-health_ok() { "$CURL" -fsS --max-time 4 "$LOCAL_URL/api/health" >/dev/null 2>&1; }
-
-wait_health() {
- local i
- for i in $(seq 1 40); do
- health_ok && return 0
- sleep 0.25
- done
- return 1
-}
-
-start_runtime_if_needed() {
- RUNTIME_PID=0
- RUNTIME_OWNED=false
- health_ok && return 0
-
- local next="$ROOT/node_modules/next/dist/bin/next" port host
- [ -f "$next" ] || fail "MSO runtime is down and Next is missing; run the installer/update first"
- [ -f "$ROOT/.next/BUILD_ID" ] || fail "MSO runtime is down and no production build exists; run: cd $ROOT && node node_modules/next/dist/bin/next build"
- host="${LOCAL_URL#http://}"; host="${host%%:*}"; port="${LOCAL_URL##*:}"
- [ "$host" = "127.0.0.1" ] || [ "$host" = "localhost" ] || fail "detached fallback supports IPv4 loopback only"
- [[ "$port" =~ ^[0-9]{1,5}$ ]] || fail "invalid local port: $port"
-
- private_file "$RUNTIME_LOG"
- : >"$RUNTIME_LOG"
- (
- cd "$ROOT"
- nohup node "$next" start --hostname 127.0.0.1 --port "$port" >>"$RUNTIME_LOG" 2>&1 &
- printf '%s' "$!"
- ) >"$STATE_ROOT/.runtime-pid"
- RUNTIME_PID="$(cat "$STATE_ROOT/.runtime-pid")"
- rm -f "$STATE_ROOT/.runtime-pid"
- wait_identity "$RUNTIME_PID" runtime || fail "runtime process did not start with the expected loopback command"
- if ! wait_health; then
- kill "$RUNTIME_PID" 2>/dev/null || true
- fail "runtime did not become healthy; see $RUNTIME_LOG"
- fi
- RUNTIME_OWNED=true
-}
-
-validate_public_origin() {
- node - "$1" <<'NODE'
-const raw = process.argv[2];
-try {
- const u = new URL(raw);
- const ok = u.protocol === "https:" && !u.username && !u.password && u.pathname === "/" && !u.search && !u.hash;
- if (!ok) process.exit(1);
- process.stdout.write(u.origin);
-} catch { process.exit(1); }
-NODE
-}
-
-write_state() {
- local provider="$1" url="$2" tunnel_pid="$3" runtime_pid="$4" runtime_owned="$5" mode="$6"
- jq -nc \
- --arg provider "$provider" --arg url "$url" --arg local "$LOCAL_URL" --arg mode "$mode" \
- --argjson tunnelPid "$tunnel_pid" --argjson runtimePid "$runtime_pid" --argjson runtimeOwned "$runtime_owned" \
- --arg startedAt "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
- '{provider:$provider,mode:$mode,url:$url,localUrl:$local,tunnelPid:$tunnelPid,runtimePid:$runtimePid,runtimeOwned:$runtimeOwned,startedAt:$startedAt}' \
- | mso_private_state_atomic_write "$STATE_FILE" >/dev/null || fail "could not persist gateway state"
-}
-
-stop_pid() {
- local pid="$1" kind="$2"
- [ "$pid" -gt 1 ] 2>/dev/null || return 0
- case "$kind" in
- tunnel) is_our_tunnel_pid "$pid" || return 0 ;;
- runtime) is_our_runtime_pid "$pid" || return 0 ;;
- esac
- kill "$pid" 2>/dev/null || true
- local i
- for i in $(seq 1 20); do pid_alive "$pid" || return 0; sleep 0.1; done
- kill -KILL "$pid" 2>/dev/null || true
-}
-
-cmd_stop() {
- local state tp rp owned
- state="$(state_read)"
- tp="$(jq -r '.tunnelPid // 0' <<<"$state")"
- rp="$(jq -r '.runtimePid // 0' <<<"$state")"
- owned="$(jq -r '.runtimeOwned // false' <<<"$state")"
- stop_pid "$tp" tunnel
- [ "$owned" = true ] && stop_pid "$rp" runtime
- mso_private_state_remove_file "$STATE_FILE" >/dev/null 2>&1 || true
- info "gateway stopped; MSO remains loopback-only"
-}
-
-active_state() {
- local state pid
- state="$(state_read)"
- pid="$(jq -r '.tunnelPid // 0' <<<"$state")"
- is_our_tunnel_pid "$pid" || return 1
- printf '%s' "$state"
-}
-
-cmd_status() {
- local state
- if ! state="$(active_state)"; then
- info "gateway: stopped"
- info "local: $LOCAL_URL"
- health_ok && info "runtime: healthy (loopback)" || info "runtime: not reachable"
- return 1
- fi
- info "gateway: running"
- info "mode: $(jq -r .mode <<<"$state")"
- info "provider:$(jq -r .provider <<<"$state" | sed 's/^/ /')"
- info "public: $(jq -r .url <<<"$state")"
- info "local: $(jq -r .localUrl <<<"$state")"
- if [ "$(jq -r .mode <<<"$state")" = temporary ]; then
- info "note: Cloudflare Quick Tunnel is temporary preview mode; live Terminal SSE is not supported by that provider"
- fi
-}
-
-cmd_url() {
- local state
- state="$(active_state)" || fail "gateway is not running; run: mso gateway start"
- jq -r .url <<<"$state"
-}
-
-cmd_start() {
- local config="" tunnel="" mode=temporary provider=cloudflare-quick public_url="" tunnel_pid i
- shift || true
- while [ $# -gt 0 ]; do
- case "$1" in
- --config) [ -n "${2-}" ] || fail "--config needs a path"; config="$2"; shift 2 ;;
- --tunnel) [ -n "${2-}" ] || fail "--tunnel needs a name or UUID"; tunnel="$2"; shift 2 ;;
- *) fail "usage: mso gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]" ;;
- esac
- done
- if active_state >/dev/null 2>&1; then
- cmd_status
- return 0
- fi
- [ -n "$CLOUDFLARED" ] || fail "cloudflared is not installed. Install the official Cloudflare Tunnel client, then rerun. MSO will not download an unpinned tunnel binary automatically."
- [ -x "$CLOUDFLARED" ] || fail "cloudflared is not executable: $CLOUDFLARED"
- if [ -n "$config$tunnel" ]; then
- [ -n "$config" ] && [ -n "$tunnel" ] || fail "named mode requires BOTH --config and --tunnel"
- [[ "$tunnel" =~ ^[A-Za-z0-9_-]{1,80}$ ]] || fail "invalid tunnel name/UUID"
- [ -f "$config" ] && [ ! -L "$config" ] || fail "config must be a regular non-symlink file: $config"
- [ "$(stat -c '%u' "$config")" = "$(id -u)" ] || fail "cloudflared config must be owned by the current user"
- config_mode="$(stat -c '%a' "$config")"
- (( (8#$config_mode & 022) == 0 )) || fail "cloudflared config must not be group/world-writable (got mode $config_mode)"
- public_url="$(validate_public_origin "${OS_PUBLIC_ORIGIN:-}" 2>/dev/null || true)"
- [ -n "$public_url" ] || fail "named mode requires OS_PUBLIC_ORIGIN=https://your-domain in $ENVF (use: mso gateway domain set https://...)"
- mode=named; provider=cloudflare-named
- fi
-
- start_runtime_if_needed
- private_file "$CF_LOG"; : >"$CF_LOG"
- if [ "$mode" = temporary ]; then
- if [ -n "${OS_PUBLIC_ORIGIN:-}" ]; then
- info "warning: OS_PUBLIC_ORIGIN is already set; temporary gateway does not override it. Generated MCP/share URLs may continue to name that stable origin."
- fi
- nohup "$CLOUDFLARED" tunnel --no-autoupdate --url "$LOCAL_URL" >>"$CF_LOG" 2>&1 &
- else
- nohup "$CLOUDFLARED" tunnel --config "$config" --no-autoupdate run "$tunnel" >>"$CF_LOG" 2>&1 &
- fi
- tunnel_pid=$!
- wait_identity "$tunnel_pid" tunnel || { [ "$RUNTIME_OWNED" = true ] && stop_pid "$RUNTIME_PID" runtime; fail "cloudflared failed to start"; }
-
- if [ "$mode" = temporary ]; then
- for i in $(seq 1 80); do
- public_url="$(grep -Eo 'https://[A-Za-z0-9-]+\.trycloudflare\.com' "$CF_LOG" | tail -1 || true)"
- [ -n "$public_url" ] && break
- pid_alive "$tunnel_pid" || break
- sleep 0.25
- done
- [ -n "$public_url" ] || { stop_pid "$tunnel_pid" tunnel; [ "$RUNTIME_OWNED" = true ] && stop_pid "$RUNTIME_PID" runtime; fail "quick tunnel did not return a public URL; see $CF_LOG"; }
- fi
- public_url="$(validate_public_origin "$public_url")" || fail "tunnel produced an invalid public origin"
-
- if [ "${MSO_GATEWAY_SKIP_PUBLIC_PROBE:-0}" != 1 ]; then
- for i in $(seq 1 24); do
- "$CURL" -fsS --max-time 5 "$public_url/api/health" >/dev/null 2>&1 && break
- [ "$i" -eq 24 ] && { stop_pid "$tunnel_pid" tunnel; [ "$RUNTIME_OWNED" = true ] && stop_pid "$RUNTIME_PID" runtime; fail "public HTTPS endpoint did not become healthy; see $CF_LOG"; }
- sleep 0.5
- done
- fi
-
- write_state "$provider" "$public_url" "$tunnel_pid" "$RUNTIME_PID" "$RUNTIME_OWNED" "$mode"
- info "gateway started"
- info "public: $public_url"
- info "local: $LOCAL_URL (still loopback-only)"
- if [ "$mode" = temporary ]; then
- info "warning: temporary Quick Tunnel is for preview/testing; Cloudflare documents no SSE support, so the live Terminal stream may not work until named/domain mode"
- fi
- info "open: mso web"
- info "stop: mso gateway stop"
-}
-
-safe_env_file() {
- [ -e "$ENVF" ] || fail "env file not found: $ENVF"
- [ -f "$ENVF" ] && [ ! -L "$ENVF" ] || fail "env file must be a regular non-symlink file"
- [ "$(stat -c '%u' "$ENVF")" = "$(id -u)" ] || fail "env file must be owned by current user"
- env_mode="$(stat -c '%a' "$ENVF")"
- (( (8#$env_mode & 077) == 0 )) || fail "env file contains secrets and must not be group/world-accessible (got mode $env_mode)"
-}
-
-env_origin() {
- safe_env_file
- sed -n 's/^OS_PUBLIC_ORIGIN=//p' "$ENVF" | tail -1
-}
-
-set_env_origin() {
- local value="$1"
- safe_env_file
- node - "$ENVF" "$value" <<'NODE'
-const fs = require('fs');
-const path = process.argv[2];
-const value = process.argv[3];
-const st = fs.lstatSync(path);
-if (!st.isFile() || st.isSymbolicLink() || st.uid !== process.getuid()) process.exit(2);
-let text = fs.readFileSync(path, 'utf8');
-const line = `OS_PUBLIC_ORIGIN=${value}`;
-if (/^OS_PUBLIC_ORIGIN=.*$/m.test(text)) text = text.replace(/^OS_PUBLIC_ORIGIN=.*$/m, line);
-else text += `${text.endsWith('\n') || text.length === 0 ? '' : '\n'}${line}\n`;
-const tmp = `${path}.mso-gateway-${process.pid}`;
-fs.writeFileSync(tmp, text, { mode: st.mode & 0o777 });
-fs.renameSync(tmp, path);
-NODE
-}
-
-clear_env_origin() {
- safe_env_file
- node - "$ENVF" <<'NODE'
-const fs = require('fs');
-const path = process.argv[2];
-const st = fs.lstatSync(path);
-if (!st.isFile() || st.isSymbolicLink() || st.uid !== process.getuid()) process.exit(2);
-let text = fs.readFileSync(path, 'utf8').replace(/^OS_PUBLIC_ORIGIN=.*\n?/gm, '');
-const tmp = `${path}.mso-gateway-${process.pid}`;
-fs.writeFileSync(tmp, text, { mode: st.mode & 0o777 });
-fs.renameSync(tmp, path);
-NODE
-}
-
-cmd_domain() {
- local sub="${1:-show}" origin host
- case "$sub" in
- show)
- origin="$(env_origin)"
- [ -n "$origin" ] && info "$origin" || info "OS_PUBLIC_ORIGIN is not set (temporary/loopback mode)" ;;
- set)
- [ -n "${2-}" ] || fail "usage: mso gateway domain set https://mso.example.com"
- origin="$(validate_public_origin "$2" 2>/dev/null || true)"
- [ -n "$origin" ] || fail "public origin must be a clean HTTPS origin (no path/query/credentials)"
- host="${origin#https://}"
- set_env_origin "$origin"
- info "saved OS_PUBLIC_ORIGIN=$origin in $ENVF"
- info "MSO still binds only to $LOCAL_URL"
- info "named Cloudflare config example:"
- cat <<CFG
- tunnel: <TUNNEL-UUID>
- credentials-file: $HOME/.cloudflared/<TUNNEL-UUID>.json
- ingress:
- - hostname: $host
- service: $LOCAL_URL
- - service: http_status:404
-CFG
- info "then: cloudflared tunnel route dns <TUNNEL-UUID-or-name> $host"
- info "and: mso gateway start --config ~/.cloudflared/config.yml --tunnel <TUNNEL-UUID-or-name>"
- info "restart/rebuild MSO after origin/split-host env changes before treating this as permanent production config" ;;
- clear)
- clear_env_origin
- info "removed OS_PUBLIC_ORIGIN; MSO returns to request-derived/loopback origin behavior" ;;
- *) fail "usage: mso gateway domain show|set <https://host>|clear" ;;
- esac
-}
-
-cmd_doctor() {
- local fails=0
- printf 'mso gateway doctor\n'
- health_ok && printf ' ok local runtime %s\n' "$LOCAL_URL" || { printf ' -- local runtime is not running (gateway start can launch the WSL fallback)\n'; }
- if [ -n "$CLOUDFLARED" ] && [ -x "$CLOUDFLARED" ]; then
- printf ' ok cloudflared %s\n' "$("$CLOUDFLARED" --version 2>/dev/null | head -1)"
- else
- printf ' FAIL cloudflared missing — install the official Cloudflare Tunnel client\n'; fails=$((fails+1))
- fi
- printf ' ok upstream is loopback-only\n'
- [ -n "$(env_origin 2>/dev/null || true)" ] && printf ' ok stable public origin configured\n' || printf ' -- no stable public origin (temporary mode)\n'
- if active_state >/dev/null 2>&1; then printf ' ok gateway process is running\n'; else printf ' -- gateway is stopped\n'; fi
- return "$fails"
-}
-
-cmd_web() {
- local mode=auto print_only=0 url state opener
- shift || true
- while [ $# -gt 0 ]; do
- case "$1" in
- --local) mode=local ;;
- --public) mode=public ;;
- --print) print_only=1 ;;
- *) fail "usage: mso web [--local|--public] [--print]" ;;
- esac
- shift
- done
- case "$mode" in
- local) url="$LOCAL_URL" ;;
- public)
- state="$(active_state)" || fail "public gateway is not running; run: mso gateway start"
- url="$(jq -r .url <<<"$state")" ;;
- auto)
- if state="$(active_state 2>/dev/null)"; then url="$(jq -r .url <<<"$state")"
- elif [ -n "${OS_PUBLIC_ORIGIN:-}" ]; then url="$(validate_public_origin "$OS_PUBLIC_ORIGIN" 2>/dev/null || true)"; [ -n "$url" ] || url="$LOCAL_URL"
- else url="$LOCAL_URL"; fi ;;
- esac
- case "$url" in
- http:*) url="$(validate_loopback_origin "$url" 2>/dev/null || true)" ;;
- https:*) url="$(validate_public_origin "$url" 2>/dev/null || true)" ;;
- *) url="" ;;
- esac
- [ -n "$url" ] || fail "refusing to pass unsafe URL to browser opener"
- [ "$print_only" -eq 1 ] && { printf '%s\n' "$url"; return; }
- if command -v wslview >/dev/null 2>&1; then opener=wslview
- elif command -v powershell.exe >/dev/null 2>&1; then
- powershell.exe -NoProfile -NonInteractive -Command 'Start-Process $args[0]' "$url" >/dev/null 2>&1 &
- info "opened $url"
- return
- elif command -v xdg-open >/dev/null 2>&1; then opener=xdg-open
- elif command -v open >/dev/null 2>&1; then opener=open
- else printf '%s\n' "$url"; info "no browser opener found; open the URL above"; return; fi
- "$opener" "$url" >/dev/null 2>&1 &
- info "opened $url"
-}
-
+LOCK_DIR="$STATE_ROOT/lifecycle.lock"
+LOCK_HELD=0
+
+# shellcheck source=scripts/lib/gateway-network.sh
+. "$ROOT/scripts/lib/gateway-network.sh"
+# shellcheck source=scripts/lib/gateway-tool.sh
+. "$ROOT/scripts/lib/gateway-tool.sh"
+# shellcheck source=scripts/lib/gateway-runtime.sh
+. "$ROOT/scripts/lib/gateway-runtime.sh"
+# shellcheck source=scripts/lib/gateway-tunnel.sh
+. "$ROOT/scripts/lib/gateway-tunnel.sh"
case "${1:-status}" in
- start) cmd_start "$@" ;;
- stop) cmd_stop ;;
- status) cmd_status ;;
- url) cmd_url ;;
- doctor) cmd_doctor ;;
- domain) shift; cmd_domain "$@" ;;
- web) cmd_web "$@" ;;
- *) fail "usage: mso gateway start|stop|status|url|doctor|domain ..." ;;
+ start) gateway_parse_start_args "$@"; gateway_with_lock gateway_cmd_start_locked ;;
+ stop) gateway_with_lock gateway_cmd_stop_locked ;;
+ status) gateway_cmd_status ;;
+ url) gateway_cmd_url ;;
+ doctor) gateway_cmd_doctor ;;
+ install) gateway_cmd_install_tool ;;
+ domain) shift; gateway_cmd_domain "$@" ;;
+ web) gateway_cmd_web "$@" ;;
+ local-start) gateway_with_lock gateway_cmd_local_start_locked ;; # internal: onboard/web WSL fallback
+ *) gateway_fail "usage: mso gateway start|stop|status|url|doctor|install|domain ..." ;;
esac
diff --git a/scripts/mso-gateway-lifecycle.test.ts b/scripts/mso-gateway-lifecycle.test.ts
new file mode 100644
index 00000000..65c8dce8
--- /dev/null
+++ b/scripts/mso-gateway-lifecycle.test.ts
@@ -0,0 +1,136 @@
+import { createHash } from "node:crypto";
+import { execFileSync, spawn, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+const ROOT = path.resolve(__dirname, "..");
+const GATEWAY = path.join(__dirname, "mso-gateway");
+const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).version as string;
+const roots: string[] = [];
+const pids = new Set<number>();
+
+function fixture() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-gateway-life-")); roots.push(dir);
+ const bin = path.join(dir, "bin"), state = path.join(dir, "state"), envFile = path.join(dir, ".env.local");
+ fs.mkdirSync(bin, { mode: 0o700 }); fs.mkdirSync(state, { mode: 0o700 });
+ fs.writeFileSync(envFile, "OS_SESSION_SECRET=fixture\n", { mode: 0o600 });
+ const curl = path.join(bin, "curl");
+ fs.writeFileSync(curl, `#!/bin/sh\nprintf '%s\\n' '{"status":"ok","buildId":"fixture","runtimeInstanceId":"fixture","version":"${VERSION}"}'\n`, { mode: 0o700 });
+ const cloudflared = path.join(bin, "cloudflared");
+ fs.writeFileSync(cloudflared, `#!/usr/bin/env node
+const fs=require('fs');
+if(process.argv.includes('--version')){console.log('cloudflared fixture');process.exit(0)}
+fs.appendFileSync(process.env.HOME + '/gateway-fake-starts', process.pid+'\\n');
+if(process.argv.includes('--url'))console.error('INF https://life-fixture.trycloudflare.com');
+process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000);
+`, { mode: 0o700 });
+ const procTcp = path.join(dir, "proc-tcp"), procTcp6 = path.join(dir, "proc-tcp6");
+ fs.writeFileSync(procTcp, " sl local_address rem_address st\n"); fs.writeFileSync(procTcp6, " sl local_address rem_address st\n");
+ const env = { ...process.env, HOME: dir, PATH: `${bin}:${process.env.PATH}`, MSO_GATEWAY_ROOT: ROOT, MSO_GATEWAY_ENV: envFile,
+ MSO_GATEWAY_STATE_DIR: state, MSO_GATEWAY_CURL: curl, MSO_GATEWAY_CLOUDFLARED: cloudflared,
+ MSO_GATEWAY_LOCAL_URL: "http://127.0.0.1:4005", MSO_GATEWAY_SKIP_PUBLIC_PROBE: "1",
+ MSO_GATEWAY_PROC_NET_TCP: procTcp, MSO_GATEWAY_PROC_NET_TCP6: procTcp6 };
+ return { dir, state, curl, cloudflared, startFile: path.join(dir, "gateway-fake-starts"), env };
+}
+
+function run(args: string[], env: NodeJS.ProcessEnv) { return execFileSync(GATEWAY, args, { encoding: "utf8", env }); }
+function identity(pid: number) {
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
+ const rest = stat.slice(stat.lastIndexOf(") ") + 2).trim().split(/\s+/);
+ return { pid, startTicks: rest[19], exe: fs.realpathSync(`/proc/${pid}/exe`),
+ cmdHash: createHash("sha256").update(fs.readFileSync(`/proc/${pid}/cmdline`)).digest("hex") };
+}
+function writeState(dir: string, value: unknown) { fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify(value), { mode: 0o600 }); }
+function alive(pid: number) { try { process.kill(pid, 0); return true; } catch { return false; } }
+function asyncStart(env: NodeJS.ProcessEnv) {
+ return new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve) => {
+ const child = spawn(GATEWAY, ["start"], { env, stdio: ["ignore", "pipe", "pipe"] });
+ let stdout = "", stderr = ""; child.stdout.on("data", (v) => stdout += v); child.stderr.on("data", (v) => stderr += v);
+ child.on("close", (code) => resolve({ code, stdout, stderr }));
+ });
+}
+
+afterEach(() => {
+ for (const pid of pids) if (alive(pid)) try { process.kill(pid, "SIGTERM"); } catch {}
+ pids.clear(); for (const dir of roots.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
+});
+
+describe("mso gateway lifecycle hardening", () => {
+ it("rolls back a tunnel when durable state persistence fails", () => {
+ const f = fixture(), pidFile = f.startFile;
+ const mv = path.join(f.dir, "bin", "mv");
+ fs.writeFileSync(mv, `#!/bin/sh
+case "$*" in *mso-private-write*state.json*) exit 1;; esac
+exec /bin/mv "$@"
+`, { mode: 0o700 });
+ const out = spawnSync(GATEWAY, ["start"], { encoding: "utf8",
+ env: f.env });
+ expect(out.status).not.toBe(0); expect(out.stderr).toContain("rolled back");
+ const pid = Number(fs.readFileSync(pidFile, "utf8").trim()); expect(alive(pid)).toBe(false);
+ expect(fs.existsSync(path.join(f.state, "state.json"))).toBe(false);
+ });
+
+
+ it("fails closed on empty or symlinked persisted state instead of treating it as absent", () => {
+ const empty = fixture(); fs.writeFileSync(path.join(empty.state, "state.json"), "", { mode: 0o600 });
+ let out = spawnSync(GATEWAY, ["status"], { encoding: "utf8", env: empty.env });
+ expect(out.status).not.toBe(0); expect(out.stderr).toContain("gateway state is empty");
+
+ const linked = fixture(), target = path.join(linked.dir, "outside.json");
+ fs.writeFileSync(target, "{}\n", { mode: 0o600 }); fs.symlinkSync(target, path.join(linked.state, "state.json"));
+ out = spawnSync(GATEWAY, ["status"], { encoding: "utf8", env: linked.env });
+ expect(out.status).not.toBe(0); expect(out.stderr).toContain("unsafe gateway state file");
+ });
+
+ it("never kills a reused PID whose persisted process identity no longer matches", async () => {
+ const f = fixture();
+ const child = spawn(f.cloudflared, ["tunnel", "--no-autoupdate", "--url", "http://127.0.0.1:4005"], { env: f.env });
+ await new Promise((r) => setTimeout(r, 120)); pids.add(child.pid!);
+ const wrong = { ...identity(child.pid!), startTicks: "0" };
+ writeState(f.state, { provider: "fixture", mode: "temporary", url: "https://old.example", localUrl: "http://127.0.0.1:4005",
+ tunnelIdentity: wrong, runtimeIdentity: null, runtimeOwned: false, startedAt: "2026-01-01T00:00:00Z" });
+ run(["stop"], f.env); expect(alive(child.pid!)).toBe(true);
+ });
+
+
+ it("can stop an owned Next-style process even after its argv/process title changes", async () => {
+ const f = fixture();
+ const child = spawn(process.execPath, ["-e", "process.title='next-server (fixture)';process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000)"]);
+ await new Promise((r) => setTimeout(r, 120)); pids.add(child.pid!);
+ const relaxed = { ...identity(child.pid!), cmdHash: null, instanceId: "fixture" };
+ writeState(f.state, { provider: "local", mode: "local", url: "http://127.0.0.1:4005", localUrl: "http://127.0.0.1:4005",
+ tunnelIdentity: null, runtimeIdentity: relaxed, runtimeOwned: true, startedAt: "2026-01-01T00:00:00Z" });
+ const closed = new Promise<void>((resolve) => child.once("close", () => resolve()));
+ run(["stop"], f.env); await Promise.race([closed, new Promise((r) => setTimeout(r, 600))]);
+ expect(alive(child.pid!)).toBe(false);
+ });
+
+ it("serializes concurrent starts so only one public tunnel is spawned", async () => {
+ const f = fixture(), startFile = f.startFile, env = f.env;
+ const [a, b] = await Promise.all([asyncStart(env), asyncStart(env)]);
+ expect(a.code).toBe(0); expect(b.code).toBe(0);
+ const spawned = fs.readFileSync(startFile, "utf8").trim().split(/\n+/).filter(Boolean);
+ expect(spawned).toHaveLength(1); pids.add(Number(spawned[0])); run(["stop"], f.env);
+ });
+
+ it("preserves owned runtime identity when only the old tunnel died", async () => {
+ const f = fixture();
+ const runtime = spawn(process.execPath, ["-e", "process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000)"]);
+ await new Promise((r) => setTimeout(r, 100)); pids.add(runtime.pid!);
+ const rid = { ...identity(runtime.pid!), cmdHash: null, instanceId: "fixture" };
+ writeState(f.state, { provider: "fixture", mode: "temporary", url: "https://dead.example", localUrl: "http://127.0.0.1:4005",
+ tunnelIdentity: null, runtimeIdentity: rid, runtimeOwned: true, startedAt: "2026-01-01T00:00:00Z" });
+ run(["start"], f.env); const state = JSON.parse(fs.readFileSync(path.join(f.state, "state.json"), "utf8"));
+ expect(state.runtimeOwned).toBe(true); expect(state.runtimeIdentity).toEqual(rid);
+ const closed = new Promise<void>((resolve) => runtime.once("close", () => resolve()));
+ run(["stop"], f.env); await Promise.race([closed, new Promise((r) => setTimeout(r, 500))]);
+ expect(alive(runtime.pid!)).toBe(false);
+ });
+
+ it("does not accept an arbitrary 2xx /api/health body as MSO", () => {
+ const f = fixture(); fs.writeFileSync(f.curl, "#!/bin/sh\nprintf '{}\\n'\n", { mode: 0o700 });
+ const out = run(["doctor"], f.env); expect(out).toContain("no verified MSO runtime");
+ });
+});
diff --git a/scripts/mso-gateway-test-fixture.ts b/scripts/mso-gateway-test-fixture.ts
new file mode 100644
index 00000000..b09afbda
--- /dev/null
+++ b/scripts/mso-gateway-test-fixture.ts
@@ -0,0 +1,93 @@
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+export const ROOT = path.resolve(__dirname, "..");
+export const GATEWAY = path.join(__dirname, "mso-gateway");
+export const CLI = path.join(ROOT, "bin/mso");
+export const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).version as string;
+
+const tempRoots: string[] = [];
+const tunnelPids = new Set<number>();
+
+export function fixture() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-gateway-"));
+ tempRoots.push(dir);
+ const bin = path.join(dir, "bin"), state = path.join(dir, "state"), envFile = path.join(dir, ".env.local");
+ fs.mkdirSync(bin, { mode: 0o700 });
+ fs.writeFileSync(envFile, "OS_SESSION_SECRET=fixture-only-not-a-real-secret\n", { mode: 0o600 });
+
+ const curl = path.join(bin, "curl");
+ fs.writeFileSync(
+ curl,
+ `#!/bin/sh\nprintf '%s\\n' '{"status":"ok","buildId":"fixture","runtimeInstanceId":"fixture","version":"${VERSION}"}'\n`,
+ { mode: 0o700 },
+ );
+
+ const cloudflared = path.join(bin, "cloudflared");
+ fs.writeFileSync(
+ cloudflared,
+ `#!/usr/bin/env node
+if (process.argv.includes('--version')) { console.log('cloudflared version fixture'); process.exit(0); }
+if (process.env.OS_SESSION_SECRET || process.env.OS_LOGIN_PASSWORD) require('fs').writeFileSync(process.env.HOME + '/cloudflared-secret-env', 'leaked');
+if (process.argv.includes('--url')) console.error('INF https://mso-gateway-fixture.trycloudflare.com');
+process.on('SIGTERM', () => process.exit(0));
+setInterval(() => {}, 1000);
+`,
+ { mode: 0o700 },
+ );
+
+ const procTcp = path.join(dir, "proc-tcp"), procTcp6 = path.join(dir, "proc-tcp6");
+ fs.writeFileSync(procTcp, " sl local_address rem_address st\n");
+ fs.writeFileSync(procTcp6, " sl local_address rem_address st\n");
+ const baseEnv = {
+ ...process.env,
+ HOME: dir,
+ MSO_GATEWAY_ROOT: ROOT,
+ MSO_GATEWAY_ENV: envFile,
+ MSO_GATEWAY_STATE_DIR: state,
+ MSO_GATEWAY_CURL: curl,
+ MSO_GATEWAY_CLOUDFLARED: cloudflared,
+ MSO_GATEWAY_LOCAL_URL: "http://127.0.0.1:4005",
+ MSO_GATEWAY_SKIP_PUBLIC_PROBE: "1",
+ MSO_GATEWAY_PROC_NET_TCP: procTcp,
+ MSO_GATEWAY_PROC_NET_TCP6: procTcp6,
+ };
+ return { dir, bin, state, envFile, curl, cloudflared, baseEnv };
+}
+
+export function runGateway(args: string[], env: NodeJS.ProcessEnv) {
+ return execFileSync(GATEWAY, args, { encoding: "utf8", env });
+}
+
+export function readFileSnapshot(file: string) {
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
+ try {
+ const stat = fs.fstatSync(fd);
+ if (!stat.isFile()) throw new Error(`expected regular file: ${file}`);
+ return { mode: stat.mode & 0o777, text: fs.readFileSync(fd, "utf8") };
+ } finally {
+ fs.closeSync(fd);
+ }
+}
+
+export function readState(stateDir: string) {
+ const statePath = path.join(stateDir, "state.json"), snapshot = readFileSnapshot(statePath);
+ const value = JSON.parse(snapshot.text) as {
+ mode: string;
+ url: string;
+ tunnelIdentity: { pid: number };
+ runtimeOwned: boolean;
+ };
+ tunnelPids.add(value.tunnelIdentity.pid);
+ return { path: statePath, snapshot, value };
+}
+
+export function cleanupGatewayFixtures() {
+ for (const pid of tunnelPids) {
+ try { process.kill(pid, "SIGTERM"); } catch { /* already stopped */ }
+ }
+ tunnelPids.clear();
+ for (const dir of tempRoots.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
+}
diff --git a/scripts/mso-gateway.test.ts b/scripts/mso-gateway.test.ts
index 3fc967c8..5e929ff4 100644
--- a/scripts/mso-gateway.test.ts
+++ b/scripts/mso-gateway.test.ts
@@ -1,88 +1,12 @@
import { execFileSync, spawnSync } from "node:child_process";
import fs from "node:fs";
-import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
+import {
+ CLI, GATEWAY, VERSION, cleanupGatewayFixtures, fixture, readFileSnapshot, readState, runGateway as run,
+} from "./mso-gateway-test-fixture";
-const ROOT = path.resolve(__dirname, "..");
-const GATEWAY = path.join(__dirname, "mso-gateway");
-const CLI = path.join(ROOT, "bin/mso");
-const tempRoots: string[] = [];
-const tunnelPids = new Set<number>();
-
-function fixture() {
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-gateway-"));
- tempRoots.push(dir);
- const bin = path.join(dir, "bin");
- const state = path.join(dir, "state");
- const envFile = path.join(dir, ".env.local");
- fs.mkdirSync(bin, { mode: 0o700 });
- fs.writeFileSync(envFile, "OS_SESSION_SECRET=fixture-only-not-a-real-secret\n", { mode: 0o600 });
-
- const curl = path.join(bin, "curl");
- fs.writeFileSync(curl, "#!/bin/sh\nexit 0\n", { mode: 0o700 });
-
- const cloudflared = path.join(bin, "cloudflared");
- fs.writeFileSync(
- cloudflared,
- `#!/usr/bin/env node
-if (process.argv.includes('--version')) { console.log('cloudflared version fixture'); process.exit(0); }
-if (process.argv.includes('--url')) console.error('INF https://mso-gateway-fixture.trycloudflare.com');
-process.on('SIGTERM', () => process.exit(0));
-setInterval(() => {}, 1000);
-`,
- { mode: 0o700 },
- );
-
- const baseEnv = {
- ...process.env,
- HOME: dir,
- MSO_GATEWAY_ROOT: ROOT,
- MSO_GATEWAY_ENV: envFile,
- MSO_GATEWAY_STATE_DIR: state,
- MSO_GATEWAY_CURL: curl,
- MSO_GATEWAY_CLOUDFLARED: cloudflared,
- MSO_GATEWAY_LOCAL_URL: "http://127.0.0.1:4005",
- MSO_GATEWAY_SKIP_PUBLIC_PROBE: "1",
- };
- return { dir, bin, state, envFile, curl, cloudflared, baseEnv };
-}
-
-function run(args: string[], env: NodeJS.ProcessEnv) {
- return execFileSync(GATEWAY, args, { encoding: "utf8", env });
-}
-
-function readFileSnapshot(file: string) {
- const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
- try {
- const stat = fs.fstatSync(fd);
- if (!stat.isFile()) throw new Error(`expected regular file: ${file}`);
- return { mode: stat.mode & 0o777, text: fs.readFileSync(fd, "utf8") };
- } finally {
- fs.closeSync(fd);
- }
-}
-
-function readState(stateDir: string) {
- const p = path.join(stateDir, "state.json");
- const snapshot = readFileSnapshot(p);
- const value = JSON.parse(snapshot.text) as {
- mode: string;
- url: string;
- tunnelPid: number;
- runtimeOwned: boolean;
- };
- tunnelPids.add(value.tunnelPid);
- return { path: p, snapshot, value };
-}
-
-afterEach(() => {
- for (const pid of tunnelPids) {
- try { process.kill(pid, "SIGTERM"); } catch { /* already stopped */ }
- }
- tunnelPids.clear();
- for (const dir of tempRoots.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
-});
+afterEach(cleanupGatewayFixtures);
describe("mso public gateway", () => {
it("runs a temporary HTTPS gateway without publishing the MSO app port", () => {
@@ -99,14 +23,58 @@ describe("mso public gateway", () => {
expect(fs.statSync(f.state).mode & 0o777).toBe(0o700);
expect(state.snapshot.mode).toBe(0o600);
expect(state.snapshot.text).not.toContain("OS_SESSION_SECRET");
+ expect(fs.existsSync(path.join(f.dir, "cloudflared-secret-env"))).toBe(false);
expect(run(["url"], f.baseEnv).trim()).toBe("https://mso-gateway-fixture.trycloudflare.com");
- expect(run(["status"], f.baseEnv)).toContain("Quick Tunnel is temporary preview mode");
+ expect(run(["status"], f.baseEnv)).toContain("Quick Tunnel is preview-only");
expect(run(["web", "--print"], f.baseEnv).trim()).toBe("https://mso-gateway-fixture.trycloudflare.com");
expect(run(["stop"], f.baseEnv)).toContain("MSO remains loopback-only");
expect(fs.existsSync(state.path)).toBe(false);
- expect(() => process.kill(state.value.tunnelPid, 0)).toThrow();
+ expect(() => process.kill(state.value.tunnelIdentity.pid, 0)).toThrow();
+ });
+
+
+
+ it("verifies a Quick Tunnel through Cloudflare DoH when the local resolver still has NXDOMAIN", () => {
+ const f = fixture();
+ fs.writeFileSync(f.curl, `#!/bin/sh
+args="$*"
+case "$args" in
+ *cloudflare-dns.com/dns-query*) printf '%s\\n' '{"Status":0,"Answer":[{"type":1,"data":"127.0.0.1"},{"type":1,"data":"104.16.230.132"}]}' ;;
+ *--resolve*) printf '%s\\n' '{"status":"ok","buildId":"fixture","runtimeInstanceId":"fixture","version":"${VERSION}"}' ;;
+ *127.0.0.1:4005/api/health*) printf '%s\\n' '{"status":"ok","buildId":"fixture","runtimeInstanceId":"fixture","version":"${VERSION}"}' ;;
+ *trycloudflare.com/api/health*) exit 6 ;;
+ *) printf '%s\\n' '{"status":"ok","buildId":"fixture","runtimeInstanceId":"fixture","version":"${VERSION}"}' ;;
+esac
+`, { mode: 0o700 });
+ const env = { ...f.baseEnv, MSO_GATEWAY_SKIP_PUBLIC_PROBE: "0", MSO_GATEWAY_PUBLIC_READY_SECONDS: "10" };
+ const started = run(["start"], env);
+ expect(started).toContain("gateway started");
+ const state = readState(f.state);
+ expect(state.value.url).toBe("https://mso-gateway-fixture.trycloudflare.com");
+ run(["stop"], env);
+ });
+
+ it("refuses tunneling when the same MSO port already has a wildcard listener", () => {
+ const f = fixture();
+ const procTcp = f.baseEnv.MSO_GATEWAY_PROC_NET_TCP!;
+ fs.writeFileSync(procTcp, " sl local_address rem_address st\n 0: 00000000:0FA5 00000000:0000 0A\n");
+ const out = spawnSync(GATEWAY, ["start"], { encoding: "utf8", env: f.baseEnv });
+ expect(out.status).not.toBe(0);
+ expect(out.stderr).toContain("already has a non-loopback listener");
+ expect(fs.existsSync(path.join(f.state, "state.json"))).toBe(false);
+ });
+
+
+ it("also refuses a listener bound to a LAN address instead of wildcard", () => {
+ const f = fixture();
+ const procTcp = f.baseEnv.MSO_GATEWAY_PROC_NET_TCP!;
+ // 192.168.1.1 in /proc/net/tcp little-endian form.
+ fs.writeFileSync(procTcp, " sl local_address rem_address st\n 0: 0101A8C0:0FA5 00000000:0000 0A\n");
+ const out = spawnSync(GATEWAY, ["start"], { encoding: "utf8", env: f.baseEnv });
+ expect(out.status).not.toBe(0);
+ expect(out.stderr).toContain("non-loopback listener");
});
it("fails closed on a non-loopback upstream", () => {
@@ -130,6 +98,26 @@ describe("mso public gateway", () => {
expect(out.stderr).toContain("refusing non-loopback/invalid upstream");
});
+
+ it("accepts only a dedicated named tunnel config for the configured MSO origin", () => {
+ const f = fixture();
+ const credentials = path.join(f.dir, "tunnel.json");
+ fs.writeFileSync(credentials, "{}\n", { mode: 0o600 });
+ const config = path.join(f.dir, "cloudflared.yml");
+ fs.writeFileSync(config, `tunnel: fixture\ncredentials-file: ${credentials}\ningress:\n - hostname: mso.example.test\n service: http://localhost:4005\n - service: http_status:404\n`, { mode: 0o600 });
+ const env = { ...f.baseEnv, OS_PUBLIC_ORIGIN: "https://mso.example.test" };
+ const started = run(["start", "--config", config, "--tunnel", "fixture"], env);
+ expect(started).toContain("https://mso.example.test");
+ const state = readState(f.state);
+ expect(state.value.mode).toBe("named");
+ run(["stop"], env);
+
+ fs.writeFileSync(config, `tunnel: fixture\ncredentials-file: ${credentials}\ningress:\n - hostname: mso.example.test\n service: http://127.0.0.1:4005\n - hostname: other.example.test\n service: http://127.0.0.1:9000\n - service: http_status:404\n`, { mode: 0o600 });
+ const rejected = spawnSync(GATEWAY, ["start", "--config", config, "--tunnel", "fixture"], { encoding: "utf8", env });
+ expect(rejected.status).not.toBe(0);
+ expect(rejected.stderr).toContain("named config must be dedicated");
+ });
+
it("rejects a group/world-writable named-tunnel config", () => {
const f = fixture();
const config = path.join(f.dir, "cloudflared.yml");
@@ -166,6 +154,15 @@ describe("mso public gateway", () => {
expect(text).not.toContain("OS_PUBLIC_ORIGIN=");
});
+ it("preserves a literal IPv6 loopback --base and port", () => {
+ const f = fixture();
+ const out = execFileSync(CLI, ["--base", "http://[::1]:4556", "web", "--local", "--print"], {
+ encoding: "utf8", env: { ...process.env, HOME: f.dir, MSO_ENV: "/dev/null",
+ MSO_GATEWAY_STATE_DIR: f.state, MSO_GATEWAY_CURL: f.curl, MSO_GATEWAY_CLOUDFLARED: f.cloudflared },
+ });
+ expect(out.trim()).toBe("http://[::1]:4556");
+ });
+
it("mso web follows an explicit loopback --base including a non-default port", () => {
const f = fixture();
const out = execFileSync(CLI, ["--base", "http://127.0.0.1:4555", "web", "--local", "--print"], {
diff --git a/scripts/mso-update b/scripts/mso-update
new file mode 100755
index 00000000..47b0e859
--- /dev/null
+++ b/scripts/mso-update
@@ -0,0 +1,87 @@
+#!/usr/bin/env bash
+# API-independent CLI updater. It keeps `mso update` useful even when :4005 is down.
+set -euo pipefail
+umask 077
+ROOT="${MSO_UPDATE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
+LOG="${MSO_UPDATE_LOG:-$HOME/.mso/self-update.log}"
+NOTICE_DIR="${MSO_UPDATE_NOTICE_DIR:-$HOME/.mso/private/update-notice}"
+# shellcheck source=scripts/lib/private-state.sh
+. "$ROOT/scripts/lib/private-state.sh"
+
+fail() { printf 'mso update: %s\n' "$*" >&2; exit 1; }
+git_root() { [ "$(git -C "$ROOT" rev-parse --show-toplevel 2>/dev/null || true)" = "$ROOT" ]; }
+current_version() { sed -n 's/^VERSION="\([^"]*\)".*/\1/p' "$ROOT/bin/mso" | head -1; }
+remote_version() { git -C "$ROOT" show origin/main:bin/mso 2>/dev/null | sed -n 's/^VERSION="\([^"]*\)".*/\1/p' | head -1; }
+behind() { git -C "$ROOT" rev-list --count HEAD..origin/main 2>/dev/null || printf 0; }
+
+require_checkout() {
+ git_root || fail "$ROOT is not a Git checkout; reinstall from the official repository"
+ [ "$(git -C "$ROOT" branch --show-current)" = main ] || fail "updates require the installed checkout to be on main"
+ [ -z "$(git -C "$ROOT" status --porcelain)" ] || fail "checkout has local changes; refusing to overwrite them"
+}
+
+fetch_main() { git -C "$ROOT" fetch --quiet origin main || fail "could not reach origin/main"; }
+
+print_status() {
+ local n local_v remote_v
+ require_checkout; fetch_main; n="$(behind)"; local_v="$(current_version)"; remote_v="$(remote_version)"
+ if [ "$n" -gt 0 ]; then
+ printf 'update available: mso %s -> %s (%s commit%s)\n' "${local_v:-unknown}" "${remote_v:-newer}" "$n" "$([ "$n" = 1 ] || printf s)"
+ git -C "$ROOT" log --format=' %h %s' -5 HEAD..origin/main
+ printf 'run: mso update\n'
+ else printf 'mso %s is up to date (%s)\n' "${local_v:-unknown}" "$(git -C "$ROOT" rev-parse --short HEAD)"; fi
+}
+
+notice() {
+ local dir stamp now last=0 n local_v remote_v
+ git_root || return 0
+ [ "$(git -C "$ROOT" branch --show-current 2>/dev/null || true)" = main ] || return 0
+ dir="$(mso_private_state_dir "$NOTICE_DIR")" || return 0; stamp="$dir/last-fetch"; now="$(date +%s)"
+ if [ -s "$stamp" ] && mso_private_state_validate_file "$stamp" >/dev/null 2>&1; then last="$(cat "$stamp" 2>/dev/null || printf 0)"; fi
+ if ! [[ "$last" =~ ^[0-9]+$ ]] || [ $((now-last)) -ge 21600 ]; then
+ printf '%s\n' "$now" | mso_private_state_atomic_write "$stamp" >/dev/null 2>&1 || true
+ (cd "$ROOT" && nohup git fetch --quiet origin main >/dev/null 2>&1 </dev/null &) || true
+ fi
+ n="$(behind)"; [ "$n" -gt 0 ] || return 0; local_v="$(current_version)"; remote_v="$(remote_version)"
+ printf 'MSO update available: %s -> %s (%s commit%s). Run: mso update\n' \
+ "${local_v:-current}" "${remote_v:-newer}" "$n" "$([ "$n" = 1 ] || printf s)" >&2
+}
+
+offline_build() {
+ local rebuild_only="$1"
+ if [ "$rebuild_only" != 1 ]; then
+ fetch_main
+ [ "$(behind)" -gt 0 ] || { printf 'MSO is already up to date.\n'; return 0; }
+ git -C "$ROOT" merge --ff-only origin/main || fail "cannot fast-forward to origin/main"
+ (cd "$ROOT" && bun install) || fail "dependency install failed"
+ fi
+ (cd "$ROOT" && bash scripts/verify-build.sh) || fail "candidate build verification failed"
+ (cd "$ROOT" && node node_modules/next/dist/bin/next build) || fail "production build failed"
+ printf 'updated to %s. No system service was active; run: mso web\n' "$(git -C "$ROOT" rev-parse --short HEAD)"
+}
+
+run_update() {
+ local rebuild_only="$1" arg=""
+ require_checkout
+ [ "$rebuild_only" != 1 ] || arg="--rebuild-only"
+ if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet mso.service; then
+ if command -v systemd-run >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1; then
+ mkdir -p "$(dirname "$LOG")"; chmod 700 "$(dirname "$LOG")" 2>/dev/null || true
+ systemd-run --user --collect --unit=mso-self-update --property=TimeoutStartSec=3600 \
+ "--property=WorkingDirectory=$ROOT" "--setenv=MSO_UPDATE_LOG=$LOG" /bin/bash "$ROOT/scripts/self-update.sh" $arg >/dev/null
+ printf 'update started safely outside mso.service. Follow: mso update log\n'
+ else
+ /bin/bash "$ROOT/scripts/self-update.sh" $arg
+ tail -n 30 "$LOG" 2>/dev/null || true
+ fi
+ else offline_build "$rebuild_only"; fi
+}
+
+case "${1:-run}" in
+ notice) notice ;;
+ status|check) print_status ;;
+ log) [ -f "$LOG" ] && tail -n "${2:-80}" "$LOG" || printf 'no update log yet: %s\n' "$LOG" ;;
+ run) case "${2-}" in "" ) run_update 0 ;; --rebuild|--rebuild-only) run_update 1 ;; *) fail "usage: mso update [--rebuild] | status | log" ;; esac ;;
+ --rebuild|--rebuild-only) run_update 1 ;;
+ *) fail "usage: mso update [--rebuild] | status | log" ;;
+esac
diff --git a/scripts/mso-update.test.ts b/scripts/mso-update.test.ts
new file mode 100644
index 00000000..99294d2e
--- /dev/null
+++ b/scripts/mso-update.test.ts
@@ -0,0 +1,59 @@
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+const SCRIPT = path.join(process.cwd(), "scripts/mso-update");
+const PRIVATE = path.join(process.cwd(), "scripts/lib/private-state.sh");
+const roots: string[] = [];
+
+function git(cwd: string, ...args: string[]) { return execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); }
+function fixture() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-update-")); roots.push(root);
+ const repo = path.join(root, "repo"), remote = path.join(root, "remote.git"), bin = path.join(root, "bin"), capture = path.join(root, "capture");
+ fs.mkdirSync(path.join(repo, "scripts/lib"), { recursive: true }); fs.mkdirSync(path.join(repo, "bin")); fs.mkdirSync(bin);
+ fs.copyFileSync(PRIVATE, path.join(repo, "scripts/lib/private-state.sh"));
+ fs.writeFileSync(path.join(repo, "scripts/verify-build.sh"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
+ fs.writeFileSync(path.join(repo, "bin/mso"), '#!/bin/sh\nVERSION="1.3.0"\n', { mode: 0o755 });
+ fs.mkdirSync(path.join(repo, "node_modules/next/dist/bin"), { recursive: true });
+ fs.writeFileSync(path.join(repo, "node_modules/next/dist/bin/next"), "fixture\n");
+ git(repo, "init", "-q", "-b", "main"); git(repo, "config", "user.name", "MSO Test"); git(repo, "config", "user.email", "[email protected]");
+ git(repo, "add", "."); git(repo, "commit", "-q", "-m", "initial"); const old = git(repo, "rev-parse", "HEAD");
+ git(root, "init", "--bare", "-q", remote); git(repo, "remote", "add", "origin", remote); git(repo, "push", "-q", "-u", "origin", "main");
+ fs.writeFileSync(path.join(repo, "bin/mso"), '#!/bin/sh\nVERSION="1.4.0"\n', { mode: 0o755 });
+ git(repo, "add", "bin/mso"); git(repo, "commit", "-q", "-m", "new cli"); const newer = git(repo, "rev-parse", "HEAD"); git(repo, "push", "-q", "origin", "main");
+ git(repo, "reset", "--hard", "-q", old);
+ fs.writeFileSync(path.join(bin, "systemctl"), "#!/bin/sh\nexit 3\n", { mode: 0o755 });
+ fs.writeFileSync(path.join(bin, "bun"), `#!/bin/sh\nprintf 'bun %s\\n' "$*" >> "${capture}"\n`, { mode: 0o755 });
+ fs.writeFileSync(path.join(bin, "node"), `#!/bin/sh\nprintf 'node %s\\n' "$*" >> "${capture}"\n`, { mode: 0o755 });
+ const env = { ...process.env, HOME: path.join(root, "home"), PATH: `${bin}:${process.env.PATH}`, MSO_UPDATE_ROOT: repo,
+ MSO_UPDATE_NOTICE_DIR: path.join(root, "notice") };
+ return { root, repo, old, newer, capture, env };
+}
+
+afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
+
+describe("mso update without a running web API", () => {
+ it("reports the incoming CLI version directly from origin/main", () => {
+ const f = fixture(); const out = execFileSync(SCRIPT, ["status"], { env: f.env, encoding: "utf8" });
+ expect(out).toContain("update available: mso 1.3.0 -> 1.4.0 (1 commit)");
+ expect(out).toContain("run: mso update"); expect(git(f.repo, "rev-parse", "HEAD")).toBe(f.old);
+ });
+
+ it("updates, verifies and builds offline when no mso.service is active", () => {
+ const f = fixture(); const out = execFileSync(SCRIPT, [], { env: f.env, encoding: "utf8" });
+ expect(out).toContain("No system service was active; run: mso web");
+ expect(git(f.repo, "rev-parse", "HEAD")).toBe(f.newer);
+ const calls = fs.readFileSync(f.capture, "utf8"); expect(calls).toContain("bun install");
+ expect(calls).toContain("node node_modules/next/dist/bin/next build");
+ });
+
+ it("prints an update notice from cached Git state without touching the web API", () => {
+ const f = fixture();
+ const result = execFileSync(SCRIPT, ["notice"], { env: f.env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
+ expect(result).toBe("");
+ const status = execFileSync(SCRIPT, ["status"], { env: f.env, encoding: "utf8" });
+ expect(status).toContain("1.3.0 -> 1.4.0");
+ });
+});
diff --git a/security/gateway-artifacts.env b/security/gateway-artifacts.env
new file mode 100644
index 00000000..1c7044ce
--- /dev/null
+++ b/security/gateway-artifacts.env
@@ -0,0 +1,7 @@
+# Immutable core gateway dependency. Reviewed against the official cloudflare/cloudflared release.
+# `mso gateway start` downloads only these exact release-tagged Linux binaries and verifies SHA-256 before first execution and on every reuse.
+CLOUDFLARED_VERSION='2026.8.2'
+CLOUDFLARED_LINUX_AMD64_URL='https://github.com/cloudflare/cloudflared/releases/download/2026.8.2/cloudflared-linux-amd64'
+CLOUDFLARED_LINUX_AMD64_SHA256='fcfb02b575a52ca1af2e3267af4e1517bcdeb30ac48c834c69abaed3c0576ad2'
+CLOUDFLARED_LINUX_ARM64_URL='https://github.com/cloudflare/cloudflared/releases/download/2026.8.2/cloudflared-linux-arm64'
+CLOUDFLARED_LINUX_ARM64_SHA256='7747d94570fb390cf47dcb4f9555c193c6355cda9793f0d878d9049e5d6a7790'