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(domains): provision persistent managed-app subdomains from CLI

Abdurrahman Fakhrulda3ce4f69dfc
diff --git a/.env.example b/.env.example
index 9a862b85..d7de9b07 100644
--- a/.env.example
+++ b/.env.example
@@ -197,6 +197,13 @@ OS_SESSION_SECRET=
# HttpOnly cookie. Cockpit sessions remain host-only and are never sent to apps.
# Existing Domain sessions are invalidated; sign in again after upgrading.
# NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE={id}.mso.example.com
+# Configure DNS/tunnel automation once with: mso domain setup --user <user> --connection <cloudflare-connection> --apply
+# Then deploy the template and run: mso mapp enable 9router
+# Private persistent routing settings + receipts live outside the code checkout.
+# OS_MANAGED_DOMAINS_STORE=~/.mso/private/managed-domains.json
+# Advanced local CLI transport; mso domain normally derives these from its selected env and port.
+# MSO_DOMAIN_ENV=/absolute/path/to/.env.local
+# MSO_DOMAIN_LOCAL_ORIGIN=http://127.0.0.1:4005
# OS_SESSION_COOKIE_DOMAIN is obsolete; retained only to clear legacy cookies.
# OS_SESSION_COOKIE_DOMAIN=
diff --git a/bin/mso b/bin/mso
index 9e711813..4676dd74 100755
--- a/bin/mso
+++ b/bin/mso
@@ -57,6 +57,7 @@
# provider * Infrastructure credentials: list | set | rm | doctor
# providers * Alias for provider
# gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
+# domain * Automatic app subdomains: setup | status | ensure | doctor | repair-env | restore
# heartbeat [once|install-cron|remove-cron] Optional fallback health/recovery
# web Open the MSO browser UI (active gateway first, else loopback)
#
diff --git a/docs/9ROUTER-INTEGRATION.md b/docs/9ROUTER-INTEGRATION.md
index 68cd5278..dfee964c 100644
--- a/docs/9ROUTER-INTEGRATION.md
+++ b/docs/9ROUTER-INTEGRATION.md
@@ -4,7 +4,9 @@
future changes do not confuse its upstream npm CLI, Docker runtime, public access, and
optional MSO dashboard proxy.
-For the proposed default owner experience and the security conditions for using MSO as the sole browser login gate, see [`9ROUTER-MSO-APPHOST-RFC.md`](./9ROUTER-MSO-APPHOST-RFC.md).
+For automatic DNS, tunnel ingress, HTTPS checks and recovery, see
+[`MANAGED-DOMAINS.md`](./MANAGED-DOMAINS.md). The older
+[`9ROUTER-MSO-APPHOST-RFC.md`](./9ROUTER-MSO-APPHOST-RFC.md) remains historical design context.
## Distribution choice
@@ -54,16 +56,19 @@ public-IP URL is only the fallback for installations without a domain. An HTTP p
is not put in an HTTPS iframe because browsers block mixed content; in that fallback case MSO
opens the direct UI as a separate origin.
-A custom domain is optional. Hostinger/Cloudflare automation may later configure DNS/TLS,
-but it is not part of install health and must never be assumed to exist. If a domain already
+A custom domain is optional. Saved Cloudflare domain settings now reconcile DNS and tunnel
+ingress after install/update/start/restart; readiness requires verified public HTTPS and
+MSO authorization. Domain failures remain separate from runtime health. If a domain already
exists, set it explicitly instead of generating another hostname:
```dotenv
NINE_ROUTER_PUBLIC_URL=https://9-router.example.com
```
-Source precedence is: explicit HTTPS `NINE_ROUTER_PUBLIC_URL` → MSO split-origin host →
-direct `IP:20128` **only when `NINE_ROUTER_EXPOSE_PUBLIC=1`**. An explicit HTTPS app domain is framed directly because it is already a
+The managed-app API advertises a verified generated domain when available, followed by an
+explicit `NINE_ROUTER_PUBLIC_URL` or direct `IP:20128` **only when
+`NINE_ROUTER_EXPOSE_PUBLIC=1`**. The feature's existing explicit HTTPS app URL remains an
+embedding override because it is already a
separate origin; this also preserves the application's own origin-scoped browser session.
## Split-origin embedding when a domain is configured
@@ -72,12 +77,13 @@ When the deployment already has a domain, use the same explicit split-origin con
```dotenv
NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE={id}.mso.example.com
-OS_SESSION_COOKIE_DOMAIN=.mso.example.com
OS_PUBLIC_ORIGIN=https://mso.example.com
```
-Create only the explicit `9router.mso.example.com` DNS/TLS route and re-authenticate so the
-widened session cookie is actually issued. When this route exists, MSO prefers it over the
+Use `mso domain setup` once, deploy the template, then `mso mapp enable 9router`.
+Only the exact `9router.mso.example.com` DNS/TLS route is provisioned. Opening the app from
+MSO exchanges a short-lived app-bound ticket for a host-only app cookie. The cockpit cookie
+is never widened; `OS_SESSION_COOKIE_DOMAIN` is obsolete. MSO prefers a configured app host over the
public-IP fallback and renders the dashboard in-shell. A failing domain must still not make the
running 9Router runtime appear unavailable.
@@ -131,11 +137,10 @@ prove an upstream cloud firewall permits arbitrary external clients.
## Failure map
-- **Old standalone domain works, new `9router.mso...` does not**: 9Router itself is likely
- fine. Check direct public-IP access first. The new name is an MSO split-origin concern
- (DNS/TLS + cookie domain + re-login), not an application-health dependency.
-- **`401` only on the split-origin host**: verify the MSO session cookie was re-issued with
- the configured cookie domain; a curl without an authenticated cookie will also get 401.
+- **Old standalone domain works, new `9router.mso...` does not**: run
+ `mso domain doctor 9router`; the DNS/tunnel/HTTPS diagnosis is separate from application health.
+- **`401` on an anonymous split-origin request**: expected. Open the application from MSO
+ to exchange a fresh app ticket; cockpit cookies do not authorize the app hostname.
- **`/health` says 404**: expected endpoint is `/api/health`.
- **npm update fails with ownership errors after Docker use**: do not mix npm-owned runtime
updates with the Docker-managed `~/.9router` server state. Keep Docker as the VPS owner.
diff --git a/docs/9ROUTER-MSO-APPHOST-RFC.md b/docs/9ROUTER-MSO-APPHOST-RFC.md
index 95268c55..5dae7f84 100644
--- a/docs/9ROUTER-MSO-APPHOST-RFC.md
+++ b/docs/9ROUTER-MSO-APPHOST-RFC.md
@@ -1,6 +1,6 @@
# 9Router default MSO app-host: design note
-Status: proposal for the implementation agent. This note records an observed deployment failure mode and the security contract the default 9Router setup should converge on. It deliberately does not change production routing or authentication by itself.
+Status: historical proposal, retained as design evidence. Current automatic DNS/tunnel setup and recovery are documented in [MANAGED-DOMAINS.md](./MANAGED-DOMAINS.md); current authentication is in [MANAGED-APPS.md](./MANAGED-APPS.md). The cookie-domain expansion discussed below is obsolete: applications now exchange an app-bound ticket for a host-only app cookie. This note is not an instruction to widen cockpit cookies or migrate an existing public deployment.
## Problem observed
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 572d4211..a7180663 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
+- `domains` provision persistent managed-app subdomains from CLI
- `models` discover model ids from custom endpoints
**Docs**
diff --git a/docs/CLI.md b/docs/CLI.md
index 6947bd56..c1253bd4 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -97,6 +97,7 @@ Commands:
provider * Infrastructure credentials: list | set | rm | doctor
providers * Alias for provider
gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
+ domain * Automatic app subdomains: setup | status | ensure | doctor | repair-env | restore
heartbeat [once|install-cron|remove-cron] Optional fallback health/recovery
web Open the MSO browser UI (active gateway first, else loopback)
diff --git a/docs/MANAGED-APPS.md b/docs/MANAGED-APPS.md
index f3e89a91..24d2c2a8 100644
--- a/docs/MANAGED-APPS.md
+++ b/docs/MANAGED-APPS.md
@@ -47,7 +47,7 @@ Managed-app health probes refuse redirects rather than follow them away from loo
|---|---|---|---|---|
| Hermes | user systemd (`hermes-dashboard.service`, `hermes-gateway.service`) or pinned Docker fallback | `127.0.0.1:9119` by default | none by default | `~/.hermes` or `HERMES_HOME` |
| OpenClaw | user systemd (`openclaw-gateway.service`) | `127.0.0.1:18789` by default | none by default | `~/.openclaw` |
-| 9Router | Docker container `9router` | `127.0.0.1:20128` by default | `http://<public-ip>:20128` when the host has a global IPv4 | `~/.9router` mounted at `/app/data` |
+| 9Router | Docker container `9router` | `127.0.0.1:20128` by default | none by default; public-IP access requires explicit `NINE_ROUTER_EXPOSE_PUBLIC=1` | `~/.9router` mounted at `/app/data` |
Detection reads systemd first, then Docker/package evidence. If MSO cannot reach the user
systemd bus, it reports that uncertainty instead of silently treating a running app as
@@ -81,9 +81,8 @@ Opening a managed app first detects it:
The app surface can switch between **UI** and **CLI** where a UI is available. Hermes and
OpenClaw use their safe split-origin embedded dashboard when configured. 9Router follows the
same rule: **a configured application domain is the primary in-shell UI**. Its Docker runtime
-also publishes port `20128`, so MSO advertises the direct
-separate-origin URL and opens it in a dedicated browser tab. This requires no domain, DNS
-provider, wildcard record, or TLS configuration.
+publishes port `20128` on loopback by default. Only an explicit public-exposure choice allows
+MSO to advertise a direct separate-origin URL and open it in a dedicated browser tab.
When no domain is configured, MSO intentionally does not iframe `http://<public-ip>:20128` inside an HTTPS cockpit: browsers
block that as mixed content. It also does not proxy a vendor SPA under the cockpit origin,
@@ -139,8 +138,10 @@ same persisted job layer used for updates.
A domain is **not an install prerequisite** for lifecycle management. 9Router's dashboard is
loopback-only after install unless a configured URL/split-origin host exists or the operator
explicitly sets `NINE_ROUTER_EXPOSE_PUBLIC=1`. Domain-provider integrations
-(Cloudflare, Hostinger, etc.) are a separate optional concern and are not called by the
-managed-app installer.
+(Cloudflare initially) are optional. After a successful install/update job, and after
+start/restart actions, saved automatic domain settings trigger reconciliation. DNS failures
+are reported separately from application success. See [`MANAGED-DOMAINS.md`](./MANAGED-DOMAINS.md)
+for one-time setup, `mso mapp enable 9router`, status and recovery.
An optional model-provider API key can be supplied to app installers that support it. Keys
are passed through the child environment rather than persisted job argv/transcripts.
@@ -241,13 +242,15 @@ split-origin decision:
```dotenv
NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE={id}.mso.example.com
-OS_SESSION_COOKIE_DOMAIN=.mso.example.com
OS_PUBLIC_ORIGIN=https://mso.example.com
```
Then provision DNS/TLS only for managed-app hostnames you actually use (for the current
catalog: `hermes`, `openclaw`, and optionally `9router`). Each hostname is rewritten
exclusively into that app's proxy; cockpit pages/API/static chunks are not served there.
+`mso domain setup` persists these settings and activates automatic provisioning after the
+required deployment. App-bound tickets exchange for host-only app cookies;
+`OS_SESSION_COOKIE_DOMAIN` is obsolete and must not be widened for this flow.
```mermaid
flowchart LR
@@ -265,9 +268,8 @@ shared the cockpit origin, it would share the owner's browser realm/session. A s
hostname makes `window.top` cross-origin. There is no supported same-origin dashboard
fallback.
-Never map an arbitrary wildcard hostname to MSO under the session-cookie domain. Provision
-only explicit names you intend to serve. Setting the cookie domain without the matching host
-gating widens where the session credential is sent.
+Provision only explicit names you intend to serve. Unknown app namespace hosts are refused.
+The cockpit session stays host-only; app authorization rechecks live device authority.
## 10. 9Router distribution and ownership
@@ -296,7 +298,7 @@ the real secret verification.
- app says "not installed" but you know it exists → check systemd-user visibility/detection
evidence before rerunning an installer;
-- 9Router is healthy but its configured `*.mso...` host fails → diagnose DNS/TLS/session-cookie state; the runtime remains healthy and the explicitly enabled direct public-IP UI is the fallback;
+- 9Router is healthy but its configured app host fails → run `mso domain doctor 9router`; inspect DNS, tunnel, app-host activation and HTTPS separately;
- 9Router UI button has no public URL → `NINE_ROUTER_EXPOSE_PUBLIC` is unset/false (the safe
default), or the explicitly exposed host has no routable address on a local interface;
- dashboard frame missing but service is healthy → split-origin embedding may be absent by
diff --git a/docs/MANAGED-DOMAINS.md b/docs/MANAGED-DOMAINS.md
new file mode 100644
index 00000000..386965c7
--- /dev/null
+++ b/docs/MANAGED-DOMAINS.md
@@ -0,0 +1,175 @@
+# Automatic managed-application domains
+
+MSO can provision an exact subdomain when a managed application is installed,
+updated, started or restarted. Configure the domain once on the MSO host, then use:
+
+```bash
+mso mapp enable 9router
+```
+
+`enable` installs an absent application, waits for its persisted install job, and
+starts it through the existing managed-app API. It also works for `hermes` and
+`openclaw`. An installed application is retained. Install options such as
+`backend=docker` are accepted only when an installation is actually needed.
+
+## One-time setup
+
+The initial provider is Cloudflare. Use an existing Cloudflare zone and an existing
+tunnel already serving the MSO cockpit. Both remotely managed tunnels and named
+local tunnels owned by `mso gateway` are supported. The local adapter refuses a
+tunnel owned by another supervisor instead of adopting or migrating it.
+
+In local mode, both the connector's launch argument and its YAML `tunnel` field
+must identify the exact tunnel UUID. A launch using an unverified tunnel-name alias
+is refused. A route update waits for the replacement connector to register before
+retiring the previous one; it preserves the running MSO process and records enough
+identity information to recover an interrupted replacement safely.
+
+Choose an existing named integration user and Cloudflare connection. Enter the API
+token through MSO's private Integrations setup form; never pass a token to a domain
+command. The connection needs Zone Read, DNS Edit and Cloudflare Tunnel Edit for
+the selected zone/account. A connector runtime token alone does not grant DNS access.
+
+```bash
+mso integrations users
+mso integrations connections <user> cloudflare
+mso integrations setup <user> cloudflare <connection>
+
+# Preview the discovered zone, account, tunnel and public environment settings.
+mso domain setup --user <user> --connection <connection> \
+ --origin https://mso.example.com \
+ --template '{id}.mso.example.com'
+
+# Save the same setup and the two public environment settings.
+mso domain setup --user <user> --connection <connection> \
+ --origin https://mso.example.com \
+ --template '{id}.mso.example.com' --apply
+
+# Activate the build-time app host template through the supported deployment path.
+mso deploy
+mso mapp enable 9router
+```
+
+For a host with no active `mso.service`, use its supported offline update/rebuild
+path (`mso update --rebuild`) to activate the template. See
+[`DEVELOPMENT.md`](./DEVELOPMENT.md) and the gateway deployment contract.
+
+`--origin` defaults to `OS_PUBLIC_ORIGIN`. The template defaults to the existing
+`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE`, or `{id}.<cockpit-hostname>` when unset.
+The CLI resolves the configured MSO loopback port; `--local` can name another clean
+HTTP loopback origin. `--zone` pins a zone name/ID, and `--tunnel` supplies the UUID
+when the existing cockpit DNS cannot identify one unambiguously. Setup checks that
+the zone and tunnel belong to the same Cloudflare account.
+
+The domain commands are local owner operations. Run them on the intended MSO host;
+`--base`, `MSO_BASE` and `OS_BASE` are rejected to prevent editing a different machine.
+Application lifecycle commands continue to use the authenticated shared MSO API.
+
+## DNS, routes and HTTPS are separate
+
+For the template above, the 9Router hostname is `9router.mso.example.com`.
+MSO first confirms that hostname's ingress to the MSO loopback origin, then creates
+an exact proxied CNAME to `<tunnel-uuid>.cfargotunnel.com`. It does not route a new
+application hostname directly to the vendor container. Existing ingress rules,
+origin settings and the final catch-all are preserved. Conflicting DNS or ingress
+records are reported for operator review instead of being overwritten.
+
+Before any provider write, the running MSO server must prove it recognizes the
+selected app hostname and rejects anonymous app requests. After the route exists,
+MSO checks the app's loopback health and verifies the public HTTPS auth gate. A DNS
+record alone cannot make the result `ready`.
+
+Cloudflare Universal SSL on a full zone normally covers the apex and first-level
+subdomains. A nested name such as `9router.mso.example.com` needs a certificate
+covering that name, for example an appropriately issued `*.mso.example.com`
+certificate. A flat template such as `{id}-mso.example.com` stays at the first
+subdomain level. Cloudflare's Total TLS documentation excludes Tunnel hostnames;
+do not assume turning it on solves nested Tunnel certificates. MSO does not
+purchase certificates or subscriptions.
+
+Provider references:
+
+- [Universal SSL limitations](https://developers.cloudflare.com/ssl/edge-certificates/universal-ssl/limitations/)
+- [Total TLS](https://developers.cloudflare.com/ssl/edge-certificates/additional-options/total-tls/)
+- [Tunnel DNS routing](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/routing-to-tunnel/dns/)
+- [Remote Tunnel configuration API](https://developers.cloudflare.com/api/resources/zero_trust/subresources/tunnels/subresources/cloudflared/subresources/configurations/methods/update/)
+
+## Durable state and retries
+
+Setup and progress live outside the source checkout in
+`~/.mso/private/managed-domains.json`. `OS_MANAGED_DOMAINS_STORE` can explicitly
+override that path. The file is owner-only and contains public routing settings,
+named credential references, a stable ownership ID and per-app receipts. Provider
+tokens remain in Integrations.
+
+Writes use a cross-process lock, a temporary file and atomic rename. The last valid
+snapshot is kept in `managed-domains.json.previous`. A corrupt or unsafe state file
+is reported; it is never silently reset. Per-app operations also share a separate
+operation lock so simultaneous app starts cannot replace each other's tunnel rules.
+
+| Phase | Meaning |
+|---|---|
+| `pending` | Desired hostname recorded; provisioning not yet verified |
+| `route-ready` | Authenticated ingress confirmed; DNS may still need work |
+| `dns-ready` | Exact DNS record confirmed; app health and public HTTPS still need verification |
+| `ready` | App health, public HTTPS and anonymous access rejection passed at `verifiedAt` |
+| `blocked` | A stage failed; the diagnostic and completed DNS/route receipts are retained |
+
+`ready` is a timestamped verification, not a continuous uptime guarantee. A retry
+rechecks existing resources and repairs only the declared app route. A timeout,
+lost response or process restart does not require inventing a new hostname.
+
+```bash
+mso domain status
+mso domain doctor 9router
+mso domain ensure 9router # read-only checks/preview
+mso domain ensure 9router --apply # resume or reconcile
+```
+
+Automatic provisioning is enabled by setup. `--manual` saves the same settings but
+requires explicit `ensure --apply` calls. Install/update success remains an
+application result; a separate redacted domain diagnostic is kept in the job log
+and managed-app view. `mso mapp enable/start/restart` returns exit code 2 when that
+result needs domain attention. `mso domain ensure --apply` and `doctor` return 2
+when the domain is not ready; invalid commands, malformed state and setup errors
+return 1.
+
+## Recover unfinished configuration
+
+If setup saved the routing state but the environment update or deployment was
+interrupted, regenerate the public environment settings from the saved state:
+
+```bash
+mso domain repair-env
+mso domain repair-env --apply
+mso deploy # or the supported offline rebuild on a fallback host
+mso domain ensure 9router --apply
+```
+
+Only `OS_PUBLIC_ORIGIN` and `NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` are updated in
+the selected env file. Other settings and secrets are preserved. Their values are
+not printed. If the state file itself is corrupt or missing, preview and restore
+the last valid private snapshot:
+
+```bash
+mso domain restore
+mso domain restore --apply
+mso domain repair-env --apply
+```
+
+Changing an already saved zone, account, tunnel or hostname template is a migration.
+Setup refuses to silently rebind those resources. Preserve the existing routes and
+plan the migration explicitly. Stop/uninstall does not delete DNS, tunnel ingress,
+certificates or saved domain state.
+
+## Authentication and application prerequisites
+
+The browser opens an app through MSO and exchanges a short-lived, app-bound ticket
+for a host-only app cookie. `OS_SESSION_COOKIE_DOMAIN` is obsolete and is not part
+of setup. Cockpit cookies and provider credentials are never forwarded to the app.
+See [`MANAGED-APPS.md`](./MANAGED-APPS.md) for HTTP/WebSocket authorization.
+
+9Router still requires an accessible Docker daemon and remains loopback-bound by
+default. Domain automation cannot replace a missing application runtime, authorize
+a Cloudflare connection, or make a certificate cover a hostname. The diagnostic
+names the missing stage so setup can continue from the existing saved work.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 4adeed2b..8bd290e2 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,15 @@
+## 2026-10-17: Persist managed-app domains and provision them through the existing MSO gateway
+
+The earlier app-host RFC described the hostname and login boundary, but enabling an application did not own a complete DNS lifecycle or leave durable evidence when setup stopped halfway through. `mso domain setup` now discovers the existing Cloudflare zone, account and named tunnel through a selected MSO Integration. Its public routing configuration, ownership ID, per-app progress, resource receipts and last error live in a private versioned store outside the checkout. Writes are atomic, retain the previous valid snapshot and serialize operations across processes; malformed or unsafe state fails visibly instead of becoming an empty configuration. The environment editor preserves unrelated values, validates the file before saving setup, and supports explicit repair after an interrupted write.
+
+`mso mapp enable <id>` installs an absent managed app, waits for its existing job and starts it through the shared API. Successful install/update jobs and start/restart actions then use the same domain provisioner. Local runtime success remains visible if domain setup needs attention, while CLI exit 2 and persistent diagnostics identify that incomplete outcome. Status, doctor and preview commands do not create infrastructure; `ensure --apply` resumes the saved plan. Stopping or uninstalling an app does not silently delete its hostname.
+
+Provisioning first checks the deployed MSO app-host authorization gate, the selected provider identity and exact-name DNS conflicts. It establishes the authenticated MSO ingress before publishing a CNAME. Remote tunnel updates preserve unrelated configuration; locally configured tunnels use only the existing MSO-owned named-gateway lifecycle. Conflicting foreign records/routes and unsafe Host overrides are refused. A matching record can be reused without taking ownership, and a lost DNS write response is resolved by rereading before retrying. App health and public HTTPS/authentication are checked separately before recording `ready`. The cockpit and app retain their existing separate, host-only authorization cookies.
+
+Nested application names require a certificate covering those exact hosts. DNS creation is not presented as TLS success, and no paid certificate is purchased automatically. Current setup, repair and migration boundaries are documented in `docs/MANAGED-DOMAINS.md`; the old RFC is retained as historical context rather than an active setup recipe.
+
+Verification on the inspected fallback-runtime host found no Docker executable, daemon socket or configured remote Docker host. The existing mandatory Tool Forge sandbox tests therefore remain an environment prerequisite for release; no live DNS, application installation or deployment is claimed from candidate-only checks.
+
## 2026-10-17: Deploying on a host with no `mso.service`, and why `bun run ship` cannot finalize there
The custom-endpoint discovery below reached `main` at `5fc9a5f`, but `bun run ship` pushed and then failed its release finalizer: *"could not safely quiesce gateway runtime at http://127.0.0.1:4005"*. Two independent environment mismatches, both in the handoff's assumptions:
diff --git a/docs/README.md b/docs/README.md
index 788e193a..47c73f8f 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -65,6 +65,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`PLUGIN-REFERENCE-MATRIX.md`](./PLUGIN-REFERENCE-MATRIX.md) | Living cross-plugin architecture matrix, audit decisions and candidate generic primitives |
| [`CONNECTED-APPS.md`](./CONNECTED-APPS.md) | Server-persisted external app connections, dynamic shell windows and lifecycle boundaries |
| [`MANAGED-APPS.md`](./MANAGED-APPS.md) | Hermes/OpenClaw/9Router lifecycle, jobs, backup/restore and dashboard access boundary |
+| [`MANAGED-DOMAINS.md`](./MANAGED-DOMAINS.md) | Automatic app DNS/tunnel routes, named Integrations, HTTPS verification and durable setup recovery |
| [`HERMES-INTEGRATION.md`](./HERMES-INTEGRATION.md) | Hermes-specific integration behaviour |
| [`OPENCLAW-INTEGRATION.md`](./OPENCLAW-INTEGRATION.md) | OpenClaw-specific integration behaviour |
| [`9ROUTER-INTEGRATION.md`](./9ROUTER-INTEGRATION.md) | 9Router immutable Docker ownership, loopback default and explicit dashboard exposure |
@@ -81,7 +82,6 @@ evidence and review freshness. The repository quality gate runs both automatical
| Document | Status |
|---|---|
-| [`9ROUTER-MSO-APPHOST-RFC.md`](./9ROUTER-MSO-APPHOST-RFC.md) | Proposed MSO-protected 9Router app host, single-login boundary and migration criteria; implementation remains pending |
| [`EXTERNAL-FEATURE-CONTRACT.md`](./EXTERNAL-FEATURE-CONTRACT.md) | v1 target contract for modular shell/external features; implementation status is explicit |
| [`TENANT-PREVIEW.md`](./TENANT-PREVIEW.md) | Disabled identity and scoped-memory runtime; live activation and full production isolation remain unimplemented |
| [`TENANT-PERSISTENCE.md`](./TENANT-PERSISTENCE.md) | Source-only durable registry, scoped memory and audit; transactions, recovery limits and operational gates |
@@ -106,6 +106,7 @@ source comments. They are **not current implementation contracts**.
| Document | Status |
|---|---|
| [`EXTERNAL-FEATURE-AUDIT-2026-09-27.md`](./EXTERNAL-FEATURE-AUDIT-2026-09-27.md) | Registry/manifest/embed source audit at 330d0cb4; migration phases remain pending |
+| [`9ROUTER-MSO-APPHOST-RFC.md`](./9ROUTER-MSO-APPHOST-RFC.md) | Historical app-host proposal; current setup/authentication contract is in MANAGED-DOMAINS and MANAGED-APPS |
| [`AUDIT-2026-08-24.md`](./AUDIT-2026-08-24.md) | Fable/Ultracode + dynamic security audit at its named commit; includes reproduced findings and release remediation |
| [`AUDIT-2026-06-11.md`](./AUDIT-2026-06-11.md) | Archived audit at its named date; later fixes changed many findings |
| [`SHELL-FIDELITY-PLAN.md`](./SHELL-FIDELITY-PLAN.md) | Historical design backlog/baseline; current shell design lives in code + architecture |
diff --git a/lib/contracts/managed-domains.ts b/lib/contracts/managed-domains.ts
new file mode 100644
index 00000000..33f31d6b
--- /dev/null
+++ b/lib/contracts/managed-domains.ts
@@ -0,0 +1,53 @@
+export interface ManagedDomainConfig {
+ publicOrigin: string;
+ hostTemplate: string;
+ localOrigin: string;
+ zoneId: string;
+ zoneName: string;
+ accountId: string;
+ tunnelId: string;
+ user: string;
+ connection: string;
+ autoProvision: boolean;
+ routeMode?: "remote" | "mso-gateway";
+}
+
+export type ManagedDomainPhase = "pending" | "dns-ready" | "route-ready" | "ready" | "blocked";
+
+export interface ManagedDomainRecord {
+ appId: string;
+ hostname: string;
+ phase: ManagedDomainPhase;
+ dnsRecordId?: string;
+ dnsAction?: "created" | "updated" | "unchanged";
+ routeAction?: "created" | "unchanged";
+ error?: string;
+ verifiedAt?: number;
+ updatedAt: number;
+}
+
+export interface ManagedDomainState {
+ version: 1;
+ revision: number;
+ ownerId: string;
+ config: ManagedDomainConfig | null;
+ apps: Record<string, ManagedDomainRecord>;
+}
+
+export interface ManagedDomainRoute {
+ hostname: string;
+ hostTemplate?: string;
+ cockpitHostname: string;
+ localOrigin: string;
+ zoneId: string;
+ zoneName: string;
+ accountId: string;
+ tunnelId: string;
+ ownerTag: string;
+ routeMode?: "remote" | "mso-gateway";
+}
+
+export interface ManagedDomainDnsResult {
+ id: string;
+ action: "created" | "updated" | "unchanged";
+}
diff --git a/lib/infra/managed-domain-client.ts b/lib/infra/managed-domain-client.ts
new file mode 100644
index 00000000..a64f7325
--- /dev/null
+++ b/lib/infra/managed-domain-client.ts
@@ -0,0 +1,70 @@
+import type { ManagedDomainRoute } from "@/lib/contracts/managed-domains";
+import { obj, request } from "./http";
+import { readInfraProvider } from "./store";
+
+const API = "https://api.cloudflare.com/client/v4";
+const ID = /^[a-f0-9]{32}$/i;
+const UUID = /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i;
+const HOST = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;
+
+export const domainName = (value: unknown): string => String(value ?? "").toLowerCase().replace(/\.$/, "");
+export type CloudflareDomainClient = {
+ tunnelPath: string;
+ call: (resource: string, label: string, init?: RequestInit) => Promise<Record<string, unknown>>;
+};
+
+export function managedDomainOrigin(value: unknown): string {
+ const url = new URL(String(value));
+ if (url.protocol !== "http:" || !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) || !url.port
+ || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
+ throw new Error("managed domain origin must be the loopback MSO HTTP service with an explicit port");
+ }
+ return url.origin;
+}
+
+export async function managedDomainClient(input: ManagedDomainRoute): Promise<CloudflareDomainClient> {
+ for (const name of [input.hostname, input.cockpitHostname, input.zoneName]) {
+ if (!HOST.test(name) || name !== domainName(name)) throw new Error("managed domain hostnames must be normalized DNS names");
+ }
+ if (!ID.test(input.zoneId) || !ID.test(input.accountId) || !UUID.test(input.tunnelId)) throw new Error("invalid Cloudflare zone, account or tunnel identifier");
+ if (input.hostname === input.cockpitHostname) throw new Error("an app domain cannot replace the MSO cockpit hostname");
+ if (!input.hostname.endsWith(`.${input.zoneName}`)
+ || !(input.cockpitHostname === input.zoneName || input.cockpitHostname.endsWith(`.${input.zoneName}`))) {
+ throw new Error("managed domain and cockpit must belong to the selected Cloudflare zone");
+ }
+ if (input.ownerTag.length > 500 || !/^mso:[a-z0-9-]+:[a-z0-9-]+$/.test(input.ownerTag)) throw new Error("invalid managed DNS ownership marker");
+ managedDomainOrigin(input.localOrigin);
+ const values = await readInfraProvider("cloudflare");
+ if (!values.apiToken) throw new Error("Cloudflare connection is not configured; complete its private setup in MSO Integrations");
+ if (values.zoneId && values.zoneId !== input.zoneId || values.accountId && values.accountId !== input.accountId) {
+ throw new Error("managed domain target differs from the selected Cloudflare connection");
+ }
+ const headers = { authorization: `Bearer ${values.apiToken}`, accept: "application/json", "content-type": "application/json" };
+ return {
+ tunnelPath: `/accounts/${encodeURIComponent(input.accountId)}/cfd_tunnel/${encodeURIComponent(input.tunnelId)}`,
+ async call(resource, label, init = {}) {
+ let response;
+ try { response = await request(`${API}${resource}`, { ...init, headers }); }
+ catch { throw new Error(`Cloudflare ${label} request failed; inspect connectivity and retry`); }
+ const body = obj(response.body);
+ if (!response.ok || body.success !== true) throw new Error(`Cloudflare ${label} HTTP ${response.status}`);
+ return body;
+ },
+ };
+}
+
+export async function inspectManagedDomainIdentity(client: CloudflareDomainClient, input: ManagedDomainRoute): Promise<"remote" | "mso-gateway"> {
+ const zone = obj((await client.call(`/zones/${encodeURIComponent(input.zoneId)}`, "zone inspection")).result);
+ if (zone.id !== input.zoneId || domainName(zone.name) !== input.zoneName || obj(zone.account).id !== input.accountId) {
+ throw new Error("Cloudflare zone ID, name and account do not match the managed domain configuration");
+ }
+ if (zone.status !== undefined && zone.status !== "active") throw new Error("selected Cloudflare zone is not active");
+ const tunnel = obj((await client.call(client.tunnelPath, "tunnel inspection")).result);
+ if (tunnel.id !== input.tunnelId || tunnel.deleted_at) throw new Error("selected Cloudflare tunnel is missing, deleted or mismatched");
+ const mode = tunnel.config_src === "cloudflare" ? "remote" : tunnel.config_src === "local" ? "mso-gateway" : null;
+ if (!mode) throw new Error("Cloudflare tunnel configuration source is unknown");
+ if (mode !== (input.routeMode ?? "remote")) {
+ throw new Error(`Cloudflare tunnel config_src=${String(tunnel.config_src)} requires ${mode} routing; run domain setup to inspect the existing owner without migrating the tunnel`);
+ }
+ return mode;
+}
diff --git a/lib/infra/managed-domain-dns.test.ts b/lib/infra/managed-domain-dns.test.ts
new file mode 100644
index 00000000..f15bdfd2
--- /dev/null
+++ b/lib/infra/managed-domain-dns.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it, vi } from "vitest";
+import type { ManagedDomainRoute } from "@/lib/contracts/managed-domains";
+import { inspectManagedDomainDns, reconcileManagedDomainDns } from "./managed-domain-dns";
+
+const input: ManagedDomainRoute = {
+ hostname: "9router.example.com", cockpitHostname: "mso.example.com", localOrigin: "http://127.0.0.1:4005",
+ zoneId: "a".repeat(32), zoneName: "example.com", accountId: "b".repeat(32),
+ tunnelId: "11111111-2222-3333-4444-555555555555", ownerTag: "mso:owner:9router",
+};
+const recordId = "d".repeat(32);
+const desired = { id: recordId, type: "CNAME", name: input.hostname,
+ content: `${input.tunnelId}.cfargotunnel.com`, proxied: true, ttl: 1, comment: input.ownerTag };
+
+function fixture(initial: Record<string, unknown>[] = []) {
+ let records = structuredClone(initial);
+ let pages = 1, loseWriteResponse = false, refuseWrite = false;
+ const call = vi.fn(async (_resource: string, _label: string, init: RequestInit = {}) => {
+ if (!init.method) return { result: structuredClone(records), result_info: { total_pages: pages } };
+ if (refuseWrite) throw new Error("Cloudflare DNS POST HTTP 403");
+ records = [{ ...records[0], id: recordId, ...JSON.parse(String(init.body)) }];
+ if (loseWriteResponse) throw new Error("network response lost");
+ return { result: structuredClone(records[0]) };
+ });
+ return { client: { call, tunnelPath: "/unused" }, call, get records() { return records; },
+ setPages(value: number) { pages = value; }, loseResponse() { loseWriteResponse = true; }, denyWrite() { refuseWrite = true; } };
+}
+
+describe("managed domain DNS ownership and retries", () => {
+ it("creates one owned proxied CNAME and repeated ensure performs no extra write", async () => {
+ const f = fixture();
+ expect(await reconcileManagedDomainDns(f.client, input)).toEqual({ id: recordId, action: "created" });
+ expect(await reconcileManagedDomainDns(f.client, input)).toEqual({ id: recordId, action: "unchanged" });
+ expect(f.records).toEqual([desired]);
+ expect(f.call.mock.calls.filter(([, , init]) => init?.method)).toHaveLength(1);
+ expect(f.call.mock.calls[0][0]).toContain("?name.exact=9router.example.com&per_page=100");
+ expect(f.call.mock.calls[0][0]).not.toContain("type=CNAME");
+ });
+
+ it("reuses an exact existing foreign CNAME without claiming ownership", async () => {
+ const f = fixture([{ ...desired, comment: "managed elsewhere", content: `${desired.content}.` }]);
+ await expect(reconcileManagedDomainDns(f.client, input)).resolves.toEqual({ id: recordId, action: "unchanged" });
+ expect(f.records[0].comment).toBe("managed elsewhere");
+ expect(f.call.mock.calls.every(([, , init]) => !init?.method)).toBe(true);
+ });
+
+ it.each([
+ { ...desired, type: "A", content: "192.0.2.1" },
+ { ...desired, type: "TXT", content: "already occupied" },
+ { ...desired, content: "foreign.example.net", comment: "someone else" },
+ { ...desired, proxied: false, comment: undefined },
+ ])("refuses occupied or foreign DNS settings without mutation", async record => {
+ const f = fixture([record]);
+ await expect(inspectManagedDomainDns(f.client, input)).rejects.toThrow("DNS conflict");
+ await expect(reconcileManagedDomainDns(f.client, input)).rejects.toThrow("DNS conflict");
+ expect(f.call.mock.calls.every(([, , init]) => !init?.method)).toBe(true);
+ });
+
+ it("updates only this app's owned CNAME and preserves unrelated record fields", async () => {
+ const f = fixture([{ ...desired, content: "old.cfargotunnel.com", proxied: false, tags: ["retained:yes"] }]);
+ await expect(reconcileManagedDomainDns(f.client, input)).resolves.toEqual({ id: recordId, action: "updated" });
+ expect(f.records[0]).toEqual({ ...desired, tags: ["retained:yes"] });
+ const mutation = f.call.mock.calls.find(([, , init]) => init?.method);
+ expect(mutation?.[0].endsWith(`/${recordId}`)).toBe(true);
+ expect(mutation?.[2]?.method).toBe("PATCH");
+ });
+
+ it("recovers an acknowledged-late POST by rereading instead of posting again", async () => {
+ const f = fixture(); f.loseResponse();
+ await expect(reconcileManagedDomainDns(f.client, input)).resolves.toEqual({ id: recordId, action: "unchanged" });
+ expect(f.call.mock.calls.filter(([, , init]) => init?.method)).toHaveLength(1);
+ });
+
+ it("propagates failed writes when the desired owned record was not created", async () => {
+ const f = fixture(); f.denyWrite();
+ await expect(reconcileManagedDomainDns(f.client, input)).rejects.toThrow("HTTP 403");
+ expect(f.records).toEqual([]);
+ });
+
+ it("rejects duplicate and incomplete lookup results before any mutation", async () => {
+ const duplicate = fixture([desired, { ...desired, id: "another" }]);
+ await expect(reconcileManagedDomainDns(duplicate.client, input)).rejects.toThrow("multiple records");
+ const truncated = fixture(); truncated.setPages(2);
+ await expect(reconcileManagedDomainDns(truncated.client, input)).rejects.toThrow("incomplete");
+ expect([...duplicate.call.mock.calls, ...truncated.call.mock.calls].every(([, , init]) => !init?.method)).toBe(true);
+ });
+
+ it("rejects malformed provider IDs before they can enter durable state", async () => {
+ const f = fixture([{ ...desired, id: "not-a-cloudflare-id" }]);
+ await expect(reconcileManagedDomainDns(f.client, input)).rejects.toThrow("identifier");
+ expect(f.call.mock.calls.every(([, , init]) => !init?.method)).toBe(true);
+ });
+});
diff --git a/lib/infra/managed-domain-dns.ts b/lib/infra/managed-domain-dns.ts
new file mode 100644
index 00000000..d5ea45f8
--- /dev/null
+++ b/lib/infra/managed-domain-dns.ts
@@ -0,0 +1,61 @@
+import type { ManagedDomainDnsResult, ManagedDomainRoute } from "@/lib/contracts/managed-domains";
+import { obj } from "./http";
+import { domainName, type CloudflareDomainClient } from "./managed-domain-client";
+
+type DnsRecord = Record<string, unknown> & { id: string };
+const dnsPath = (input: ManagedDomainRoute) => `/zones/${encodeURIComponent(input.zoneId)}/dns_records`;
+const target = (input: ManagedDomainRoute) => `${input.tunnelId}.cfargotunnel.com`;
+const matches = (record: DnsRecord, input: ManagedDomainRoute) => record.type === "CNAME"
+ && domainName(record.content) === target(input) && record.proxied === true;
+
+async function readRecord(client: CloudflareDomainClient, input: ManagedDomainRoute): Promise<DnsRecord | null> {
+ const data = await client.call(`${dnsPath(input)}?name.exact=${encodeURIComponent(input.hostname)}&per_page=100`, "exact DNS lookup");
+ if (!Array.isArray(data.result)) throw new Error("Cloudflare DNS lookup returned an invalid record list");
+ const pages = Number(obj(data.result_info).total_pages ?? 1);
+ if (!Number.isFinite(pages) || pages > 1 || data.result.length >= 100) throw new Error("Cloudflare DNS lookup is incomplete; refusing a partial ownership check");
+ const records = data.result.map(obj);
+ if (records.some(record => domainName(record.name) !== input.hostname)) throw new Error("Cloudflare exact DNS lookup returned another hostname");
+ if (records.length > 1) throw new Error(`DNS conflict: multiple records occupy ${input.hostname}`);
+ if (!records.length) return null;
+ const record = records[0];
+ if (typeof record.id !== "string" || !/^[a-f0-9]{32}$/.test(record.id)) throw new Error("Cloudflare DNS record has no usable identifier");
+ return record as DnsRecord;
+}
+
+function assertCompatible(record: DnsRecord | null, input: ManagedDomainRoute): void {
+ if (!record) return;
+ if (record.type !== "CNAME") throw new Error(`DNS conflict: ${input.hostname} already has a non-CNAME record`);
+ if (!matches(record, input) && record.comment !== input.ownerTag) {
+ throw new Error(`DNS conflict: ${input.hostname} is not owned by this MSO app; its target and proxy settings were preserved`);
+ }
+}
+
+export async function inspectManagedDomainDns(client: CloudflareDomainClient, input: ManagedDomainRoute): Promise<void> {
+ assertCompatible(await readRecord(client, input), input);
+}
+
+export async function reconcileManagedDomainDns(client: CloudflareDomainClient, input: ManagedDomainRoute): Promise<ManagedDomainDnsResult> {
+ const current = await readRecord(client, input);
+ assertCompatible(current, input);
+ if (current && matches(current, input)) return { id: current.id, action: "unchanged" };
+ const payload = { type: "CNAME", name: input.hostname, content: target(input), proxied: true, ttl: 1, comment: input.ownerTag };
+ const action = current ? "updated" : "created";
+ let receipt;
+ try {
+ receipt = obj((await client.call(current ? `${dnsPath(input)}/${encodeURIComponent(current.id)}` : dnsPath(input),
+ `DNS ${current ? "PATCH" : "POST"}`, { method: current ? "PATCH" : "POST", body: JSON.stringify(payload) })).result);
+ } catch (error) {
+ // A timed-out write can already be committed remotely; never repeat it blindly.
+ const observed = await readRecord(client, input).catch(() => null);
+ if (observed && matches(observed, input) && observed.comment === input.ownerTag) {
+ return { id: observed.id, action: "unchanged" };
+ }
+ throw error;
+ }
+ const observed = await readRecord(client, input);
+ if (!observed || !matches(observed, input) || observed.comment !== input.ownerTag
+ || typeof receipt.id !== "string" || receipt.id !== observed.id || current && current.id !== observed.id) {
+ throw new Error("Cloudflare DNS write could not be verified; retry to reconcile the existing record");
+ }
+ return { id: observed.id, action };
+}
diff --git a/lib/infra/managed-domain-gateway.ts b/lib/infra/managed-domain-gateway.ts
new file mode 100644
index 00000000..c71a58eb
--- /dev/null
+++ b/lib/infra/managed-domain-gateway.ts
@@ -0,0 +1,33 @@
+import { execFile } from "node:child_process";
+import path from "node:path";
+import { promisify } from "node:util";
+import type { ManagedDomainRoute } from "@/lib/contracts/managed-domains";
+import { childEnv } from "@/lib/host/child-env";
+import { redactText } from "@/lib/security/redact-text";
+
+const execute = promisify(execFile);
+
+async function gatewayRoute(action: "inspect" | "ensure", input: ManagedDomainRoute): Promise<{ action: "created" | "unchanged" }> {
+ try {
+ const result = await execute(path.join(process.cwd(), "scripts", "mso-gateway"), ["app-route", action, input.hostname, input.tunnelId], {
+ cwd: process.cwd(), encoding: "utf8", timeout: 120_000, maxBuffer: 64 * 1024,
+ env: { ...(childEnv() as NodeJS.ProcessEnv), MSO_GATEWAY_ROOT: process.cwd(), MSO_GATEWAY_ENV: process.env.MSO_DOMAIN_ENV ?? path.join(process.cwd(), ".env.local"), MSO_GATEWAY_LOCAL_URL: input.localOrigin,
+ MSO_GATEWAY_EXPECT_PUBLIC_ORIGIN: `https://${input.cockpitHostname}`,
+ MSO_GATEWAY_EXPECT_APP_HOST_TEMPLATE: input.hostTemplate ?? "",
+ },
+ });
+ const value = JSON.parse(result.stdout);
+ if (value.hostname !== input.hostname || value.tunnelId !== input.tunnelId || !["created", "unchanged"].includes(value.action)) throw new Error("gateway returned an invalid app-route receipt");
+ return { action: value.action };
+ } catch (error) {
+ const detail = error as Error & { stderr?: string };
+ throw new Error(`MSO-owned named tunnel: ${redactText(detail.stderr?.trim() || detail.message || "route operation failed", 512)}`);
+ }
+}
+
+export async function inspectManagedDomainGateway(input: ManagedDomainRoute): Promise<void> {
+ await gatewayRoute("inspect", input);
+}
+export function ensureManagedDomainGateway(input: ManagedDomainRoute): Promise<{ action: "created" | "unchanged" }> {
+ return gatewayRoute("ensure", input);
+}
diff --git a/lib/infra/managed-domain-route.test.ts b/lib/infra/managed-domain-route.test.ts
new file mode 100644
index 00000000..0146cbee
--- /dev/null
+++ b/lib/infra/managed-domain-route.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it, vi } from "vitest";
+import type { ManagedDomainRoute } from "@/lib/contracts/managed-domains";
+import { inspectRemoteManagedDomain, reconcileRemoteManagedDomain } from "./managed-domain-route";
+
+const input: ManagedDomainRoute = {
+ hostname: "9router.example.com", cockpitHostname: "mso.example.com", localOrigin: "http://127.0.0.1:4005",
+ zoneId: "a".repeat(32), zoneName: "example.com", accountId: "b".repeat(32),
+ tunnelId: "11111111-2222-3333-4444-555555555555", ownerTag: "mso:owner:9router",
+};
+const cockpit = { hostname: input.cockpitHostname, service: input.localOrigin, originRequest: { connectTimeout: 20 } };
+const app = { ...cockpit, hostname: input.hostname };
+const terminal = { service: "http_status:404" };
+const original = { ingress: [cockpit, { hostname: "other.example.com", service: "http://127.0.0.1:8080" },
+ { hostname: "*.example.com", service: "http://127.0.0.1:9090" }, terminal], originRequest: { tcpKeepAlive: 30 }, "warp-routing": { enabled: true } };
+
+function fixture(config: Record<string, unknown> = original) {
+ let saved = structuredClone(config);
+ let corruptAfterWrite = false, reorderKeys = false;
+ const call = vi.fn(async (_resource: string, _label: string, init: RequestInit = {}) => {
+ if (init.method) {
+ saved = JSON.parse(String(init.body)).config;
+ if (corruptAfterWrite) saved["warp-routing"] = { enabled: false };
+ }
+ const observed = reorderKeys ? Object.fromEntries(Object.entries(saved).reverse()) : saved;
+ return { result: { config: structuredClone(observed), source: "cloudflare", tunnel_id: input.tunnelId } };
+ });
+ return { client: { call, tunnelPath: "/accounts/account/cfd_tunnel/tunnel" }, call,
+ get config() { return saved; }, concurrentChange() { corruptAfterWrite = true; }, reorder() { reorderKeys = true; } };
+}
+
+describe("managed domain tunnel route reconciliation", () => {
+ it("inserts before wildcard, preserves unrelated settings, and is idempotent", async () => {
+ const f = fixture();
+ await expect(reconcileRemoteManagedDomain(f.client, input)).resolves.toEqual({ action: "created" });
+ expect(f.config).toEqual({ ...original, ingress: [original.ingress[0], original.ingress[1], app, original.ingress[2], terminal] });
+ await expect(reconcileRemoteManagedDomain(f.client, input)).resolves.toEqual({ action: "unchanged" });
+ expect(f.call.mock.calls.filter(([, , init]) => init?.method)).toHaveLength(1);
+ expect(f.call.mock.calls.find(([, , init]) => init?.method)?.[2]?.method).toBe("PUT");
+ });
+
+ it("copies cockpit transport options while adapting its explicit Host header", async () => {
+ const f = fixture({ ingress: [{ ...cockpit, originRequest: { connectTimeout: 20, httpHostHeader: input.cockpitHostname } }, terminal] });
+ await reconcileRemoteManagedDomain(f.client, input);
+ expect((f.config.ingress as Record<string, unknown>[])[1]).toEqual({ ...app,
+ originRequest: { connectTimeout: 20, httpHostHeader: input.hostname } });
+ });
+
+ it("accepts provider JSON key reordering while preserving ingress order", async () => {
+ const f = fixture(); f.reorder();
+ await expect(reconcileRemoteManagedDomain(f.client, input)).resolves.toEqual({ action: "created" });
+ });
+
+ it.each([
+ { ingress: [{ ...cockpit, service: "http://127.0.0.1:9000" }, terminal] },
+ { ingress: [{ ...cockpit, path: "/dashboard" }, terminal] },
+ { ingress: [cockpit, cockpit, terminal] },
+ { ingress: [{ hostname: "*.example.com", service: input.localOrigin }, cockpit, terminal] },
+ { ingress: [terminal, cockpit] },
+ { ingress: [cockpit] },
+ { ingress: [cockpit, { ...app, service: "http://127.0.0.1:20128" }, terminal] },
+ { ingress: [cockpit, { ...app, path: "/dashboard" }, terminal] },
+ { ingress: [cockpit, app, { ...app, path: "/api" }, terminal] },
+ ])("refuses mismatched, shadowed or ambiguous existing routes", async config => {
+ const f = fixture(config);
+ await expect(inspectRemoteManagedDomain(f.client, input)).rejects.toThrow();
+ expect(f.call.mock.calls.every(([, , init]) => !init?.method)).toBe(true);
+ });
+
+ it.each([
+ { ingress: [cockpit, terminal], originRequest: { httpHostHeader: input.cockpitHostname } },
+ { ingress: [{ ...cockpit, originRequest: { httpHostHeader: "wrong.example.com" } }, terminal] },
+ { ingress: [cockpit, { ...app, originRequest: { httpHostHeader: input.cockpitHostname } }, terminal] },
+ ])("refuses origin Host overrides that would defeat the app auth router", async config => {
+ const f = fixture(config);
+ await expect(inspectRemoteManagedDomain(f.client, input)).rejects.toThrow("httpHostHeader");
+ expect(f.call.mock.calls.every(([, , init]) => !init?.method)).toBe(true);
+ });
+
+ it("detects an unrelated concurrent change in the full configuration reread", async () => {
+ const f = fixture(); f.concurrentChange();
+ await expect(reconcileRemoteManagedDomain(f.client, input)).rejects.toThrow("changed during verification");
+ expect(f.call.mock.calls.filter(([, , init]) => init?.method)).toHaveLength(1);
+ });
+});
diff --git a/lib/infra/managed-domain-route.ts b/lib/infra/managed-domain-route.ts
new file mode 100644
index 00000000..63963a08
--- /dev/null
+++ b/lib/infra/managed-domain-route.ts
@@ -0,0 +1,83 @@
+import { isDeepStrictEqual } from "node:util";
+import type { ManagedDomainRoute } from "@/lib/contracts/managed-domains";
+import { obj } from "./http";
+import { domainName, managedDomainOrigin, type CloudflareDomainClient } from "./managed-domain-client";
+
+type Rule = Record<string, unknown>;
+type Snapshot = { config: Record<string, unknown>; ingress: Rule[]; cockpit: Rule; targetIndex: number };
+
+function matchesHost(rule: Rule, hostname: string): boolean {
+ if (!rule.hostname || rule.hostname === "*") return true;
+ const name = domainName(rule.hostname);
+ return name === hostname || name.startsWith("*.") && hostname.endsWith(name.slice(1));
+}
+
+function assertService(rule: Rule, input: ManagedDomainRoute, label: string): void {
+ let service;
+ try { service = managedDomainOrigin(rule.service); } catch { /* A foreign service is a route conflict. */ }
+ if (service !== managedDomainOrigin(input.localOrigin)) throw new Error(`${label} route does not point to the configured loopback MSO origin`);
+}
+
+function assertHostHeader(rule: Rule, config: Record<string, unknown>, hostname: string): void {
+ const header = obj(rule.originRequest).httpHostHeader ?? obj(config.originRequest).httpHostHeader;
+ if (header !== undefined && header !== "" && domainName(header) !== hostname) {
+ throw new Error(`Tunnel originRequest.httpHostHeader would replace ${hostname}; correct that override before provisioning`);
+ }
+}
+
+function singleHostRule(ingress: Rule[], hostname: string, required: boolean): number {
+ const indices = ingress.flatMap((rule, index) => domainName(rule.hostname) === hostname ? [index] : []);
+ if (indices.length > 1 || indices.some(index => Boolean(ingress[index].path))) throw new Error(`Tunnel route for ${hostname} is ambiguous or path-limited`);
+ if (!indices.length) {
+ if (required) throw new Error("the existing MSO cockpit must have one explicit whole-host tunnel route");
+ return -1;
+ }
+ const index = indices[0];
+ if (ingress.slice(0, index).some(rule => matchesHost(rule, hostname))) throw new Error(`Tunnel route for ${hostname} is shadowed by an earlier rule`);
+ return index;
+}
+
+export async function inspectRemoteManagedDomain(client: CloudflareDomainClient, input: ManagedDomainRoute): Promise<Snapshot> {
+ const result = obj((await client.call(`${client.tunnelPath}/configurations`, "tunnel configuration read")).result);
+ if (result.source !== undefined && result.source !== "cloudflare" || result.tunnel_id !== undefined && result.tunnel_id !== input.tunnelId) {
+ throw new Error("Cloudflare tunnel configuration identity or source changed");
+ }
+ const config = obj(result.config);
+ if (!Array.isArray(config.ingress) || !config.ingress.length) throw new Error("Cloudflare tunnel has no valid ingress configuration");
+ const ingress = config.ingress.map(obj);
+ if (ingress.some(rule => typeof rule.service !== "string" || !rule.service)) throw new Error("Cloudflare tunnel contains an invalid ingress rule");
+ const last = ingress[ingress.length - 1];
+ if (last.hostname || last.path || ingress.slice(0, -1).some(rule => !rule.hostname && !rule.path)) {
+ throw new Error("Cloudflare tunnel catch-all must be the final ingress rule");
+ }
+ const cockpitIndex = singleHostRule(ingress, input.cockpitHostname, true);
+ const cockpit = ingress[cockpitIndex];
+ assertService(cockpit, input, "MSO cockpit");
+ assertHostHeader(cockpit, config, input.cockpitHostname);
+ const targetIndex = singleHostRule(ingress, input.hostname, false);
+ if (targetIndex >= 0) {
+ assertService(ingress[targetIndex], input, "Existing app");
+ assertHostHeader(ingress[targetIndex], config, input.hostname);
+ } else {
+ assertHostHeader({}, config, input.hostname);
+ }
+ return { config, ingress, cockpit, targetIndex };
+}
+
+export async function reconcileRemoteManagedDomain(client: CloudflareDomainClient, input: ManagedDomainRoute): Promise<{ action: "created" | "unchanged" }> {
+ const before = await inspectRemoteManagedDomain(client, input);
+ if (before.targetIndex >= 0) return { action: "unchanged" };
+ const ingress = [...before.ingress];
+ const originRequest = { ...obj(before.cockpit.originRequest) };
+ if (originRequest.httpHostHeader) originRequest.httpHostHeader = input.hostname;
+ const route = { ...before.cockpit, hostname: input.hostname, ...(before.cockpit.originRequest ? { originRequest } : {}) };
+ const firstMatch = ingress.findIndex(rule => matchesHost(rule, input.hostname));
+ ingress.splice(firstMatch, 0, route);
+ const config = { ...before.config, ingress };
+ await client.call(`${client.tunnelPath}/configurations`, "tunnel configuration PUT", { method: "PUT", body: JSON.stringify({ config }) });
+ const observed = await inspectRemoteManagedDomain(client, input);
+ if (observed.targetIndex < 0 || !isDeepStrictEqual(observed.config, config)) {
+ throw new Error("Cloudflare tunnel update changed during verification; inspect concurrent changes before retrying");
+ }
+ return { action: "created" };
+}
diff --git a/lib/infra/managed-domain.test.ts b/lib/infra/managed-domain.test.ts
new file mode 100644
index 00000000..e82eec70
--- /dev/null
+++ b/lib/infra/managed-domain.test.ts
@@ -0,0 +1,109 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { ManagedDomainRoute } from "@/lib/contracts/managed-domains";
+import { request } from "./http";
+import { readInfraProvider } from "./store";
+import { ensureManagedDomainGateway, inspectManagedDomainGateway } from "./managed-domain-gateway";
+import { ensureManagedDomainDns, ensureManagedDomainRoute, inspectManagedDomainRoute } from "./managed-domain";
+
+vi.mock("./store", () => ({ readInfraProvider: vi.fn() }));
+vi.mock("./http", async importOriginal => ({ ...await importOriginal<typeof import("./http")>(), request: vi.fn() }));
+vi.mock("./managed-domain-gateway", () => ({ ensureManagedDomainGateway: vi.fn(), inspectManagedDomainGateway: vi.fn() }));
+
+const input: ManagedDomainRoute = {
+ hostname: "9router.example.com", cockpitHostname: "mso.example.com", localOrigin: "http://127.0.0.1:4005",
+ zoneId: "a".repeat(32), zoneName: "example.com", accountId: "b".repeat(32),
+ tunnelId: "11111111-2222-3333-4444-555555555555", ownerTag: "mso:owner:9router",
+};
+let source: string, zoneAccount: string, records: Record<string, unknown>[];
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ source = "cloudflare"; zoneAccount = input.accountId; records = [];
+ vi.mocked(readInfraProvider).mockResolvedValue({ apiToken: "private-test-token", zoneId: input.zoneId, accountId: input.accountId });
+ vi.mocked(inspectManagedDomainGateway).mockResolvedValue(undefined);
+ vi.mocked(ensureManagedDomainGateway).mockResolvedValue({ action: "unchanged" });
+ vi.mocked(request).mockImplementation(async (url, init = {}) => {
+ expect(init.headers).toMatchObject({ authorization: "Bearer private-test-token" });
+ const path = new URL(url).pathname;
+ let result: unknown;
+ if (path.endsWith("/configurations")) result = { source, tunnel_id: input.tunnelId, config: { ingress: [
+ { hostname: input.cockpitHostname, service: input.localOrigin }, { service: "http_status:404" },
+ ] } };
+ else if (path.endsWith("/dns_records")) result = records;
+ else if (path.includes("/cfd_tunnel/")) result = { id: input.tunnelId, config_src: source, deleted_at: null };
+ else result = { id: input.zoneId, name: input.zoneName, account: { id: zoneAccount }, status: "active" };
+ return { status: 200, ok: true, body: { success: true, result }, text: "" };
+ });
+});
+
+describe("managed domain provider preflight and source dispatch", () => {
+ it("checks the selected connection, zone, tunnel, cockpit and DNS without writes", async () => {
+ await inspectManagedDomainRoute(input);
+ expect(readInfraProvider).toHaveBeenCalledWith("cloudflare");
+ expect(request).toHaveBeenCalledTimes(4);
+ expect(vi.mocked(request).mock.calls.every(([, init]) => !init?.method)).toBe(true);
+ expect(inspectManagedDomainGateway).not.toHaveBeenCalled();
+ });
+
+ it("rejects a foreign zone account before inspecting or changing the tunnel", async () => {
+ zoneAccount = "f".repeat(32);
+ await expect(inspectManagedDomainRoute(input)).rejects.toThrow("zone ID, name and account");
+ expect(request).toHaveBeenCalledTimes(1);
+ });
+
+ it("rejects a connection whose configured target differs without making requests", async () => {
+ vi.mocked(readInfraProvider).mockResolvedValue({ apiToken: "private-test-token", zoneId: "f".repeat(32) });
+ await expect(inspectManagedDomainRoute(input)).rejects.toThrow("selected Cloudflare connection");
+ expect(request).not.toHaveBeenCalled();
+ });
+
+ it("rejects local and unknown source tunnels before any DNS operation", async () => {
+ source = "local";
+ await expect(ensureManagedDomainDns(input)).rejects.toThrow("config_src=local");
+ source = "unknown";
+ await expect(inspectManagedDomainRoute(input)).rejects.toThrow("configuration source is unknown");
+ expect(vi.mocked(request).mock.calls.every(([url, init]) => !url.includes("dns_records") && !init?.method)).toBe(true);
+ expect(ensureManagedDomainGateway).not.toHaveBeenCalled();
+ });
+
+ it("delegates an explicitly selected local tunnel to the MSO-owned gateway", async () => {
+ source = "local";
+ const local = { ...input, routeMode: "mso-gateway" as const, hostTemplate: "{id}.example.com" };
+ await inspectManagedDomainRoute(local);
+ await expect(ensureManagedDomainRoute(local)).resolves.toEqual({ action: "unchanged" });
+ expect(inspectManagedDomainGateway).toHaveBeenCalledWith(local);
+ expect(ensureManagedDomainGateway).toHaveBeenCalledWith(local);
+ expect(vi.mocked(request).mock.calls.every(([url]) => !url.includes("configurations"))).toBe(true);
+ });
+
+ it("requires fresh setup when a stored local tunnel has become remote", async () => {
+ await expect(ensureManagedDomainRoute({ ...input, routeMode: "mso-gateway" })).rejects.toThrow("config_src=cloudflare");
+ expect(ensureManagedDomainGateway).not.toHaveBeenCalled();
+ expect(vi.mocked(request).mock.calls.every(([url, init]) => !url.includes("configurations") && !init?.method)).toBe(true);
+ });
+
+ it("propagates local ownership failure before DNS lookup or any mutation", async () => {
+ source = "local";
+ vi.mocked(inspectManagedDomainGateway).mockRejectedValue(new Error("tunnel is externally owned"));
+ await expect(inspectManagedDomainRoute({ ...input, routeMode: "mso-gateway" })).rejects.toThrow("externally owned");
+ expect(vi.mocked(request).mock.calls.every(([url, init]) => !url.includes("dns_records") && !init?.method)).toBe(true);
+ });
+
+ it("includes DNS conflict inspection in the no-write preflight", async () => {
+ records = [{ id: "d".repeat(32), name: input.hostname, type: "A", content: "192.0.2.1" }];
+ await expect(inspectManagedDomainRoute(input)).rejects.toThrow("DNS conflict");
+ expect(vi.mocked(request).mock.calls.every(([, init]) => !init?.method)).toBe(true);
+ });
+
+ it.each(["https://127.0.0.1:4005", "http://127.0.0.1", "http://192.0.2.1:4005", "http://user:[email protected]:4005", "http://127.0.0.1:4005/path"])(
+ "rejects an unsafe or ambiguous local origin %s before credential use", async localOrigin => {
+ await expect(inspectManagedDomainRoute({ ...input, localOrigin })).rejects.toThrow("loopback MSO HTTP service");
+ expect(request).not.toHaveBeenCalled(); expect(readInfraProvider).not.toHaveBeenCalled();
+ });
+
+ it("never reflects a credential-bearing transport error", async () => {
+ vi.mocked(request).mockRejectedValue(new Error("Authorization: Bearer private-test-token"));
+ await expect(inspectManagedDomainRoute(input)).rejects.toThrow("zone inspection request failed");
+ try { await inspectManagedDomainRoute(input); } catch (error) { expect(String(error)).not.toContain("private-test-token"); }
+ });
+});
diff --git a/lib/infra/managed-domain.ts b/lib/infra/managed-domain.ts
new file mode 100644
index 00000000..b59756ad
--- /dev/null
+++ b/lib/infra/managed-domain.ts
@@ -0,0 +1,25 @@
+import type { ManagedDomainDnsResult, ManagedDomainRoute } from "@/lib/contracts/managed-domains";
+import { inspectManagedDomainIdentity, managedDomainClient } from "./managed-domain-client";
+import { inspectManagedDomainDns, reconcileManagedDomainDns } from "./managed-domain-dns";
+import { ensureManagedDomainGateway, inspectManagedDomainGateway } from "./managed-domain-gateway";
+import { inspectRemoteManagedDomain, reconcileRemoteManagedDomain } from "./managed-domain-route";
+
+export async function inspectManagedDomainRoute(input: ManagedDomainRoute): Promise<void> {
+ const client = await managedDomainClient(input);
+ const mode = await inspectManagedDomainIdentity(client, input);
+ if (mode === "mso-gateway") await inspectManagedDomainGateway(input);
+ else await inspectRemoteManagedDomain(client, input);
+ await inspectManagedDomainDns(client, input);
+}
+
+export async function ensureManagedDomainDns(input: ManagedDomainRoute): Promise<ManagedDomainDnsResult> {
+ const client = await managedDomainClient(input);
+ await inspectManagedDomainIdentity(client, input);
+ return reconcileManagedDomainDns(client, input);
+}
+
+export async function ensureManagedDomainRoute(input: ManagedDomainRoute): Promise<{ action: "created" | "unchanged" }> {
+ const client = await managedDomainClient(input);
+ const mode = await inspectManagedDomainIdentity(client, input);
+ return mode === "mso-gateway" ? ensureManagedDomainGateway(input) : reconcileRemoteManagedDomain(client, input);
+}
diff --git a/lib/managed-apps/domain-config.test.ts b/lib/managed-apps/domain-config.test.ts
new file mode 100644
index 00000000..78ee845d
--- /dev/null
+++ b/lib/managed-apps/domain-config.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest";
+import { cleanDomainOrigin, domainHostname, managedDomainHostname, validateDomainConfig, validateDomainState } from "./domain-config";
+import type { ManagedDomainConfig, ManagedDomainState } from "@/lib/contracts/managed-domains";
+
+const config: ManagedDomainConfig = {
+ publicOrigin: "https://mso.example.com", hostTemplate: "{id}.mso.example.com",
+ localOrigin: "http://127.0.0.1:4005", zoneId: "a".repeat(32), zoneName: "example.com",
+ accountId: "b".repeat(32), tunnelId: "12345678-1234-1234-1234-123456789abc",
+ user: "owner", connection: "cloudflare-main", autoProvision: true,
+};
+const state = (): ManagedDomainState => ({ version: 1, revision: 1,
+ ownerId: "87654321-1234-1234-1234-123456789abc", config, apps: {} });
+
+describe("managed-domain configuration", () => {
+ it("derives known app hosts inside the selected zone without retaining the input object", () => {
+ const parsed = validateDomainConfig(config);
+ expect(parsed).toEqual(config);
+ expect(parsed).not.toBe(config);
+ expect(managedDomainHostname(parsed, "9router")).toBe("9router.mso.example.com");
+ expect(validateDomainConfig({ ...config, hostTemplate: "{id}-mso.example.com" }).hostTemplate).toBe("{id}-mso.example.com");
+ expect(() => managedDomainHostname(parsed, "arbitrary")).toThrow(/unknown managed application/);
+ });
+
+ it.each([undefined, "remote", "mso-gateway"])("accepts the supported route mode %s", routeMode => {
+ expect(validateDomainConfig({ ...config, routeMode }).routeMode).toBe(routeMode);
+ });
+
+ it.each(["*.example.com", "EXAMPLE.com", "127.0.0.1", "localhost", "bad_label.example.com", "-bad.example.com", "bad-.example.com", "example.com.", `${"a".repeat(64)}.example.com`])(
+ "rejects an invalid DNS hostname: %s", value => expect(() => domainHostname(value)).toThrow(),
+ );
+
+ it("canonicalizes public HTTPS and explicit loopback origins", () => {
+ expect(cleanDomainOrigin("https://mso.example.com:443/")).toBe(config.publicOrigin);
+ expect(cleanDomainOrigin("http://[::1]:4005", true)).toBe("http://[::1]:4005");
+ expect(cleanDomainOrigin("http://localhost:4005", true)).toBe("http://localhost:4005");
+ });
+
+ it.each(["http://mso.example.com", "https://mso.example.com:444", "https://user:[email protected]", "https://mso.example.com/path", "https://mso.example.com/?q=1", "https://mso.example.com/#fragment", "https://127.0.0.1"])(
+ "rejects unsafe public origins: %s", value => expect(() => cleanDomainOrigin(value)).toThrow(),
+ );
+
+ it.each(["http://192.168.1.10:4005", "https://127.0.0.1:4005", "http://localhost", "http://0.0.0.0:4005", "http://127.0.0.1:4005/path"])(
+ "rejects a target that is not an explicit HTTP loopback origin: %s", value => expect(() => cleanDomainOrigin(value, true)).toThrow(),
+ );
+
+ it.each([
+ { apiToken: "not-a-real-secret" }, { routeMode: "external" }, { routeMode: ["remote"] }, { user: "../owner" },
+ { accountId: "other-account" }, { tunnelId: "not-a-uuid" }, { autoProvision: "yes" },
+ { publicOrigin: "https://mso.example.com/" }, { publicOrigin: "https://mso.other.com" },
+ { hostTemplate: "{id}.other.com" }, { hostTemplate: "app.{id}.example.com" },
+ { hostTemplate: "{id}.{id}.example.com" }, { hostTemplate: "{id}.com" },
+ { publicOrigin: "https://9router.mso.example.com" },
+ ])("refuses invalid routing or secret-bearing fields: %j", override => {
+ expect(() => validateDomainConfig({ ...config, ...override })).toThrow();
+ });
+
+ it("validates saved app identity, resource IDs, and bounded diagnostics", () => {
+ const valid = state();
+ valid.apps["9router"] = { appId: "9router", hostname: "9router.mso.example.com", phase: "dns-ready", dnsRecordId: "c".repeat(32), updatedAt: 10 };
+ expect(validateDomainState(valid)).toEqual(valid);
+ for (const override of [{ hostname: "9router.other.com" }, { appId: "hermes" }, { phase: "finished" }, { phase: ["ready"] }, { dnsAction: ["created"] }, { routeAction: ["created"] }, { dnsRecordId: "invalid" }, { error: "x".repeat(513) }, { verifiedAt: 1.5 }, { token: "not-a-real-secret" }]) {
+ expect(() => validateDomainState({ ...valid, apps: { "9router": { ...valid.apps["9router"], ...override } } })).toThrow();
+ }
+ expect(() => validateDomainState({ ...valid, config: null })).toThrow();
+ expect(() => validateDomainState({ ...valid, revision: -1 })).toThrow();
+ expect(() => validateDomainState({ ...valid, version: 2 })).toThrow();
+ });
+});
diff --git a/lib/managed-apps/domain-config.ts b/lib/managed-apps/domain-config.ts
new file mode 100644
index 00000000..a54d16bd
--- /dev/null
+++ b/lib/managed-apps/domain-config.ts
@@ -0,0 +1,73 @@
+import { isIP } from "node:net";
+import type { ManagedDomainConfig, ManagedDomainState } from "@/lib/contracts/managed-domains";
+import { MANAGED_APP_IDS } from "./types";
+
+const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
+const HEX = /^[a-f0-9]{32}$/;
+const UUID = /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/;
+const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
+const CONFIG_KEYS = ["publicOrigin", "hostTemplate", "localOrigin", "zoneId", "zoneName", "accountId", "tunnelId", "user", "connection", "autoProvision"];
+const RECORD_KEYS = ["appId", "hostname", "phase", "dnsRecordId", "dnsAction", "routeAction", "error", "verifiedAt", "updatedAt"];
+const PHASES = new Set(["pending", "dns-ready", "route-ready", "ready", "blocked"]);
+
+function object(value: unknown): Record<string, unknown> {
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid managed-domain configuration");
+ return value as Record<string, unknown>;
+}
+function keys(value: Record<string, unknown>, allowed: string[]): void {
+ if (Object.keys(value).some(key => !allowed.includes(key))) throw new Error("unknown managed-domain field; credentials belong in Integrations");
+}
+export function domainHostname(value: unknown): string {
+ if (typeof value !== "string" || value.length > 253 || !value.includes(".") || isIP(value) ||
+ value !== value.toLowerCase() || value.split(".").some(label => !LABEL.test(label))) throw new Error("invalid DNS hostname");
+ return value;
+}
+export function cleanDomainOrigin(value: string, local = false): string {
+ let url: URL;
+ try { url = new URL(value); } catch { throw new Error("invalid domain origin"); }
+ if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) throw new Error("domain origin must not contain credentials, a path, query or fragment");
+ if (local) {
+ if (url.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) || !url.port) throw new Error("domain target must be an HTTP loopback origin with an explicit port");
+ } else {
+ if (url.protocol !== "https:" || url.port) throw new Error("public origin must use HTTPS on port 443");
+ domainHostname(url.hostname);
+ }
+ return url.origin;
+}
+export function managedDomainHostname(config: ManagedDomainConfig, appId: string): string {
+ if (!(MANAGED_APP_IDS as readonly string[]).includes(appId)) throw new Error("unknown managed application");
+ return domainHostname(config.hostTemplate.replace("{id}", appId));
+}
+export function validateDomainConfig(value: unknown): ManagedDomainConfig {
+ const raw = object(value); keys(raw, [...CONFIG_KEYS, "routeMode"]);
+ if (CONFIG_KEYS.some(key => key === "autoProvision" ? typeof raw[key] !== "boolean" : typeof raw[key] !== "string")) throw new Error("incomplete managed-domain configuration");
+ if (raw.routeMode !== undefined && (typeof raw.routeMode !== "string" || !["remote", "mso-gateway"].includes(raw.routeMode))) throw new Error("invalid managed-domain route mode");
+ const config = raw as unknown as ManagedDomainConfig;
+ if (!HEX.test(config.zoneId) || !HEX.test(config.accountId) || !UUID.test(config.tunnelId)) throw new Error("zone/account IDs must be 32 lowercase hex characters; tunnel ID must be a UUID");
+ if (!ID.test(config.user) || !ID.test(config.connection)) throw new Error("select a named MSO integration user and connection");
+ if (cleanDomainOrigin(config.publicOrigin) !== config.publicOrigin || cleanDomainOrigin(config.localOrigin, true) !== config.localOrigin) throw new Error("domain origins must use their canonical spelling");
+ domainHostname(config.zoneName);
+ if (!config.hostTemplate.startsWith("{id}") || config.hostTemplate.split("{id}").length !== 2) throw new Error("host template must begin with exactly one {id}");
+ const cockpit = new URL(config.publicOrigin).hostname;
+ for (const host of [cockpit, ...MANAGED_APP_IDS.map(id => managedDomainHostname(config, id))]) {
+ if (host !== config.zoneName && !host.endsWith(`.${config.zoneName}`)) throw new Error(`hostname is outside selected zone ${config.zoneName}`);
+ }
+ if (MANAGED_APP_IDS.some(id => managedDomainHostname(config, id) === cockpit)) throw new Error("application and cockpit origins must differ");
+ return { ...config };
+}
+export function validateDomainState(value: unknown): ManagedDomainState {
+ const raw = object(value); keys(raw, ["version", "revision", "ownerId", "config", "apps"]);
+ if (raw.version !== 1 || !Number.isSafeInteger(raw.revision) || Number(raw.revision) < 0 || typeof raw.ownerId !== "string" || !UUID.test(raw.ownerId)) throw new Error("invalid managed-domain state; use the previous snapshot to recover");
+ const config = raw.config === null ? null : validateDomainConfig(raw.config);
+ const apps = object(raw.apps);
+ for (const [id, value] of Object.entries(apps)) {
+ const row = object(value); keys(row, RECORD_KEYS);
+ if (!config || row.appId !== id || row.hostname !== managedDomainHostname(config, id) || typeof row.phase !== "string" || !PHASES.has(row.phase) || !Number.isSafeInteger(row.updatedAt)) throw new Error("invalid managed-domain application state");
+ if (row.dnsRecordId !== undefined && (typeof row.dnsRecordId !== "string" || !HEX.test(row.dnsRecordId))) throw new Error("invalid domain DNS record ID");
+ if (row.dnsAction !== undefined && (typeof row.dnsAction !== "string" || !["created", "updated", "unchanged"].includes(row.dnsAction))) throw new Error("invalid domain DNS action");
+ if (row.routeAction !== undefined && (typeof row.routeAction !== "string" || !["created", "unchanged"].includes(row.routeAction))) throw new Error("invalid domain route action");
+ if (row.error !== undefined && (typeof row.error !== "string" || row.error.length > 512)) throw new Error("invalid domain diagnostic");
+ if (row.verifiedAt !== undefined && !Number.isSafeInteger(row.verifiedAt)) throw new Error("invalid domain verification timestamp");
+ }
+ return { ...raw, config } as unknown as ManagedDomainState;
+}
diff --git a/lib/managed-apps/domain-discovery.ts b/lib/managed-apps/domain-discovery.ts
new file mode 100644
index 00000000..73863b65
--- /dev/null
+++ b/lib/managed-apps/domain-discovery.ts
@@ -0,0 +1,39 @@
+import { listCloudflareZones } from "@/lib/infra/cloudflare";
+import { readInfraProvider } from "@/lib/infra/store";
+import { obj, request } from "@/lib/infra/http";
+import { cleanDomainOrigin } from "./domain-config";
+import type { ManagedDomainConfig } from "@/lib/contracts/managed-domains";
+
+type DiscoveredDomainTarget = Pick<ManagedDomainConfig, "zoneId" | "zoneName" | "accountId" | "tunnelId" | "routeMode">;
+
+export async function discoverManagedDomainTarget(publicOrigin: string, zoneHint?: string, tunnelHint?: string): Promise<DiscoveredDomainTarget> {
+ const hostname = new URL(cleanDomainOrigin(publicOrigin)).hostname;
+ const values = await readInfraProvider("cloudflare");
+ if (!values.apiToken) throw new Error("Cloudflare connection is not configured; complete its private setup in MSO Integrations");
+ const zones = (await listCloudflareZones(values)).filter(zone => hostname === zone.name || hostname.endsWith(`.${zone.name}`));
+ const selected = zoneHint ?? values.zoneId;
+ const zone = selected ? zones.find(zone => zone.id === selected || zone.name === selected) : zones.sort((a, b) => b.name.length - a.name.length)[0];
+ if (!zone) throw new Error("no selected accessible Cloudflare zone contains the MSO public origin");
+ const base = "https://api.cloudflare.com/client/v4";
+ const headers = { authorization: `Bearer ${values.apiToken}`, accept: "application/json" };
+ const detail = await request(`${base}/zones/${encodeURIComponent(zone.id)}`, { headers });
+ if (!detail.ok || obj(detail.body).success !== true) throw new Error(`Cloudflare zone inspection HTTP ${detail.status}`);
+ const accountId = obj(obj(obj(detail.body).result).account).id;
+ if (typeof accountId !== "string" || values.accountId && accountId !== values.accountId) throw new Error("selected Cloudflare zone does not match the connection account");
+ let tunnelId = tunnelHint;
+ if (!tunnelId) {
+ const lookup = await request(`${base}/zones/${encodeURIComponent(zone.id)}/dns_records?type=CNAME&name.exact=${encodeURIComponent(hostname)}&per_page=100`, { headers });
+ const data = obj(lookup.body);
+ if (!lookup.ok || data.success !== true || !Array.isArray(data.result)) throw new Error(`Cloudflare cockpit DNS lookup HTTP ${lookup.status}`);
+ const rows = data.result.map(obj).filter(row => row.name === hostname && row.type === "CNAME");
+ if (Number(obj(data.result_info).total_pages ?? 1) > 1 || rows.length !== 1) throw new Error("cannot identify one existing MSO tunnel; specify --tunnel <UUID>");
+ tunnelId = /^([a-f0-9-]{36})\.cfargotunnel\.com\.?$/.exec(String(rows[0].content))?.[1];
+ }
+ if (!tunnelId || !/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/.test(tunnelId)) throw new Error("MSO DNS does not identify a Cloudflare Tunnel; specify --tunnel <UUID>");
+ const tunnel = await request(`${base}/accounts/${encodeURIComponent(accountId)}/cfd_tunnel/${tunnelId}`, { headers });
+ const data = obj(tunnel.body), result = obj(data.result);
+ if (!tunnel.ok || data.success !== true || result.id !== tunnelId || result.deleted_at) throw new Error("cannot inspect the selected active Cloudflare tunnel");
+ const routeMode = result.config_src === "cloudflare" ? "remote" : result.config_src === "local" ? "mso-gateway" : null;
+ if (!routeMode) throw new Error("Cloudflare tunnel configuration source is unknown");
+ return { zoneId: zone.id, zoneName: zone.name, accountId, tunnelId, routeMode };
+}
diff --git a/lib/managed-apps/domain-health.ts b/lib/managed-apps/domain-health.ts
new file mode 100644
index 00000000..c8ff2a33
--- /dev/null
+++ b/lib/managed-apps/domain-health.ts
@@ -0,0 +1,9 @@
+import { getManagedAppDefinition } from "./catalog";
+import { managedAppHealth } from "./health";
+import type { ManagedAppId } from "./types";
+
+export async function probeManagedAppRuntime(id: ManagedAppId): Promise<void> {
+ if (await managedAppHealth(getManagedAppDefinition(id)) !== true) {
+ throw new Error(`${id} is not healthy on its configured loopback endpoint; start the application, then retry mso domain ensure ${id} --apply`);
+ }
+}
diff --git a/lib/managed-apps/domain-jobs.test.ts b/lib/managed-apps/domain-jobs.test.ts
new file mode 100644
index 00000000..98c0c0d7
--- /dev/null
+++ b/lib/managed-apps/domain-jobs.test.ts
@@ -0,0 +1,42 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+vi.mock("./domain-lifecycle", () => ({ appendDomainProvisioning: vi.fn(async () => undefined) }));
+const { appendDomainProvisioning } = await import("./domain-lifecycle");
+const { startManagedAppJob, readManagedAppJob } = await import("./jobs");
+const { liveRecord, cancelJob } = await import("./job-runner");
+let directory: string;
+beforeEach(async () => {
+ directory = await fs.mkdtemp(path.join(os.tmpdir(), "mso-domain-jobs-"));
+ vi.spyOn(os, "homedir").mockReturnValue(directory);
+ vi.mocked(appendDomainProvisioning).mockReset().mockResolvedValue();
+});
+afterEach(async () => { vi.restoreAllMocks(); await fs.rm(directory, { recursive: true, force: true }); });
+async function settled(id: string) {
+ await vi.waitFor(() => expect(liveRecord(id)).toBeUndefined());
+ return readManagedAppJob(id);
+}
+it("keeps the install job running until domain progress has been recorded", async () => {
+ let complete!: () => void;
+ vi.mocked(appendDomainProvisioning).mockImplementation(async (_id, append) => {
+ await new Promise<void>(resolve => { complete = resolve; });
+ append("[mso domain] certificate pending; retry ensure --apply\n");
+ });
+ const started = await startManagedAppJob({ applicationId: "9router", kind: "install", argv: [process.execPath, "-e", "process.exit(0)"] });
+ await vi.waitFor(() => expect(appendDomainProvisioning).toHaveBeenCalledOnce());
+ expect((await readManagedAppJob(started.id))?.status).toBe("running");
+ expect(cancelJob(started.id, "9router")).toBe(false);
+ complete();
+ const done = await settled(started.id);
+ expect(done).toMatchObject({ status: "succeeded", exitCode: 0 });
+ expect(done?.log).toContain("certificate pending");
+});
+it("does not provision after a failed installer or an uninstall", async () => {
+ const failed = await startManagedAppJob({ applicationId: "9router", kind: "install", argv: [process.execPath, "-e", "process.exit(2)"] });
+ expect((await settled(failed.id))?.status).toBe("failed");
+ const removed = await startManagedAppJob({ applicationId: "9router", kind: "uninstall", argv: [process.execPath, "-e", "process.exit(0)"] });
+ expect((await settled(removed.id))?.status).toBe("succeeded");
+ expect(appendDomainProvisioning).not.toHaveBeenCalled();
+});
diff --git a/lib/managed-apps/domain-lifecycle.ts b/lib/managed-apps/domain-lifecycle.ts
new file mode 100644
index 00000000..9bb9479b
--- /dev/null
+++ b/lib/managed-apps/domain-lifecycle.ts
@@ -0,0 +1,36 @@
+import type { ManagedDomainRecord } from "@/lib/contracts/managed-domains";
+import { redactText } from "@/lib/security/redact-text";
+import { managedDomainHostname } from "./domain-config";
+import { ensureManagedAppDomain } from "./domain-provision";
+import { readManagedDomains } from "./domain-store";
+import type { ManagedAppId } from "./types";
+
+export interface ManagedDomainView {
+ domain: ManagedDomainRecord | null;
+ domainDiagnostic: string | null;
+}
+const diagnostic = (error: unknown) => redactText(error instanceof Error ? error.message : "managed-domain configuration is unavailable", 512);
+
+export async function readManagedDomainView(id: ManagedAppId): Promise<ManagedDomainView> {
+ try {
+ const state = await readManagedDomains();
+ const domain = state.apps[id] ?? (state.config ? {
+ appId: id, hostname: managedDomainHostname(state.config, id), phase: "pending" as const, updatedAt: 0,
+ } : null);
+ return { domain, domainDiagnostic: domain?.error ?? null };
+ } catch (error) { return { domain: null, domainDiagnostic: diagnostic(error) }; }
+}
+
+/** Preserve application success while reporting DNS/configuration failures separately. */
+export async function provisionDomainAfterStart(id: ManagedAppId): Promise<ManagedDomainView> {
+ try {
+ const domain = await ensureManagedAppDomain(id, true);
+ return { domain, domainDiagnostic: domain?.error ?? null };
+ } catch (error) { return { domain: null, domainDiagnostic: diagnostic(error) }; }
+}
+
+export async function appendDomainProvisioning(id: ManagedAppId, append: (text: string) => void): Promise<void> {
+ const { domain, domainDiagnostic } = await provisionDomainAfterStart(id);
+ if (domain) append(`[mso domain] ${domain.hostname}: ${domain.phase}\n`);
+ if (domainDiagnostic) append(`[mso domain] ${domainDiagnostic}; retry: mso domain ensure ${id} --apply\n`);
+}
diff --git a/lib/managed-apps/domain-manager.test.ts b/lib/managed-apps/domain-manager.test.ts
new file mode 100644
index 00000000..cbaa1958
--- /dev/null
+++ b/lib/managed-apps/domain-manager.test.ts
@@ -0,0 +1,34 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+vi.mock("./domain-lifecycle", () => ({ provisionDomainAfterStart: vi.fn(), readManagedDomainView: vi.fn() }));
+vi.mock("./runner", () => ({ commandExists: vi.fn(async () => false), resolveCommand: vi.fn(async () => null), runProgram: vi.fn(async () => ({ code: 0, stdout: "LoadState=not-found", stderr: "" })) }));
+vi.mock("./docker", () => ({ dockerUsable: vi.fn(async () => true), requireDocker: vi.fn(), runDocker: vi.fn(async args => ({ code: 0, stdout: args[0] === "ps" ? "9router" : "true", stderr: "" })) }));
+vi.mock("./lock", () => ({ acquireOperation: vi.fn(() => true), activeOperation: vi.fn(() => null), releaseOperation: vi.fn(), withManagedAppOperationLease: async (_id: string, run: () => Promise<void>) => run() }));
+vi.mock("./job-store", () => ({ listJobRecords: vi.fn(async () => []) }));
+vi.mock("./backups", () => ({ createBackup: vi.fn() }));
+const { provisionDomainAfterStart, readManagedDomainView } = await import("./domain-lifecycle");
+const { requireDocker } = await import("./docker");
+const { performManagedAppAction } = await import("./manager");
+beforeEach(() => {
+ vi.mocked(requireDocker).mockReset().mockResolvedValue();
+ vi.mocked(provisionDomainAfterStart).mockReset().mockResolvedValue({ domain: null, domainDiagnostic: null });
+ vi.mocked(readManagedDomainView).mockReset().mockResolvedValue({ domain: null, domainDiagnostic: null });
+ vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response(null, { status: 200 }));
+});
+afterEach(() => vi.restoreAllMocks());
+it.each(["start", "restart"] as const)("provisions after successful %s without misreporting a DNS error as an app failure", async action => {
+ vi.mocked(provisionDomainAfterStart).mockResolvedValue({ domain: null, domainDiagnostic: "Cloudflare needs authorization" });
+ const view = await performManagedAppAction("9router", action);
+ expect(requireDocker).toHaveBeenCalledWith([action, "9router"], 30_000);
+ expect(provisionDomainAfterStart).toHaveBeenCalledWith("9router");
+ expect(view).toMatchObject({ state: "running", domainDiagnostic: "Cloudflare needs authorization" });
+});
+it("does not provision when the local start fails", async () => {
+ vi.mocked(requireDocker).mockRejectedValue(new Error("Docker denied the start"));
+ await expect(performManagedAppAction("9router", "start")).rejects.toThrow("Docker denied");
+ expect(provisionDomainAfterStart).not.toHaveBeenCalled();
+});
+it("advertises a verified domain through the managed app view", async () => {
+ vi.mocked(readManagedDomainView).mockResolvedValue({ domain: { appId: "9router", hostname: "9router.mso.example.com", phase: "ready", updatedAt: 1, verifiedAt: 1 }, domainDiagnostic: null });
+ expect((await performManagedAppAction("9router", "start")).publicDashboardUrl).toBe("https://9router.mso.example.com");
+});
diff --git a/lib/managed-apps/domain-probe.test.ts b/lib/managed-apps/domain-probe.test.ts
new file mode 100644
index 00000000..9b8dfbe0
--- /dev/null
+++ b/lib/managed-apps/domain-probe.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { ManagedDomainConfig } from "@/lib/contracts/managed-domains";
+import { probeLocalManagedDomain, probePublicManagedDomain } from "./domain-probe";
+
+const hostname = "9router.mso.example.com";
+const config = { localOrigin: "http://127.0.0.1:4005" } as ManagedDomainConfig;
+const bootstrap = (marker = "9router", type = "application/javascript; charset=utf-8", status = 200) => new Response("bootstrap", {
+ status, headers: { "x-mso-managed-app": marker, "content-type": type },
+});
+const anonymous = (status = 401, marker = "9router") => new Response("unauthorized", {
+ status, headers: { "x-mso-managed-app": marker },
+});
+afterEach(() => vi.unstubAllGlobals());
+
+describe("managed-domain route verification", () => {
+ it("probes both local routes with the desired app Host and without session credentials", async () => {
+ const fetcher = vi.fn().mockResolvedValueOnce(bootstrap()).mockResolvedValueOnce(anonymous());
+ vi.stubGlobal("fetch", fetcher);
+ await probeLocalManagedDomain(config, hostname, "9router");
+ expect(fetcher.mock.calls.map(([url]) => String(url))).toEqual([
+ "http://127.0.0.1:4005/__mso_app_bootstrap.js", "http://127.0.0.1:4005/dashboard",
+ ]);
+ for (const [, options] of fetcher.mock.calls) {
+ expect(options).toMatchObject({ headers: { host: hostname }, redirect: "error", cache: "no-store" });
+ expect(Object.keys(options.headers)).toEqual(["host"]);
+ expect(options.signal).toBeInstanceOf(AbortSignal);
+ }
+ });
+
+ it("verifies public HTTPS using the actual hostname without overriding Host", async () => {
+ const fetcher = vi.fn().mockResolvedValueOnce(bootstrap()).mockResolvedValueOnce(anonymous());
+ vi.stubGlobal("fetch", fetcher);
+ await probePublicManagedDomain(hostname, "9router");
+ expect(fetcher.mock.calls.map(([url]) => String(url))).toEqual([
+ `https://${hostname}/__mso_app_bootstrap.js`, `https://${hostname}/dashboard`,
+ ]);
+ expect(fetcher.mock.calls.every(([, options]) => options.headers === undefined && options.redirect === "error")).toBe(true);
+ });
+
+ it.each([
+ ["hermes", "application/javascript", 200],
+ ["", "application/javascript", 200],
+ ["9router", "text/html", 200],
+ ["9router", "application/javascript", 404],
+ ] as const)("rejects a bootstrap response for the wrong route (%s, %s, %s)", async (marker, type, status) => {
+ const fetcher = vi.fn().mockResolvedValueOnce(bootstrap(marker, type, status));
+ vi.stubGlobal("fetch", fetcher);
+ await expect(probeLocalManagedDomain(config, hostname, "9router")).rejects.toThrow(/routing is not active/);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([[200, "9router"], [403, "9router"], [401, "hermes"], [401, ""]] as const)(
+ "refuses readiness without the selected app's anonymous 401 (%s, %s)", async (status, marker) => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(bootstrap()).mockResolvedValueOnce(anonymous(status, marker)));
+ await expect(probePublicManagedDomain(hostname, "9router")).rejects.toThrow(/anonymous application access is not rejected/);
+ },
+ );
+
+ it("reports an exact-host HTTPS failure as pending with a retry instruction", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("certificate hostname mismatch")));
+ await expect(probePublicManagedDomain(hostname, "9router")).rejects.toThrow(`HTTPS/auth verification pending for ${hostname}`);
+ await expect(probePublicManagedDomain(hostname, "9router")).rejects.toThrow(/certificate covering this exact hostname; retry mso domain ensure 9router --apply/);
+ });
+
+ it("rejects unsafe targets before issuing any request", async () => {
+ const fetcher = vi.fn();
+ vi.stubGlobal("fetch", fetcher);
+ await expect(probeLocalManagedDomain({ ...config, localOrigin: "http://192.168.1.20:4005" }, hostname, "9router")).rejects.toThrow();
+ await expect(probePublicManagedDomain("9router.example.com@localhost", "9router")).rejects.toThrow();
+ expect(fetcher).not.toHaveBeenCalled();
+ });
+});
diff --git a/lib/managed-apps/domain-probe.ts b/lib/managed-apps/domain-probe.ts
new file mode 100644
index 00000000..755505c1
--- /dev/null
+++ b/lib/managed-apps/domain-probe.ts
@@ -0,0 +1,32 @@
+import type { ManagedDomainConfig } from "@/lib/contracts/managed-domains";
+import { cleanDomainOrigin, domainHostname } from "./domain-config";
+
+async function probe(origin: string, hostname: string, appId: string, local: boolean): Promise<void> {
+ cleanDomainOrigin(origin, local); domainHostname(hostname);
+ const headers = local ? { host: hostname } : undefined;
+ const response = await fetch(new URL("/__mso_app_bootstrap.js", origin), {
+ headers, redirect: "error", cache: "no-store", signal: AbortSignal.timeout(8_000),
+ });
+ await response.body?.cancel();
+ if (response.status !== 200 || response.headers.get("x-mso-managed-app") !== appId || !response.headers.get("content-type")?.startsWith("application/javascript")) {
+ throw new Error(local
+ ? "MSO app-host routing is not active locally; run mso domain repair-env --apply, then mso deploy (or mso update --rebuild for a gateway-owned runtime), and retry"
+ : "public hostname does not reach the selected MSO application auth gate");
+ }
+ const anonymous = await fetch(new URL("/dashboard", origin), {
+ headers, redirect: "error", cache: "no-store", signal: AbortSignal.timeout(8_000),
+ });
+ await anonymous.body?.cancel();
+ if (anonymous.status !== 401 || anonymous.headers.get("x-mso-managed-app") !== appId) throw new Error("anonymous application access is not rejected by MSO; refusing to report the domain ready");
+}
+
+export function probeLocalManagedDomain(config: ManagedDomainConfig, hostname: string, appId: string): Promise<void> {
+ return probe(config.localOrigin, hostname, appId, true);
+}
+export async function probePublicManagedDomain(hostname: string, appId: string): Promise<void> {
+ try { await probe(`https://${hostname}`, hostname, appId, false); }
+ catch (error) {
+ const message = error instanceof Error ? error.message : "HTTPS probe failed";
+ throw new Error(`HTTPS/auth verification pending for ${hostname}: ${message}. Check DNS propagation, the tunnel connector and a certificate covering this exact hostname; retry mso domain ensure ${appId} --apply`);
+ }
+}
diff --git a/lib/managed-apps/domain-provision.test.ts b/lib/managed-apps/domain-provision.test.ts
new file mode 100644
index 00000000..99a36523
--- /dev/null
+++ b/lib/managed-apps/domain-provision.test.ts
@@ -0,0 +1,97 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { ManagedDomainConfig } from "@/lib/contracts/managed-domains";
+
+vi.mock("@/lib/infra/connection-service", () => ({ withIntegrationSelection: vi.fn(async (_selector, run) => run()) }));
+vi.mock("@/lib/infra/managed-domain", () => ({ inspectManagedDomainRoute: vi.fn(), ensureManagedDomainDns: vi.fn(), ensureManagedDomainRoute: vi.fn() }));
+vi.mock("./domain-probe", () => ({ probeLocalManagedDomain: vi.fn(), probePublicManagedDomain: vi.fn() }));
+vi.mock("./domain-health", () => ({ probeManagedAppRuntime: vi.fn() }));
+const provider = await import("@/lib/infra/managed-domain");
+const probes = await import("./domain-probe");
+const { probeManagedAppRuntime } = await import("./domain-health");
+const { ensureManagedAppDomain } = await import("./domain-provision");
+const { readManagedDomains, saveManagedDomainConfig } = await import("./domain-store");
+const { provisionDomainAfterStart, readManagedDomainView } = await import("./domain-lifecycle");
+
+const config: ManagedDomainConfig = { publicOrigin: "https://mso.example.com", hostTemplate: "{id}.mso.example.com",
+ localOrigin: "http://127.0.0.1:4005", zoneId: "a".repeat(32), zoneName: "example.com", accountId: "b".repeat(32),
+ tunnelId: "11111111-1111-4111-8111-111111111111", user: "owner", connection: "dns", autoProvision: true };
+let directory: string;
+beforeEach(async () => {
+ directory = await fs.mkdtemp(path.join(os.tmpdir(), "mso-domain-provision-"));
+ vi.stubEnv("OS_MANAGED_DOMAINS_STORE", path.join(directory, "domains.json"));
+ vi.mocked(probes.probeLocalManagedDomain).mockReset().mockResolvedValue();
+ vi.mocked(probes.probePublicManagedDomain).mockReset().mockResolvedValue();
+ vi.mocked(probeManagedAppRuntime).mockReset().mockResolvedValue();
+ vi.mocked(provider.inspectManagedDomainRoute).mockReset().mockResolvedValue();
+ vi.mocked(provider.ensureManagedDomainDns).mockReset().mockResolvedValue({ id: "c".repeat(32), action: "created" });
+ vi.mocked(provider.ensureManagedDomainRoute).mockReset().mockResolvedValue({ action: "created" });
+});
+afterEach(async () => { vi.unstubAllEnvs(); await fs.rm(directory, { recursive: true, force: true }); });
+
+it("makes no external writes before the deployed MSO auth gate passes", async () => {
+ await saveManagedDomainConfig(config);
+ vi.mocked(probes.probeLocalManagedDomain).mockRejectedValueOnce(new Error("template needs a deploy"));
+ expect(await ensureManagedAppDomain("9router")).toMatchObject({ phase: "blocked", error: "template needs a deploy" });
+ expect(provider.inspectManagedDomainRoute).not.toHaveBeenCalled();
+ expect(provider.ensureManagedDomainDns).not.toHaveBeenCalled();
+ expect((await readManagedDomains()).apps["9router"].phase).toBe("blocked");
+});
+
+it("retains an authenticated route across DNS interruption and resumes to verified HTTPS", async () => {
+ await saveManagedDomainConfig(config);
+ vi.mocked(provider.ensureManagedDomainDns).mockRejectedValueOnce(new Error("DNS authorization unavailable"));
+ const interrupted = await ensureManagedAppDomain("9router");
+ expect(interrupted).toMatchObject({ phase: "blocked", routeAction: "created" });
+ expect(interrupted?.dnsRecordId).toBeUndefined();
+ expect(interrupted?.verifiedAt).toBeUndefined();
+ vi.mocked(provider.ensureManagedDomainRoute).mockResolvedValue({ action: "unchanged" });
+ expect(await ensureManagedAppDomain("9router")).toMatchObject({ phase: "ready", routeAction: "unchanged", dnsRecordId: "c".repeat(32), verifiedAt: expect.any(Number) });
+ expect((await readManagedDomainView("9router")).domainDiagnostic).toBeNull();
+});
+
+it("publishes DNS only after the app ingress has been confirmed", async () => {
+ await saveManagedDomainConfig(config);
+ vi.mocked(provider.ensureManagedDomainDns).mockImplementation(async () => {
+ expect((await readManagedDomains()).apps["9router"]).toMatchObject({ phase: "route-ready", routeAction: "created" });
+ return { id: "c".repeat(32), action: "created" };
+ });
+ expect((await ensureManagedAppDomain("9router"))?.phase).toBe("ready");
+});
+
+it("does not call a routed hostname ready while HTTPS or the application is unhealthy", async () => {
+ await saveManagedDomainConfig(config);
+ vi.mocked(probes.probePublicManagedDomain).mockRejectedValueOnce(new Error("certificate does not cover this hostname"));
+ expect(await ensureManagedAppDomain("9router")).toMatchObject({ phase: "blocked", routeAction: "created" });
+ vi.mocked(probeManagedAppRuntime).mockRejectedValueOnce(new Error("runtime not healthy"));
+ const result = await provisionDomainAfterStart("9router");
+ expect(result.domain?.verifiedAt).toBeUndefined();
+ expect(result.domainDiagnostic).toBe("runtime not healthy");
+});
+
+it("serializes applications without losing either desired record", async () => {
+ await saveManagedDomainConfig(config);
+ let active = 0, peak = 0;
+ vi.mocked(provider.ensureManagedDomainRoute).mockImplementation(async () => {
+ active++; peak = Math.max(peak, active);
+ await new Promise(resolve => setTimeout(resolve, 25));
+ active--; return { action: "created" };
+ });
+ const results = await Promise.all([ensureManagedAppDomain("9router"), ensureManagedAppDomain("hermes")]);
+ expect(results.map(row => row?.phase)).toEqual(["ready", "ready"]);
+ expect(peak).toBe(1);
+ expect(Object.keys((await readManagedDomains()).apps).sort()).toEqual(["9router", "hermes"]);
+});
+
+it("respects manual mode, and exposes corrupt configuration without undoing an app start", async () => {
+ expect(await provisionDomainAfterStart("9router")).toEqual({ domain: null, domainDiagnostic: null });
+ await saveManagedDomainConfig({ ...config, autoProvision: false });
+ expect((await provisionDomainAfterStart("9router")).domain).toBeNull();
+ expect(provider.ensureManagedDomainDns).not.toHaveBeenCalled();
+ expect((await ensureManagedAppDomain("9router"))?.phase).toBe("ready");
+ await fs.writeFile(process.env.OS_MANAGED_DOMAINS_STORE!, "{broken", { mode: 0o600 });
+ expect((await provisionDomainAfterStart("9router")).domainDiagnostic).toBeTruthy();
+ expect(await fs.readFile(process.env.OS_MANAGED_DOMAINS_STORE!, "utf8")).toBe("{broken");
+});
diff --git a/lib/managed-apps/domain-provision.ts b/lib/managed-apps/domain-provision.ts
new file mode 100644
index 00000000..f20d0bb0
--- /dev/null
+++ b/lib/managed-apps/domain-provision.ts
@@ -0,0 +1,74 @@
+import type { ManagedDomainRecord, ManagedDomainRoute } from "@/lib/contracts/managed-domains";
+import { withIntegrationSelection } from "@/lib/infra/connection-service";
+import { inspectManagedDomainRoute, ensureManagedDomainDns, ensureManagedDomainRoute } from "@/lib/infra/managed-domain";
+import { redactText } from "@/lib/security/redact-text";
+import { managedDomainHostname } from "./domain-config";
+import { probeManagedAppRuntime } from "./domain-health";
+import { probeLocalManagedDomain, probePublicManagedDomain } from "./domain-probe";
+import { mutateManagedDomains, readManagedDomains, withManagedDomainOperation } from "./domain-store";
+import type { ManagedAppId } from "./types";
+
+export async function ensureManagedAppDomain(id: ManagedAppId, automatic = false): Promise<ManagedDomainRecord | null> {
+ const initial = await readManagedDomains();
+ if (!initial.config || automatic && !initial.config.autoProvision) return null;
+ return withManagedDomainOperation(async () => {
+ const state = await readManagedDomains();
+ const config = state.config;
+ if (!config || automatic && !config.autoProvision) return null;
+ const hostname = managedDomainHostname(config, id);
+ const route: ManagedDomainRoute = {
+ hostname, hostTemplate: config.hostTemplate, cockpitHostname: new URL(config.publicOrigin).hostname, localOrigin: config.localOrigin,
+ zoneId: config.zoneId, zoneName: config.zoneName, accountId: config.accountId,
+ tunnelId: config.tunnelId, ownerTag: `mso:${state.ownerId}:${id}`,
+ routeMode: config.routeMode,
+ };
+ const current: ManagedDomainRecord = { ...state.apps[id], appId: id, hostname, phase: "pending", updatedAt: Date.now() };
+ delete current.error; delete current.verifiedAt;
+ const persist = async (patch: Partial<ManagedDomainRecord>) => {
+ Object.assign(current, patch, { updatedAt: Date.now() });
+ await mutateManagedDomains(next => { next.apps[id] = { ...current }; });
+ };
+ await persist({ phase: "pending" });
+ try {
+ // Arm and verify the existing auth router before introducing a public DNS route.
+ await probeLocalManagedDomain(config, hostname, id);
+ await withIntegrationSelection({ user: config.user, connection: config.connection }, async () => {
+ await inspectManagedDomainRoute(route);
+ // The authenticated ingress must be active before DNS can make the name public.
+ const ingress = await ensureManagedDomainRoute(route);
+ await persist({ phase: "route-ready", routeAction: ingress.action });
+ const dns = await ensureManagedDomainDns(route);
+ await persist({ phase: "dns-ready", dnsRecordId: dns.id, dnsAction: dns.action });
+ });
+ await probeManagedAppRuntime(id);
+ await probePublicManagedDomain(hostname, id);
+ await persist({ phase: "ready", verifiedAt: Date.now() });
+ } catch (error) {
+ await persist({ phase: "blocked", error: redactText(error instanceof Error ? error.message : "domain provisioning failed", 512) });
+ }
+ return { ...current };
+ });
+}
+
+export async function inspectManagedAppDomain(id: ManagedAppId): Promise<{ configured: boolean; hostname?: string; checks?: Record<string, string> }> {
+ const state = await readManagedDomains();
+ const config = state.config;
+ if (!config) return { configured: false };
+ const hostname = managedDomainHostname(config, id);
+ const checks: Record<string, string> = {};
+ for (const [name, check] of [
+ ["local", () => probeLocalManagedDomain(config, hostname, id)],
+ ["provider", () => withIntegrationSelection({ user: config.user, connection: config.connection }, () => inspectManagedDomainRoute({
+ hostname, hostTemplate: config.hostTemplate, cockpitHostname: new URL(config.publicOrigin).hostname, localOrigin: config.localOrigin,
+ zoneId: config.zoneId, zoneName: config.zoneName, accountId: config.accountId, tunnelId: config.tunnelId,
+ ownerTag: `mso:${state.ownerId}:${id}`,
+ routeMode: config.routeMode,
+ }))],
+ ["runtime", () => probeManagedAppRuntime(id)],
+ ["https", () => probePublicManagedDomain(hostname, id)],
+ ] as const) {
+ try { await check(); checks[name] = "ok"; }
+ catch (error) { checks[name] = redactText(error instanceof Error ? error.message : "check failed", 512); }
+ }
+ return { configured: true, hostname, checks };
+}
diff --git a/lib/managed-apps/domain-store.test.ts b/lib/managed-apps/domain-store.test.ts
new file mode 100644
index 00000000..2fe19ea4
--- /dev/null
+++ b/lib/managed-apps/domain-store.test.ts
@@ -0,0 +1,120 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { ManagedDomainConfig } from "@/lib/contracts/managed-domains";
+import { mutateManagedDomains, readManagedDomains, restoreManagedDomains, saveManagedDomainConfig, withManagedDomainOperation } from "./domain-store";
+
+const config: ManagedDomainConfig = {
+ publicOrigin: "https://mso.example.com", hostTemplate: "{id}.mso.example.com",
+ localOrigin: "http://127.0.0.1:4005", zoneId: "a".repeat(32), zoneName: "example.com",
+ accountId: "b".repeat(32), tunnelId: "12345678-1234-1234-1234-123456789abc",
+ user: "owner", connection: "cloudflare-main", autoProvision: true,
+};
+let directory: string;
+let file: string;
+beforeEach(async () => {
+ directory = await fs.mkdtemp(path.join(os.tmpdir(), "mso-domain-store-"));
+ file = path.join(directory, "domains.json");
+ vi.stubEnv("OS_MANAGED_DOMAINS_STORE", file);
+});
+afterEach(async () => {
+ vi.unstubAllEnvs();
+ await fs.rm(directory, { recursive: true, force: true });
+});
+
+describe("persistent managed-domain state", () => {
+ it("starts unconfigured and reloads the committed identity and configuration from disk", async () => {
+ expect(await readManagedDomains()).toMatchObject({ version: 1, revision: 0, config: null, apps: {} });
+ const saved = await saveManagedDomainConfig(config);
+ expect(saved.revision).toBe(1);
+ expect(await readManagedDomains()).toEqual(saved);
+ expect(JSON.parse(await fs.readFile(file, "utf8"))).toEqual(saved);
+ expect((await fs.stat(file)).mode & 0o777).toBe(0o600);
+ expect((await fs.stat(file)).uid).toBe(process.getuid?.());
+ });
+
+ it("retains a valid previous snapshot and restores it after a corrupt write", async () => {
+ const first = await saveManagedDomainConfig(config);
+ await saveManagedDomainConfig({ ...config, autoProvision: false });
+ expect(JSON.parse(await fs.readFile(`${file}.previous`, "utf8"))).toEqual(first);
+ expect((await fs.stat(`${file}.previous`)).mode & 0o777).toBe(0o600);
+ await fs.writeFile(file, "{interrupted-json", { mode: 0o600 });
+ await expect(readManagedDomains()).rejects.toThrow();
+ await expect(saveManagedDomainConfig(config)).rejects.toThrow();
+ expect(await fs.readFile(file, "utf8")).toBe("{interrupted-json");
+ const restored = await restoreManagedDomains();
+ expect(restored).toEqual({ ...first, revision: first.revision + 1 });
+ expect(await readManagedDomains()).toEqual(restored);
+ });
+
+ it("refuses malformed snapshots and never silently resets the store", async () => {
+ await saveManagedDomainConfig(config);
+ const invalid = { ...(await readManagedDomains()), version: 99 };
+ const content = JSON.stringify(invalid);
+ await fs.writeFile(file, content);
+ await expect(mutateManagedDomains(state => { state.apps = {}; })).rejects.toThrow();
+ expect(await fs.readFile(file, "utf8")).toBe(content);
+ await expect(restoreManagedDomains()).rejects.toThrow(/no previous/);
+ });
+
+ it("does not rebind an existing deployment or overwrite a good snapshot on validation failure", async () => {
+ await saveManagedDomainConfig(config);
+ const before = await fs.readFile(file, "utf8");
+ await expect(saveManagedDomainConfig({ ...config, tunnelId: "87654321-1234-1234-1234-123456789abc" })).rejects.toThrow(/different routing/);
+ await expect(mutateManagedDomains(state => { state.revision = -2; })).rejects.toThrow();
+ expect(await fs.readFile(file, "utf8")).toBe(before);
+ });
+
+ it("keeps each application when concurrent callers update the same store", async () => {
+ const initial = await saveManagedDomainConfig(config);
+ await Promise.all(["9router", "hermes", "openclaw"].map(appId => mutateManagedDomains(state => {
+ state.apps[appId] = { appId, hostname: `${appId}.mso.example.com`, phase: "pending", updatedAt: 10 };
+ })));
+ const state = await readManagedDomains();
+ expect(Object.keys(state.apps).sort()).toEqual(["9router", "hermes", "openclaw"]);
+ expect(state.revision).toBe(initial.revision + 3);
+ expect(state.ownerId).toBe(initial.ownerId);
+ });
+
+ it("serializes provisioning operations and releases the lock after a failure", async () => {
+ let active = 0;
+ let maximum = 0;
+ await Promise.all([1, 2, 3].map(() => withManagedDomainOperation(async () => {
+ maximum = Math.max(maximum, ++active);
+ await new Promise(resolve => setTimeout(resolve, 5));
+ active--;
+ })));
+ expect(maximum).toBe(1);
+ await expect(withManagedDomainOperation(async () => { throw new Error("provider failed"); })).rejects.toThrow("provider failed");
+ await expect(withManagedDomainOperation(async () => "retry")).resolves.toBe("retry");
+ });
+
+ it("refuses readable-by-others state without repairing or replacing it", async () => {
+ await saveManagedDomainConfig(config);
+ await fs.chmod(file, 0o644);
+ await expect(readManagedDomains()).rejects.toThrow(/unsafe/);
+ await expect(saveManagedDomainConfig(config)).rejects.toThrow(/unsafe/);
+ expect((await fs.stat(file)).mode & 0o777).toBe(0o644);
+ });
+
+ it("refuses a symlinked state file during reads, writes, and snapshot recovery", async () => {
+ await saveManagedDomainConfig(config);
+ await saveManagedDomainConfig({ ...config, autoProvision: false });
+ const target = path.join(directory, "unrelated.txt");
+ await fs.writeFile(target, "untouched", { mode: 0o600 });
+ await fs.unlink(file);
+ await fs.symlink(target, file);
+ await expect(readManagedDomains()).rejects.toThrow();
+ await expect(saveManagedDomainConfig(config)).rejects.toThrow();
+ await expect(restoreManagedDomains()).rejects.toThrow(/unsafe/);
+ expect(await fs.readFile(target, "utf8")).toBe("untouched");
+ expect((await fs.lstat(file)).isSymbolicLink()).toBe(true);
+ });
+
+ it("rejects an unsafe parent instead of creating state there", async () => {
+ await fs.chmod(directory, 0o777);
+ await expect(saveManagedDomainConfig(config)).rejects.toThrow(/parent/);
+ await expect(fs.stat(file)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+});
diff --git a/lib/managed-apps/domain-store.ts b/lib/managed-apps/domain-store.ts
new file mode 100644
index 00000000..d4585757
--- /dev/null
+++ b/lib/managed-apps/domain-store.ts
@@ -0,0 +1,87 @@
+import { constants, promises as fs } from "node:fs";
+import { randomUUID } from "node:crypto";
+import os from "node:os";
+import path from "node:path";
+import { expandOwnerStorePath } from "@/lib/owner-store-path.js";
+import { pinSecurityStorePath } from "@/lib/security-store-path";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import type { ManagedDomainConfig, ManagedDomainState } from "@/lib/contracts/managed-domains";
+import { validateDomainConfig, validateDomainState } from "./domain-config";
+
+const MAX_BYTES = 64 * 1024;
+export const managedDomainStorePath = () => expandOwnerStorePath(process.env.OS_MANAGED_DOMAINS_STORE ?? path.join(os.homedir(), ".mso", "private", "managed-domains.json"));
+const empty = (): ManagedDomainState => ({ version: 1, revision: 0, ownerId: randomUUID(), config: null, apps: {} });
+
+async function readFile(file: string): Promise<ManagedDomainState | null> {
+ let handle;
+ try {
+ handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size < 1 || stat.size > MAX_BYTES || stat.uid !== process.getuid?.() || (stat.mode & 0o077)) throw new Error("unsafe managed-domain state file");
+ return validateDomainState(JSON.parse(await handle.readFile("utf8")));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw error;
+ } finally { await handle?.close(); }
+}
+async function atomicWrite(file: string, state: ManagedDomainState): Promise<void> {
+ const text = JSON.stringify(validateDomainState(state), null, 2) + "\n";
+ if (Buffer.byteLength(text) > MAX_BYTES) throw new Error("managed-domain state capacity exceeded");
+ const temporary = `${file}.${randomUUID()}.tmp`;
+ try {
+ const handle = await fs.open(temporary, "wx", 0o600);
+ try { await handle.writeFile(text); await handle.sync(); } finally { await handle.close(); }
+ await fs.rename(temporary, file);
+ } finally { await fs.unlink(temporary).catch(() => undefined); }
+}
+export async function readManagedDomains(): Promise<ManagedDomainState> {
+ const pinned = await pinSecurityStorePath(managedDomainStorePath());
+ try { return await readFile(pinned.file) ?? empty(); }
+ finally { await pinned.directory.close(); }
+}
+export function withManagedDomainOperation<T>(run: () => Promise<T>): Promise<T> {
+ return withSecurityStoreLock(`${managedDomainStorePath()}.operation`, run, { busyTimeoutMs: 5_000 });
+}
+export function mutateManagedDomains<T>(change: (state: ManagedDomainState) => T): Promise<T> {
+ return withSecurityStoreLock(managedDomainStorePath(), async () => {
+ const pinned = await pinSecurityStorePath(managedDomainStorePath());
+ try {
+ const previous = await readFile(pinned.file);
+ const state = previous ? structuredClone(previous) : empty();
+ const result = change(state);
+ state.revision++;
+ validateDomainState(state);
+ if (previous) await atomicWrite(`${pinned.file}.previous`, previous);
+ await atomicWrite(pinned.file, state);
+ await pinned.directory.sync();
+ return result;
+ } finally { await pinned.directory.close(); }
+ });
+}
+export function saveManagedDomainConfig(input: ManagedDomainConfig): Promise<ManagedDomainState> {
+ const config = validateDomainConfig(input);
+ return withManagedDomainOperation(() => mutateManagedDomains(state => {
+ // Rebinding an existing hostname/account is a migration, not a retry.
+ if (state.config && Object.entries(config).some(([key, value]) => key !== "autoProvision" && state.config![key as keyof ManagedDomainConfig] !== value)) {
+ throw new Error("domain configuration already exists with different routing; preserve and migrate existing routes before replacing it");
+ }
+ state.config = config;
+ return state;
+ }));
+}
+export function restoreManagedDomains(): Promise<ManagedDomainState> {
+ return withManagedDomainOperation(() => withSecurityStoreLock(managedDomainStorePath(), async () => {
+ const pinned = await pinSecurityStorePath(managedDomainStorePath());
+ try {
+ const previous = await readFile(`${pinned.file}.previous`);
+ if (!previous) throw new Error("no previous managed-domain snapshot exists");
+ // Never follow or replace an unexpected object at the state filename.
+ const stat = await fs.lstat(pinned.file).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; return null; });
+ if (stat && (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))) throw new Error("unsafe managed-domain state file");
+ previous.revision++;
+ await atomicWrite(pinned.file, previous);
+ await pinned.directory.sync();
+ return previous;
+ } finally { await pinned.directory.close(); }
+ }));
+}
diff --git a/lib/managed-apps/health.ts b/lib/managed-apps/health.ts
new file mode 100644
index 00000000..6dd23ecd
--- /dev/null
+++ b/lib/managed-apps/health.ts
@@ -0,0 +1,13 @@
+import { managedAppUpstream } from "./upstream-target";
+import type { ManagedAppDefinition } from "./types";
+
+export async function managedAppHealth(definition: ManagedAppDefinition): Promise<boolean | null> {
+ try {
+ const base = managedAppUpstream(definition.dashboardUrl);
+ const target = new URL(definition.healthPath ?? "/health", base);
+ if (target.origin !== base.origin) return null;
+ const response = await fetch(target, { cache: "no-store", redirect: "error", signal: AbortSignal.timeout(4_000) });
+ await response.body?.cancel();
+ return response.ok;
+ } catch { return null; }
+}
diff --git a/lib/managed-apps/job-runner.ts b/lib/managed-apps/job-runner.ts
index 812cc330..0be0f141 100644
--- a/lib/managed-apps/job-runner.ts
+++ b/lib/managed-apps/job-runner.ts
@@ -1,5 +1,6 @@
import "server-only";
import { auditJobCompletion } from "./job-audit";
+import { appendDomainProvisioning } from "./domain-lifecycle";
import { spawnJobChild } from "./job-child";
import { pruneJobRecords, writeJobRecord } from "./job-store";
import { releaseOperation } from "./lock";
@@ -156,13 +157,23 @@ async function run(rt: Runtime, options: StartManagedAppJobOptions): Promise<voi
rt.dirty = true;
if (options.prepare) await options.prepare((text) => append(rt, text));
if (rt.record.argv.length) {
+ let succeeded = false;
+ let childExit: number | null = null;
await spawnJobChild(rt.record.argv, options, {
append: (text) => append(rt, text),
- finish: (status, exitCode, error) => finish(rt, status, exitCode, error),
+ finish: (status, exitCode, error) => {
+ if (status === "succeeded" && ["install", "update"].includes(rt.record.kind)) { succeeded = true; childExit = exitCode; }
+ else finish(rt, status, exitCode, error);
+ },
register: (terminate) => {
rt.terminate = terminate;
},
});
+ if (succeeded) {
+ rt.terminate = undefined;
+ await appendDomainProvisioning(rt.record.applicationId, text => append(rt, text));
+ finish(rt, "succeeded", childExit, null);
+ }
} else finish(rt, "succeeded", null, null); // prepare-only job (an in-process restore)
} catch (error) {
finish(rt, "failed", null, error instanceof Error ? error.message : String(error));
diff --git a/lib/managed-apps/manager.ts b/lib/managed-apps/manager.ts
index 3a2ae391..9c2d3393 100644
--- a/lib/managed-apps/manager.ts
+++ b/lib/managed-apps/manager.ts
@@ -1,9 +1,10 @@
import "server-only";
import os from "node:os";
-import { managedAppUpstream } from "./upstream-target";
+import { managedAppHealth } from "./health";
import { createBackup } from "./backups";
import { getManagedAppDefinition, listManagedAppDefinitions } from "./catalog";
import { dockerUsable, requireDocker, runDocker } from "./docker";
+import { provisionDomainAfterStart, readManagedDomainView } from "./domain-lifecycle";
import { acquireOperation, activeOperation, releaseOperation, withManagedAppOperationLease } from "./lock";
import { redact } from "./redact";
import { listJobRecords } from "./job-store";
@@ -67,19 +68,6 @@ async function running(installation: Installation, strict = false): Promise<bool
return false;
}
-async function health(definition: ManagedAppDefinition): Promise<boolean | null> {
- try {
- const base = managedAppUpstream(definition.dashboardUrl);
- const target = new URL(definition.healthPath ?? "/health", base);
- if (target.origin !== base.origin) return null;
- const response = await fetch(target, { cache: "no-store", redirect: "error", signal: AbortSignal.timeout(4_000) });
- await response.body?.cancel();
- return response.ok;
- } catch {
- return null;
- }
-}
-
/** Globally-routable IPv4 only. Private/CGNAT/link-local addresses are useful for
* MSO's internal proxy but are not the "works without a domain" address a user
* can open from their own browser. No external IP-discovery service is called. */
@@ -153,7 +141,7 @@ export async function getManagedApp(id: ManagedAppId): Promise<ManagedAppView> {
const definition = getManagedAppDefinition(id);
const installation = await detect(definition);
const isRunning = await running(installation);
- const isHealthy = isRunning ? await health(definition) : null;
+ const isHealthy = isRunning ? await managedAppHealth(definition) : null;
const operation = activeOperation(id);
const state = operation === "start"
? "starting"
@@ -165,6 +153,7 @@ export async function getManagedApp(id: ManagedAppId): Promise<ManagedAppView> {
? "running"
: "stopped";
const dockerInstallAvailable = definition.installBackends.includes("docker") && installation.type === "not-installed" && await dockerUsable();
+ const domainView = await readManagedDomainView(id);
return {
id,
name: definition.name,
@@ -175,7 +164,8 @@ export async function getManagedApp(id: ManagedAppId): Promise<ManagedAppView> {
healthy: isHealthy,
version: await version(definition),
dashboardAvailable: isRunning && isHealthy !== false,
- publicDashboardUrl: directDashboardUrl(definition),
+ publicDashboardUrl: domainView.domain?.phase === "ready" ? `https://${domainView.domain.hostname}` : directDashboardUrl(definition),
+ ...domainView,
supportedActions: actionsFor(installation),
// Only ever attached to a NEGATIVE reading. An app detected as present has
// been seen, and nothing about the bus can make that observation wrong.
@@ -244,7 +234,9 @@ export async function performManagedAppAction(id: ManagedAppId, action: ManagedA
versionCache.delete(id);
}
});
- return getManagedApp(id);
+ const domain = action === "start" || action === "restart" ? await provisionDomainAfterStart(id) : null;
+ const view = await getManagedApp(id);
+ return domain?.domainDiagnostic ? { ...view, domainDiagnostic: domain.domainDiagnostic } : view;
}
export async function getManagedAppLogs(id: ManagedAppId): Promise<ManagedAppLogs> {
diff --git a/lib/managed-apps/session.ts b/lib/managed-apps/session.ts
index 38a1072c..917f66ed 100644
--- a/lib/managed-apps/session.ts
+++ b/lib/managed-apps/session.ts
@@ -42,28 +42,29 @@ export async function managedAppSession(request: Request, id: ManagedAppId): Pro
}
const SCRIPT = "(async()=>{const p=new URLSearchParams(location.hash.slice(1));const t=p.get('app_ticket');p.delete('app_ticket');history.replaceState(null,'',location.pathname+location.search+(p.toString()?'#'+p.toString():''));if(!t){document.body.textContent='Open this application from MSO to authorize it.';return;}const r=await fetch('/__mso_app_auth',{method:'POST',headers:{authorization:'Bearer '+t},credentials:'include',cache:'no-store'});if(!r.ok){document.body.textContent='Application authorization failed. Reopen it from MSO.';return;}location.reload();})().catch(()=>{document.body.textContent='Application authorization failed.';});";
-function response(body: string | null, status: number, contentType = "text/plain; charset=utf-8") {
+function response(id: ManagedAppId, body: string | null, status: number, contentType = "text/plain; charset=utf-8") {
return new NextResponse(body, { status, headers: {
"content-type": contentType, "cache-control": "no-store, no-transform",
"cdn-cache-control": "no-store", "cloudflare-cdn-cache-control": "no-store",
"referrer-policy": "no-referrer", "x-content-type-options": "nosniff",
+ "x-mso-managed-app": id,
"content-security-policy": `default-src 'none'; script-src 'self'; connect-src 'self'; frame-ancestors ${cockpitOrigin() ?? "'none'"}`,
} });
}
// An app receives a purpose- and origin-bound credential, never the cockpit cookie.
export async function gateManagedApp(request: NextRequest, id: ManagedAppId): Promise<NextResponse | null> {
- if (request.nextUrl.pathname === "/__mso_app_bootstrap.js") return request.method === "GET" ? response(SCRIPT, 200, "application/javascript; charset=utf-8") : response(null, 404);
+ if (request.nextUrl.pathname === "/__mso_app_bootstrap.js") return request.method === "GET" ? response(id, SCRIPT, 200, "application/javascript; charset=utf-8") : response(id, null, 404);
if (request.nextUrl.pathname === "/__mso_app_auth") {
- if (request.method !== "POST" || request.headers.get("origin") !== managedAppOrigin(id)) return response(null, 403);
+ if (request.method !== "POST" || request.headers.get("origin") !== managedAppOrigin(id)) return response(id, null, 403);
const token = /^Bearer ([A-Za-z0-9._-]{20,4096})$/.exec(request.headers.get("authorization") ?? "")?.[1];
const secret = process.env.OS_SESSION_SECRET ?? "";
const session = token ? verifyManagedAppSession(id, token, secret, "ticket") : null;
- if (!session || !await liveSessionAuthorized(session, "operator")) return response(null, 401);
- const result = response(null, 204);
+ if (!session || !await liveSessionAuthorized(session, "operator")) return response(id, null, 401);
+ const result = response(id, null, 204);
result.cookies.set(MANAGED_APP_SESSION_COOKIE, createManagedAppCookie(id, session, secret), { httpOnly: true, secure: true, sameSite: "strict", path: "/", maxAge:Math.max(0,Math.floor((Math.min(session.parent_expires_at,Date.now()+COOKIE_TTL)-Date.now())/1000)) });
return result;
}
if (await managedAppSession(request, id)) return null;
- if (request.method !== "GET" || request.headers.get("sec-fetch-dest") !== "iframe" && request.headers.get("sec-fetch-dest") !== "document") return response(null, 401);
- return response('<!doctype html><meta charset="utf-8"><title>MSO application authorization</title><body><p>Authorizing application...</p><script src="/__mso_app_bootstrap.js" defer></script></body>', 200, "text/html; charset=utf-8");
+ if (request.method !== "GET" || request.headers.get("sec-fetch-dest") !== "iframe" && request.headers.get("sec-fetch-dest") !== "document") return response(id, null, 401);
+ return response(id, '<!doctype html><meta charset="utf-8"><title>MSO application authorization</title><body><p>Authorizing application...</p><script src="/__mso_app_bootstrap.js" defer></script></body>', 200, "text/html; charset=utf-8");
}
diff --git a/lib/managed-apps/types.ts b/lib/managed-apps/types.ts
index b0ccaa06..69f76331 100644
--- a/lib/managed-apps/types.ts
+++ b/lib/managed-apps/types.ts
@@ -1,3 +1,5 @@
+import type { ManagedDomainRecord } from "@/lib/contracts/managed-domains";
+
export const MANAGED_APP_IDS = ["hermes", "openclaw", "9router"] as const;
export type ManagedAppId = (typeof MANAGED_APP_IDS)[number];
@@ -61,6 +63,9 @@ export interface ManagedAppView {
* application domain when present, otherwise a public-IP:port fallback. null for
* loopback-only apps/hosts. This is never the trusted internal health target. */
publicDashboardUrl: string | null;
+ /** Durable DNS/route/HTTPS progress; application health is reported separately. */
+ domain?: ManagedDomainRecord | null;
+ domainDiagnostic?: string | null;
supportedActions: ManagedAppAction[];
/** Why this reading may be wrong, when MSO knows that it might be.
*
diff --git a/lib/security-store-path.ts b/lib/security-store-path.ts
index c3735daa..70c211bb 100644
--- a/lib/security-store-path.ts
+++ b/lib/security-store-path.ts
@@ -11,6 +11,7 @@ const STORE_ENV = [
"OS_A2A_STORE", "OS_A2A_TASK_STORE", "OS_A2A_CREDENTIAL_STORE", "OS_A2A_INBOUND_TOKEN_STORE",
"OS_A2A_LOCAL_AUTH_STORE", "OS_LOCAL_AGENT_MESSAGE_STORE", "OS_LOCAL_AGENT_PRESENCE_STORE",
"OS_CONFIG_STORE", "OS_PREFS_PATH", "OS_SKILL_MEMORY_STORE", "MSO_SURFACE_APPS_FILE",
+ "OS_MANAGED_DOMAINS_STORE",
] as const;
const DIRECTORY_ENV = ["OS_TOOL_FORGE_DIR", "OS_AGENT_MEMORY_DIR", "OS_AGENT_SESSIONS_DIR", "OS_PROJECT_AGENT_TASKS_DIR"] as const;
const expand = (value: string) => path.resolve(expandOwnerStorePath(value));
diff --git a/scripts/cli/commands-host.sh b/scripts/cli/commands-host.sh
index 50b9b242..8d52ed7d 100755
--- a/scripts/cli/commands-host.sh
+++ b/scripts/cli/commands-host.sh
@@ -110,15 +110,11 @@ case "$cmd" in
printf ' ok public origin (%s)\n' "$OS_PUBLIC_ORIGIN"
fi
- # Not a chk with a pass/fail: serving NO managed-app dashboards is supported.
- tpl="${NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE-}"; dom="${OS_SESSION_COOKIE_DOMAIN-}"
- if [ -n "$tpl" ] && [ -n "$dom" ]; then
- echo " ok app dashboards ($tpl) — after changing this, REBUILD and sign in again"
- elif [ -z "$tpl$dom" ]; then
- echo " -- app dashboards (off: no app host — managed-app windows open on the CLI view)"
+ tpl="${NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE-}"
+ if [ -n "$tpl" ]; then
+ echo " ok app dashboards ($tpl) — host-only app sessions; REBUILD after changing the template"
else
- printf ' FAIL app dashboards — set BOTH NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE and OS_SESSION_COOKIE_DOMAIN, or neither\n'
- fails=$((fails+1))
+ echo " -- app dashboards (off: no app host — managed-app windows open on the CLI view)"
fi
local_runtime=0
diff --git a/scripts/cli/commands-runtime.sh b/scripts/cli/commands-runtime.sh
index 4b909811..c66da372 100755
--- a/scripts/cli/commands-runtime.sh
+++ b/scripts/cli/commands-runtime.sh
@@ -18,6 +18,7 @@ case "$cmd" in
# ── 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" "$@" ;;
+ domain) source "$ROOT/scripts/cli/domains.sh"; run_domains "$@" ;;
heartbeat) MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" "$ROOT/scripts/mso-heartbeat" "$@" ;;
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 "$@" ;;
@@ -34,6 +35,7 @@ case "$cmd" in
# ── managed apps (hermes, openclaw…) ─────────────────────────────────────
apps) jget "/api/v1/apps" ;;
mapp)
+ source "$ROOT/scripts/cli/managed-apps.sh"
sub="${1:-list}"; shift || true
case "$sub" in
catalog) jget "/api/v1/app-catalog" ;;
@@ -48,6 +50,8 @@ case "$cmd" in
# Cached result only. The live probe is `update <id> check` (POST), gated.
pending) jget "/api/v1/managed-apps/$(enc "${1:?id}")/update" ;;
install) jpost "/api/v1/managed-apps/$(enc "${1:?id}")/install" "$(kv_args "${@:2}")" ;;
+ enable) mso_mapp_enable "$@" ;;
+ start|stop|restart) mso_mapp_lifecycle "$sub" "$@" ;;
update) jpost "/api/v1/managed-apps/$(enc "${1:?id}")/update" "$(kv_args "${@:2}")" ;;
# start|stop|restart|backup — MANAGED_APP_ACTIONS in lib/managed-apps/types.ts.
power) [ -n "${2-}" ] || die "usage: mso mapp power <id> <start|stop|restart|backup>"
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index 91054dce..2f448e1e 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -23,6 +23,7 @@ verbs() {
# you're wrong.
U_camoufox="camoufox status|start|stop|session"
U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"
+U_domain="domain status|setup --user <user> --connection <cloudflare-connection> [--origin <https://host>] [--template <{id}.host>] [--zone <name|id>] [--tunnel <UUID>] [--local <http://loopback:port>] [--manual] [--apply]|ensure <id> [--apply]|doctor <id>|repair-env [--apply]|restore [--apply]"
U_doctor="doctor [--fix]"
U_flow="flow list|inspect <id> [--project <project>]|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|save|delete <id> --revision <revision> [--input <JSON|@file>]"
U_workflow="workflow list|embeds|embed-save --input <JSON|@file>|show <id>|create --input <JSON|@file>|save <id> --revision <revision> --input <JSON|@file>|clone <id>|delete <id> --revision <revision>|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|runs <id>|versions <id>|restore <id> --revision <current> --version <saved>|catalog [--query q]|templates|template <id>|variables|variable-set <KEY> --input <JSON> [--secret]|variable-delete <KEY>|ai --prompt <text>"
@@ -32,7 +33,7 @@ U_agent_groups="agent-groups list|show <id>|create --input <JSON|@file>|save <id
U_provider="provider list|show <id>|setup <provider> <user> <connection>|set <id>|rm <id>|doctor [id]|projects|zones"
U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"
U_agent="agent [--continue|-c|--resume|-r <latest|index|id|title>|--yolo|-yolo] | agent --oneshot <prompt> [--json] [--approve-scope read|write|exec]"
-U_mapp="mapp catalog|shell-list|shell-save <JSON|@file>|list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"
+U_mapp="mapp enable <id> [install-key=value...]|start|stop|restart <id>|catalog|shell-list|shell-save <JSON|@file>|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]"
@@ -81,6 +82,7 @@ mso_cli_unknown() {
}
mso_cli_main() {
+ if [ "${1-}" = domain ] && { [ "${2-}" = help ] || [ "${2-}" = --help ] || [ "${2-}" = -h ]; }; then mso_cmd_runtime domain help; return; fi
if [ $# -ge 2 ]; then
case "$2" in
-h|--help|help)
@@ -102,7 +104,7 @@ mso_cli_main() {
case "$cmd" in
version|--version|-V|-v|ls|cat|raw|share|usage|search|project-candidates|write|mkdir|rm|mv|cp|zip|upload|exec|stats|ps|units|unit|packages|cleanup|status|health|doctor)
mso_cmd_host "$cmd" "$@" ;;
- agent|chat|model|setup|onboard|provider|providers|integrations|channels|agent-groups|flow|workflow|gateway|heartbeat|web|camoufox|apps|mapp|term)
+ agent|chat|model|setup|onboard|provider|providers|integrations|channels|agent-groups|flow|workflow|gateway|domain|heartbeat|web|camoufox|apps|mapp|term)
mso_cmd_runtime "$cmd" "$@" ;;
ai|cockpit|threads|agent-sessions|agents|org|a2a|memory|memory-graph|agent-vault|config|prefs|federation|models|jev|skills|changelog|stock)
mso_cmd_state "$cmd" "$@" ;;
diff --git a/scripts/cli/doctor-managed-apps.test.ts b/scripts/cli/doctor-managed-apps.test.ts
new file mode 100644
index 00000000..ba2b6193
--- /dev/null
+++ b/scripts/cli/doctor-managed-apps.test.ts
@@ -0,0 +1,53 @@
+import { spawnSync } from "node:child_process";
+import { expect, it } from "vitest";
+
+const fixture = `
+set -euo pipefail
+source scripts/cli/commands-host.sh
+ROOT="$PWD"; ENVF=scripts/cli/commands-host.sh
+PASS=fixture-password; OS_SESSION_SECRET=fixture-secret
+B=http://127.0.0.1:3000; JAR=fixture-cookie
+node(){ return 0; }
+service_manager_read(){ return 1; }
+cli_device(){ printf fixture-device; }
+dev_script(){ return 0; }
+mso_private_state_remove_file(){ return 0; }
+mso_private_state_ensure_file(){ printf '%s' "$1"; }
+curl(){ [ "$DOCTOR_RUNTIME_UP" = 1 ] || return 7; printf '{"status":"ok","service":"mso"}'; }
+jget(){ [ "$DOCTOR_RUNTIME_UP" = 1 ] || return 7; printf '{"authenticated":true}'; }
+mso_cmd_host doctor
+`;
+
+const doctor = (template: string, legacyCookieDomain: string, runtimeUp = true) => spawnSync("bash", ["-c", fixture], {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE: template,
+ OS_SESSION_COOKIE_DOMAIN: legacyCookieDomain,
+ OS_PUBLIC_ORIGIN: "",
+ DOCTOR_RUNTIME_UP: runtimeUp ? "1" : "0",
+ },
+});
+
+it.each([
+ ["", ""],
+ ["", ".example.com"],
+ ["https://{app}.example.com", ""],
+ ["https://{app}.example.com", ".example.com"],
+])("supports optional dashboard template %s with legacy cookie domain %s", (template, legacyCookieDomain) => {
+ const result = doctor(template, legacyCookieDomain);
+ expect(result.status).toBe(0);
+ expect(result.stdout).toContain(template ? `ok app dashboards (${template})` : "app dashboards (off:");
+ expect(result.stdout).not.toContain("FAIL");
+ expect(result.stdout).not.toContain("OS_SESSION_COOKIE_DOMAIN");
+ expect(result.stdout).toContain("all good.");
+});
+
+it("reports an unavailable runtime without inventing a dashboard configuration failure", () => {
+ const result = doctor("", ".example.com", false);
+ expect(result.status).toBe(1);
+ expect(result.stdout).toContain("FAIL reachable");
+ expect(result.stdout).toContain("app dashboards (off:");
+ expect(result.stdout).not.toContain("FAIL app dashboards");
+ expect(result.stdout).not.toContain("all good.");
+});
diff --git a/scripts/cli/domains.sh b/scripts/cli/domains.sh
new file mode 100644
index 00000000..bbe67e22
--- /dev/null
+++ b/scripts/cli/domains.sh
@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+# Owner-local domain settings remain available when the MSO web runtime is down.
+run_domains() {
+ [ -z "${BASE_OVERRIDE:-}${MSO_BASE:-}${OS_BASE:-}" ] \
+ || die "domain commands configure THIS host; omit --base/MSO_BASE/OS_BASE and run on the intended MSO host"
+ need bun
+ local domain_env domain_local
+ domain_env="$(realpath -m -- "$ENVF")"
+ domain_local="$(gateway_local_url)"
+ (cd "$ROOT"; MSO_DOMAIN_ENV="$domain_env" MSO_DOMAIN_LOCAL_ORIGIN="$domain_local" \
+ bun --no-env-file --conditions=react-server "$ROOT/scripts/mso-domain.ts" "$@")
+}
diff --git a/scripts/cli/managed-apps.sh b/scripts/cli/managed-apps.sh
new file mode 100644
index 00000000..af721652
--- /dev/null
+++ b/scripts/cli/managed-apps.sh
@@ -0,0 +1,33 @@
+#!/usr/bin/env bash
+# One application lifecycle: install if absent, wait for its job, then start.
+mso_mapp_result() {
+ local result="$1"
+ printf '%s\n' "$result"
+ if jq -e '.app.domainDiagnostic != null' <<<"$result" >/dev/null; then
+ echo "mso: application action completed; domain setup needs attention (see domainDiagnostic above)" >&2
+ return 2
+ fi
+}
+
+mso_mapp_lifecycle() {
+ local action="$1" id="${2:?application ID required}" response
+ [ "$#" -eq 2 ] || die "usage: mso mapp $action <id>"
+ response="$(jpost "/api/v1/managed-apps/$(enc "$id")" "$(jq -nc --arg a "$action" '{action:$a}')")" || return $?
+ mso_mapp_result "$response"
+}
+
+mso_mapp_enable() {
+ local id="${1:?application ID required}" response job
+ shift
+ case "$id" in hermes|openclaw|9router) ;; *) die "choose hermes, openclaw or 9router" ;; esac
+ response="$(jget "/api/v1/managed-apps/$(enc "$id")")"
+ if ! jq -e '.app.installed == true' <<<"$response" >/dev/null; then
+ response="$(jpost "/api/v1/managed-apps/$(enc "$id")/install" "$(kv_args "$@")")"
+ job="$(jq -r '.job.id // empty' <<<"$response")"
+ [ -n "$job" ] || die "installer did not return a job ID"
+ wait_managed_job "$id" "$job" >&2
+ elif [ "$#" -gt 0 ]; then
+ die "application is already installed; install options cannot change an existing installation"
+ fi
+ mso_mapp_lifecycle start "$id"
+}
diff --git a/scripts/cli/managed-apps.test.ts b/scripts/cli/managed-apps.test.ts
new file mode 100644
index 00000000..47875e30
--- /dev/null
+++ b/scripts/cli/managed-apps.test.ts
@@ -0,0 +1,44 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import { expect, it } from "vitest";
+
+const fixture = `
+set -euo pipefail
+source scripts/cli/managed-apps.sh
+die(){ echo "$*" >&2; exit 1; }
+enc(){ printf '%s' "$1"; }
+kv_args(){ printf '{}'; }
+jget(){ [ "$1" = /api/v1/managed-apps/9router ]; printf '{"app":{"installed":false}}'; }
+jpost(){
+ if [ "$1" = /api/v1/managed-apps/9router/install ]; then printf '{"job":{"id":"job-one"}}';
+ else [ "$1" = /api/v1/managed-apps/9router ]; jq -e '.action=="start"' <<<"$2" >/dev/null; printf '{"app":{"installed":true,"state":"running","domain":{"phase":"ready"}}}'; fi
+}
+wait_managed_job(){ [ "$1" = 9router ] && [ "$2" = job-one ]; echo 'waited for install'; }
+`;
+
+it("enables a missing app through install, job completion and the shared start API", () => {
+ const result = spawnSync("bash", ["-c", fixture + "mso_mapp_enable 9router"], { encoding: "utf8" });
+ expect(result.status).toBe(0);
+ expect(JSON.parse(result.stdout).app).toMatchObject({ installed: true, state: "running", domain: { phase: "ready" } });
+ expect(result.stderr).toContain("waited for install");
+});
+it("keeps an installed app and reports DNS attention through a nonzero exit", () => {
+ const script = fixture + `
+jget(){ printf '{"app":{"installed":true}}'; }
+jpost(){ [ "$1" = /api/v1/managed-apps/9router ]; printf '{"app":{"state":"running","domainDiagnostic":"certificate pending"}}'; }
+mso_mapp_enable 9router
+`;
+ const result = spawnSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(result.status).toBe(2);
+ expect(JSON.parse(result.stdout).app.state).toBe("running");
+ expect(result.stderr).toContain("domain setup needs attention");
+});
+it("refuses invalid IDs and fails before start when installation failed", () => {
+ expect(() => execFileSync("bash", ["-c", fixture + "mso_mapp_enable other"], { stdio: "pipe" })).toThrow();
+ expect(() => execFileSync("bash", ["-c", fixture + '\nwait_managed_job(){ return 1; }\nmso_mapp_enable 9router'], { stdio: "pipe" })).toThrow();
+});
+it("preserves a failed lifecycle request instead of reporting a successful action", () => {
+ const result = spawnSync("bash", ["-c", fixture + '\njpost(){ echo "request failed" >&2; return 22; }\nmso_mapp_lifecycle start 9router'], { encoding: "utf8" });
+ expect(result.status).toBe(22);
+ expect(result.stdout).toBe("");
+ expect(result.stderr).toContain("request failed");
+});
diff --git a/scripts/domain-cli.test.ts b/scripts/domain-cli.test.ts
new file mode 100644
index 00000000..56e6ee51
--- /dev/null
+++ b/scripts/domain-cli.test.ts
@@ -0,0 +1,38 @@
+import { spawnSync } from "node:child_process";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, expect, it } from "vitest";
+let directory: string;
+beforeEach(async () => { directory = await fs.mkdtemp(path.join(os.tmpdir(), "mso-domain-cli-")); });
+afterEach(async () => { await fs.rm(directory, { recursive: true, force: true }); });
+function run(...args: string[]) {
+ return spawnSync("bun", ["--no-env-file", "--conditions=react-server", "scripts/mso-domain.ts", ...args], {
+ encoding: "utf8", timeout: 10_000,
+ env: { ...process.env, OS_MANAGED_DOMAINS_STORE: path.join(directory, "domains.json") },
+ });
+}
+it("shows unconfigured status through the actual local Bun entrypoint", async () => {
+ const result = run("status");
+ expect(result.status, result.stderr).toBe(0);
+ expect(JSON.parse(result.stdout)).toMatchObject({ version: 1, config: null, apps: {}, desired: {} });
+ expect(await fs.stat(path.join(directory, "domains.json")).catch(() => null)).toBeNull();
+});
+it("rejects incomplete/unknown/credential arguments before any setup write", async () => {
+ for (const args of [["setup", "--origin", "https://mso.example.com"], ["setup", "--api-token", "example-value"], ["status", "--apply"], ["status", "9router"], ["ensure", "other"], ["doctor", "9router", "--apply"]]) {
+ const result = run(...args);
+ expect(result.status, args.join(" ")).toBe(1);
+ expect(result.stdout).toBe("");
+ expect(result.stderr).not.toContain("example-value");
+ }
+ expect(await fs.stat(path.join(directory, "domains.json")).catch(() => null)).toBeNull();
+});
+it("prints a usable help contract and returns attention for an unconfigured ensure", () => {
+ const help = run("help");
+ expect(help.status, help.stderr).toBe(0);
+ expect(help.stdout).toContain("mso domain setup");
+ expect(help.stdout).toContain("host-only");
+ const ensure = run("ensure", "9router", "--apply");
+ expect(ensure.status, ensure.stderr).toBe(2);
+ expect(JSON.parse(ensure.stdout)).toMatchObject({ configured: false });
+});
diff --git a/scripts/domain-env.test.ts b/scripts/domain-env.test.ts
new file mode 100644
index 00000000..14b19bb1
--- /dev/null
+++ b/scripts/domain-env.test.ts
@@ -0,0 +1,76 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { ManagedDomainConfig } from "../lib/contracts/managed-domains";
+import { managedDomainEnvironment } from "./domain-env";
+
+const config: ManagedDomainConfig = {
+ publicOrigin: "https://mso.example.com", hostTemplate: "{id}.mso.example.com",
+ localOrigin: "http://127.0.0.1:4005", zoneId: "a".repeat(32), zoneName: "example.com",
+ accountId: "b".repeat(32), tunnelId: "12345678-1234-1234-1234-123456789abc",
+ user: "owner", connection: "cloudflare-main", autoProvision: true,
+};
+const privateLines = "# Keep settings\nOS_SESSION_SECRET='fixture-value-only'\nOTHER=value=with=equals\n# OS_PUBLIC_ORIGIN=https://comment.example.com\n";
+let directory: string;
+let file: string;
+beforeEach(async () => {
+ directory = await fs.mkdtemp(path.join(os.tmpdir(), "mso-domain-env-"));
+ file = path.join(directory, ".env.local");
+ await fs.writeFile(file, `${privateLines}export OS_PUBLIC_ORIGIN=https://old.example.com\nNEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE={id}.old.example.com\n`, { mode: 0o600 });
+});
+afterEach(async () => { await fs.rm(directory, { recursive: true, force: true }); });
+
+describe("managed-domain environment repair", () => {
+ it("previews only public values without changing the env file or returning secrets", async () => {
+ const before = await fs.readFile(file, "utf8");
+ const result = await managedDomainEnvironment(file, config);
+ expect(result).toMatchObject({ changed: true, applied: false, values: {
+ OS_PUBLIC_ORIGIN: config.publicOrigin, NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE: config.hostTemplate,
+ } });
+ expect(JSON.stringify(result)).not.toContain("fixture-value-only");
+ expect(await fs.readFile(file, "utf8")).toBe(before);
+ });
+
+ it("replaces duplicate public assignments, preserves unrelated content, and remains idempotent", async () => {
+ await fs.appendFile(file, "OS_PUBLIC_ORIGIN=https://duplicate.example.com\n");
+ const first = await managedDomainEnvironment(file, config, true);
+ const changed = await fs.readFile(file, "utf8");
+ expect(first).toMatchObject({ changed: true, applied: true, restartRequired: true });
+ expect(changed).toBe(`${privateLines}OS_PUBLIC_ORIGIN=${config.publicOrigin}\nNEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE=${config.hostTemplate}\n`);
+ expect((await fs.stat(file)).mode & 0o777).toBe(0o600);
+ expect(await managedDomainEnvironment(file, config, true)).toMatchObject({ changed: false, applied: true, restartRequired: false });
+ expect(await fs.readFile(file, "utf8")).toBe(changed);
+ });
+
+ it("preserves a final unrelated line without a newline", async () => {
+ await fs.writeFile(file, "UNRELATED='last-line'");
+ await managedDomainEnvironment(file, config, true);
+ expect(await fs.readFile(file, "utf8")).toBe(`UNRELATED='last-line'\nOS_PUBLIC_ORIGIN=${config.publicOrigin}\nNEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE=${config.hostTemplate}\n`);
+ });
+
+ it("does not recreate a missing env file with incomplete server settings", async () => {
+ await fs.unlink(file);
+ await expect(managedDomainEnvironment(file, config, true)).rejects.toMatchObject({ code: "ENOENT" });
+ await expect(fs.stat(file)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+
+ it("refuses permissive files and invalid routing before rewriting existing settings", async () => {
+ const before = await fs.readFile(file, "utf8");
+ await fs.chmod(file, 0o644);
+ await expect(managedDomainEnvironment(file, config, true)).rejects.toThrow(/must be private/);
+ await fs.chmod(file, 0o600);
+ await expect(managedDomainEnvironment(file, { ...config, hostTemplate: "{id}.other.com" }, true)).rejects.toThrow();
+ expect(await fs.readFile(file, "utf8")).toBe(before);
+ });
+
+ it("refuses a symlink instead of editing the referenced env file", async () => {
+ const target = path.join(directory, "unrelated.env");
+ await fs.rename(file, target);
+ const before = await fs.readFile(target, "utf8");
+ await fs.symlink(target, file);
+ await expect(managedDomainEnvironment(file, config, true)).rejects.toThrow();
+ expect(await fs.readFile(target, "utf8")).toBe(before);
+ expect((await fs.lstat(file)).isSymbolicLink()).toBe(true);
+ });
+});
diff --git a/scripts/domain-env.ts b/scripts/domain-env.ts
new file mode 100644
index 00000000..11bc89a2
--- /dev/null
+++ b/scripts/domain-env.ts
@@ -0,0 +1,39 @@
+import { constants, promises as fs } from "node:fs";
+import { randomUUID } from "node:crypto";
+import { pinSecurityStorePath } from "../lib/security-store-path";
+import { withSecurityStoreLock } from "../lib/security-store-lock";
+import type { ManagedDomainConfig } from "../lib/contracts/managed-domains";
+import { validateDomainConfig } from "../lib/managed-apps/domain-config";
+
+export async function managedDomainEnvironment(file: string, input: ManagedDomainConfig, apply = false) {
+ const config = validateDomainConfig(input);
+ return withSecurityStoreLock(file, async () => {
+ const pinned = await pinSecurityStorePath(file);
+ try {
+ const handle = await fs.open(pinned.file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ let text: string;
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) || stat.size > 1024 * 1024) throw new Error("MSO env file must be private, owner-owned, and regular");
+ text = await handle.readFile("utf8");
+ } finally { await handle.close(); }
+ const values = { OS_PUBLIC_ORIGIN: config.publicOrigin, NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE: config.hostTemplate };
+ let next = text;
+ for (const [name, value] of Object.entries(values)) {
+ next = next.replace(new RegExp(`^(?:export[ \\t]+)?${name}[ \\t]*=.*(?:\\r?\\n|$)`, "gm"), "");
+ next += `${next.endsWith("\n") || !next ? "" : "\n"}${name}=${value}\n`;
+ }
+ const changed = next !== text;
+ if (apply && changed) {
+ const temporary = `${pinned.file}.${randomUUID()}.tmp`;
+ try {
+ const out = await fs.open(temporary, "wx", 0o600);
+ try { await out.writeFile(next); await out.sync(); } finally { await out.close(); }
+ await fs.rename(temporary, pinned.file);
+ await pinned.directory.sync();
+ } finally { await fs.unlink(temporary).catch(() => undefined); }
+ }
+ return { file, changed, applied: apply, values, restartRequired: changed };
+ } finally { await pinned.directory.close(); }
+ });
+}
diff --git a/scripts/lib/gateway-app-route-reload.sh b/scripts/lib/gateway-app-route-reload.sh
new file mode 100644
index 00000000..9b14671d
--- /dev/null
+++ b/scripts/lib/gateway-app-route-reload.sh
@@ -0,0 +1,124 @@
+#!/usr/bin/env bash
+# Persist connector replacement intent so retries can retire a leftover owned child.
+
+gateway_app_route_record_read() {
+ local file="$STATE_ROOT/app-route-reload.json"
+ if [ ! -e "$file" ] && [ ! -L "$file" ]; then printf '{}\n'; return 0; fi
+ mso_private_state_validate_file "$file" >/dev/null || gateway_fail "unsafe managed app route reload state"
+ jq -ce 'select(type=="object")' "$file" || gateway_fail "invalid managed app route reload state"
+}
+
+gateway_app_route_record() {
+ local result="$1" previous="$2" current="$3" phase="$4"
+ jq -nc --arg root "$GATEWAY_CANONICAL_ROOT" --arg scope "$GATEWAY_SCOPE_ID" --arg config "$GATEWAY_CONFIG" --arg tunnel "$GATEWAY_APP_TUNNEL_ID" \
+ --arg phase "$phase" --argjson result "$result" --argjson previous "$previous" --argjson current "$current" \
+ '{root:$root,scopeId:$scope,configPath:$config,tunnelId:$tunnel,phase:$phase,configSha256:$result.configSha256,previousIdentity:$previous,tunnelIdentity:$current}' \
+ | mso_private_state_atomic_write "$STATE_ROOT/app-route-reload.json" >/dev/null
+}
+
+gateway_app_route_record_matches() {
+ jq -e --arg root "$GATEWAY_CANONICAL_ROOT" --arg scope "$GATEWAY_SCOPE_ID" --arg config "$GATEWAY_CONFIG" --arg tunnel "$GATEWAY_APP_TUNNEL_ID" \
+ '.root==$root and .scopeId==$scope and .configPath==$config and .tunnelId==$tunnel' <<<"$1" >/dev/null
+}
+
+gateway_app_route_restore_previous() {
+ local state record current previous inspection
+ state="$(gateway_state_read)" || gateway_fail "cannot read gateway recovery state"
+ current="$(jq -c '.tunnelIdentity // null' <<<"$state")"
+ [ "$current" != null ] || return 0
+ gateway_identity_matches_retry "$current" && return 0
+ record="$(gateway_app_route_record_read)"
+ [ "$(jq -r '.phase // empty' <<<"$record")" = pending ] || return 0
+ jq -e --argjson current "$current" '.tunnelIdentity==$current and .previousIdentity!=null' <<<"$record" >/dev/null \
+ || gateway_fail "pending reload does not prove a prior connector for this interrupted state"
+ gateway_app_route_expected_context "$state" ensure
+ previous="$(jq -c .previousIdentity <<<"$record")"
+ gateway_app_route_owned_recipe "$previous"
+ gateway_app_route_record_matches "$record" || gateway_fail "pending reload belongs to another gateway or config"
+ inspection="$(gateway_app_route_config inspect)" || return 1
+ [ "$(jq -r .configSha256 <<<"$inspection")" = "$(jq -r .configSha256 <<<"$record")" ] \
+ || gateway_fail "named config changed after the interrupted reload"
+ gateway_identity_matches "$previous" || gateway_fail "prior connector changed before recovery"
+ # Change only the connector pointer. Runtime identity, env provenance, and all
+ # other durable fields remain exactly as recorded by the interrupted swap.
+ jq -c --argjson previous "$previous" '.tunnelIdentity=$previous' <<<"$state" \
+ | mso_private_state_atomic_write "$STATE_FILE" >/dev/null \
+ || gateway_fail "could not restore the proven prior connector state"
+}
+
+gateway_app_route_loaded() {
+ local record current
+ record="$(gateway_app_route_record_read)"
+ gateway_app_route_record_matches "$record" || return 1
+ current="$(jq -c .tunnelIdentity <<<"$GATEWAY_APP_STATE")"
+ jq -e --argjson result "$1" --argjson current "$current" \
+ '.phase=="ready" and .configSha256==$result.configSha256 and .tunnelIdentity==$current' <<<"$record" >/dev/null
+}
+
+gateway_app_route_recover_pending() {
+ local record current previous replacement
+ record="$(gateway_app_route_record_read)"
+ gateway_app_route_record_matches "$record" || return 0
+ [ "$(jq -r '.phase // empty' <<<"$record")" = pending ] || return 0
+ current="$(jq -c .tunnelIdentity <<<"$GATEWAY_APP_STATE")"
+ previous="$(jq -c '.previousIdentity // null' <<<"$record")"
+ replacement="$(jq -c '.tunnelIdentity // null' <<<"$record")"
+ if [ "$(jq -cS . <<<"$current")" = "$(jq -cS . <<<"$replacement")" ]; then
+ [ "$previous" = null ] || gateway_stop_identity "$previous" || gateway_fail "previous owned connector is still running"
+ elif [ "$(jq -cS . <<<"$current")" = "$(jq -cS . <<<"$previous")" ]; then
+ [ "$replacement" = null ] || gateway_stop_identity "$replacement" || gateway_fail "uncommitted owned connector is still running"
+ else
+ gateway_fail "managed app route reload state does not match the active connector"
+ fi
+}
+
+gateway_app_route_wait_connected() {
+ local seconds="${MSO_GATEWAY_PUBLIC_READY_SECONDS:-30}" deadline
+ [[ "$seconds" =~ ^[0-9]+$ ]] && [ "$seconds" -ge 10 ] && [ "$seconds" -le 120 ] \
+ || gateway_fail "MSO_GATEWAY_PUBLIC_READY_SECONDS must be an integer from 10 to 120"
+ deadline=$((SECONDS+seconds))
+ while [ "$SECONDS" -lt "$deadline" ]; do
+ gateway_identity_matches "$TUNNEL_IDENTITY" || return 1
+ grep -q 'Registered tunnel connection' "$PROVIDER_LOG" && return 0
+ sleep 0.2
+ done
+ return 1
+}
+
+gateway_app_route_reload() {
+ local result="$1" previous replacement hash published_log="$PROVIDER_LOG"
+ previous="$(jq -c .tunnelIdentity <<<"$GATEWAY_APP_STATE")"
+ hash="$(sha256sum -- "$GATEWAY_CONFIG" | awk '{print $1}')"
+ [ "$hash" = "$(jq -r .configSha256 <<<"$result")" ] || gateway_fail "named config changed before connector reload"
+ gateway_identity_matches "$previous" || gateway_fail "owned connector changed before reload"
+ # A fresh private inode ensures readiness cannot come from the old connector's
+ # still-open log descriptor. MSO's runtime and the old connector remain live.
+ PROVIDER_LOG="$(mktemp "$STATE_ROOT/.app-route-provider.XXXXXX.log")" \
+ || gateway_fail "cannot create a private replacement connector log"
+ gateway_private_file "$PROVIDER_LOG"
+ TUNNEL_IDENTITY=null; RUNTIME_STARTED_NOW=false
+ gateway_spawn_tunnel || gateway_fail "replacement connector did not start; existing connector remains active"
+ gateway_app_route_wait_connected || gateway_fail "replacement connector did not register a tunnel connection; previous connector remains active"
+ gateway_probe_public || gateway_fail "replacement connector could not verify the public MSO route"
+ gateway_refresh_tunnel_identity || gateway_fail "replacement connector lost its captured identity"
+ replacement="$TUNNEL_IDENTITY"
+ gateway_app_route_record "$result" "$previous" "$replacement" pending \
+ || gateway_fail "cannot persist connector replacement intent; existing connector remains active"
+ # The durable pending record owns cleanup from this point, including a crash
+ # before the state swap. EXIT must not kill an already-persisted replacement.
+ GATEWAY_PENDING_CLEANUP=0; TUNNEL_PENDING_PID=0; TUNNEL_PENDING_TICKS=''
+ if ! gateway_write_state cloudflare-named named "$GATEWAY_PUBLIC_URL" "$replacement"; then
+ gateway_stop_identity "$replacement" || true
+ gateway_fail "cannot persist replacement connector state; previous connector was retained"
+ fi
+ gateway_identity_matches "$replacement" || gateway_fail "replacement connector stopped; previous connector was retained for recovery"
+ gateway_stop_identity "$previous" || gateway_fail "previous connector is still running; reload can be retried"
+ gateway_probe_public && gateway_identity_matches "$replacement" \
+ || gateway_fail "replacement connector is not healthy; route config and pending reload were preserved for retry"
+ gateway_app_route_record "$result" null "$replacement" ready \
+ || gateway_fail "connector is healthy but its route receipt could not be saved; retry is safe"
+ gateway_private_file "$published_log"
+ mv -fT -- "$PROVIDER_LOG" "$published_log"
+ PROVIDER_LOG="$published_log"
+ GATEWAY_APP_STATE="$(gateway_state_read)"
+}
diff --git a/scripts/lib/gateway-app-route.sh b/scripts/lib/gateway-app-route.sh
new file mode 100644
index 00000000..785d809c
--- /dev/null
+++ b/scripts/lib/gateway-app-route.sh
@@ -0,0 +1,104 @@
+#!/usr/bin/env bash
+# Exact managed-app routes on an already MSO-owned named Cloudflare connector.
+
+GATEWAY_APP_ROUTE_HELPER="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/gateway-named-config.mjs"
+# shellcheck source=scripts/lib/gateway-app-route-reload.sh
+. "$(dirname "$GATEWAY_APP_ROUTE_HELPER")/gateway-app-route-reload.sh"
+
+gateway_app_route_config() {
+ node "$GATEWAY_APP_ROUTE_HELPER" "$ROOT" "$GATEWAY_CONFIG" "$GATEWAY_PUBLIC_URL" "$LOCAL_URL" \
+ "$GATEWAY_APP_TEMPLATE" "$1" "$GATEWAY_APP_HOST" "$GATEWAY_APP_TUNNEL_ID"
+}
+
+gateway_app_route_expected_context() {
+ local state="$1" action="$2" public expected
+ jq -e --arg root "$GATEWAY_CANONICAL_ROOT" '.provider=="cloudflare-named" and .mode=="named" and .root==$root and .tunnelIdentity!=null' <<<"$state" >/dev/null \
+ || gateway_fail "app routes require an existing MSO-owned named Cloudflare gateway"
+ public="$(gateway_validate_public_origin "${OS_PUBLIC_ORIGIN:-}" 2>/dev/null || true)"
+ expected="$(gateway_validate_public_origin "${GATEWAY_APP_EXPECT_PUBLIC:-}" 2>/dev/null || true)"
+ [ -n "$expected" ] && [ "$public" = "$expected" ] && [ "$(jq -r .url <<<"$state")" = "$public" ] \
+ || gateway_fail "expected public origin does not match this gateway and OS_PUBLIC_ORIGIN"
+ GATEWAY_APP_TEMPLATE="${GATEWAY_APP_EXPECT_TEMPLATE:-${NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE:-}}"
+ [ -n "$GATEWAY_APP_TEMPLATE" ] || gateway_fail "a managed app host template is required"
+ if [ "$action" = ensure ]; then
+ [ "$GATEWAY_APP_TEMPLATE" = "${NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE:-}" ] \
+ || gateway_fail "managed app host template is not active in the gateway env file"
+ fi
+ GATEWAY_MODE=named; GATEWAY_PROVIDER=cloudflare-named; GATEWAY_PUBLIC_URL="$public"
+}
+
+gateway_app_route_owned_recipe() {
+ local identity="$1" pid i found=0
+ local -a argv
+ jq -e '.cmdHash | type=="string" and test("^[0-9a-f]{64}$")' <<<"$identity" >/dev/null \
+ || gateway_fail "named connector lacks an exact recorded command identity"
+ gateway_identity_matches_retry "$identity" || gateway_fail "recorded named connector is not alive with its owned identity"
+ pid="$(jq -r .pid <<<"$identity")"
+ mapfile -d '' -t argv <"/proc/$pid/cmdline" || gateway_fail "cannot inspect the owned connector launch recipe"
+ for ((i=0; i<${#argv[@]}; i++)); do
+ [ "$((i+7))" = "${#argv[@]}" ] || continue
+ if [ "${argv[$((i+1))]}" = tunnel ] && [ "${argv[$((i+2))]}" = --config ] &&
+ [ "${argv[$((i+4))]}" = --no-autoupdate ] && [ "${argv[$((i+5))]}" = run ]; then
+ CLOUDFLARED="${argv[$i]}"; GATEWAY_CONFIG="${argv[$((i+3))]}"; GATEWAY_TUNNEL="${argv[$((i+6))]}"; found=1; break
+ fi
+ done
+ [ "$found" = 1 ] || gateway_fail "named connector does not match the MSO-owned launch recipe"
+ [[ "$CLOUDFLARED" = /* && "$GATEWAY_CONFIG" = /* && "$GATEWAY_TUNNEL" =~ ^[A-Za-z0-9_-]{1,80}$ ]] \
+ || gateway_fail "unsafe named connector launch recipe"
+ [ "$GATEWAY_TUNNEL" = "$GATEWAY_APP_TUNNEL_ID" ] \
+ || gateway_fail "owned connector must run the exact requested tunnel UUID"
+ [ -f "$CLOUDFLARED" ] && [ ! -L "$CLOUDFLARED" ] && [ -x "$CLOUDFLARED" ] \
+ || gateway_fail "recorded cloudflared executable is unavailable or unsafe"
+ gateway_identity_matches "$identity" || gateway_fail "named connector changed during inspection"
+}
+
+gateway_app_route_context() {
+ local action="$1" state identity
+ state="$(gateway_state_read)" || gateway_fail "cannot read the selected gateway state"
+ gateway_app_route_expected_context "$state" "$action"
+ identity="$(jq -c .tunnelIdentity <<<"$state")"
+ gateway_app_route_owned_recipe "$identity"
+ GATEWAY_APP_STATE="$state"
+ gateway_assert_port_loopback_only
+ gateway_runtime_from_state "$state"
+ gateway_assert_managed_runtime_trusted
+ LOCAL_HEALTH_IDENTITY="$(gateway_health_url_identity "$LOCAL_URL" "${RUNTIME_INSTANCE_ID:-}")" \
+ || gateway_fail "selected local MSO runtime is not healthy"
+ gateway_health_url_matches_identity "$GATEWAY_PUBLIC_URL" "$LOCAL_HEALTH_IDENTITY" \
+ || gateway_fail "public gateway does not match the selected local MSO runtime"
+ GATEWAY_APP_INSPECTION="$(gateway_app_route_config inspect)" || return 1
+}
+
+gateway_app_route_receipt() {
+ jq -c '{action,tunnelId,hostname}' <<<"$1"
+}
+
+gateway_app_route_inspect() {
+ gateway_app_route_context inspect
+ gateway_app_route_receipt "$GATEWAY_APP_INSPECTION"
+}
+
+gateway_app_route_ensure_locked() {
+ local result
+ gateway_app_route_restore_previous
+ gateway_app_route_context ensure
+ gateway_app_route_recover_pending
+ result="$(gateway_app_route_config ensure)" || return 1
+ if ! gateway_app_route_loaded "$result"; then
+ gateway_app_route_reload "$result"
+ fi
+ gateway_app_route_receipt "$result"
+}
+
+gateway_cmd_app_route() {
+ [ "$#" = 3 ] || gateway_fail "usage: mso gateway app-route inspect|ensure <hostname> <tunnel-uuid>"
+ GATEWAY_APP_HOST="$2"; GATEWAY_APP_TUNNEL_ID="$3"
+ # Provider status messages must never contaminate the JSON receipt on stdout.
+ gateway_info() { printf '%s\n' "$*" >&2; }
+ gateway_provider_load_cloudflare_adapter
+ case "$1" in
+ inspect) gateway_app_route_inspect ;;
+ ensure) gateway_with_lock gateway_with_runtime_shared gateway_app_route_ensure_locked ;;
+ *) gateway_fail "usage: mso gateway app-route inspect|ensure <hostname> <tunnel-uuid>" ;;
+ esac
+}
diff --git a/scripts/lib/gateway-named-config.mjs b/scripts/lib/gateway-named-config.mjs
new file mode 100644
index 00000000..8c2b8629
--- /dev/null
+++ b/scripts/lib/gateway-named-config.mjs
@@ -0,0 +1,111 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { createHash, randomBytes } from 'node:crypto';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+
+const loadModule = createRequire(import.meta.url);
+
+function object(value) { return value && typeof value === 'object' && !Array.isArray(value); }
+function reject(message) { throw new Error(message); }
+function hostname(value) {
+ return typeof value === 'string' && value.length <= 253 && value.split('.').length > 1 &&
+ value.split('.').every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label));
+}
+function appHosts(template) {
+ if (!template) return [];
+ if (!template.startsWith('{id}') || template.split('{id}').length !== 2) reject('invalid managed app host template');
+ const hosts = ['hermes', 'openclaw', '9router'].map((id) => template.replace('{id}', id));
+ if (!hosts.every(hostname)) reject('invalid managed app host template');
+ return hosts;
+}
+function readConfig(root, file) {
+ const YAML = loadModule(path.join(root, 'node_modules/yaml'));
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
+ let stat, text;
+ try {
+ stat = fs.fstatSync(fd);
+ if (!stat.isFile() || stat.uid !== process.getuid() || (stat.mode & 0o022)) reject('unsafe named tunnel config');
+ if (stat.size > 1024 * 1024) reject('named tunnel config is too large');
+ text = fs.readFileSync(fd, 'utf8');
+ } finally { fs.closeSync(fd); }
+ const doc = YAML.parseDocument(text, { uniqueKeys: true });
+ if (doc.errors.length) reject('invalid named tunnel YAML');
+ const cfg = doc.toJS({ maxAliasCount: 10 });
+ if (!object(cfg)) reject('invalid named tunnel config');
+ return { doc, cfg, text, stat };
+}
+function validateConfig(cfg, file, publicOrigin, localOrigin, template, exact = false) {
+ const publicHost = new URL(publicOrigin).hostname;
+ const local = new URL(localOrigin), allowed = new Set(appHosts(template));
+ if (allowed.has(publicHost)) reject('managed app host collides with cockpit');
+ const rules = cfg.ingress;
+ if (!Array.isArray(rules) || rules.length < 2 || rules.length > 5) reject('named config requires cockpit and exact managed app ingress');
+ const last = rules.at(-1);
+ if (!object(last) || Object.keys(last).some((key) => key !== 'service') || last.service !== 'http_status:404') reject('named config must end in http_status:404');
+ const seen = new Set();
+ for (const [index, rule] of rules.slice(0, -1).entries()) {
+ if (!object(rule) || typeof rule.hostname !== 'string') reject('invalid exact ingress host');
+ const host = rule.hostname.toLowerCase();
+ if ((index === 0 && host !== publicHost) || (index > 0 && !allowed.has(host)) || seen.has(host)) reject('unrelated or duplicate ingress host');
+ if (rule.path !== undefined) reject('path-limited ingress is not a managed application route');
+ seen.add(host);
+ let service;
+ try { service = new URL(rule.service); } catch { reject('invalid ingress service'); }
+ const octets = service.hostname.split('.');
+ const loopback = ['localhost', '[::1]'].includes(service.hostname) ||
+ (octets.length === 4 && octets[0] === '127' && octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255));
+ if (service.protocol !== 'http:' || !loopback || service.port !== local.port || service.pathname !== '/' ||
+ service.username || service.password || service.search || service.hash || ((index > 0 || exact) && service.origin !== local.origin)) reject('ingress must target the selected MSO loopback origin');
+ for (const request of [cfg.originRequest, rule.originRequest]) {
+ if (request !== undefined && !object(request)) reject('invalid originRequest');
+ }
+ const override = rule.originRequest?.httpHostHeader ?? cfg.originRequest?.httpHostHeader;
+ if (override !== undefined && (typeof override !== 'string' || override.toLowerCase() !== host)) reject('ingress Host override would bypass managed app routing');
+ }
+ let cred = cfg['credentials-file'];
+ if (typeof cred !== 'string' || !cred.trim()) reject('named config requires credentials-file');
+ cred = cred.trim();
+ if (cred.startsWith('~/')) cred = path.join(process.env.HOME || '', cred.slice(2));
+ if (!path.isAbsolute(cred)) cred = path.resolve(path.dirname(file), cred);
+ const st = fs.lstatSync(cred);
+ if (!st.isFile() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077)) reject('credentials-file must be private and owner-owned');
+}
+function atomicReplace(file, snapshot, text) {
+ const current = fs.lstatSync(file);
+ if (!current.isFile() || current.isSymbolicLink() || current.dev !== snapshot.stat.dev || current.ino !== snapshot.stat.ino ||
+ current.mode !== snapshot.stat.mode || fs.readFileSync(file, 'utf8') !== snapshot.text) reject('named tunnel config changed concurrently');
+ const temp = path.join(path.dirname(file), `.mso-app-route-${process.pid}-${randomBytes(6).toString('hex')}`);
+ const fd = fs.openSync(temp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, snapshot.stat.mode & 0o777);
+ try {
+ try { fs.writeFileSync(fd, text); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+ fs.renameSync(temp, file);
+ const directory = fs.openSync(path.dirname(file), fs.constants.O_RDONLY);
+ try { fs.fsyncSync(directory); } finally { fs.closeSync(directory); }
+ } finally { if (fs.existsSync(temp)) fs.unlinkSync(temp); }
+}
+function execute(args) {
+ const [root, file, publicOrigin, localOrigin, template, action = 'validate', host, tunnelId] = args;
+ const snapshot = readConfig(root, file);
+ validateConfig(snapshot.cfg, file, publicOrigin, localOrigin, template, action !== 'validate');
+ if (action === 'validate') return;
+ if (!['inspect', 'ensure'].includes(action) || !appHosts(template).includes(host)) reject('unknown managed app hostname or operation');
+ if (!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(tunnelId) || snapshot.cfg.tunnel !== tunnelId) reject('named tunnel UUID does not match the requested tunnel');
+ const exists = snapshot.cfg.ingress.some((rule) => rule.hostname?.toLowerCase() === host);
+ let text = snapshot.text;
+ if (!exists && action === 'ensure') {
+ const rule = { hostname: host, service: localOrigin };
+ if (snapshot.cfg.originRequest?.httpHostHeader !== undefined) rule.originRequest = { httpHostHeader: host };
+ const node = snapshot.doc.createNode(rule);
+ snapshot.doc.get('ingress', true).items.splice(snapshot.cfg.ingress.length - 1, 0, node);
+ validateConfig(snapshot.doc.toJS({ maxAliasCount: 10 }), file, publicOrigin, localOrigin, template, true);
+ text = String(snapshot.doc);
+ atomicReplace(file, snapshot, text);
+ }
+ return { action: exists ? 'unchanged' : 'created', tunnelId, hostname: host, configSha256: createHash('sha256').update(text).digest('hex') };
+}
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ try { const result = execute(process.argv.slice(2)); if (result) process.stdout.write(JSON.stringify(result) + '\n'); }
+ catch (error) { process.stderr.write(`mso gateway: ${error.code ? 'cannot safely read named config or credential metadata' : error.message}\n`); process.exitCode = 1; }
+}
+export { appHosts, readConfig, validateConfig, atomicReplace, execute };
diff --git a/scripts/lib/gateway-tunnel.sh b/scripts/lib/gateway-tunnel.sh
index 0620ff4c..bd84f037 100644
--- a/scripts/lib/gateway-tunnel.sh
+++ b/scripts/lib/gateway-tunnel.sh
@@ -1,5 +1,6 @@
#!/usr/bin/env bash
# Cloudflare tunnel start path. The application port always remains loopback-only.
+GATEWAY_NAMED_CONFIG_HELPER="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/gateway-named-config.mjs"
gateway_parse_start_args() {
GATEWAY_CONFIG=""; GATEWAY_TUNNEL=""; GATEWAY_MODE=temporary; GATEWAY_PROVIDER=cloudflare-quick
@@ -14,35 +15,7 @@ gateway_parse_start_args() {
}
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
+ node "$GATEWAY_NAMED_CONFIG_HELPER" "$ROOT" "$GATEWAY_CONFIG" "$GATEWAY_PUBLIC_URL" "$LOCAL_URL" "${NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE:-}"
}
gateway_validate_named_tunnel() {
diff --git a/scripts/mso-domain.ts b/scripts/mso-domain.ts
new file mode 100644
index 00000000..c2d3162e
--- /dev/null
+++ b/scripts/mso-domain.ts
@@ -0,0 +1,125 @@
+#!/usr/bin/env bun
+import path from "node:path";
+import { withIntegrationSelection } from "../lib/infra/connection-service";
+import { inspectManagedDomainRoute } from "../lib/infra/managed-domain";
+import { cleanDomainOrigin, managedDomainHostname, validateDomainConfig } from "../lib/managed-apps/domain-config";
+import { discoverManagedDomainTarget } from "../lib/managed-apps/domain-discovery";
+import { ensureManagedAppDomain, inspectManagedAppDomain } from "../lib/managed-apps/domain-provision";
+import { managedDomainStorePath, readManagedDomains, restoreManagedDomains, saveManagedDomainConfig } from "../lib/managed-apps/domain-store";
+import { MANAGED_APP_IDS, type ManagedAppId } from "../lib/managed-apps/types";
+import { redactText } from "../lib/security/redact-text";
+import { managedDomainEnvironment } from "./domain-env";
+
+const HELP = `mso domain: persistent managed-application DNS and tunnel routes
+
+ mso domain status
+ mso domain setup --user <integration-user> --connection <cloudflare-connection>
+ [--origin https://mso.example.com] [--template '{id}.mso.example.com']
+ [--zone <zone-name-or-id>] [--tunnel <UUID>] [--local http://127.0.0.1:4005]
+ [--manual] [--apply]
+ mso domain ensure <hermes|openclaw|9router> [--apply]
+ mso domain doctor <hermes|openclaw|9router>
+ mso domain repair-env [--apply]
+ mso domain restore [--apply]
+
+Setup discovers the existing zone/account/tunnel from the MSO hostname, then stores
+only named credential references. Enter Cloudflare credentials privately in MSO
+Integrations. Required API access: Zone Read, DNS Edit, and Cloudflare Tunnel Edit.
+Setup/ensure/repair-env/restore preview by default; --apply performs that operation.
+After first setup, run mso deploy (or mso update --rebuild for a gateway-owned
+runtime) to activate the app-host template. App installs, starts and restarts
+then provision automatically unless setup uses --manual.
+Existing remotely managed tunnels and MSO-owned named local tunnels are supported.
+External local tunnels are left untouched. DNS and HTTPS readiness are separate.
+App hosts retain MSO authorization through app-bound, host-only cookies.
+Nested hosts need an edge certificate covering their exact hostname; MSO never
+purchases a certificate or treats a DNS record as proof that HTTPS works.`;
+
+const [action = "status", ...argv] = process.argv.slice(2);
+const options: Record<string, string | boolean> = {};
+let appId: string | undefined;
+const valueFlags = new Set(["user", "connection", "origin", "template", "zone", "tunnel", "local"]);
+for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (!arg.startsWith("--")) { if (appId) fail("only one application ID is allowed"); appId = arg; continue; }
+ const name = arg.slice(2);
+ if (Object.hasOwn(options, name)) fail(`duplicate option --${name}`);
+ if (["apply", "manual", "json"].includes(name)) options[name] = true;
+ else if (valueFlags.has(name) && argv[i + 1] && !argv[i + 1].startsWith("--")) options[name] = argv[++i];
+ else fail(`unknown or incomplete option --${name}`);
+}
+function fail(message: string): never { process.stderr.write(`mso domain: ${redactText(message, 1024)}\n`); process.exit(1); }
+function emit(value: unknown) { process.stdout.write(JSON.stringify(value, null, 2) + "\n"); }
+function str(key: string) { return typeof options[key] === "string" ? options[key] as string : undefined; }
+function selectedApp(): ManagedAppId {
+ if (!(MANAGED_APP_IDS as readonly string[]).includes(appId ?? "")) fail("choose hermes, openclaw or 9router");
+ return appId as ManagedAppId;
+}
+function envFile() { return path.resolve(process.env.MSO_DOMAIN_ENV ?? path.join(process.cwd(), ".env.local")); }
+
+async function main() {
+ if (["help", "--help", "-h"].includes(action)) { process.stdout.write(HELP + "\n"); return; }
+ if (!["status", "setup", "ensure", "doctor", "repair-env", "restore"].includes(action)) fail("unknown command; run mso domain help");
+ if (action !== "setup" && Object.keys(options).some(key => valueFlags.has(key) || key === "manual")) fail("setup options belong only to mso domain setup");
+ if (!["ensure", "doctor"].includes(action) && appId) fail("this command takes no application ID");
+ if (["status", "doctor"].includes(action) && options.apply) fail(`${action} is read-only; omit --apply`);
+ if (action === "status") {
+ const state = await readManagedDomains();
+ emit({ store: managedDomainStorePath(), ...state, desired: state.config ? Object.fromEntries(MANAGED_APP_IDS.map(id => [id, `https://${managedDomainHostname(state.config!, id)}`])) : {} });
+ return;
+ }
+ if (action === "setup") {
+ if (appId) fail("setup takes named options, not an application ID");
+ const publicOrigin = cleanDomainOrigin(str("origin") ?? process.env.OS_PUBLIC_ORIGIN ?? "");
+ const user = str("user"), connection = str("connection");
+ if (!user || !connection) fail("--user and --connection select the existing Cloudflare integration");
+ const target = await withIntegrationSelection({ user, connection }, () => discoverManagedDomainTarget(publicOrigin, str("zone"), str("tunnel")));
+ const config = validateDomainConfig({ ...target, publicOrigin, user, connection,
+ hostTemplate: str("template") ?? (process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE?.trim() || `{id}.${new URL(publicOrigin).hostname}`),
+ localOrigin: cleanDomainOrigin(str("local") ?? process.env.MSO_DOMAIN_LOCAL_ORIGIN ?? "http://127.0.0.1:4005", true),
+ autoProvision: options.manual !== true,
+ });
+ const saved = await readManagedDomains();
+ let environment = await managedDomainEnvironment(envFile(), config, false);
+ await withIntegrationSelection({ user, connection }, () => inspectManagedDomainRoute({ ...target,
+ hostname: managedDomainHostname(config, "9router"), hostTemplate: config.hostTemplate, cockpitHostname: new URL(publicOrigin).hostname,
+ localOrigin: config.localOrigin, ownerTag: `mso:${saved.ownerId}:9router`,
+ }));
+ if (options.apply) {
+ await saveManagedDomainConfig(config);
+ try { environment = await managedDomainEnvironment(envFile(), config, true); }
+ catch (error) {
+ throw new Error(`Domain configuration was saved, but the environment update failed: ${error instanceof Error ? error.message : "write failed"}. Retry mso domain repair-env --apply`);
+ }
+ }
+ emit({ applied: options.apply === true, config, environment, store: managedDomainStorePath(),
+ next: "Run mso deploy (or mso update --rebuild for a gateway-owned runtime) once to activate this template, then mso mapp enable 9router (or mso domain ensure 9router --apply for an already running app).",
+ tls: "Every generated hostname requires valid HTTPS; nested names may require an explicitly issued edge certificate.",
+ });
+ return;
+ }
+ if (action === "ensure") {
+ const id = selectedApp();
+ if (!options.apply) { emit({ preview: true, ...(await inspectManagedAppDomain(id)), next: `mso domain ensure ${id} --apply` }); return; }
+ const result = await ensureManagedAppDomain(id);
+ emit(result ?? { configured: false, next: "mso domain setup --user <user> --connection <connection> --apply" });
+ if (!result || result.phase !== "ready") process.exitCode = 2;
+ return;
+ }
+ if (action === "doctor") {
+ const result = await inspectManagedAppDomain(selectedApp()); emit(result);
+ if (!result.configured || Object.values(result.checks ?? {}).some(value => value !== "ok")) process.exitCode = 2;
+ return;
+ }
+ if (appId) fail("this command takes no application ID");
+ if (action === "repair-env") {
+ const { config } = await readManagedDomains();
+ if (!config) fail("no saved domain setup exists");
+ emit(await managedDomainEnvironment(envFile(), config, options.apply === true)); return;
+ }
+ if (action === "restore") {
+ emit(options.apply ? await restoreManagedDomains() : { preview: true, source: `${managedDomainStorePath()}.previous`, next: "mso domain restore --apply; mso domain repair-env --apply" }); return;
+ }
+ fail("unknown command; run mso domain help");
+}
+try { await main(); } catch (error) { fail(error instanceof Error ? error.message : "operation failed"); }
diff --git a/scripts/mso-gateway b/scripts/mso-gateway
index e8f235f5..5dd8607d 100755
--- a/scripts/mso-gateway
+++ b/scripts/mso-gateway
@@ -7,6 +7,8 @@ umask 077
ROOT="${MSO_GATEWAY_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
ENVF="${MSO_GATEWAY_ENV:-$ROOT/.env.local}"
LOCAL_URL_OVERRIDE="${MSO_GATEWAY_LOCAL_URL:-}"
+GATEWAY_APP_EXPECT_PUBLIC="${MSO_GATEWAY_EXPECT_PUBLIC_ORIGIN:-}"
+GATEWAY_APP_EXPECT_TEMPLATE="${MSO_GATEWAY_EXPECT_APP_HOST_TEMPLATE:-}"
LOCAL_URL=""
STATE_ROOT_OVERRIDE="${MSO_GATEWAY_STATE_DIR:-}"
UPDATE_STATE_DIR_REQUESTED="${MSO_UPDATE_STATE_DIR:-$HOME/.mso/private/update-state}"
@@ -105,6 +107,7 @@ case "${1:-status}" in
doctor) gateway_cmd_doctor ;;
install) gateway_provider_install ;;
domain) shift; gateway_cmd_domain "$@" ;;
+ app-route) shift; . "$ROOT/scripts/lib/gateway-app-route.sh"; gateway_cmd_app_route "$@" ;;
web) gateway_cmd_web "$@" ;;
local-start) gateway_with_lock gateway_with_runtime_shared gateway_cmd_local_start_locked ;; # internal: onboard/web/update fallback
runtime-assert-update-safe) gateway_with_lock gateway_cmd_runtime_assert_update_safe_locked ;; # internal: read-only offline-build preflight
diff --git a/scripts/mso-gateway-app-route-recovery.test.ts b/scripts/mso-gateway-app-route-recovery.test.ts
new file mode 100644
index 00000000..278dae10
--- /dev/null
+++ b/scripts/mso-gateway-app-route-recovery.test.ts
@@ -0,0 +1,93 @@
+import { spawn, spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it, onTestFinished } from "vitest";
+import { GATEWAY, ROOT, fixture, runGateway } from "./mso-gateway-test-fixture";
+
+const TUNNEL = "11111111-2222-4333-8444-555555555555", HOST = "9router.mso.example.test";
+const TEMPLATE = "{id}.mso.example.test";
+function processIdentity(pid: number) {
+ const proc = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
+ return { pid, startTicks: proc.slice(proc.lastIndexOf(") ") + 2).split(" ")[19], exe: fs.realpathSync(`/proc/${pid}/exe`),
+ cmdHash: createHash("sha256").update(fs.readFileSync(`/proc/${pid}/cmdline`)).digest("hex") };
+}
+function stop(pid: number) { try { process.kill(pid, "SIGTERM"); } catch { /* already stopped by the gateway */ } }
+
+async function interruptedSwap() {
+ const f = fixture(), config = path.join(f.dir, "cloudflared.yml"), credential = path.join(f.dir, "credential.json");
+ fs.writeFileSync(credential, "fixture-credential-metadata-only", { mode: 0o600 });
+ fs.writeFileSync(config, `tunnel: ${TUNNEL}\ncredentials-file: ${credential}\ningress:\n - hostname: mso.example.test\n service: http://127.0.0.1:4005\n - hostname: ${HOST}\n service: http://127.0.0.1:4005\n - service: http_status:404\n`, { mode: 0o600 });
+ fs.appendFileSync(f.envFile, `OS_PUBLIC_ORIGIN=https://mso.example.test\nNEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE=${TEMPLATE}\n`);
+ fs.writeFileSync(f.cloudflared, `#!/usr/bin/env node
+const fs = require('fs');
+if (fs.existsSync(process.env.HOME + '/deny-connector')) process.exit(17);
+console.error('Registered tunnel connection');
+process.on('SIGTERM', () => process.exit(0)); setInterval(() => {}, 1000);
+`, { mode: 0o700 });
+ const env = { ...f.baseEnv, NODE_ENV: "test" as const, MSO_GATEWAY_EXPECT_PUBLIC_ORIGIN: "https://mso.example.test", MSO_GATEWAY_EXPECT_APP_HOST_TEMPLATE: TEMPLATE };
+ runGateway(["start", "--config", config, "--tunnel", TUNNEL], env);
+ const stateFile = path.join(f.state, "state.json"), recordFile = path.join(f.state, "app-route-reload.json");
+ const original = JSON.parse(fs.readFileSync(stateFile, "utf8"));
+ onTestFinished(() => stop(original.tunnelIdentity.pid));
+ const replacement = spawn(process.execPath, [f.cloudflared, "tunnel", "--config", config, "--no-autoupdate", "run", TUNNEL], { stdio: "ignore", env: { ...env, HOME: f.dir } });
+ const dead = processIdentity(replacement.pid!);
+ await new Promise<void>((resolve) => { replacement.once("exit", () => resolve()); replacement.kill(); });
+ const record = { root: fs.realpathSync(ROOT), scopeId: original.scopeId, configPath: config, tunnelId: TUNNEL, phase: "pending",
+ configSha256: createHash("sha256").update(fs.readFileSync(config)).digest("hex"), previousIdentity: original.tunnelIdentity, tunnelIdentity: dead };
+ fs.writeFileSync(stateFile, JSON.stringify({ ...original, tunnelIdentity: dead }), { mode: 0o600 });
+ fs.writeFileSync(recordFile, JSON.stringify(record), { mode: 0o600 });
+ return { ...f, env, config, stateFile, recordFile, original, record };
+}
+function ensure(f: Awaited<ReturnType<typeof interruptedSwap>>) {
+ return spawnSync(GATEWAY, ["app-route", "ensure", HOST, TUNNEL], { encoding: "utf8", env: f.env, timeout: 25_000 });
+}
+
+describe("interrupted named connector swaps", () => {
+ it("restores a proven live prior connector before normal validation, then completes the saved route on retry", async () => {
+ const f = await interruptedSwap();
+ const inspect = spawnSync(GATEWAY, ["app-route", "inspect", HOST, TUNNEL], { encoding: "utf8", env: f.env });
+ expect(inspect.status).toBe(1);
+ expect(JSON.parse(fs.readFileSync(f.stateFile, "utf8")).tunnelIdentity).toEqual(f.record.tunnelIdentity);
+ fs.writeFileSync(path.join(f.dir, "deny-connector"), "1", { mode: 0o600 });
+ const first = ensure(f);
+ expect(first.status, first.stderr).toBe(1);
+ expect(first.stderr).toContain("replacement connector did not start");
+ expect(JSON.parse(fs.readFileSync(f.stateFile, "utf8"))).toEqual(f.original);
+ expect(() => process.kill(f.original.tunnelIdentity.pid, 0)).not.toThrow();
+ fs.unlinkSync(path.join(f.dir, "deny-connector"));
+ const second = ensure(f);
+ expect(second.status, second.stderr).toBe(0);
+ expect(JSON.parse(second.stdout)).toEqual({ action: "unchanged", tunnelId: TUNNEL, hostname: HOST });
+ const after = JSON.parse(fs.readFileSync(f.stateFile, "utf8"));
+ expect(after.runtimeIdentity).toEqual(f.original.runtimeIdentity);
+ expect(after.runtimeOwned).toBe(f.original.runtimeOwned);
+ expect(after.envFile).toEqual(f.original.envFile);
+ expect(after.tunnelIdentity.pid).not.toBe(f.original.tunnelIdentity.pid);
+ expect(JSON.parse(fs.readFileSync(f.recordFile, "utf8")).phase).toBe("ready");
+ }, 40_000);
+
+ it.each(["root", "scopeId", "configPath", "tunnelId", "replacement"])("refuses a mismatched %s recovery receipt", async (field) => {
+ const f = await interruptedSwap(), before = fs.readFileSync(f.stateFile, "utf8");
+ const record: Record<string, unknown> = { ...f.record };
+ if (field === "replacement") record.tunnelIdentity = { ...f.record.tunnelIdentity, startTicks: "0" };
+ else record[field] = "unrelated";
+ fs.writeFileSync(f.recordFile, JSON.stringify(record), { mode: 0o600 });
+ const result = ensure(f);
+ expect(result.status).toBe(1);
+ expect(fs.readFileSync(f.stateFile, "utf8")).toBe(before);
+ expect(() => process.kill(f.original.tunnelIdentity.pid, 0)).not.toThrow();
+ }, 25_000);
+
+ it("does not adopt an alive unrelated process from a malformed pending receipt", async () => {
+ const f = await interruptedSwap(), before = fs.readFileSync(f.stateFile, "utf8");
+ const unrelated = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
+ onTestFinished(() => stop(unrelated.pid!));
+ fs.writeFileSync(f.recordFile, JSON.stringify({ ...f.record, previousIdentity: processIdentity(unrelated.pid!) }), { mode: 0o600 });
+ const result = ensure(f);
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain("MSO-owned launch recipe");
+ expect(fs.readFileSync(f.stateFile, "utf8")).toBe(before);
+ expect(() => process.kill(unrelated.pid!, 0)).not.toThrow();
+ }, 25_000);
+});
diff --git a/scripts/mso-gateway-app-route.test.ts b/scripts/mso-gateway-app-route.test.ts
new file mode 100644
index 00000000..ddec2770
--- /dev/null
+++ b/scripts/mso-gateway-app-route.test.ts
@@ -0,0 +1,136 @@
+import { spawn, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it, onTestFinished } from "vitest";
+import YAML from "yaml";
+import { GATEWAY, fixture, readState, runGateway } from "./mso-gateway-test-fixture";
+
+const TUNNEL = "11111111-2222-4333-8444-555555555555";
+const HOST = "9router.mso.example.test";
+const TEMPLATE = "{id}.mso.example.test";
+
+function namedFixture(template = TEMPLATE) {
+ const f = fixture(), config = path.join(f.dir, "cloudflared.yml"), credentials = path.join(f.dir, "credentials.json");
+ fs.writeFileSync(credentials, "fixture-not-a-credential", { mode: 0o600 });
+ fs.writeFileSync(config, `# Preserve operator settings\ntunnel: ${TUNNEL}\ncredentials-file: ${credentials}\nloglevel: info\ningress:\n - hostname: mso.example.test\n service: http://127.0.0.1:4005\n - service: http_status:404\n`, { mode: 0o600 });
+ fs.appendFileSync(f.envFile, `OS_PUBLIC_ORIGIN=https://mso.example.test\n${template ? `NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE=${template}\n` : ""}`);
+ fs.writeFileSync(f.cloudflared, `#!/usr/bin/env node
+const fs = require('fs'), home = process.env.HOME;
+if (process.argv.includes('--version')) { console.log('cloudflared fixture'); process.exit(0); }
+if (fs.existsSync(home + '/deny-connector')) process.exit(17);
+if (process.env.OS_SESSION_SECRET) fs.writeFileSync(home + '/cloudflared-secret-env', 'leaked');
+fs.appendFileSync(home + '/gateway-fake-starts', 'start\\n');
+const connected = !fs.existsSync(home + '/never-connected');
+if (connected) console.error('Registered tunnel connection');
+process.on('SIGTERM', () => process.exit(0));
+setInterval(() => { if (connected) console.error('Registered tunnel connection'); }, 1000);
+`, { mode: 0o700 });
+ const env = { ...f.baseEnv, NODE_ENV: "test" as const, NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE: "", MSO_GATEWAY_EXPECT_PUBLIC_ORIGIN: "https://mso.example.test", MSO_GATEWAY_EXPECT_APP_HOST_TEMPLATE: TEMPLATE };
+ runGateway(["start", "--config", config, "--tunnel", TUNNEL], env);
+ return { ...f, env, config, credentials };
+}
+
+function route(f: ReturnType<typeof namedFixture>, action = "ensure", host = HOST, tunnel = TUNNEL, extra = {}) {
+ return spawnSync(GATEWAY, ["app-route", action, host, tunnel], { encoding: "utf8", env: { ...f.env, ...extra }, timeout: 25_000 });
+}
+
+describe("MSO-owned named gateway app routes", () => {
+ it("inspects a proposed template before setup without modifying config or connector state", () => {
+ const f = namedFixture("");
+ const before = fs.readFileSync(f.config, "utf8"), state = readState(f.state).snapshot.text;
+ const result = route(f, "inspect");
+ expect(result.status, result.stderr).toBe(0);
+ expect(JSON.parse(result.stdout)).toEqual({ action: "created", hostname: HOST, tunnelId: TUNNEL });
+ expect(fs.readFileSync(f.config, "utf8")).toBe(before);
+ expect(readState(f.state).snapshot.text).toBe(state);
+ const ensure = route(f);
+ expect(ensure.status).toBe(1);
+ expect(ensure.stderr).toContain("not active");
+ expect(fs.readFileSync(f.config, "utf8")).toBe(before);
+ }, 20_000);
+
+ it("adds an exact route, keeps the MSO runtime identity, and does not restart again on retry", () => {
+ const f = namedFixture(), stateFile = path.join(f.state, "state.json");
+ const runtime = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
+ onTestFinished(() => { runtime.kill(); });
+ const proc = fs.readFileSync(`/proc/${runtime.pid}/stat`, "utf8");
+ const owned = { pid: runtime.pid, startTicks: proc.slice(proc.lastIndexOf(") ") + 2).split(" ")[19],
+ exe: fs.realpathSync(`/proc/${runtime.pid}/exe`), cmdHash: null, instanceId: "fixture" };
+ const state = JSON.parse(fs.readFileSync(stateFile, "utf8"));
+ fs.writeFileSync(stateFile, JSON.stringify({ ...state, runtimeOwned: true, runtimeIdentity: owned }), { mode: 0o600 });
+ const before = readState(f.state).value;
+ const credentialBefore = fs.statSync(f.credentials);
+ const first = route(f);
+ expect(first.status, first.stderr).toBe(0);
+ expect(JSON.parse(first.stdout)).toEqual({ action: "created", hostname: HOST, tunnelId: TUNNEL });
+ const cfgText = fs.readFileSync(f.config, "utf8"), cfg = YAML.parse(cfgText);
+ expect(cfgText).toContain("# Preserve operator settings");
+ expect(cfg.loglevel).toBe("info");
+ expect(cfg["credentials-file"]).toBe(f.credentials);
+ expect(cfg.ingress).toEqual([
+ { hostname: "mso.example.test", service: "http://127.0.0.1:4005" },
+ { hostname: HOST, service: "http://127.0.0.1:4005" },
+ { service: "http_status:404" },
+ ]);
+ const after = readState(f.state).value;
+ expect(after.runtimeOwned).toBe(before.runtimeOwned);
+ expect(JSON.parse(fs.readFileSync(stateFile, "utf8")).runtimeIdentity).toEqual(owned);
+ expect(() => process.kill(runtime.pid!, 0)).not.toThrow();
+ expect(after.tunnelIdentity.pid).not.toBe(before.tunnelIdentity.pid);
+ expect(fs.statSync(f.credentials).mtimeMs).toBe(credentialBefore.mtimeMs);
+ expect(fs.existsSync(path.join(f.dir, "cloudflared-secret-env"))).toBe(false);
+ const second = route(f);
+ expect(second.status, second.stderr).toBe(0);
+ expect(JSON.parse(second.stdout).action).toBe("unchanged");
+ expect(readState(f.state).value.tunnelIdentity.pid).toBe(after.tunnelIdentity.pid);
+ expect(fs.readFileSync(f.startFile, "utf8").trim().split("\n")).toHaveLength(2);
+ }, 30_000);
+
+ it("retries a saved YAML route after connector startup fails while preserving the previous connector", () => {
+ const f = namedFixture(), before = readState(f.state).value;
+ fs.writeFileSync(path.join(f.dir, "deny-connector"), "1", { mode: 0o600 });
+ const first = route(f);
+ expect(first.status).toBe(1);
+ expect(YAML.parse(fs.readFileSync(f.config, "utf8")).ingress[1].hostname).toBe(HOST);
+ expect(readState(f.state).value.tunnelIdentity.pid).toBe(before.tunnelIdentity.pid);
+ expect(() => process.kill(before.tunnelIdentity.pid, 0)).not.toThrow();
+ fs.unlinkSync(path.join(f.dir, "deny-connector"));
+ const second = route(f);
+ expect(second.status, second.stderr).toBe(0);
+ expect(JSON.parse(second.stdout).action).toBe("unchanged");
+ expect(readState(f.state).value.tunnelIdentity.pid).not.toBe(before.tunnelIdentity.pid);
+ }, 30_000);
+
+ it("keeps the previous connector when an alive replacement never connects, ignoring old log traffic", () => {
+ const f = namedFixture(), before = readState(f.state).snapshot.text;
+ const previous = readState(f.state).value.tunnelIdentity;
+ fs.writeFileSync(path.join(f.dir, "never-connected"), "1", { mode: 0o600 });
+ const result = route(f, "ensure", HOST, TUNNEL, { MSO_GATEWAY_PUBLIC_READY_SECONDS: "10" });
+ expect(result.status, result.stderr).toBe(1);
+ expect(result.stderr).toContain("did not register a tunnel connection");
+ expect(readState(f.state).snapshot.text).toBe(before);
+ expect(() => process.kill(previous.pid, 0)).not.toThrow();
+ expect(fs.readFileSync(path.join(f.state, "provider.log"), "utf8")).toContain("Registered tunnel connection");
+ expect(fs.readFileSync(f.startFile, "utf8").trim().split("\n")).toHaveLength(2);
+ }, 30_000);
+
+ it.each([
+ { label: "wrong origin", host: HOST, tunnel: TUNNEL, extra: { MSO_GATEWAY_EXPECT_PUBLIC_ORIGIN: "https://other.example.test" } },
+ { label: "unknown app", host: "other.mso.example.test", tunnel: TUNNEL, extra: {} },
+ { label: "wrong tunnel", host: HOST, tunnel: "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee", extra: {} },
+ ])("rejects $label without changing the named config", ({ host, tunnel, extra }) => {
+ const f = namedFixture(), before = fs.readFileSync(f.config, "utf8");
+ const result = route(f, "ensure", host, tunnel, extra);
+ expect(result.status).toBe(1);
+ expect(fs.readFileSync(f.config, "utf8")).toBe(before);
+ }, 20_000);
+
+ it("does not adopt an externally managed gateway", () => {
+ const f = fixture();
+ const env = { ...f.baseEnv, OS_PUBLIC_ORIGIN: "https://mso.example.test", MSO_GATEWAY_EXPECT_PUBLIC_ORIGIN: "https://mso.example.test", MSO_GATEWAY_EXPECT_APP_HOST_TEMPLATE: TEMPLATE };
+ const result = spawnSync(GATEWAY, ["app-route", "ensure", HOST, TUNNEL], { encoding: "utf8", env });
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain("existing MSO-owned named Cloudflare gateway");
+ expect(fs.existsSync(f.startFile)).toBe(false);
+ });
+});
diff --git a/scripts/mso-gateway-named-config.test.ts b/scripts/mso-gateway-named-config.test.ts
new file mode 100644
index 00000000..1ff9a05d
--- /dev/null
+++ b/scripts/mso-gateway-named-config.test.ts
@@ -0,0 +1,77 @@
+import { 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 YAML from "yaml";
+
+const ROOT = path.resolve(__dirname, "..");
+const HELPER = path.join(__dirname, "lib/gateway-named-config.mjs");
+const TUNNEL = "11111111-2222-4333-8444-555555555555";
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); });
+
+function fixture() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-named-config-")); dirs.push(dir);
+ const file = path.join(dir, "config.yml"), cred = path.join(dir, "credential.json");
+ fs.writeFileSync(cred, "must-not-be-read", { mode: 0o600 });
+ const cfg: Record<string, unknown> = { tunnel: TUNNEL, "credentials-file": cred, ingress: [
+ { hostname: "mso.example.test", service: "http://127.0.0.1:4005" }, { service: "http_status:404" },
+ ] };
+ const write = () => fs.writeFileSync(file, YAML.stringify(cfg), { mode: 0o600 });
+ write();
+ return { dir, file, cred, cfg, write };
+}
+function run(file: string, action = "inspect", template = "{id}.mso.example.test", host = "9router.mso.example.test") {
+ return spawnSync(process.execPath, [HELPER, ROOT, file, "https://mso.example.test", "http://127.0.0.1:4005", template, action, host, TUNNEL], { encoding: "utf8", timeout: 3000 });
+}
+
+describe("named gateway YAML policy", () => {
+ it.each(["{id}.mso.example.test", "{id}-mso.example.test"])("supports exact managed app template %s", (template) => {
+ const f = fixture(), host = template.replace("{id}", "9router");
+ expect(run(f.file, "ensure", template, host).status).toBe(0);
+ expect(run(f.file, "validate", template, host).status).toBe(0);
+ expect(YAML.parse(fs.readFileSync(f.file, "utf8")).ingress[1]).toEqual({ hostname: host, service: "http://127.0.0.1:4005" });
+ });
+
+ it.each([
+ { hostname: "*.mso.example.test", service: "http://127.0.0.1:4005" },
+ { hostname: "mso.example.test", service: "http://127.0.0.1:4005" },
+ { hostname: "9router.mso.example.test", service: "http://127.0.0.1:4005", path: "/admin" },
+ { hostname: "9router.mso.example.test", service: "http://127.0.0.2:4005" },
+ { hostname: "9router.mso.example.test", service: "http://127.0.0.1:4005", originRequest: { httpHostHeader: "mso.example.test" } },
+ ])("rejects conflicting/unsafe app ingress %#", (rule) => {
+ const f = fixture(); (f.cfg.ingress as unknown[]).splice(1, 0, rule); f.write();
+ const before = fs.readFileSync(f.file, "utf8");
+ expect(run(f.file, "ensure").status).toBe(1);
+ expect(fs.readFileSync(f.file, "utf8")).toBe(before);
+ });
+
+ it("overrides a valid cockpit-wide Host header for the app while preserving other global settings", () => {
+ const f = fixture(); f.cfg.originRequest = { httpHostHeader: "mso.example.test", connectTimeout: "20s" }; f.write();
+ const result = run(f.file, "ensure");
+ expect(result.status, result.stderr).toBe(0);
+ const cfg = YAML.parse(fs.readFileSync(f.file, "utf8"));
+ expect(cfg.originRequest).toEqual(f.cfg.originRequest);
+ expect(cfg.ingress[1].originRequest.httpHostHeader).toBe("9router.mso.example.test");
+ });
+
+ it("rejects cockpit Host overrides and a different loopback listener in app-route mode", () => {
+ const f = fixture(); f.cfg.originRequest = { httpHostHeader: "other.example.test" }; f.write();
+ expect(run(f.file).status).toBe(1);
+ delete f.cfg.originRequest;
+ (f.cfg.ingress as { service: string }[])[0].service = "http://127.0.0.2:4005"; f.write();
+ expect(run(f.file).status).toBe(1);
+ expect(run(f.file, "validate").status).toBe(0);
+ });
+
+ it("rejects a symlink or FIFO config without blocking", () => {
+ const f = fixture(), link = path.join(f.dir, "link.yml"), fifo = path.join(f.dir, "fifo.yml");
+ fs.symlinkSync(f.file, link);
+ expect(run(link).status).toBe(1);
+ expect(spawnSync("mkfifo", [fifo]).status).toBe(0);
+ const result = run(fifo);
+ expect(result.error).toBeUndefined();
+ expect(result.status).toBe(1);
+ });
+});