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): add loopback-only public web gateway

Rahman06f4e83fcd43
diff --git a/.env.example b/.env.example
index 1f2a112b..3ce149ee 100644
--- a/.env.example
+++ b/.env.example
@@ -130,6 +130,10 @@ OS_SESSION_SECRET=
# usable the policy emits `frame-ancestors 'none'` and the window stays blank —
# closed, on purpose, rather than naming a guessed origin as a permitted framer.
# OS_PUBLIC_ORIGIN=https://mso.example.com
+# The CLI can set/clear the stable value safely with:
+# mso gateway domain set https://mso.example.com
+# mso gateway domain clear
+# Temporary `mso gateway start` Quick Tunnels deliberately do NOT write this value.
# --- 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 097d1eaa..81caf3e2 100644
--- a/README.md
+++ b/README.md
@@ -187,15 +187,51 @@ shell profiles, or enable global hooks. Installing the RTK binary is a separate
system change.
MSO binds **`127.0.0.1` by default**, so nothing is published directly to your network.
-Reach it with an SSH tunnel and open `http://localhost:4005`:
+On a laptop/WSL install, the supported public-preview path keeps that invariant and creates an
+**outbound HTTPS tunnel** instead of opening port 4005 to the LAN/Internet:
+
+```bash
+mso gateway doctor
+mso gateway start # temporary HTTPS URL; requires the official cloudflared client
+mso web # opens the active public URL, or loopback when no gateway is running
+mso gateway status
+mso gateway stop
+```
+
+Temporary mode uses a Cloudflare Quick Tunnel and does **not** change `OS_PUBLIC_ORIGIN`, the
+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.
+
+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
+uses SSE, so that stream can be unavailable in temporary mode. Files, Settings and ordinary UI/API
+requests still use the normal authenticated HTTPS surface. For full-time/full-feature access, use a
+named tunnel/custom domain or another production HTTPS reverse proxy.
+
+For a stable domain, keep MSO on loopback and make the public origin explicit:
+
+```bash
+mso gateway domain set https://mso.example.com
+# create/configure the named Cloudflare Tunnel using the example printed above, then:
+mso gateway start --config ~/.cloudflared/config.yml --tunnel mso
+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
+SSH-only connection instead, use:
```bash
ssh -N -L 4005:127.0.0.1:4005 you@your-server
```
-The tunnel is not just hygiene. The session cookie is `Secure`; ordinary plain-HTTP IP
-addresses drop it. For a permanent setup use Tailscale Serve or a TLS reverse proxy to
-`127.0.0.1:4005`. Bind wider only when the network/firewall design explicitly requires it.
+The local tunnel is not just hygiene. The session cookie is `Secure`; ordinary plain-HTTP public IP
+addresses drop it. Bind wider only when the network/firewall design explicitly requires it.
Useful installer controls:
diff --git a/bin/mso b/bin/mso
index b4d0dd06..1ff17781 100755
--- a/bin/mso
+++ b/bin/mso
@@ -43,6 +43,8 @@
# 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
+# web Open the MSO browser UI (active gateway first, else loopback)
#
# Browser
# camoufox * Power the anti-detection VNC browser + read its password
@@ -110,13 +112,14 @@
# MSO_ENV Same as --env
# MSO_PASSWORD Overrides OS_LOGIN_PASSWORD from the env file
# MSO_DEVICE Overrides this CLI's device id (~/.mso/cli.device.id)
+# MSO_GATEWAY_LOCAL_URL Loopback upstream for gateway/web (default http://127.0.0.1:4005)
#
# READ = OS_FS_READ_ROOTS; WRITE = home + ~/projects; exec = full host power.
#
# Docs: https://github.com/rahmanef63/mso
set -euo pipefail
-VERSION="1.2.0"
+VERSION="1.3.0"
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
die() { echo "mso: $*" >&2; exit 1; }
@@ -140,6 +143,29 @@ set -a; . "$ENVF" 2>/dev/null || true; set +a
need() { command -v "$1" >/dev/null || die "missing dependency: $1"; }
need curl; need jq; need realpath; need stat; need mktemp; need sha256sum
+
+# Resolve the LOCAL upstream for gateway/web without ever widening the app bind.
+# Priority: explicit override → a loopback --base/MSO_BASE → the installed service's
+# PORT → MSO_PORT → 4005. This keeps non-default installer ports working on Linux
+# while WSL/no-systemd users still have an explicit override for manually-started
+# runtimes.
+gateway_local_url() {
+ local port=""
+ if [ -n "${MSO_GATEWAY_LOCAL_URL:-}" ]; then
+ printf '%s' "$MSO_GATEWAY_LOCAL_URL"
+ return
+ fi
+ case "$B" in
+ 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 \
+ | tr ' ' '\n' | sed -n 's/^PORT=//p' | head -1)
+ fi
+ port="${port:-${MSO_PORT:-4005}}"
+ [[ "$port" =~ ^[0-9]{1,5}$ ]] || die "invalid MSO gateway port: $port"
+ printf 'http://127.0.0.1:%s' "$port"
+}
# shellcheck source=scripts/lib/private-state.sh
. "$ROOT/scripts/lib/private-state.sh"
@@ -463,6 +489,7 @@ 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_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"
@@ -593,6 +620,10 @@ case "$cmd" in
onboard) run_onboard "${1-}" ;;
+ # ── local/public gateway + browser launcher ───────────────────────────────
+ gateway) local_url="$(gateway_local_url)"; MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$local_url" "$ROOT/scripts/mso-gateway" "$@" ;;
+ web) local_url="$(gateway_local_url)"; MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$local_url" "$ROOT/scripts/mso-gateway" web "$@" ;;
+
# ── camoufox (the real browser the Browser app drives) ────────────────────
camoufox)
case "${1:-status}" in
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 6df32be8..bb46a99e 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,6 +6,10 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
## 2026-08-30
+**Added**
+
+- `gateway` add loopback-only public web gateway
+
**Fixed**
- `install` survive Bun bin metadata corruption
diff --git a/docs/CLI.md b/docs/CLI.md
index d07df50a..0412f895 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -77,6 +77,8 @@ 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
+ web Open the MSO browser UI (active gateway first, else loopback)
Browser
camoufox * Power the anti-detection VNC browser + read its password
@@ -144,6 +146,7 @@ Environment:
MSO_ENV Same as --env
MSO_PASSWORD Overrides OS_LOGIN_PASSWORD from the env file
MSO_DEVICE Overrides this CLI's device id (~/.mso/cli.device.id)
+ MSO_GATEWAY_LOCAL_URL Loopback upstream for gateway/web (default http://127.0.0.1:4005)
READ = OS_FS_READ_ROOTS; WRITE = home + ~/projects; exec = full host power.
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 07b36d7f..ac5c8e3c 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -136,6 +136,54 @@ ssh -N -L 4005:127.0.0.1:4005 you@your-server
Then open `http://localhost:4005`. A `Secure` cookie is accepted on localhost, but ordinary
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:
+
+```bash
+mso gateway doctor
+mso gateway start
+mso gateway url
+mso web
+# when finished
+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
+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.
+
+This is intentionally labeled **temporary preview**. The random `trycloudflare.com` URL changes on
+restart, and Cloudflare Quick Tunnels do not support Server-Sent Events; MSO Terminal's live output
+uses SSE. Use a named tunnel/stable HTTPS origin for full functionality.
+
+Do not add the random Quick Tunnel URL to `OS_PUBLIC_ORIGIN`: that variable is deployment authority
+for stable MCP/share/CSP URLs. If a stable value is already configured, temporary mode leaves it
+untouched and warns that generated links may continue to name the stable origin.
+
+### Stable custom domain / named Cloudflare Tunnel
+
+```bash
+mso gateway domain set https://mso.example.com
+```
+
+The command validates a clean HTTPS origin, atomically updates only `OS_PUBLIC_ORIGIN` in
+`.env.local`, and prints a named-tunnel ingress example whose upstream remains loopback. Create the
+Cloudflare tunnel/DNS credentials using Cloudflare's official CLI, then start it without putting a
+token on the command line:
+
+```bash
+mso gateway start --config ~/.cloudflared/config.yml --tunnel mso
+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
+changing stable origin or split-host environment configuration.
+
### Tailscale (recommended)
Keep MSO on loopback and publish it with Tailscale Serve so the browser reaches an HTTPS
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 7080cef8..6e6770cf 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -2,6 +2,23 @@
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 — WSL Bun bin-metadata build resilience (SHIPPED)
A second real Ubuntu/WSL install reached checkout and a complete Bun 1.3.14 dependency install,
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 8b5d57a1..81eb3726 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -20,6 +20,25 @@ 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`.
+
+### Temporary gateway opens, but Terminal does not stream
+
+Cloudflare Quick Tunnels are the no-custom-domain preview mode and do not support Server-Sent
+Events. MSO Terminal output is an SSE stream, so use a named Cloudflare Tunnel/stable HTTPS origin
+for full Terminal behavior. `mso gateway status` labels a Quick Tunnel as temporary.
+
+### `mso gateway stop` leaves my manually-started MSO runtime running
+
+Expected. The gateway only stops a Next runtime when it launched that exact loopback process and
+recorded it as gateway-owned. An existing systemd/manual runtime is outside the gateway lifecycle.
+This prevents `stop` from terminating an unrelated or pre-existing process.
+
### Login returns success but the browser is logged out immediately
The session cookie is `Secure`. Plain HTTP on a normal IP/hostname causes browsers to drop
diff --git a/lib/security-store-lock.test.ts b/lib/security-store-lock.test.ts
index d8f1905e..39493a08 100644
--- a/lib/security-store-lock.test.ts
+++ b/lib/security-store-lock.test.ts
@@ -29,7 +29,10 @@ describe("security-store stale recovery", () => {
entered.push(index);
await new Promise((resolve) => setTimeout(resolve, 2));
active -= 1;
- }, { waitMs: 1, busyTimeoutMs: 2_000, staleMs: 1 }),
+ // Coverage runs instrument hundreds of files in parallel and can delay fsync-heavy
+ // contenders beyond 2s without changing mutual exclusion. Keep the test budget
+ // below Vitest's outer timeout while avoiding a scheduler-dependent false failure.
+ }, { waitMs: 1, busyTimeoutMs: 4_000, staleMs: 1 }),
));
expect(maxActive).toBe(1);
expect(entered).toHaveLength(24);
diff --git a/next.config.mjs b/next.config.mjs
index 7699dc99..ee8864c4 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -109,6 +109,8 @@ const nextConfig = {
// every rahmanef.com subdomain is HTTPS-only.
{ key: "Strict-Transport-Security", value: "max-age=31536000" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
+ // MSO is a private control plane even when reached through a temporary HTTPS tunnel.
+ { key: "X-Robots-Tag", value: "noindex, nofollow, noarchive" },
// Public remote shell — never allow it to be framed (clickjacking on
// exec/fs buttons). The full Content-Security-Policy (incl. a nonce'd
// script-src) is set PER-REQUEST in proxy.ts so a fresh nonce can gate
diff --git a/scripts/mso-gateway b/scripts/mso-gateway
new file mode 100755
index 00000000..c5a075a2
--- /dev/null
+++ b/scripts/mso-gateway
@@ -0,0 +1,428 @@
+#!/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.
+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}"
+STATE_ROOT="${MSO_GATEWAY_STATE_DIR:-$HOME/.mso/private/gateway}"
+CLOUDFLARED="${MSO_GATEWAY_CLOUDFLARED:-$(command -v cloudflared 2>/dev/null || true)}"
+CURL="${MSO_GATEWAY_CURL:-$(command -v curl 2>/dev/null || true)}"
+
+# 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"
+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"
+}
+
+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 ..." ;;
+esac
diff --git a/scripts/mso-gateway.test.ts b/scripts/mso-gateway.test.ts
new file mode 100644
index 00000000..3fc967c8
--- /dev/null
+++ b/scripts/mso-gateway.test.ts
@@ -0,0 +1,184 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+const ROOT = 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 });
+});
+
+describe("mso public gateway", () => {
+ it("runs a temporary HTTPS gateway without publishing the MSO app port", () => {
+ const f = fixture();
+ const started = run(["start"], f.baseEnv);
+ expect(started).toContain("gateway started");
+ expect(started).toContain("https://mso-gateway-fixture.trycloudflare.com");
+ expect(started).toContain("still loopback-only");
+
+ const state = readState(f.state);
+ expect(state.value.mode).toBe("temporary");
+ expect(state.value.url).toBe("https://mso-gateway-fixture.trycloudflare.com");
+ expect(state.value.runtimeOwned).toBe(false);
+ 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(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(["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();
+ });
+
+ it("fails closed on a non-loopback upstream", () => {
+ const f = fixture();
+ const out = spawnSync(GATEWAY, ["start"], {
+ encoding: "utf8",
+ env: { ...f.baseEnv, MSO_GATEWAY_LOCAL_URL: "http://0.0.0.0:4005" },
+ });
+ expect(out.status).not.toBe(0);
+ expect(out.stderr).toContain("refusing non-loopback/invalid upstream");
+ expect(fs.existsSync(path.join(f.state, "state.json"))).toBe(false);
+ });
+
+ it("does not confuse a hostname beginning with 127 for loopback", () => {
+ const f = fixture();
+ const out = spawnSync(GATEWAY, ["start"], {
+ encoding: "utf8",
+ env: { ...f.baseEnv, MSO_GATEWAY_LOCAL_URL: "http://127.attacker.example:4005" },
+ });
+ expect(out.status).not.toBe(0);
+ expect(out.stderr).toContain("refusing non-loopback/invalid upstream");
+ });
+
+ it("rejects a group/world-writable named-tunnel config", () => {
+ const f = fixture();
+ const config = path.join(f.dir, "cloudflared.yml");
+ fs.writeFileSync(config, "tunnel: fixture\n", { mode: 0o666 });
+ fs.chmodSync(config, 0o666);
+ const out = spawnSync(GATEWAY, ["start", "--config", config, "--tunnel", "fixture"], {
+ encoding: "utf8",
+ env: { ...f.baseEnv, OS_PUBLIC_ORIGIN: "https://mso.example.test" },
+ });
+ expect(out.status).not.toBe(0);
+ expect(out.stderr).toContain("must not be group/world-writable");
+ });
+
+ it("atomically sets and clears a clean HTTPS stable origin without touching other env values", () => {
+ const f = fixture();
+ run(["domain", "set", "https://mso.example.test"], f.baseEnv);
+ let snapshot = readFileSnapshot(f.envFile);
+ let text = snapshot.text;
+ expect(text).toContain("OS_SESSION_SECRET=fixture-only-not-a-real-secret");
+ expect(text).toContain("OS_PUBLIC_ORIGIN=https://mso.example.test");
+ expect(snapshot.mode).toBe(0o600);
+
+ const bad = spawnSync(GATEWAY, ["domain", "set", "http://mso.example.test/path"], {
+ encoding: "utf8",
+ env: f.baseEnv,
+ });
+ expect(bad.status).not.toBe(0);
+ expect(readFileSnapshot(f.envFile).text).toBe(text);
+
+ run(["domain", "clear"], f.baseEnv);
+ snapshot = readFileSnapshot(f.envFile);
+ text = snapshot.text;
+ expect(text).toContain("OS_SESSION_SECRET=fixture-only-not-a-real-secret");
+ expect(text).not.toContain("OS_PUBLIC_ORIGIN=");
+ });
+
+ 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"], {
+ 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://127.0.0.1:4555");
+ });
+});