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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(operations): add evidence-backed comparison and delegated control
Rahman52b6a7074bce
diff --git a/.env.example b/.env.exampleindex fa13dc15..1f2a112b 100644--- a/.env.example+++ b/.env.example@@ -3,8 +3,10 @@# controls the machine it runs on. No database, no external backend.# --- Auth (required) ----# Single-owner login. Min 6 chars; use a strong password for any exposed host.-# Device approval is an additional browser allowlist, not standards-based 2FA.+# Owner-first deployment login. Min 6 chars; use a strong password for any exposed host.+# Each approved browser is assigned Viewer, Operator, or Owner. Roles are device-scoped+# application controls over one Unix service account—not named-user SSO or Linux users.+# Device approval is a browser allowlist, not standards-based MFA.OS_LOGIN_PASSWORD=change-me# HMAC key that signs the session cookie. MUST be strong — generate with:# openssl rand -hex 32@@ -45,6 +47,31 @@ OS_SESSION_SECRET=# 1 = direct proxy (default). 2 = Cloudflare → nginx → app, etc.# OS_TRUSTED_PROXY_HOPS=1++# --- System Monitor Service Center (optional) ---+# Inventory for system/user *.service units is read-only by default. Logs require+# Operator/Owner. Lifecycle requires BOTH Operator/Owner and an exact comma/space+# separated scope:unit entry below. Wildcards, paths, flags and non-service units+# are ignored/rejected. Example:+# OS_SERVICE_CONTROL_UNITS=user:mso.service,system:nginx.service+# System units use the process user's existing permission. Set =1 only when you have+# deliberately granted narrowly-scoped non-interactive sudo for the exact units/actions.+# Never pair this with broad NOPASSWD systemctl/root access.+# OS_SERVICE_CONTROL_USE_SUDO=0+# Advanced binary overrides; normally leave unset. Useful only on unusual layouts/tests.+# MSO_SYSTEMCTL_BIN=/usr/bin/systemctl+# MSO_JOURNALCTL_BIN=/usr/bin/journalctl+# MSO_SUDO_BIN=/usr/bin/sudo+#+# Package Updates reads the EXISTING local cache only; it never refreshes or applies.+# Auto-detected managers: apt, dnf, yum, pacman, zypper. Optional detection/binary overrides:+# MSO_PACKAGE_MANAGER=apt+# MSO_APT_BIN=/usr/bin/apt+# MSO_DNF_BIN=/usr/bin/dnf+# MSO_YUM_BIN=/usr/bin/yum+# MSO_PACMAN_BIN=/usr/bin/pacman+# MSO_ZYPPER_BIN=/usr/bin/zypper+# --- Stock photo search (optional) ---# The image picker's Stock tab searches the keyless Openverse API by default.# Set an Unsplash Access Key (https://unsplash.com/developers) to search@@ -163,7 +190,7 @@ OS_SESSION_SECRET=# OS_SESSION_COOKIE_DOMAIN=mso.example.com# --- Storage paths (optional overrides) ----# OS_DEVICE_STORE=~/.mso/auth-devices.json # approved-device allowlist+# OS_DEVICE_STORE=~/.mso/auth-devices.json # approved devices + live roles# OS_CONFIG_STORE=~/.mso/config.json # BYOK key + model# OS_PREFS_PATH=~/.mso/prefs.json # synced UI prefs (theme, layout)# OS_MEMORY_STORE=~/.mso/memory.json # assistant long-term memory@@ -173,10 +200,10 @@ OS_SESSION_SECRET=# MSO_SKILL_INSTALL_ROOT=~/.mso/skills# --- Camoufox browser (the Browser app) ----# The noVNC/websockify endpoint proxy.ts rewrites /camoufox-vnc/* to, behind the same-# verified-session check that guards /api/v1/exec. It MUST stay loopback: the rewrite-# leaves this server, so a value pointing off-box turns the cockpit into an open relay,-# and proxy.ts 404s any non-loopback hostname rather than trusting it.+# The reserved split-origin camoufox host is mapped by proxy.ts to this noVNC/websockify+# endpoint only after a live Operator/Owner role check. The retired same-origin+# /camoufox-vnc/* path always 404s. This endpoint MUST stay loopback: a value pointing+# off-box would turn the viewer proxy into a relay, and proxy.ts rejects it.# CAMOUFOX_NOVNC_URL=http://127.0.0.1:6080## Plaintext copy of the VNC password, written beside x11vnc's own passwd blob (which isdiff --git a/AGENTS.md b/AGENTS.mdindex 9b9862b2..c9ef7e98 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -38,6 +38,17 @@ skill. Public MCP tool names, schemas, scope, audit metadata, parity, toolset siexternal mappings, skill trust/routing, and client action refresh are one release contract.Do not declare an MCP change complete until that full contract is verified.++## Comparison and privileged operations++- `docs/comparison-data.json` is the comparison SSOT. Generate README/`docs/COMPARISON.md` with+ `node scripts/gen-comparison.mjs`; never edit those outputs manually or improve an MSO rating+ without existing code evidence. Use official sources and honor the freshness gate.+- Preserve the live Viewer/Operator/Owner route policy. UI filtering is not authorization; unknown+ mutations must fail to Owner. Device roles are not Linux users or SSO.+- System service actions require exact owner allowlisting and fixed argv. Do not add wildcard units,+ raw `systemctl` arguments, or package-update/apply buttons to the Viewer/Operator surface.+## ShippingFollow `CLAUDE.md`: update `docs/PROGRESS.md`, run the relevant gates, and ship throughdiff --git a/CLAUDE.md b/CLAUDE.mdindex e8b9d712..740c42a5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -8,17 +8,18 @@ agent — it runs AS a host process and controls its own machine.- Stack: Next 16 (App Router) · React 19 · Tailwind 4 · shadcn/ui · TypeScript.**No `middleware.ts` — `proxy.ts`** (Next 16 rename).-- Auth: password + device approval → HMAC signed-cookie session (`lib/auth/`).- No Convex, no Clerk.+- Auth: password + device approval → HMAC signed-cookie session plus live+ Viewer/Operator/Owner role (`lib/auth/`). No Convex, no Clerk; roles are device-scoped+ over one Unix service account, not named-user SSO.- Host access: `lib/host/` does fs/exec/sys directly (Node `fs` + `child_process`),bounded by `OS_FS_READ_ROOTS` / `OS_FS_WRITE_ROOTS`.- Layout: `app/` + `frontend/slices/<slug>/`; barrel-only cross-slice imports(`@/features/<slug>`).## Read first-- `docs/PROGRESS.md` — **THE source of truth for what exists.** Newest entry at top;- read the top few and you know the current state. Everything else in `docs/` is- history or a plan, and history goes stale.+- `docs/PROGRESS.md` — source of truth for historical **WHY**, newest entry first.+ Current code and the current-reference documents classified by `docs/README.md` define what+ exists now; dated audits/plans may intentionally preserve obsolete details.- `README.md` — what it is, features, security model, quickstart.- `.env.example` — every var you can actually set. Reconciled against `process.env`in code on 2026-08-03 (Camoufox, memory/threads paths, `NEXT_DEPLOYMENT_ID`,@@ -48,6 +49,18 @@ there is nothing to keep in sync and no way for it to disagree with history. PROis the WHY; CHANGELOG is the WHAT, and it is what Settings → About renders as"What's new" so a shipped change is visible in the running app.++**Comparison is generated policy, not hand-written marketing.** Edit only+`docs/comparison-data.json`, then run `node scripts/gen-comparison.mjs`. The generator owns the+README block and `docs/COMPARISON.md`, requires an existing repo evidence path for each MSO cell,+restricts competitor sources to reviewed official hosts, and expires review after 90 days. Do not+raise a rating because a feature is planned; implementation evidence must land first.++**Service Center never becomes a shell-shaped button collection.** Inventory is Viewer, bounded+journal is Operator, and lifecycle is Operator plus an exact `OS_SERVICE_CONTROL_UNITS` match. Unit+names/actions are fixed argv and wildcards are rejected. Package visibility is cache-only and has no+apply action. New network/storage/user/firewall modules need their own typed policy and tests.+**New workflow skills use `bun run skill:new`, then `bun run skill:check`.** The source template is `templates/mso-skill-flow/SKILL.md.template`; do not hand-copy an untrusted skill into the official root.**Systematic implementation is the default.** Resolve the canonical source and running target;@@ -97,15 +110,17 @@ browser ──https──> mso (Next.js :4005) ──── lib/host → Node fssigned-cookie auth (lib/auth)```The Browser app is **Camoufox** — a real anti-fingerprinting Firefox on a headless-X display on this host, streamed in over noVNC through `/camoufox-vnc/*` (gated in-`proxy.ts` by the same verified-session check that guards `/api/v1/exec`). It-replaced BOTH the old Playwright sidecar (`os-browser`, :4002, retired) and the-sandboxed-iframe browser that briefly followed it — an iframe cannot render most of-the web, because X-Frame-Options refuses framing on the majority of real sites.+X display on this host, streamed over noVNC from the reserved split-origin host+`camoufox.<managed-app-domain>`. `proxy.ts` requires a live Operator/Owner device role,+strips cockpit credentials before loopback noVNC, and permanently 404s the retired+same-origin `/camoufox-vnc/*` path. It replaced BOTH the old Playwright sidecar+(`os-browser`, :4002, retired) and the sandboxed-iframe browser that briefly followed it—an+iframe cannot render most of the web because X-Frame-Options refuses framing on many sites.`os-browser/` stays in-repo only as dev tooling (scripts/e2e use its Playwrightinstall). See the Browser/camoufox note further down for the systemd user unit.- `/api/v1/*` = the host API (fs/exec/sys/term/apps/camoufox/managed-apps), every- route `verifyAuth` (session cookie) first. There is no `/api/v1/browser`.+ route resolves the live device role first. Only explicitly listed reads are Viewer; every unclassified route+ fails up to Owner. Operator exceptions must be explicit and bounded. There is no `/api/v1/browser`.Client picks mock (default) vs live in Settings → Server.- `/api/auth/*` = login/logout/me/devices. `/api/config` = BYOK AI key.- Persistence is local: window layout + app registry in localStorage; device@@ -362,8 +377,8 @@ the escape hatch for anything without a named verb.- One shared CLI device id lives in `~/.mso/cli.device.id` (auto-created, approveonce with `mso approve $(cat ~/.mso/cli.device.id)`). `audit.js` and`image-editor.sh` read the same file — do not reintroduce per-script hardcoded ids.-- Local verbs (`-h`, `approve`, `devices`, `service`, `build`) never log in, so they- still work while the service is down.+- Local verbs (`-h`, `approve`, `devices`, `device role`, `service`, `build`) can use the+ private device store/systemd directly where documented, so recovery still works while the service is down.## Local dev```bash@@ -371,7 +386,7 @@ bun installcp .env.example .env.local # set OS_LOGIN_PASSWORD + OS_SESSION_SECRETbun run typecheckbun run dev # OS desktop at :3000 (mock data by default)-node scripts/approve-device.js <deviceId> "my device" # approve a login device+node scripts/approve-device.js <deviceId> "my device" --role owner # bootstrap login```## Package manager: bun installs, Node runs (migrated from pnpm 2026-08-03)diff --git a/README.md b/README.mdindex bcfebe3a..d1939071 100644--- a/README.md+++ b/README.md@@ -22,7 +22,7 @@<img alt="Open Source" src="https://img.shields.io/badge/Open%20Source-MIT-green" /><img alt="Self-hosted" src="https://img.shields.io/badge/Self--hosted-yes-2f7bf6" /><img alt="Public Alpha" src="https://img.shields.io/badge/Public%20Alpha-Developer%20Preview-f59e0b" />- <img alt="Single-owner" src="https://img.shields.io/badge/Single--owner-focused-111827" />+ <img alt="Device roles" src="https://img.shields.io/badge/Device%20roles-Viewer%20%C2%B7%20Operator%20%C2%B7%20Owner-111827" /><img alt="Tailscale recommended" src="https://img.shields.io/badge/Tailscale%20recommended-VPN%20first-7c3aed" /></p>@@ -34,7 +34,7 @@<img alt="bun" src="https://img.shields.io/badge/bun-1.3-fbf0df?logo=bun&logoColor=black" /></p>-**Manef Shell OS** (**MSO** in the UI) is an open-source, mobile-friendly visual shell for a Linux server you own. It brings a real terminal, file manager, live system metrics, and a BYOK AI assistant into one private browser workspace without running a full remote desktop.+**Manef Shell OS** (**MSO** in the UI) is an open-source, mobile-friendly visual shell for a Linux server you own. It brings a real terminal, file manager, live system metrics, service/package visibility, device-scoped roles, and a BYOK AI assistant into one private browser workspace without running a full remote desktop.MSO is **Public Alpha / Developer Preview** software. It runs on top of Linux as a normal non-root Node process. It is not an operating system, Linux distribution, desktop environment, VPS provider, or production-grade security platform.@@ -52,11 +52,13 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy## What you can do-**Control** — terminal, files, and system monitor for the server you own.+**Control** — terminal, files, services, package visibility, and system health for the server you own.- **Open a real terminal** — interactive PTY support for tools like `vim`, `top`, and `ssh`.- **Manage files** — browse, upload, search, preview, rename, move, copy, zip, and delete within configured filesystem roots.- **Inspect system health** — view live CPU, memory, disk, network, process, and uptime signals.+- **Operate services safely** — inventory system and user `systemd` units, read bounded journal output, and expose start/stop/restart only for exact owner-configured allowlist entries.+- **See pending package updates** — read the package manager’s existing local cache without refreshing repositories or applying an upgrade.- **Update itself** — Settings → About shows what is on `origin/main`, lists the incoming commits, and runs the whole deploy (pull → verify the build out-of-tree → build → restart) from a button. The verification runs first on purpose: a commit that does not compile becomes a refusal, not an outage. The updater runs in the owner's systemd user manager and does not require passwordless sudo. Same thing from a shell: `mso update run`.- **Manage other apps on the box** — detect, start/stop/restart, health, version, logs, and state backups for separate applications you already run (Hermes, OpenClaw, 9Router), driven through their own systemd/Docker/CLI contracts. 9Router uses its configured application domain or split-origin host as the in-shell dashboard; its Docker port is loopback-only unless public exposure is explicitly enabled. See [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md).@@ -64,7 +66,8 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy- **Edit project files** — open text/code files from the file manager without context switching.- **Preview almost anything** — images (including HEIC/TIFF), audio, video, PDFs, plain text, Markdown, CSV/TSV and HTML, with ← → paging through the folder. Formats no browser can render (Office, iWork, archives, installers) say so and offer the download instead of a blank frame. HTML renders in a fully sandboxed frame, never as a document on MSO's own origin.-- **Keep admin context together** — move between terminal, files, metrics, and browser views.+- **Keep admin context together** — move between terminal, files, metrics, services, package updates, and browser views.+- **Delegate by device** — approve a browser as Viewer, Operator, or Owner. Roles are rechecked on every request; they are an MSO application boundary, not Linux accounts or enterprise SSO.**Extend** — Alfa AI, modular slices, and custom apps.@@ -76,13 +79,13 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy## What can you do with MSO?**Fix a server issue from your phone**-Check system health, open a real terminal, inspect logs, and restart a service without opening a laptop.+Check system health, inspect a failed unit and its logs, restart an exact allowlisted service, or open the owner terminal without opening a laptop.**Manage project files visually**Browse, upload, rename, preview, and edit files without remembering every shell command.**Work with your server in one workspace**-Move between terminal, files, metrics, browser, and AI without switching between several admin tools.+Move between terminal, files, metrics, services, package updates, browser, and AI without switching between several admin tools.## Live demo@@ -205,10 +208,13 @@ mso onboard # guided AI/app/skill setupmso skills available # curated installable skillsmso skills install ponytail caveman rtk -ymso device pending # who typed the password and is waiting-mso device approve <id> "my phone"+mso device approve <id> "my phone" --role viewermso ls ~/projects # files; `raw` for binaries, `zip`/`upload` for transfersmso exec "df -h" # host shellmso stats # cpu / mem / disk+mso units # system + user systemd inventory+mso unit logs user mso.service+mso packages # cached updates; never applies themmso camoufox start # power the anti-detection browsermso mapp logs hermes # managed apps (hermes, openclaw, 9router)mso term open # interactive PTY@@ -226,13 +232,14 @@ links every committed official skill in `claude-skills/` into `~/.claude/skills/## Security warning-An authenticated MSO session can read allowed files and run commands as the user that owns the process. Treat it like SSH in a browser.+An authenticated **Owner** session can read allowed files and run commands as the Unix user that owns the process. Viewer and Operator devices are server-gated to narrower surfaces, but all roles still share one MSO deployment and one underlying Unix account.- Run as a dedicated non-root user.- Prefer Tailscale or a VPN; otherwise use HTTPS plus a strict firewall or allowlist.- Use a strong `OS_SESSION_SECRET` and a strong `OS_LOGIN_PASSWORD`.-- Approve only devices you own; device approval is an allowlist, not standards-based 2FA.+- Approve only trusted devices; use Viewer by default, Operator only for bounded operational work, and Owner only where full host authority is intended. Device approval is an allowlist, not standards-based MFA or a named-user directory.- Keep write roots narrow with `OS_FS_WRITE_ROOTS`.+- Service inventory is read-only by default. Lifecycle buttons require Operator/Owner **and** an exact `OS_SERVICE_CONTROL_UNITS` entry; wildcards are rejected. Package visibility reads only the existing local cache and never upgrades the host.- Never commit `.env.local`, API keys, or data from `~/.mso`.- Managed-app dashboards are not embedded by default. 9Router is loopback-only by default; a direct public-IP bind requires `NINE_ROUTER_EXPOSE_PUBLIC=1`, while a configured application hostname remains its preferred in-shell UI. Give each vendor UI a separate explicit hostname such as `hermes.mso.example.com`; there is no supported same-origin iframe mode.- Camoufox/noVNC is also never served on the cockpit origin. It uses the reserved split-origin host such as `camoufox.mso.example.com`; the legacy `/camoufox-vnc/*` path is permanently closed.@@ -256,7 +263,7 @@ flowchart LRU["Phone / Browser"]subgraph VPS["Your Linux server"]APP["MSO / mso<br/>Next.js 16 · React 19"]- HOST["Host layer<br/>fs · PTY · sys metrics"]+ HOST["Host layer<br/>fs · PTY · metrics · services · packages"]SLICES["Feature slices<br/>Files · Terminal · Monitor · Assistant"]AI["Alfa AI<br/>BYOK"]MANAGED["Managed apps<br/>Hermes · OpenClaw · 9Router<br/>own runtime + data"]@@ -273,20 +280,26 @@ Deep dive: [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md).## Comparison-The tools below have different scopes. This comparison is intended to explain where MSO fits, not to claim it replaces every specialized server administration tool.--| | **MSO** | Cockpit | ttyd | FileBrowser | Netdata | Tailscale SSH |-|---|:---:|:---:|:---:|:---:|:---:|:---:|-| Product maturity | Early alpha | Mature | Varies | Mature | Mature | Mature |-| Third-party security audit | No | Varies | Varies | Varies | Varies | Yes |-| Multi-user support | No | Yes | Varies | Yes | Yes | Yes |-| Mobile-first interface | Yes | Partial | Varies | Partial | Partial | Not a focus |-| Real PTY | Yes | Yes | Yes | No | No | Yes |-| File manager | Yes | Partial | No | Yes | No | No |-| Metrics | Yes | Yes | No | No | Yes | No |-| Built-in AI | Yes, BYOK | No | No | No | No | No |-| Setup complexity | One script | Varies | Low | Low | Varies | Low |-| Service/package administration | Basic | Strong | Not a focus | Not a focus | Metrics focus | SSH only |+<!-- comparison:start -->+**Positioning:** MSO is designed to be the most complete mobile-first, AI-native private Linux workspace for an owner or small trusted team. It does not claim to replace specialist products at their strongest specialty.++● strong · ◐ partial/scope-limited · — not a product surface++| Product | Best fit | Workspace | Host ops | Delivery | Observability | Delegation | AI / MCP |+|---|---|:---:|:---:|:---:|:---:|:---:|:---:|+| **MSO** | Mobile-first private Linux workspace | ● | ◐ | ◐ | ◐ | ◐ | ● |+| **Cockpit** | Deep graphical Linux administration | ◐ | ● | ◐ | ◐ | ● | — |+| **Coolify** | Self-hosted Git/PaaS delivery | ◐ | ◐ | ● | ◐ | ● | — |+| **Portainer** | Container and stack operations | ◐ | ◐ | ● | ◐ | ◐ | — |+| **Netdata** | High-resolution observability and RCA | ◐ | — | — | ● | ◐ | ◐ |+| **Tailscale SSH** | Identity-aware private remote access | — | ◐ | — | — | ● | — |+| **File Browser** | Focused web file management | ◐ | — | — | — | ◐ | — |+| **ttyd** | Small, focused web terminal | ◐ | — | — | — | ◐ | — |+| **CasaOS** | Friendly personal-cloud home server | ◐ | ◐ | ◐ | ◐ | — | — |+| **Runtipi** | Curated one-click self-hosted apps | ◐ | — | ● | ◐ | — | — |++Reviewed against official product documentation on **2026-08-29**. Ratings describe product scope, not benchmark scores. See [methodology, evidence, and per-cell notes](docs/COMPARISON.md) and the [execution roadmap](docs/COMPETITIVE-ROADMAP.md).+<!-- comparison:end -->## Development@@ -301,6 +314,7 @@ Quality gates:```bashbun run verify # typecheck + lint + test + checks + auditnode scripts/check-docs.mjs # docs links/toolset/slice drift+node scripts/gen-comparison.mjs --check # comparison evidence + 90-day freshnessbash scripts/verify-build.sh # build HEAD out-of-tree — safe on the prod checkoutbash -n scripts/install.sh```@@ -339,6 +353,8 @@ Not currently supported:| [docs/CLI.md](./docs/CLI.md) | Generated `mso` command-line reference || [docs/DEVELOPMENT.md](./docs/DEVELOPMENT.md) | Local dev, gates and exact release flow || [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md) | Current AppShell/host/MCP/managed-app architecture |+| [docs/COMPARISON.md](./docs/COMPARISON.md) | Generated comparison methodology, evidence and per-cell notes |+| [docs/COMPETITIVE-ROADMAP.md](./docs/COMPETITIVE-ROADMAP.md) | Executed comparison plan, deliberate boundaries and next measurable investments || [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md) | Hermes/OpenClaw/9Router lifecycle, jobs, update, backup/restore and origins || [docs/HERMES-INTEGRATION.md](./docs/HERMES-INTEGRATION.md) | Hermes-specific managed-app behaviour || [docs/OPENCLAW-INTEGRATION.md](./docs/OPENCLAW-INTEGRATION.md) | OpenClaw-specific managed-app behaviour |@@ -352,7 +368,7 @@ Not currently supported:## Status-MSO is **Public Alpha / Developer Preview**. The core auth, filesystem bounds, terminal, metrics, and slice architecture are implemented, but the project is still early and unaudited. Expect rough edges, breaking changes, and missing production hardening.+MSO is **Public Alpha / Developer Preview**. The core role-aware auth, filesystem bounds, terminal, metrics, Service Center, and slice architecture are implemented, but the project is still early and unaudited. Expect rough edges, breaking changes, and missing production hardening.## Licensediff --git a/SECURITY.md b/SECURITY.mdindex 01704c01..f16fdf07 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -19,8 +19,9 @@ Camoufox profile data or full environment files.## Deployment warning-An authenticated MSO owner session can read allowed files and run commands as the Linux user-that owns the process. Treat it like SSH in a browser.+An authenticated MSO **Owner** session can read allowed files and run commands as the Linux user+that owns the process. Treat Owner like SSH in a browser. Viewer and Operator are narrower+application roles, but they still share the same deployment and underlying Unix account.- Run MSO as a dedicated non-root user.- Prefer Tailscale/VPN for a real deployment.@@ -32,12 +33,26 @@ that owns the process. Treat it like SSH in a browser.## Authentication and sessions-The owner login is password + device approval. A correct password on a new browser creates a-pending device; an already-approved device or the server must approve it before a normal-session is issued. The browser session cookie is HMAC signed and `Secure`.+The deployment login is password + device approval. A correct password on a new browser creates a+pending device; an Owner device or the local server CLI assigns it one live role before a normal+session is issued:-Changing `OS_SESSION_SECRET` invalidates existing sessions. Removing a device from the-allowlist revokes that browser. Device approval is an allowlist, not standards-based MFA.+- **Viewer** — read-scoped workspace surfaces such as bounded files, telemetry, service inventory,+ package visibility, docs and previews;+- **Operator** — Viewer plus bounded operational surfaces such as Camoufox, managed-app start/stop/restart/backup,+ service journals and exact-allowlisted service actions;+- **Owner** — full MSO host authority, including writes, PTY/exec, credentials, self-update, MCP,+ device administration and managed-app install/update.++Roles are read from the private device store on every request; demotion and revocation therefore do+not wait for the signed cookie to expire. Shared Appearance, Theme and Quicklink preferences may be read by delegated devices but changed only by Owner because the current store is deployment-wide, not per-device. The UI also filters inaccessible apps, but the route policy+is the actual boundary: unknown mutations fail up to Owner by default. Role-less records created by+older MSO versions migrate as Owner; malformed role values fail down to Viewer.++Changing `OS_SESSION_SECRET` invalidates existing sessions. Removing a device from the allowlist+revokes that browser. Device approval is an allowlist, not standards-based MFA, a named-user+directory, Linux-account mapping, or enterprise SSO. Multiple people can use distinct approved+devices, but they still authenticate to one deployment secret and one Unix service account.## Filesystem and command boundary@@ -51,6 +66,19 @@ short accident tripwire, not a sandbox. Interactive Terminal PTYs are even morekeystrokes cannot be reliably parsed into commands, so authentication and PTY sessionlifecycle—not the one-shot command matcher—are the boundary.+## Service and package operations++System Monitor exposes system/user `systemd` inventory to Viewer devices. Journal reads require+Operator, are capped, and accept only validated `.service` unit names. Lifecycle actions require+Operator or Owner **and** an exact `scope:unit` entry in `OS_SERVICE_CONTROL_UNITS`; empty is the+default, wildcards and malformed entries are rejected, and the host helper uses fixed argv without+a shell. System-scope control additionally depends on the Unix user's existing permission, or an+explicit `OS_SERVICE_CONTROL_USE_SUDO=1` deployment with narrowly-scoped non-interactive sudo.++Package Updates is visibility-only. It reads the supported package manager's existing local cache+with bounded commands (`apt list --upgradable`, cache-only DNF/YUM, `pacman -Qu`, or no-refresh+Zypper). It does not refresh metadata, install packages, or perform an upgrade.+## Alfa model dataAlfa credentials are stored server-side in private host config. BYOK means the owner controls@@ -106,7 +134,7 @@ pages/API/static chunks are not served there. Keep DNS explicit; do not point arwildcards inside the shared cookie domain at MSO.Camoufox/noVNC uses the same browser-realm principle through the reserved `camoufox` host in-that namespace. The host accepts only approved-session GET/HEAD requests, strips cockpit+that namespace. The host accepts only Operator/Owner-session GET/HEAD requests, strips cockpitcookies/authorization before loopback noVNC, and applies a restrictive CSP. The old`/camoufox-vnc/*` cockpit path is permanently closed. Revoking an approved device also stops theCamoufox service cgroup so an already-established VNC WebSocket is evicted.@@ -133,10 +161,11 @@ app identity, state path and symlink collisions before writing, then creates an## In scope-- auth/session/device-approval bypass;+- auth/session/device-approval or role-escalation bypass;- practical login rate-limit defeat;- filesystem-jail or credential-denylist escape;-- unauthenticated access to live host/config routes;+- unauthorized access to live host/config routes or a role-restricted app;+- service-control allowlist bypass, unit/argv injection, or package-visibility mutation;- CSRF/clickjacking that triggers owner host actions;- MCP scope/OAuth bypass or bearer validation failure;- managed-app origin escape into the cockpit or a sibling app;@@ -146,7 +175,8 @@ app identity, state path and symlink collisions before writing, then creates an## Out of scope-- an already-authenticated owner intentionally using documented owner capabilities;+- an already-authenticated Owner intentionally using documented Owner capabilities;+- an Operator intentionally controlling an exact owner-allowlisted service;- bypassing the one-shot destructive-command regex after the user already granted shellexecution—it is not presented as a sandbox;- deployments that ignore the minimum documented posture;@@ -158,7 +188,7 @@ app identity, state path and symlink collisions before writing, then creates an- change `OS_SESSION_SECRET` to invalidate browser sessions;- change `OS_LOGIN_PASSWORD` to rotate the owner password;-- remove entries from `~/.mso/auth-devices.json` to revoke browsers;+- change device roles or revoke browsers in Settings → Devices / `mso device`; use the local CLI for recovery;- remove/revoke MCP tokens from Settings → MCP;- rotate provider credentials from Settings → AI or the corresponding environment source;- rotate managed-app credentials if a state snapshot containing them was exposed.diff --git a/app/[[...slug]]/page.tsx b/app/[[...slug]]/page.tsxindex 9acf525b..07d47d57 100644--- a/app/[[...slug]]/page.tsx+++ b/app/[[...slug]]/page.tsx@@ -1,7 +1,7 @@import type { Metadata } from "next";import { notFound } from "next/navigation";import { OsRoot } from "../os-root";-import { getSession } from "@/lib/auth/require-session";+import { getSessionContext } from "@/lib/auth/require-session";// Optional catch-all: the OS is one client shell, but every app is deep-linkable// (`/files/home/user`, `/code`, `/terminal`). The shell reads the path on the@@ -43,6 +43,7 @@ export default async function Page({ params }: { params: Promise<{ slug?: string// SessionProvider's initial state → the shell paints on the first render with// no client /api/auth/me probe and no Splash. cookies() makes this dynamic —// intended (the app is never SSG; next.config cacheComponents:false).- const initialStatus = (await getSession()) ? "in" : "out";- return <OsRoot initialStatus={initialStatus} />;+ const context = await getSessionContext();+ const initialStatus = context ? "in" : "out";+ return <OsRoot initialStatus={initialStatus} initialRole={context?.role ?? null} />;}diff --git a/app/api/assistant/route.test.ts b/app/api/assistant/route.test.tsindex 4f32b720..8f2f6b53 100644--- a/app/api/assistant/route.test.ts+++ b/app/api/assistant/route.test.ts@@ -7,10 +7,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";// Mocked BEFORE the route is imported. Each test resets the modules so the// per-process rate-limit bucket starts clean (otherwise tests leak state via// the singleton Map in lib/host/rate-limit).-const stableSession = { device_id: "test-device" };+const stableContext = {+ session: { device_id: "test-device", issued_at: 1, expires_at: 2 },+ device: { label: "test owner", approvedAt: 1, role: "owner" as const },+ role: "owner" as const,+};vi.mock("@/lib/auth/require-session", () => ({- getSession: vi.fn(async () => stableSession),+ getSessionContext: vi.fn(async () => stableContext),}));// Stub config: a valid key short-circuits the early 501 path so we hit the@@ -96,12 +100,25 @@ describe("/api/assistant rate limit", () => {it("does not rate-limit when the session is missing — returns 401 instead", async () => {const mod = await import("@/lib/auth/require-session");- vi.mocked(mod.getSession).mockResolvedValueOnce(null);+ vi.mocked(mod.getSessionContext).mockResolvedValueOnce(null);const { POST } = await import("./route");const res = await POST(makeReq());expect(res.status).toBe(401);});+ it("rejects a delegated non-owner before touching provider state", async () => {+ const mod = await import("@/lib/auth/require-session");+ vi.mocked(mod.getSessionContext).mockResolvedValueOnce({+ ...stableContext,+ device: { ...stableContext.device, role: "operator" },+ role: "operator",+ });+ const { POST } = await import("./route");+ const res = await POST(makeReq());+ expect(res.status).toBe(403);+ await expect(res.json()).resolves.toEqual({ error: "owner_role_required" });+ });+it("reports the selected provider when its API key is missing", async () => {const cfg = await import("@/lib/config/store");vi.mocked(cfg.readConfig).mockResolvedValueOnce({ provider: "openai", model: "gpt-4o" });diff --git a/app/api/assistant/route.ts b/app/api/assistant/route.tsindex 1a474160..894012a8 100644--- a/app/api/assistant/route.ts+++ b/app/api/assistant/route.ts@@ -1,5 +1,5 @@import Anthropic from "@anthropic-ai/sdk";-import { getSession } from "@/lib/auth/require-session";+import { getSessionContext } from "@/lib/auth/require-session";import {resolveModelRef,hostCredentialStore,@@ -116,13 +116,13 @@ export async function POST(req: Request) {);}- const session = await getSession();- if (!session) return Response.json({ error: "unauthorized" }, { status: 401 });+ const context = await getSessionContext();+ if (!context) return Response.json({ error: "unauthorized" }, { status: 401 });+ if (context.role !== "owner") return Response.json({ error: "owner_role_required" }, { status: 403 });- // Per-session bucket so two browsers on different approved devices each get- // their own quota. Falls back to "anon" only when the typed payload is missing- // a device_id (shouldn't happen — getSession() already rejects those).- if (rateLimited(`assistant:${session.device_id ?? "anon"}`, ASSISTANT_MAX, ASSISTANT_WINDOW_MS)) {+ // Per-device bucket so two owner browsers each get their own quota. Role is+ // resolved live from the store; a demotion takes effect before any provider call.+ if (rateLimited(`assistant:${context.session.device_id}`, ASSISTANT_MAX, ASSISTANT_WINDOW_MS)) {return Response.json({ error: "rate_limited" },{ status: 429, headers: { "Retry-After": String(Math.ceil(ASSISTANT_WINDOW_MS / 1000)) } },diff --git a/app/api/auth/devices/route.test.ts b/app/api/auth/devices/route.test.tsindex 2c2c9aed..7ff2a2d7 100644--- a/app/api/auth/devices/route.test.ts+++ b/app/api/auth/devices/route.test.ts@@ -1,42 +1,96 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";+const CURRENT = "b".repeat(32);+const DEVICE = "a".repeat(32);+const session = { current: "owner" as "viewer" | "operator" | "owner" | null };const mocks = vi.hoisted(() => ({- requireSession: vi.fn(async () => true),approveDevice: vi.fn(async () => {}),+ setDeviceRole: vi.fn(async () => {}),isApproved: vi.fn(async () => true),revokeDevice: vi.fn(async () => {}),listDevices: vi.fn(async () => ({ approved: {}, pending: {} })),terminate: vi.fn(async () => {}),+ audit: vi.fn(async () => {}),}));-vi.mock("@/lib/auth/require-session", () => ({ requireSession: mocks.requireSession }));+vi.mock("@/lib/auth/require-session", () => ({+ getSessionContext: vi.fn(async () => session.current ? ({+ session: { device_id: CURRENT, issued_at: 1, expires_at: 2 },+ device: { label: "current", approvedAt: 1, role: session.current },+ role: session.current,+ }) : null),+}));vi.mock("@/lib/auth/device-store", () => ({approveDevice: mocks.approveDevice,+ setDeviceRole: mocks.setDeviceRole,isApproved: mocks.isApproved,revokeDevice: mocks.revokeDevice,listDevices: mocks.listDevices,isValidDeviceId: (value: unknown) => typeof value === "string" && /^[a-f0-9-]{16,128}$/i.test(value),}));vi.mock("@/lib/camoufox/service", () => ({ terminateCamoufoxSessions: mocks.terminate }));+vi.mock("@/lib/host", () => ({ audit: mocks.audit }));-const DEVICE = "a".repeat(32);const post = (body: unknown) => new NextRequest("https://mso.example/api/auth/devices", {- method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),});beforeEach(() => {- for (const mock of Object.values(mocks)) mock.mockClear();- mocks.requireSession.mockResolvedValue(true);- mocks.isApproved.mockResolvedValue(true);- mocks.terminate.mockResolvedValue(undefined);+ session.current = "owner";+ mocks.approveDevice.mockReset().mockResolvedValue(undefined);+ mocks.setDeviceRole.mockReset().mockResolvedValue(undefined);+ mocks.isApproved.mockReset().mockResolvedValue(true);+ mocks.revokeDevice.mockReset().mockResolvedValue(undefined);+ mocks.listDevices.mockReset().mockResolvedValue({ approved: {}, pending: {} });+ mocks.terminate.mockReset().mockResolvedValue(undefined);+ mocks.audit.mockReset().mockResolvedValue(undefined);+});++describe("device access roles", () => {+ it("requires an owner for listing and every mutation", async () => {+ const { GET, POST } = await import("./route");+ session.current = "operator";+ expect((await GET()).status).toBe(403);+ expect((await POST(post({ action: "approve", deviceId: DEVICE }))).status).toBe(403);+ expect(mocks.approveDevice).not.toHaveBeenCalled();+ });++ it("approves pending devices as viewer unless the owner chooses another role", async () => {+ const { POST } = await import("./route");+ expect((await POST(post({ action: "approve", deviceId: DEVICE, label: "phone" }))).status).toBe(200);+ expect(mocks.approveDevice).toHaveBeenCalledWith(DEVICE, "phone", "viewer");+ await POST(post({ action: "approve", deviceId: DEVICE, role: "operator" }));+ expect(mocks.approveDevice).toHaveBeenLastCalledWith(DEVICE, undefined, "operator");+ });++ it("changes a different device role and audits the decision", async () => {+ const { POST } = await import("./route");+ expect((await POST(post({ action: "set_role", deviceId: DEVICE, role: "operator" }))).status).toBe(200);+ expect(mocks.setDeviceRole).toHaveBeenCalledWith(DEVICE, "operator");+ expect(mocks.audit).toHaveBeenCalledWith(expect.objectContaining({+ action: "auth.device",+ actor: CURRENT,+ target: DEVICE,+ detail: "role=operator",+ }));+ });++ it("refuses to demote or revoke the device making the request", async () => {+ const { POST } = await import("./route");+ expect((await POST(post({ action: "set_role", deviceId: CURRENT, role: "viewer" }))).status).toBe(409);+ expect((await POST(post({ action: "revoke", deviceId: CURRENT }))).status).toBe(409);+ expect(mocks.setDeviceRole).not.toHaveBeenCalled();+ expect(mocks.revokeDevice).not.toHaveBeenCalled();+ });});describe("device revocation runtime teardown", () => {it("revokes first, then terminates every live Camoufox socket", async () => {const { POST } = await import("./route");- const res = await POST(post({ action: "revoke", deviceId: DEVICE }));- expect(res.status).toBe(200);+ expect((await POST(post({ action: "revoke", deviceId: DEVICE }))).status).toBe(200);expect(mocks.revokeDevice).toHaveBeenCalledWith(DEVICE);expect(mocks.terminate).toHaveBeenCalledOnce();expect(mocks.revokeDevice.mock.invocationCallOrder[0]).toBeLessThan(mocks.terminate.mock.invocationCallOrder[0]);@@ -46,23 +100,21 @@ describe("device revocation runtime teardown", () => {mocks.isApproved.mockResolvedValue(false);const { POST } = await import("./route");expect((await POST(post({ action: "revoke", deviceId: DEVICE }))).status).toBe(200);- expect(mocks.revokeDevice).toHaveBeenCalledOnce();expect(mocks.terminate).not.toHaveBeenCalled();});- it("reports partial failure honestly while keeping the device revoked", async () => {+ it("reports partial teardown failure while keeping the device revoked", async () => {mocks.terminate.mockRejectedValue(new Error("user bus unavailable"));const { POST } = await import("./route");- const res = await POST(post({ action: "revoke", deviceId: DEVICE }));- expect(res.status).toBe(503);- await expect(res.json()).resolves.toEqual({ error: "device_revoked_browser_teardown_failed", revoked: true });+ const response = await POST(post({ action: "revoke", deviceId: DEVICE }));+ expect(response.status).toBe(503);+ await expect(response.json()).resolves.toEqual({ error: "device_revoked_browser_teardown_failed", revoked: true });expect(mocks.revokeDevice).toHaveBeenCalledOnce();});- it("does not touch browser runtime during approval", async () => {+ it("also tears down the shared viewer when a device becomes viewer-only", async () => {const { POST } = await import("./route");- expect((await POST(post({ action: "approve", deviceId: DEVICE, label: "phone" }))).status).toBe(200);- expect(mocks.approveDevice).toHaveBeenCalledWith(DEVICE, "phone");- expect(mocks.terminate).not.toHaveBeenCalled();+ expect((await POST(post({ action: "set_role", deviceId: DEVICE, role: "viewer" }))).status).toBe(200);+ expect(mocks.terminate).toHaveBeenCalledOnce();});});diff --git a/app/api/auth/devices/route.ts b/app/api/auth/devices/route.tsindex a7d34e10..738e2ab9 100644--- a/app/api/auth/devices/route.ts+++ b/app/api/auth/devices/route.ts@@ -5,29 +5,34 @@ import {isValidDeviceId,listDevices,revokeDevice,+ setDeviceRole,} from "@/lib/auth/device-store";-import { requireSession } from "@/lib/auth/require-session";+import { getSessionContext } from "@/lib/auth/require-session";+import { DeviceRoleError, isDeviceRole } from "@/lib/auth/roles";import { terminateCamoufoxSessions } from "@/lib/camoufox/service";+import { audit } from "@/lib/host";export const runtime = "nodejs";export const dynamic = "force-dynamic";-// In-app device management. Only an already-authenticated (trusted) session may-// list pending devices and approve/revoke them — so the owner can approve a new-// device from one that's already logged in, without the CLI.+async function ownerContext() {+ const context = await getSessionContext();+ if (!context || context.role !== "owner") return null;+ return context;+}export async function GET() {- if (!(await requireSession())) {- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!(await ownerContext())) {+ return NextResponse.json({ error: "Owner role required" }, { status: 403 });}- return NextResponse.json(await listDevices());+ return NextResponse.json(await listDevices(), { headers: { "Cache-Control": "no-store" } });}export async function POST(req: NextRequest) {- if (!(await requireSession())) {- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });- }- let body: { action?: string; deviceId?: string; label?: string };+ const context = await ownerContext();+ if (!context) return NextResponse.json({ error: "Owner role required" }, { status: 403 });++ let body: { action?: string; deviceId?: string; label?: string; role?: unknown };try {body = await req.json();} catch {@@ -37,25 +42,69 @@ export async function POST(req: NextRequest) {if (!isValidDeviceId(deviceId)) {return NextResponse.json({ error: "Missing or invalid device id" }, { status: 400 });}- if (action === "approve") {- await approveDevice(deviceId, typeof label === "string" ? label : undefined);- } else if (action === "revoke") {- const wasApproved = await isApproved(deviceId);- // Revoke first: after this write, the target device cannot start a new viewer- // or reconnect. Then tear down the shared VNC unit to evict any live socket.- await revokeDevice(deviceId);- if (wasApproved) {- try {- await terminateCamoufoxSessions();- } catch {- return NextResponse.json(- { error: "device_revoked_browser_teardown_failed", revoked: true },- { status: 503, headers: { "Cache-Control": "no-store" } },- );+ if ((action === "revoke" || action === "set_role") && deviceId === context.session.device_id) {+ return NextResponse.json(+ { error: "Use another owner device or the local CLI to change this device" },+ { status: 409 },+ );+ }++ try {+ if (action === "approve") {+ // Least privilege in the web UI: an omitted role creates a viewer. The local+ // bootstrap CLI preserves its historical owner default separately.+ const role = body.role === undefined ? "viewer" : body.role;+ if (!isDeviceRole(role)) return NextResponse.json({ error: "Invalid device role" }, { status: 400 });+ await approveDevice(deviceId, typeof label === "string" ? label : undefined, role);+ await audit({+ action: "auth.device",+ actor: context.session.device_id,+ target: deviceId,+ detail: `approved as ${role}`,+ });+ } else if (action === "set_role") {+ if (!isDeviceRole(body.role)) return NextResponse.json({ error: "Invalid device role" }, { status: 400 });+ await setDeviceRole(deviceId, body.role);+ if (body.role === "viewer") await terminateCamoufoxSessions().catch(() => {});+ await audit({+ action: "auth.device",+ actor: context.session.device_id,+ target: deviceId,+ detail: `role=${body.role}`,+ });+ } else if (action === "revoke") {+ const wasApproved = await isApproved(deviceId);+ // Revoke first: after this write, the target cannot start a new request or+ // reconnect. Then tear down the shared VNC unit to evict a live socket.+ await revokeDevice(deviceId);+ await audit({+ action: "auth.device",+ actor: context.session.device_id,+ target: deviceId,+ detail: "revoked",+ });+ if (wasApproved) {+ try {+ await terminateCamoufoxSessions();+ } catch {+ return NextResponse.json(+ { error: "device_revoked_browser_teardown_failed", revoked: true },+ { status: 503, headers: { "Cache-Control": "no-store" } },+ );+ }}+ } else {+ return NextResponse.json({ error: "action must be approve, set_role, or revoke" }, { status: 400 });}- } else {- return NextResponse.json({ error: "action must be approve or revoke" }, { status: 400 });+ } catch (error) {+ if (error instanceof DeviceRoleError) {+ return NextResponse.json({ error: error.message }, { status: 409 });+ }+ throw error;}- return NextResponse.json({ ok: true, ...(await listDevices()) });++ return NextResponse.json(+ { ok: true, ...(await listDevices()) },+ { headers: { "Cache-Control": "no-store" } },+ );}diff --git a/app/api/auth/me/route.ts b/app/api/auth/me/route.tsindex 5a76d77a..ad6eb3b1 100644--- a/app/api/auth/me/route.ts+++ b/app/api/auth/me/route.ts@@ -1,14 +1,17 @@import { NextResponse } from "next/server";-import { getSession } from "@/lib/auth/require-session";+import { getSessionContext } from "@/lib/auth/require-session";export const runtime = "nodejs";export const dynamic = "force-dynamic";-// Lightweight session probe for the client AuthGate. No secrets returned.+// Lightweight live authorization probe. Role is resolved from the device store on+// every request, never trusted from a long-lived cookie.export async function GET() {- const session = await getSession();+ const context = await getSessionContext();return NextResponse.json({- authenticated: session !== null,- deviceId: session?.device_id ?? null,- });+ authenticated: context !== null,+ deviceId: context?.session.device_id ?? null,+ deviceLabel: context?.device.label ?? null,+ role: context?.role ?? null,+ }, { headers: { "Cache-Control": "no-store" } });}diff --git a/app/api/config/route.ts b/app/api/config/route.tsindex 58add928..f374b52b 100644--- a/app/api/config/route.ts+++ b/app/api/config/route.ts@@ -26,7 +26,7 @@ const mask = (k: string) => (k ? `${k.slice(0, 6)}…${k.slice(-4)}` : "");// raw keys never leave the server.export async function GET() {- if (!(await requireSession())) {+ if (!(await requireSession("owner"))) {return NextResponse.json({ error: "Unauthorized" }, { status: 401 });}const cfg = await readConfig();@@ -64,7 +64,7 @@ export async function GET() {type CustomBody = { name?: string; baseURL?: string; baseUrl?: string; apiKey?: string; protocol?: string; models?: string[] };export async function POST(req: NextRequest) {- if (!(await requireSession())) {+ if (!(await requireSession("owner"))) {return NextResponse.json({ error: "Unauthorized" }, { status: 401 });}let body: {@@ -138,7 +138,7 @@ export async function POST(req: NextRequest) {}export async function DELETE(req: NextRequest) {- if (!(await requireSession())) {+ if (!(await requireSession("owner"))) {return NextResponse.json({ error: "Unauthorized" }, { status: 401 });}const slug = new URL(req.url).searchParams.get("provider")?.trim();diff --git a/app/api/mcp/activity/route.ts b/app/api/mcp/activity/route.tsindex 157cd31f..5a8a26d6 100644--- a/app/api/mcp/activity/route.ts+++ b/app/api/mcp/activity/route.ts@@ -5,7 +5,7 @@ import { readMcpActivity } from "@/lib/mcp/activity";export const dynamic = "force-dynamic";export async function GET(req: Request) {- if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ if (!(await verifyAuth(req, "owner"))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });const q = new URL(req.url).searchParams;const limit = Math.min(Math.max(Number(q.get("limit") ?? 80) || 80, 1), 200);return NextResponse.json({ entries: await readMcpActivity(limit) });diff --git a/app/api/mcp/tokens/route.ts b/app/api/mcp/tokens/route.tsindex e2e038eb..a063be34 100644--- a/app/api/mcp/tokens/route.ts+++ b/app/api/mcp/tokens/route.ts@@ -13,12 +13,12 @@ import { toolsetInfo } from "@/lib/mcp/toolset";export const dynamic = "force-dynamic";export async function GET(req: Request) {- if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ if (!(await verifyAuth(req, "owner"))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });return NextResponse.json({ enabled: mcpEnabled(), maxScope: maxScope(), toolset: toolsetInfo(TOOLS), tokens: await listTokens() });}export async function DELETE(req: Request) {- if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ if (!(await verifyAuth(req, "owner"))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });const id = new URL(req.url).searchParams.get("id");if (id === "all") return NextResponse.json({ revoked: await revokeAllTokens() });if (!id) return NextResponse.json({ error: "id required" }, { status: 400 });diff --git a/app/api/memory/route.ts b/app/api/memory/route.tsindex 2e7cff74..3c2939cb 100644--- a/app/api/memory/route.ts+++ b/app/api/memory/route.ts@@ -8,12 +8,12 @@ export const dynamic = "force-dynamic";// Alfa's cross-session memory (facts recalled into the system prompt). Session-gated.// GET → list · POST { text } → add · DELETE ?id=<id> → removeexport async function GET() {- if (!(await requireSession())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });return NextResponse.json({ memories: await listMemories() });}export async function POST(req: NextRequest) {- if (!(await requireSession())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });let body: { text?: string };try {body = await req.json();@@ -25,7 +25,7 @@ export async function POST(req: NextRequest) {}export async function DELETE(req: NextRequest) {- if (!(await requireSession())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });const id = req.nextUrl.searchParams.get("id");if (!id) return NextResponse.json({ error: "id required" }, { status: 400 });await removeMemory(id);diff --git a/app/api/models/route.ts b/app/api/models/route.tsindex 5704d368..15f3dde3 100644--- a/app/api/models/route.ts+++ b/app/api/models/route.ts@@ -13,7 +13,7 @@ export const dynamic = "force-dynamic";// Each row carries capability/pricing meta (context, cost, tools, reasoning); the// model field stays free-text so an id not in the catalog still works.export async function GET(req: NextRequest) {- if (!(await requireSession())) {+ if (!(await requireSession("owner"))) {return NextResponse.json({ error: "Unauthorized" }, { status: 401 });}const provider = req.nextUrl.searchParams.get("provider");diff --git a/app/api/models/test/route.ts b/app/api/models/test/route.tsindex 8f0e2a59..e042219d 100644--- a/app/api/models/test/route.ts+++ b/app/api/models/test/route.ts@@ -12,7 +12,7 @@ export const dynamic = "force-dynamic";// Returns { ok:true } or { ok:false, error } (HTTP 200 either way — a failed key is// a normal UX outcome, not a server error). Mirrors models-rahmanef-com testCredential.export async function POST() {- if (!(await requireSession())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });let resolved;let customProvider = false;diff --git a/app/api/oauth/[provider]/route.ts b/app/api/oauth/[provider]/route.tsindex 13a49766..875e0493 100644--- a/app/api/oauth/[provider]/route.ts+++ b/app/api/oauth/[provider]/route.ts@@ -12,7 +12,7 @@ export const dynamic = "force-dynamic";// Session-gated; the token bundle lands in the 0600 host config file, and on// success the provider is selected so the assistant uses it immediately.export async function POST(req: NextRequest, ctx: { params: Promise<{ provider: string }> }) {- if (!(await requireSession())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });const { provider } = await ctx.params;let body: { action?: string };try {diff --git a/app/api/prefs/route.test.ts b/app/api/prefs/route.test.tsnew file mode 100644index 00000000..9476bd90--- /dev/null+++ b/app/api/prefs/route.test.ts@@ -0,0 +1,47 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";++const mocks = vi.hoisted(() => ({+ requireSession: vi.fn(async () => true),+ readPrefs: vi.fn(async () => ({ quicklinks: [] })),+ writePrefs: vi.fn(async () => ({ quicklinks: [], updatedAt: 1 })),+}));+vi.mock("@/lib/auth/require-session", () => ({ requireSession: mocks.requireSession }));+vi.mock("@/lib/prefs/store", () => ({ readPrefs: mocks.readPrefs, writePrefs: mocks.writePrefs }));++beforeEach(() => {+ mocks.requireSession.mockReset().mockResolvedValue(true);+ mocks.readPrefs.mockClear();+ mocks.writePrefs.mockClear();+});++describe("shared preferences role boundary", () => {+ it("allows any approved device to read the deployment preferences", async () => {+ const { GET } = await import("./route");+ expect((await GET()).status).toBe(200);+ expect(mocks.requireSession).toHaveBeenCalledWith();+ expect(mocks.readPrefs).toHaveBeenCalledOnce();+ });++ it("requires Owner before changing cross-device preferences", async () => {+ const { POST } = await import("./route");+ const request = new NextRequest("https://mso.example/api/prefs", {+ method: "POST", headers: { "content-type": "application/json" },+ body: JSON.stringify({ quicklinks: [] }),+ });+ expect((await POST(request)).status).toBe(200);+ expect(mocks.requireSession).toHaveBeenCalledWith("owner");+ expect(mocks.writePrefs).toHaveBeenCalledWith({ quicklinks: [] });+ });++ it("does not parse or persist a delegated device's mutation", async () => {+ mocks.requireSession.mockResolvedValue(false);+ const { POST } = await import("./route");+ const request = new NextRequest("https://mso.example/api/prefs", {+ method: "POST", headers: { "content-type": "application/json" },+ body: JSON.stringify({ quicklinks: [{ id: "x" }] }),+ });+ expect((await POST(request)).status).toBe(401);+ expect(mocks.writePrefs).not.toHaveBeenCalled();+ });+});diff --git a/app/api/prefs/route.ts b/app/api/prefs/route.tsindex 884e4e37..82633bcd 100644--- a/app/api/prefs/route.ts+++ b/app/api/prefs/route.ts@@ -16,7 +16,9 @@ export async function GET() {}export async function POST(req: NextRequest) {- if (!(await requireSession())) {+ // These preferences are shared across every approved device, not personal to+ // the caller. Delegated devices may consume them, but only Owner may mutate them.+ if (!(await requireSession("owner"))) {return NextResponse.json({ error: "Unauthorized" }, { status: 401 });}let body: { tweaks?: Record<string, unknown>; quicklinks?: unknown };diff --git a/app/api/skills/route.ts b/app/api/skills/route.tsindex 9198e61f..39a1917f 100644--- a/app/api/skills/route.ts+++ b/app/api/skills/route.ts@@ -32,7 +32,7 @@ export async function GET(req: NextRequest) {? NextResponse.json({ skill, content: `# ${skill.name}\n\n${skill.description}\n\nDemo mode only lists this skill; it does not run host automation.` }): NextResponse.json({ skills: demoSkills, recipes: [] });}- if (!(await requireSession())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });if (query) {const { TOOLS } = await import("@/lib/mcp/tools");diff --git a/app/api/threads/route.ts b/app/api/threads/route.tsindex 71595dcb..962111d7 100644--- a/app/api/threads/route.ts+++ b/app/api/threads/route.ts@@ -11,7 +11,7 @@ export const dynamic = "force-dynamic";// POST { id, title?, createdAt?, messages[], history[] } → save (create/update)// DELETE ?id=<id> → removeexport async function GET(req: NextRequest) {- if (!(await requireSession())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });const id = req.nextUrl.searchParams.get("id");if (id) {const t = await getThread(id);@@ -21,7 +21,7 @@ export async function GET(req: NextRequest) {}export async function POST(req: NextRequest) {- if (!(await requireSession())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });let body: Partial<ChatThread>;try {body = await req.json();@@ -46,7 +46,7 @@ export async function POST(req: NextRequest) {}export async function DELETE(req: NextRequest) {- if (!(await requireSession())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });const id = req.nextUrl.searchParams.get("id");if (!id) return NextResponse.json({ error: "id required" }, { status: 400 });await deleteThread(id);diff --git a/app/api/v1/camoufox/session/route.ts b/app/api/v1/camoufox/session/route.tsindex 8e3c8168..189c8f06 100644--- a/app/api/v1/camoufox/session/route.ts+++ b/app/api/v1/camoufox/session/route.ts@@ -26,7 +26,7 @@ const PASSWD_FILE = process.env.CAMOUFOX_VNC_PASSWD_TEXTexport async function GET() {// Demo has no host, no display and no session — never hand out a credential there.if (IS_DEMO) return NextResponse.json({ error: "unavailable" }, { status: 404 });- if (!(await requireSession())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!(await requireSession("operator"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });const password = (await fs.readFile(PASSWD_FILE, "utf8").catch(() => "")).trim();// Absent file = the operator has not set one. Say so plainly rather than 500 — thediff --git a/app/api/v1/managed-apps/[id]/jobs/[jobId]/route.ts b/app/api/v1/managed-apps/[id]/jobs/[jobId]/route.tsindex 512b1bca..3269222c 100644--- a/app/api/v1/managed-apps/[id]/jobs/[jobId]/route.ts+++ b/app/api/v1/managed-apps/[id]/jobs/[jobId]/route.ts@@ -42,7 +42,7 @@ export async function GET(req: Request, context: { params: Promise<{ id: string;// is still inside its mandatory pre-flight backup — abandoning that copy is the// outcome the backup exists to prevent.export async function DELETE(req: Request, context: { params: Promise<{ id: string; jobId: string }> }) {- if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ if (!(await verifyAuth(req, "owner"))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });if (IS_DEMO) return NextResponse.json({ error: "demo mode is read-only" }, { status: 403 });const { id, jobId } = await context.params;if (!isManagedAppId(id)) return NextResponse.json({ error: "unknown managed application" }, { status: 404 });diff --git a/app/api/v1/managed-apps/job-cancel-route.test.ts b/app/api/v1/managed-apps/job-cancel-route.test.tsindex 9f5e144a..dbffb1d1 100644--- a/app/api/v1/managed-apps/job-cancel-route.test.ts+++ b/app/api/v1/managed-apps/job-cancel-route.test.ts@@ -10,10 +10,11 @@ vi.mock("server-only", () => ({}));const demo = vi.hoisted(() => ({ value: false }));const authed = vi.hoisted(() => ({ value: true }));+const requiredRoles = vi.hoisted(() => [] as Array<string | undefined>);const limited = vi.hoisted(() => ({ value: false }));const actor = vi.hoisted(() => ({ value: "device-7f3a" as string | null }));-vi.mock("@/lib/agent/server", () => ({ verifyAuth: async () => authed.value }));+vi.mock("@/lib/agent/server", () => ({ verifyAuth: async (_req: Request, role?: string) => { requiredRoles.push(role); return authed.value; } }));vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: async () => actor.value }));vi.mock("@/lib/demo", () => ({get IS_DEMO() {@@ -44,6 +45,7 @@ beforeEach(() => {authed.value = true;limited.value = false;actor.value = "device-7f3a";+ requiredRoles.length = 0;vi.mocked(audit).mockClear();vi.mocked(rateLimited).mockClear();vi.mocked(cancelManagedAppJob).mockClear().mockReturnValue(true);@@ -54,6 +56,7 @@ describe("cancelling a wedged job", () => {const response = await del();expect(response.status).toBe(202);+ expect(requiredRoles).toEqual(["owner"]);expect(cancelManagedAppJob).toHaveBeenCalledWith(JOB_ID, "hermes");expect(vi.mocked(audit)).toHaveBeenCalledWith(expect.objectContaining({ target: "hermes", ok: true, detail: "job.cancel", actor: "device-7f3a" }),diff --git a/app/api/v1/sys/packages/route.test.ts b/app/api/v1/sys/packages/route.test.tsnew file mode 100644index 00000000..eef1cfc3--- /dev/null+++ b/app/api/v1/sys/packages/route.test.ts@@ -0,0 +1,37 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async () => true),+ actor: vi.fn(async () => "viewer-device"),+ rateLimited: vi.fn(() => false),+ updates: vi.fn(async () => ({ manager: "apt", available: true, updates: [], truncated: false, checkedAt: "now", source: "local-cache" })),+}));+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.actor }));+vi.mock("@/lib/host", () => ({ rateLimited: mocks.rateLimited }));+vi.mock("@/lib/host/package-updates", () => ({ packageUpdates: mocks.updates }));++beforeEach(() => {+ mocks.verifyAuth.mockReset().mockResolvedValue(true);+ mocks.rateLimited.mockReset().mockReturnValue(false);+ mocks.updates.mockClear();+});++describe("package update visibility API", () => {+ it("returns local-cache visibility without a mutation endpoint", async () => {+ const { GET } = await import("./route");+ const response = await GET(new Request("https://mso.example/api/v1/sys/packages"));+ expect(response.status).toBe(200);+ expect(mocks.updates).toHaveBeenCalledOnce();+ });++ it("stops unauthorized or excessive checks before running a package manager", async () => {+ const { GET } = await import("./route");+ mocks.verifyAuth.mockResolvedValue(false);+ expect((await GET(new Request("https://mso.example/api/v1/sys/packages"))).status).toBe(401);+ mocks.verifyAuth.mockResolvedValue(true);+ mocks.rateLimited.mockReturnValue(true);+ expect((await GET(new Request("https://mso.example/api/v1/sys/packages"))).status).toBe(429);+ expect(mocks.updates).not.toHaveBeenCalled();+ });+});diff --git a/app/api/v1/sys/packages/route.ts b/app/api/v1/sys/packages/route.tsnew file mode 100644index 00000000..8caca8af--- /dev/null+++ b/app/api/v1/sys/packages/route.ts@@ -0,0 +1,16 @@+import { NextResponse } from "next/server";+import { verifyAuth } from "@/lib/agent/server";+import { rateLimited } from "@/lib/host";+import { packageUpdates } from "@/lib/host/package-updates";+import { getSessionActor } from "@/lib/auth/require-session";++export const dynamic = "force-dynamic";++export async function GET(req: Request) {+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const actor = await getSessionActor();+ if (rateLimited(`sys-package-updates:${actor ?? "unknown"}`, 10, 60_000)) {+ return NextResponse.json({ error: "too many package update checks" }, { status: 429 });+ }+ return NextResponse.json(await packageUpdates(), { headers: { "Cache-Control": "no-store" } });+}diff --git a/app/api/v1/sys/services/logs/route.test.ts b/app/api/v1/sys/services/logs/route.test.tsnew file mode 100644index 00000000..e5cde349--- /dev/null+++ b/app/api/v1/sys/services/logs/route.test.ts@@ -0,0 +1,41 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async () => true),+ actor: vi.fn(async () => "operator-device"),+ rateLimited: vi.fn(() => false),+ logs: vi.fn(async () => ({ unit: "mso.service", scope: "user", entries: ["ok"], available: true })),+}));+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.actor }));+vi.mock("@/lib/host", () => ({+ rateLimited: mocks.rateLimited,+ apiError: (_label: string, error: unknown) => Response.json({ error: String(error) }, { status: 400 }),+}));+vi.mock("@/lib/host/services", () => ({ serviceLogs: mocks.logs }));++beforeEach(() => {+ mocks.verifyAuth.mockReset().mockResolvedValue(true);+ mocks.actor.mockClear();+ mocks.rateLimited.mockReset().mockReturnValue(false);+ mocks.logs.mockClear();+});++describe("service logs API", () => {+ it("passes only bounded query fields to the host helper", async () => {+ const { GET } = await import("./route");+ const response = await GET(new Request("https://mso.example/api/v1/sys/services/logs?scope=user&unit=mso.service&limit=9999"));+ expect(response.status).toBe(200);+ expect(mocks.logs).toHaveBeenCalledWith("user", "mso.service", 9999);+ });++ it("rejects unauthorized and rate-limited requests before journalctl", async () => {+ const { GET } = await import("./route");+ mocks.verifyAuth.mockResolvedValue(false);+ expect((await GET(new Request("https://mso.example/api/v1/sys/services/logs"))).status).toBe(401);+ mocks.verifyAuth.mockResolvedValue(true);+ mocks.rateLimited.mockReturnValue(true);+ expect((await GET(new Request("https://mso.example/api/v1/sys/services/logs"))).status).toBe(429);+ expect(mocks.logs).not.toHaveBeenCalled();+ });+});diff --git a/app/api/v1/sys/services/logs/route.ts b/app/api/v1/sys/services/logs/route.tsnew file mode 100644index 00000000..ec551d40--- /dev/null+++ b/app/api/v1/sys/services/logs/route.ts@@ -0,0 +1,26 @@+import { NextResponse } from "next/server";+import { verifyAuth } from "@/lib/agent/server";+import { apiError, rateLimited } from "@/lib/host";+import { serviceLogs } from "@/lib/host/services";+import { getSessionActor } from "@/lib/auth/require-session";+import type { ServiceScope } from "@/lib/os-api/types";++export const dynamic = "force-dynamic";++export async function GET(req: Request) {+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const actor = await getSessionActor();+ if (rateLimited(`sys-service-logs:${actor ?? "unknown"}`, 30, 60_000)) {+ return NextResponse.json({ error: "too many service log requests" }, { status: 429 });+ }+ const query = new URL(req.url).searchParams;+ try {+ return NextResponse.json(await serviceLogs(+ query.get("scope") as ServiceScope,+ query.get("unit") ?? "",+ Number(query.get("limit") ?? 120),+ ), { headers: { "Cache-Control": "no-store" } });+ } catch (error) {+ return apiError("sys/services/logs", error);+ }+}diff --git a/app/api/v1/sys/services/route.test.ts b/app/api/v1/sys/services/route.test.tsnew file mode 100644index 00000000..2dcaeb76--- /dev/null+++ b/app/api/v1/sys/services/route.test.ts@@ -0,0 +1,71 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async () => true),+ list: vi.fn(async () => ({ services: [], diagnostics: [], truncated: false, controlAllowlistConfigured: false, generatedAt: "now" })),+ power: vi.fn(async () => ({ unit: "mso.service", scope: "user", load: "loaded", active: "active", sub: "running", description: "MSO", controllable: true })),+ audit: vi.fn(async () => {}),+ actor: vi.fn(async () => "owner-device"),+ rateLimited: vi.fn(() => false),+}));+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));+vi.mock("@/lib/host", () => ({+ audit: mocks.audit,+ rateLimited: mocks.rateLimited,+ apiError: (_label: string, error: unknown) => Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 400 }),+}));+vi.mock("@/lib/host/services", () => ({+ listSystemServices: mocks.list,+ servicePower: mocks.power,+}));+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.actor }));++beforeEach(() => {+ for (const mock of Object.values(mocks)) mock.mockClear();+ mocks.verifyAuth.mockResolvedValue(true);+ mocks.rateLimited.mockReturnValue(false);+});++describe("system service API", () => {+ it("returns bounded inventory through the viewer policy", async () => {+ const { GET } = await import("./route");+ const request = new Request("https://mso.example/api/v1/sys/services");+ expect((await GET(request)).status).toBe(200);+ expect(mocks.verifyAuth).toHaveBeenCalledWith(request);+ expect(mocks.list).toHaveBeenCalledOnce();+ });++ it("passes only typed scope/unit/action to the allowlisted host helper and audits it", async () => {+ const { POST } = await import("./route");+ const request = new Request("https://mso.example/api/v1/sys/services", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ scope: "user", unit: "mso.service", action: "restart" }),+ });+ expect((await POST(request)).status).toBe(200);+ expect(mocks.power).toHaveBeenCalledWith("user", "mso.service", "restart");+ expect(mocks.audit).toHaveBeenCalledWith(expect.objectContaining({+ action: "sys.service", actor: "owner-device", target: "user:mso.service", detail: "restart",+ }));+ });++ it("does not call the host when authorization fails", async () => {+ mocks.verifyAuth.mockResolvedValue(false);+ const { POST } = await import("./route");+ const response = await POST(new Request("https://mso.example/api/v1/sys/services", { method: "POST", body: "{}" }));+ expect(response.status).toBe(401);+ expect(mocks.power).not.toHaveBeenCalled();+ });++ it("rate-limits inventory and actions per approved device before spawning", async () => {+ mocks.rateLimited.mockReturnValue(true);+ const { GET, POST } = await import("./route");+ expect((await GET(new Request("https://mso.example/api/v1/sys/services"))).status).toBe(429);+ expect((await POST(new Request("https://mso.example/api/v1/sys/services", {+ method: "POST", headers: { "content-type": "application/json" },+ body: JSON.stringify({ scope: "user", unit: "mso.service", action: "restart" }),+ }))).status).toBe(429);+ expect(mocks.list).not.toHaveBeenCalled();+ expect(mocks.power).not.toHaveBeenCalled();+ });+});diff --git a/app/api/v1/sys/services/route.ts b/app/api/v1/sys/services/route.tsnew file mode 100644index 00000000..e2cf4f9c--- /dev/null+++ b/app/api/v1/sys/services/route.ts@@ -0,0 +1,51 @@+import { NextResponse } from "next/server";+import { verifyAuth } from "@/lib/agent/server";+import { apiError, audit, rateLimited } from "@/lib/host";+import { listSystemServices, servicePower } from "@/lib/host/services";+import { getSessionActor } from "@/lib/auth/require-session";+import type { ServiceAction, ServiceScope } from "@/lib/os-api/types";++export const dynamic = "force-dynamic";++export async function GET(req: Request) {+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const actor = await getSessionActor();+ if (rateLimited(`sys-services-list:${actor ?? "unknown"}`, 30, 60_000)) {+ return NextResponse.json({ error: "too many service inventory requests" }, { status: 429 });+ }+ try {+ return NextResponse.json(await listSystemServices(), { headers: { "Cache-Control": "no-store" } });+ } catch (error) {+ return apiError("sys/services", error);+ }+}++export async function POST(req: Request) {+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ let body: { scope?: ServiceScope; unit?: string; action?: ServiceAction };+ try { body = await req.json(); }+ catch { return NextResponse.json({ error: "invalid request body" }, { status: 400 }); }+ const actor = await getSessionActor();+ if (rateLimited(`sys-service-action:${actor ?? "unknown"}`, 12, 60_000)) {+ return NextResponse.json({ error: "too many service actions" }, { status: 429 });+ }+ try {+ const service = await servicePower(body.scope as ServiceScope, body.unit as string, body.action as ServiceAction);+ await audit({+ action: "sys.service",+ actor,+ target: `${service.scope}:${service.unit}`,+ detail: body.action,+ });+ return NextResponse.json(service, { headers: { "Cache-Control": "no-store" } });+ } catch (error) {+ await audit({+ action: "sys.service",+ actor,+ target: `${body.scope ?? "?"}:${body.unit ?? "?"}`,+ detail: error instanceof Error ? error.message : String(error),+ ok: false,+ });+ return apiError("sys/services", error);+ }+}diff --git a/app/oauth/authorize/actions.ts b/app/oauth/authorize/actions.tsindex 05262f2a..0df31bf6 100644--- a/app/oauth/authorize/actions.ts+++ b/app/oauth/authorize/actions.ts@@ -19,7 +19,7 @@ export async function approve(form: FormData): Promise<ApprovalResult> {if (!mcpEnabled()) return { ok: false, error: "MCP is disabled on this server." };// The session cookie is the ONLY thing authorizing this. Re-checked here and not// inherited from the page render — a page can be cached, an action cannot.- if (!(await requireSession())) return { ok: false, error: "Not signed in." };+ if (!(await requireSession("owner"))) return { ok: false, error: "Not signed in." };const clientId = String(form.get("client_id") ?? "");const redirectUri = String(form.get("redirect_uri") ?? "");diff --git a/app/os-root.tsx b/app/os-root.tsxindex e2c07582..ad7729e7 100644--- a/app/os-root.tsx+++ b/app/os-root.tsx@@ -9,67 +9,63 @@ import {TOPSIDE_PERSIST_KEY,BUILTIN_APPS,topsideCapabilities,+ type AppDescriptor,type ShellManifest,} from "@/features/os-shell";import { AppearanceProvider } from "@/lib/appearance";import { QuicklinksProvider } from "@/lib/quicklinks";-import "@/features/os-shell/integrations"; // side-effect: lock guard + context menus + palette commands+import "@/features/os-shell/integrations";import { OsApiProvider } from "@/lib/os-api";-import { AuthGate, SessionProvider, useSession, type SessionStatus } from "@/features/auth";+import { AuthGate, SessionProvider, useSession, type DeviceRole, type SessionStatus } from "@/features/auth";+import { appAllowedForRole } from "@/lib/auth/app-access";import { useInstalledApps, useDisabledIds } from "@/features/app-store";-// Inside the auth boundary so it can read the owner's installed runtime apps and-// merge them with the built-ins (dynamic registry). Brand + the built-in app set-// + shell features live in `os-shell/shell.manifest.ts`. The owner can disable any-// built-in app or shell feature from the App Store; we filter the manifest by that-// disabled set so they leave the dock/Launchpad/Spotlight (and feature slots).function Shell() {const dynamic = useInstalledApps();const disabled = useDisabledIds();- const { status } = useSession();+ const { status, role } = useSession();const manifest: ShellManifest = useMemo(() => {const off = new Set(disabled);- const apps = [...BUILTIN_APPS, ...dynamic].filter((app) => !off.has(app.id));- // The shell looks identical signed in or out, but it is NOT the same thing:- // signed out every host call is mock, so most apps are showing fixtures. The- // one app that explains that — and offers the two real next steps, sign in or- // install your own — is Docs, so it gets promoted to the front of the dock and- // the mobile quick row while signed out. Signed in it drops back to its normal- // place; by then you are on your own box and the docs are just reference.- const ordered =- status === "out"- ? [- ...apps.filter((a) => a.id === "docs").map((a) => ({ ...a, pinned: true })),- ...apps.filter((a) => a.id !== "docs"),- ]- : apps;+ const all = [...BUILTIN_APPS, ...dynamic].filter((app) => !off.has(app.id));+ // Signed-out is the unrestricted mock showcase. A live delegated session sees+ // only apps its role can actually use; unknown runtime apps fail closed for+ // non-owners because their host contract cannot be inferred safely.+ const apps = status === "in" ? all.filter((app) => appAllowedForRole(app.id, role)) : all;+ const ordered = status === "out"+ ? [+ ...apps.filter((app) => app.id === "docs").map((app) => ({ ...app, pinned: true })),+ ...apps.filter((app) => app.id !== "docs"),+ ]+ : apps;return {brand: TOPSIDE_BRAND,apps: ordered,- features: TOPSIDE_FEATURES.filter((f) => !off.has(f.id)),+ features: TOPSIDE_FEATURES.filter((feature) => !off.has(feature.id)),persistKey: TOPSIDE_PERSIST_KEY,capabilities: topsideCapabilities,};- }, [dynamic, disabled, status]);+ }, [dynamic, disabled, status, role]);return <AppShell manifest={manifest} />;}-export function OsRoot({ initialStatus }: { initialStatus?: SessionStatus }) {+export function OsRoot({+ initialStatus,+ initialRole,+}: {+ initialStatus?: SessionStatus;+ initialRole?: DeviceRole | null;+}) {return (<AppearanceProvider><QuicklinksProvider><A11yCommands />- {/* Skip-link: first focusable element on the page so keyboard users- can bypass the menu bar/dock and land on the shell surface. Hidden- until focused (`focus:not-sr-only`). Target id="main-content" is- set on the desktop surface root in appshell/components/desktop.tsx. */}<ahref="#main-content"className="sr-only focus:not-sr-only focus:absolute focus:left-2 focus:top-2 focus:z-[var(--z-skip-link)] focus:rounded-md focus:bg-foreground focus:px-3 focus:py-2 focus:text-background focus:outline-2 focus:outline-ring">Skip to main content</a>- <SessionProvider initialStatus={initialStatus}>+ <SessionProvider initialStatus={initialStatus} initialRole={initialRole}><AuthGate><OsApiProvider><Shell />diff --git a/bin/mso b/bin/msoindex f07ce48a..b4d0dd06 100755--- a/bin/mso+++ b/bin/mso@@ -5,7 +5,7 @@## mso.rahmanef.com is only ONE frontend. Everything it can do is a call to the# same /api surface, so this CLI reaches every feature without a browser.-# Auth = signed session cookie (password + approved device), cached in a jar.+# Auth = signed session cookie (password + approved device role), cached in a jar.## Options:# --base <url> API base to talk to (default http://127.0.0.1:4005)@@ -35,6 +35,9 @@# exec <cmd…> Run a shell command on the host (full power)# stats CPU, memory, disk# ps Process table+# units [query] systemd service inventory (system + user)+# unit * logs | start | stop | restart for exact allowlisted units+# packages Cached package-update visibility (never applies updates)# cleanup [--run] Reclaimable junk; --run actually deletes it# status Public service status (no session needed)# health Is this CLI's session valid?@@ -64,9 +67,9 @@# stock <query> [page] Stock-image search (Unsplash key optional, Openverse fallback)## Devices (a local file — these work while the service is down)-# device * list | pending | approve | revoke | revoke all --yes+# device * list | pending | approve [--role] | role | revoke | revoke all --yes# devices Alias for `device list`-# approve <id> [label] Approve a device id+# approve <id> [label] [--role ...] Approve a device id# revoke <id> Revoke one device# whoami This CLI's device id + session state# login Force a fresh login@@ -89,8 +92,8 @@# First thing to run when something is off — it names the broken layer.# mso device pending# See who typed the correct password and is waiting to be let in.-# mso device approve <id> "my phone"-# Let that device sign in.+# mso device approve <id> "my phone" --role viewer+# Let that device sign in with least-privilege read access.# mso exec "systemctl status nginx"# Run anything on the host, as the user that owns the process.# mso camoufox start && mso camoufox session@@ -462,8 +465,9 @@ verbs() {U_camoufox="camoufox status|start|stop|session"U_mapp="mapp list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows>|stream <id>|close <id>"-U_device="device list|pending|approve <id> [label]|revoke <id>|revoke all --yes"+U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner]|role <id> <role>|revoke <id>|revoke all --yes"U_service="service status|start|stop|restart|logs [n]"+U_unit="unit logs <system|user> <unit> [limit]|start|stop|restart <system|user> <unit>"U_update="update status|run [true]|log"U_threads="threads list|show <id>|save <json>|rm <id>"U_memory="memory list|add <text>|rm <id>"@@ -520,6 +524,23 @@ case "$cmd" inexec) jpost "/api/v1/exec/run" "$(jq -n --arg c "$*" '{cmd:$c}')" ;;stats) jget "/api/v1/sys/stats" ;;ps) jget "/api/v1/sys/processes" ;;+ units)+ data=$(jget "/api/v1/sys/services")+ if [ -n "${1-}" ]; then+ jq -r --arg q "${1,,}" '.services[] | select(((.unit+" "+.description+" "+.scope+" "+.active+" "+.sub)|ascii_downcase|contains($q))) | "\(.scope):\(.unit)\t\(.active)/\(.sub)\t\(.description)\(if .controllable then " [allowlisted]" else "" end)"' <<<"$data"+ else+ jq -r '.services[] | "\(.scope):\(.unit)\t\(.active)/\(.sub)\t\(.description)\(if .controllable then " [allowlisted]" else "" end)"' <<<"$data"+ fi ;;+ unit)+ sub="${1:-}"; scope="${2:-}"; unit="${3:-}"+ case "$sub" in+ logs) [ -n "$scope" ] && [ -n "$unit" ] || die "usage: mso $U_unit"+ jget "/api/v1/sys/services/logs?scope=$(enc "$scope")&unit=$(enc "$unit")&limit=$(enc "${4:-120}")" | jq -r '.entries[]?' ;;+ start|stop|restart) [ -n "$scope" ] && [ -n "$unit" ] || die "usage: mso $U_unit"+ jpost "/api/v1/sys/services" "$(jq -n --arg s "$scope" --arg u "$unit" --arg a "$sub" '{scope:$s,unit:$u,action:$a}')" ;;+ *) die "usage: mso $U_unit" ;;+ esac ;;+ packages) jget "/api/v1/sys/packages" ;;cleanup) if [ "${1-}" = "--run" ]; then jpost "/api/v1/sys/cleanup"; else jget "/api/v1/sys/cleanup"; fi ;;status) jget "/api/status" ;;health) jget "/api/auth/me" ;;@@ -693,14 +714,16 @@ case "$cmd" incase "${1:-list}" inlist) dev_script --list ;;pending) dev_script --pending ;;- approve) [ -n "${2-}" ] || die "usage: mso device approve <deviceId> [label]"+ approve) [ -n "${2-}" ] || die "usage: mso device approve <deviceId> [label] [--role viewer|operator|owner]"dev_script "$2" "${@:3}" ;;+ role) [ -n "${2-}" ] && [ -n "${3-}" ] || die "usage: mso device role <deviceId> <viewer|operator|owner>"+ dev_script --set-role "$2" "$3" ;;revoke) [ -n "${2-}" ] || die "usage: mso device revoke <deviceId> | all --yes"if [ "$2" = "all" ]; then dev_script --revoke-all "${3-}"else dev_script --revoke "$2"; fi ;;*) die "usage: mso $U_device" ;;esac ;;- approve) [ -n "${1-}" ] || die "usage: mso approve <deviceId> [label] (ids: mso device list)"+ approve) [ -n "${1-}" ] || die "usage: mso approve <deviceId> [label] [--role viewer|operator|owner] (ids: mso device list)"dev_script "$1" "${@:2}" ;;revoke) [ -n "${1-}" ] || die "usage: mso revoke <deviceId> (ids: mso device list)"dev_script --revoke "$1" ;;diff --git a/bin/mso.test.ts b/bin/mso.test.tsindex 9124999b..828abbeb 100644--- a/bin/mso.test.ts+++ b/bin/mso.test.ts@@ -195,13 +195,13 @@ describe("bin/mso", () => {});const list = withStore("device", "list");- expect(list).toContain(`mso device approve ${pendingId} ${JSON.stringify(nasty)}`);+ expect(list).toContain(`mso device approve ${pendingId} ${JSON.stringify(nasty)} --role viewer`);expect(list).toContain(`mso device revoke ${approvedId}`);// The bare id stays on its own line — way (1) still works.expect(list).toMatch(new RegExp(`^ {2}${pendingId} `, "m"));expect(withStore("device", "pending")).toContain(- `mso device approve ${pendingId} ${JSON.stringify(nasty)}`,+ `mso device approve ${pendingId} ${JSON.stringify(nasty)} --role viewer`,);});diff --git a/docs/9ROUTER-INTEGRATION.md b/docs/9ROUTER-INTEGRATION.mdindex b361da14..0fa2411b 100644--- a/docs/9ROUTER-INTEGRATION.md+++ b/docs/9ROUTER-INTEGRATION.md@@ -60,7 +60,7 @@ NINE_ROUTER_PUBLIC_URL=https://9-router.example.com```Source precedence is: explicit HTTPS `NINE_ROUTER_PUBLIC_URL` → MSO split-origin host →-public `IP:20128`. An explicit HTTPS app domain is framed directly because it is already a+direct `IP:20128` **only when `NINE_ROUTER_EXPOSE_PUBLIC=1`**. An explicit HTTPS app domain is framed directly because it is already aseparate origin; this also preserves the application's own origin-scoped browser session.## Split-origin embedding when a domain is configureddiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 17ec3da8..ba1adada 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -10,8 +10,8 @@ bounded host layer rather than each implementing filesystem or process access.```mermaidflowchart LR- B[Browser / phone] -->|HTTPS + signed session| N[MSO Next.js :4005]- C[CLI `mso`] -->|local HTTP + approved device session| N+ B[Browser / phone] -->|HTTPS + live device role| N[MSO Next.js :4005]+ C[CLI `mso`] -->|local HTTP + approved device role| NA[Alfa] -->|HostTool catalog + per-call approvals| H[lib/host]X[ChatGPT / Claude / Cursor] -->|OAuth bearer + MCP| M[/mcp dispatcher]N --> API[/api/v1/*]@@ -19,7 +19,7 @@ flowchart LRM --> HM --> D[project + skill discovery]H --> F[filesystem jail]- H --> P[PTY / exec / system metrics]+ H --> P[PTY / exec / metrics / services / packages]H --> MA[managed apps]MA --> HE[Hermes]MA --> OC[OpenClaw]@@ -30,9 +30,9 @@ flowchart LR| Boundary | Authority | Notes ||---|---|---|-| Browser owner session | `lib/auth/*`, `/api/auth/*` | Password + approved device + HMAC-signed cookie. |+| Browser device session | `lib/auth/*`, `/api/auth/*` | Password + approved device + HMAC-signed cookie; live Viewer/Operator/Owner role. || Host operations | `lib/host/*` | Filesystem roots, credential denylist, process/system operations, audit. |-| Web host API | `/api/v1/*` | Session-gated routes; routes delegate into `lib/host`. |+| Web host API | `/api/v1/*` | Live-role-gated routes; unknown mutations fail up to Owner and routes delegate into `lib/host`. || CLI | `bin/mso` | Another frontend over the same web API; `docs/CLI.md` is generated from it. || Alfa | `frontend/slices/assistant/host-tools/*` | Stable tool catalog; reads run immediately, mutations require human approval. || MCP | `lib/mcp/*`, `/mcp`, `/oauth/*` | OAuth 2.1 + PKCE; `read < write < exec` token scope. |@@ -52,7 +52,7 @@ frontend/slices/ vertical application slicesappshell/ generic shell frameworkfeatures/ shell featuresos-shell/ MSO manifest + capability adapters-lib/auth/ login/session/device approval+lib/auth/ login/session/device approval + live roleslib/host/ bounded host capability implementationlib/mcp/ OAuth/MCP tool catalog and dispatcherlib/managed-apps/ Hermes/OpenClaw/9Router lifecycle/update/backup/proxy@@ -110,7 +110,7 @@ through the app catch-all.- `fs/*` — list/read/search/write/upload/move/copy/delete/zip/usage- `exec/run` — one-shot captured command execution- `term/*` — interactive PTY lifecycle and streaming-- `sys/*` — stats, processes, cleanup, audit and self-update+- `sys/*` — stats, processes, service inventory/journal/allowlisted lifecycle, package-cache visibility, cleanup, audit and self-update- `camoufox/*` — browser service/session control- `managed-apps/*` — Hermes/OpenClaw/9Router lifecycle, jobs, backups and optional proxying@@ -123,6 +123,20 @@ Interactive PTYs are intentionally stronger than filtered one-shot exec. A PTY ilogin shell; raw keystrokes do not have reliable command boundaries. Authentication andsession lifecycle are therefore the boundary, not the one-shot destructive-command regex.+### 5.1 Device role policy++Approved browsers carry no role claim in their cookie. `getSessionContext()` resolves the current+device record on every request, so demotion/revocation is immediate. Viewer owns bounded read+surfaces; Operator receives only named operational exceptions; Owner receives mutation/shell/config+authority. The centralized route policy treats every explicit read routes as Viewer and every unclassified route as Owner, so a newly added POST fails closed until deliberately classified. The shell+filters app descriptors for usability, but server policy—not hidden UI—is the authorization layer.++System Monitor's Service Center follows the same model: inventory is Viewer, journal is Operator,+and lifecycle is Operator plus an exact `OS_SERVICE_CONTROL_UNITS` match. Package visibility runs+cache-only and exposes no apply action. These are MSO roles over one Unix process account, not an+identity directory, Linux-user switch, or tenant boundary. Appearance/Theme/Quicklinks are still a+single deployment-wide prefs document: delegated devices read it; Owner is the only writer.+## 6. Alfa versus MCPAlfa and MCP are two separate model-facing catalogs on purpose.@@ -187,7 +201,7 @@ See `docs/MANAGED-APPS.md`, `docs/HERMES-INTEGRATION.md`,The Browser app is a real Camoufox Firefox session on a headless X display. It is streamedthrough noVNC on a reserved split-origin host such as `camoufox.mso.example.com`. That host-verifies the approved device, strips cockpit cookies/authorization before upstream, and maps+verifies an Operator/Owner device, strips cockpit cookies/authorization before upstream, and mapsevery path only to loopback noVNC. The old same-origin `/camoufox-vnc/*` route always returns404. The service is a systemd **user** unit and is deliberately off by default; the UI starts itwhen needed. `scripts/camoufox-vnc-service` owns the launch contract.@@ -219,11 +233,11 @@ supported recovery rebuild. See `docs/INSTALL.md`, `docs/DEVELOPMENT.md` andWhen sources disagree, use this order:1. current code + runtime descriptors (`GET /mcp`, `/api/health`);-2. generated contracts (`docs/CLI.md`, `docs/CHANGELOG.md`);+2. generated contracts (`docs/CLI.md`, `docs/CHANGELOG.md`, `docs/COMPARISON.md`);3. current reference docs listed in `docs/README.md`;4. `docs/PROGRESS.md` for historical reasoning;5. dated audits/plans for their point-in-time context only.-`node scripts/check-docs.mjs` checks current-reference links and selected machine-verifiable-facts (MCP toolset and slice counts) so common drift becomes a gate failure instead of a+`node scripts/check-docs.mjs` plus `node scripts/gen-comparison.mjs --check` check current-reference links,+selected machine-verifiable facts, comparison evidence and source-review freshness so common drift becomes a gate failure instead of afuture archaeology task.diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 267e5aef..1df95fc4 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.**Added**+- `operations` add evidence-backed comparison and delegated control- `mcp` add bounded async exec jobs**Fixed**diff --git a/docs/CLI.md b/docs/CLI.mdindex 4e149539..81e650f9 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -39,7 +39,7 @@ Usage: mso [options] <command> [args]mso.rahmanef.com is only ONE frontend. Everything it can do is a call to thesame /api surface, so this CLI reaches every feature without a browser.-Auth = signed session cookie (password + approved device), cached in a jar.+Auth = signed session cookie (password + approved device role), cached in a jar.Options:--base <url> API base to talk to (default http://127.0.0.1:4005)@@ -69,6 +69,9 @@ Commands:exec <cmd…> Run a shell command on the host (full power)stats CPU, memory, diskps Process table+ units [query] systemd service inventory (system + user)+ unit * logs | start | stop | restart for exact allowlisted units+ packages Cached package-update visibility (never applies updates)cleanup [--run] Reclaimable junk; --run actually deletes itstatus Public service status (no session needed)health Is this CLI's session valid?@@ -98,9 +101,9 @@ Commands:stock <query> [page] Stock-image search (Unsplash key optional, Openverse fallback)Devices (a local file — these work while the service is down)- device * list | pending | approve | revoke | revoke all --yes+ device * list | pending | approve [--role] | role | revoke | revoke all --yesdevices Alias for `device list`- approve <id> [label] Approve a device id+ approve <id> [label] [--role ...] Approve a device idrevoke <id> Revoke one devicewhoami This CLI's device id + session statelogin Force a fresh login@@ -123,8 +126,8 @@ Examples:First thing to run when something is off — it names the broken layer.mso device pendingSee who typed the correct password and is waiting to be let in.- mso device approve <id> "my phone"- Let that device sign in.+ mso device approve <id> "my phone" --role viewer+ Let that device sign in with least-privilege read access.mso exec "systemctl status nginx"Run anything on the host, as the user that owns the process.mso camoufox start && mso camoufox sessiondiff --git a/docs/COMPARISON.md b/docs/COMPARISON.mdnew file mode 100644index 00000000..07610312--- /dev/null+++ b/docs/COMPARISON.md@@ -0,0 +1,205 @@+<!-- Generated by scripts/gen-comparison.mjs from docs/comparison-data.json. Do not edit by hand. -->+# Product comparison++Last reviewed: **2026-08-29** · freshness gate: **90 days**++MSO is designed to be the most complete mobile-first, AI-native private Linux workspace for an owner or small trusted team. It does not claim to replace specialist products at their strongest specialty.++## Method++- Ratings describe the documented product surface, not speed, popularity, or a universal winner.+- `●` means a first-class strength, `◐` means partial or deliberately narrow scope, and `—` means it is not a meaningful product surface.+- MSO cells must point to repository evidence that exists at build time.+- Competitor claims use official project documentation only and must be manually re-reviewed before the freshness window expires.+- Edition-dependent or adjacent capabilities are marked partial unless they are consistently core to the product.++## Criteria++### Workspace++A unified browser workspace with mobile-aware navigation across files, terminal, editors, apps, and host views.++### Host ops++General Linux host operations such as services, logs, package visibility, network, storage, users, and system configuration.++### Delivery++Application/container deployment, Git integration, previews, lifecycle, backups, and rollback.++### Observability++Metrics, history, alerting, anomaly detection, correlations, and incident analysis.++### Delegation++Least-privilege roles, multiple identities/devices, auditability, and SSO or policy integration.++### AI / MCP++Built-in AI assistance plus structured remote tool/API control of the workspace.++## Matrix++| Product | Best fit | Workspace | Host ops | Delivery | Observability | Delegation | AI / MCP |+|---|---|:---:|:---:|:---:|:---:|:---:|:---:|+| **MSO** | Mobile-first private Linux workspace | ● | ◐ | ◐ | ◐ | ◐ | ● |+| **Cockpit** | Deep graphical Linux administration | ◐ | ● | ◐ | ◐ | ● | — |+| **Coolify** | Self-hosted Git/PaaS delivery | ◐ | ◐ | ● | ◐ | ● | — |+| **Portainer** | Container and stack operations | ◐ | ◐ | ● | ◐ | ◐ | — |+| **Netdata** | High-resolution observability and RCA | ◐ | — | — | ● | ◐ | ◐ |+| **Tailscale SSH** | Identity-aware private remote access | — | ◐ | — | — | ● | — |+| **File Browser** | Focused web file management | ◐ | — | — | — | ◐ | — |+| **ttyd** | Small, focused web terminal | ◐ | — | — | — | ◐ | — |+| **CasaOS** | Friendly personal-cloud home server | ◐ | ◐ | ◐ | ◐ | — | — |+| **Runtipi** | Curated one-click self-hosted apps | ◐ | — | ● | ◐ | — | — |++## Notes and evidence++### MSO++**Best fit:** Mobile-first private Linux workspace++- **Workspace ●:** Files, real PTY, code/media editors, managed apps, responsive shells, PWA, and CLI share one API surface. Evidence: `app/os-root.tsx`, `frontend/slices/files-manager/app.tsx`, `frontend/slices/os-terminal/components/pty-terminal.tsx`, `frontend/slices/appshell/responsive/responsive-provider.tsx`.+- **Host ops ◐:** Live metrics/processes, service inventory and logs, exact allowlisted systemd lifecycle, package-cache visibility, full owner shell. No first-class network/storage/user administration yet. Evidence: `lib/host/sys.ts`, `lib/host/services.ts`, `lib/host/package-updates.ts`, `frontend/slices/system-monitor/app.tsx`.+- **Delivery ◐:** Pinned managed-app install/update/backup/rollback paths exist, but MSO is not yet a general Git-to-container PaaS. Evidence: `lib/managed-apps/install.ts`, `lib/managed-apps/update.ts`, `lib/managed-apps/backups.ts`.+- **Observability ◐:** Live host metrics and processes are built in; long-term history, alert rules, anomaly correlation, and RCA remain specialist gaps. Evidence: `frontend/slices/system-monitor/app.tsx`, `frontend/slices/system-monitor/lib/use-stats-history.ts`, `lib/host/sys.ts`.+- **Delegation ◐:** Approved devices have live Viewer, Operator, and Owner roles with audit and immediate revocation. This is not a full user directory, Linux-account mapping, or SSO system. Evidence: `lib/auth/roles.ts`, `lib/auth/device-store.ts`, `app/api/auth/devices/route.ts`, `app/os-root.tsx`.+- **AI / MCP ●:** BYOK Alfa, structured host/editor tools, remote OAuth/PKCE MCP, CLI parity, and project-aware tool discovery are native product surfaces. Evidence: `app/api/assistant/route.ts`, `app/mcp/route.ts`, `lib/mcp/dispatch.ts`, `frontend/slices/assistant/app.tsx`.++Official sources:+- [MSO repository](https://github.com/rahmanef63/mso)++### Cockpit++**Best fit:** Deep graphical Linux administration++- **Workspace ◐:** Integrated browser administration and terminal, with optional applications; not an editor-centric mobile workspace.+- **Host ops ●:** Network, firewall, storage, logs, software updates, users, systemd, VMs, containers, and multi-server administration.+- **Delivery ◐:** Can administer containers and VMs, but is not primarily a Git-to-production PaaS.+- **Observability ◐:** Detailed host metrics and journal correlation, without Netdata-class alerting/anomaly depth.+- **Delegation ●:** Uses normal Linux users and privileges and supports network-wide login/SSO approaches.+- **AI / MCP —:** No built-in AI assistant or remote MCP control plane in the core product.++Official sources:+- [Cockpit project overview](https://cockpit-project.org/)++### Coolify++**Best fit:** Self-hosted Git/PaaS delivery++- **Workspace ◐:** Dashboard and real-time terminal center on deployed resources rather than a general files/editors workspace.+- **Host ops ◐:** Server setup automations, terminal, monitoring, and cleanup; not a general Linux administration cockpit.+- **Delivery ●:** Git integrations, automatic and preview deployments, one-click services, SSL, databases, backups, webhooks, and API.+- **Observability ◐:** Deployment/server/container monitoring and notifications, but not deep per-second anomaly/RCA analytics.+- **Delegation ●:** Team projects, roles, and permissions are first-class product features.+- **AI / MCP —:** No native AI workspace or MCP host control comparable to MSO.++Official sources:+- [Coolify features](https://coolify.io/docs)+- [Coolify CI/CD](https://coolify.io/docs/applications/ci-cd)++### Portainer++**Best fit:** Container and stack operations++- **Workspace ◐:** Container consoles, logs, stack editors, and resource views; not a general host files/editor workspace.+- **Host ops ◐:** Strong container-platform operations, but host systemd/network/storage administration is outside the core scope.+- **Delivery ●:** Docker/Swarm/Kubernetes/Podman resources, stacks, GitOps updates, environment management, and migration/duplication.+- **Observability ◐:** Container state, logs, and resource inspection; not a Netdata-class observability system.+- **Delegation ◐:** Access controls are available; advanced RBAC is edition-dependent.+- **AI / MCP —:** No native AI/MCP workspace control plane.++Official sources:+- [Portainer documentation](https://docs.portainer.io/)+- [Portainer stack operations](https://docs.portainer.io/2.33-lts/user/docker/stacks/edit)++### Netdata++**Best fit:** High-resolution observability and RCA++- **Workspace ◐:** Rich monitoring dashboard rather than a files/terminal/editor workspace.+- **Host ops —:** Observes hosts and services; it is not a general administration shell.+- **Delivery —:** Does not provide general application deployment workflows.+- **Observability ●:** Per-second metrics, alerts, anomaly scores, correlation, cross-node analysis, and AI-generated incident insights.+- **Delegation ◐:** Cloud/team access exists, but identity and remote host access are not its primary comparison axis.+- **AI / MCP ◐:** AI Insights explains telemetry and recommends actions; it does not expose a general host-action MCP surface.++Official sources:+- [Netdata charts](https://learn.netdata.cloud/docs/dashboards-and-charts/charts)+- [Netdata AI Insights](https://learn.netdata.cloud/docs/netdata-ai/insights)++### Tailscale SSH++**Best fit:** Identity-aware private remote access++- **Workspace —:** An access layer, not a graphical workspace.+- **Host ops ◐:** Carries SSH sessions to the host; administration remains command-line tooling on the target.+- **Delivery —:** No application delivery control plane.+- **Observability —:** Connection/audit data is not host observability.+- **Delegation ●:** Identity, ACLs, SSH checks, session controls, revocation, and recording integrations are core strengths.+- **AI / MCP —:** No built-in AI/MCP host workspace.++Official sources:+- [Tailscale SSH](https://tailscale.com/docs/features/tailscale-ssh)++### File Browser++**Best fit:** Focused web file management++- **Workspace ◐:** Strong upload/delete/preview/edit file surface, without a complete server workspace.+- **Host ops —:** No general service, package, network, or storage administration.+- **Delivery —:** No application deployment control plane.+- **Observability —:** No host metrics/alerting system.+- **Delegation ◐:** File-focused users/scopes, not a complete host privilege model.+- **AI / MCP —:** No native AI/MCP control.++Official sources:+- [File Browser repository](https://github.com/filebrowser/filebrowser)++### ttyd++**Best fit:** Small, focused web terminal++- **Workspace ◐:** Excellent terminal transport, but intentionally only one command/terminal surface.+- **Host ops —:** Any operations come from the command it exposes, not from structured host controls.+- **Delivery —:** No application deployment workflow.+- **Observability —:** No host observability system.+- **Delegation ◐:** Basic/auth-proxy options and read-only mode, without a product-wide role model.+- **AI / MCP —:** No native AI/MCP workspace.++Official sources:+- [ttyd repository](https://github.com/tsl0922/ttyd)++### CasaOS++**Best fit:** Friendly personal-cloud home server++- **Workspace ◐:** Friendly personal-cloud dashboard, files, widgets, and apps, but not a developer/operations workspace with full PTY/editor depth.+- **Host ops ◐:** Home-server status and storage/app management rather than deep Linux administration.+- **Delivery ◐:** One-click Docker application ecosystem, not Git/preview-oriented PaaS delivery.+- **Observability ◐:** Dashboard status/widgets without specialist alerting and RCA depth.+- **Delegation —:** Not positioned around least-privilege team administration.+- **AI / MCP —:** No native AI/MCP workspace control.++Official sources:+- [CasaOS repository](https://github.com/IceWhaleTech/CasaOS)++### Runtipi++**Best fit:** Curated one-click self-hosted apps++- **Workspace ◐:** App-centric home-server dashboard rather than a unified developer/operations workspace.+- **Host ops —:** General Linux host administration is not the primary product surface.+- **Delivery ●:** Curated/custom app stores, preconfigured Compose apps, lifecycle, logs, updates, persistence, and per-app backups.+- **Observability ◐:** App state/logs, not deep infrastructure observability.+- **Delegation —:** Not positioned as a multi-admin identity/RBAC control plane.+- **AI / MCP —:** No native AI/MCP host workspace.++Official sources:+- [Runtipi app store](https://runtipi.io/docs/learn/apps-and-app-store)+- [Runtipi folder and backup model](https://runtipi.io/docs/reference/folder-structure)++## Interpretation++MSO can lead its chosen category by integrating daily work that otherwise requires several tools: files, PTY, editors, service/package visibility, managed apps, device-scoped roles, AI, MCP, and CLI parity. It should not dilute that advantage by pretending to be a deeper Linux administrator than Cockpit, a broader PaaS than Coolify, a stronger container control plane than Portainer, a richer observability platform than Netdata, or a stronger identity network than Tailscale.diff --git a/docs/COMPETITIVE-ROADMAP.md b/docs/COMPETITIVE-ROADMAP.mdnew file mode 100644index 00000000..93b21e10--- /dev/null+++ b/docs/COMPETITIVE-ROADMAP.md@@ -0,0 +1,41 @@+# Competitive execution roadmap++Status: active product strategy · updated 2026-08-29++## Goal++Make MSO the strongest **mobile-first, AI-native private Linux workspace for an owner or small trusted team**. “Strongest” is measured against the documented comparison criteria, not claimed as a universal replacement for specialist tools.++## Executed in this release++| Phase | Deliverable | Status | Verification contract |+|---|---|---:|---|+| P0 | Versioned comparison data, official-source links, generated README/detail docs, 90-day freshness gate | Done | `node scripts/gen-comparison.mjs --check` |+| P1 | Device-scoped Viewer / Operator / Owner roles, live demotion/revocation, role-aware shell and server authorization | Done | auth, route, proxy, CLI, and policy tests |+| P1 | System Monitor Service Center: system/user service inventory, bounded journal, exact allowlisted lifecycle | Done | parser, policy, route, typecheck, and build tests |+| P1 | Package-update visibility from existing local cache; no refresh/install/upgrade action | Done | multi-manager parser tests and API/CLI parity |+| P1 | CLI parity for roles, services, logs, lifecycle, and package visibility | Done | CLI documentation and route-coverage tests |+| P1 | Current documentation synchronized across architecture, security, installation, FAQ, Product Hunt, and contributor guidance | Done | docs/comparison/CLI checks plus repository verify |++## Deliberate boundaries++The following are **not** silently represented as complete:++1. **Full Linux administration.** Cockpit remains deeper for network, firewall, storage, users, SELinux, VM, and multi-host administration. MSO should integrate these only through bounded, typed modules—not by adding arbitrary privileged buttons.+2. **General PaaS delivery.** Coolify remains stronger for Git push/PR deployments, broad service templates, databases, SSL automation, and multi-server delivery. MSO currently manages a curated app set.+3. **Container orchestration.** Portainer remains stronger for Docker/Swarm/Kubernetes/Podman stacks, resource governance, and GitOps.+4. **Long-term observability.** Netdata remains stronger for per-second history, alerting, anomaly detection, correlation, and incident RCA. MSO has live host telemetry and a short in-window history.+5. **Identity network and SSO.** Tailscale/Cockpit remain stronger for external identity, ACLs, Linux-user mapping, SSO, and recorded access. MSO roles are approved-device roles under one Unix account.+6. **Large app ecosystem.** CasaOS/Runtipi remain stronger for broad consumer one-click app catalogs and per-app self-hosting workflows.++## Next measurable investments++These are ordered by value to MSO’s chosen category, not by copying competitors feature-for-feature:++1. **Persistent alerts and history:** bounded local time-series retention, thresholds, notification adapters, and incident timeline export.+2. **Typed deployment recipes:** Git source, build, health check, rollback, secret references, and preview environments without exposing arbitrary shell templates.+3. **Identity upgrade:** named people, role assignment per identity, optional OIDC, session inventory, and audit attribution while preserving device approval.+4. **Host modules:** network, storage, firewall, and user administration as separate typed capabilities with independent permissions and tests.+5. **Ecosystem contract:** signed managed-app recipes, compatibility metadata, backup/restore conformance, and community review workflow.++A future phase may only change a comparison rating after implementation evidence exists and the generator accepts it.diff --git a/docs/DEMO-SCRIPT.md b/docs/DEMO-SCRIPT.mdindex a9750ab9..f0d61d56 100644--- a/docs/DEMO-SCRIPT.md+++ b/docs/DEMO-SCRIPT.md@@ -9,28 +9,28 @@ Open MSO on a phone and show the iOS/Android shell adapting to the viewport.## 6–14 sec — system health-Open System Monitor and show CPU, memory, disk and processes.+Open System Monitor: show Overview metrics, then Services status/log affordances and the read-only Updates cache. In a public demo these use mock data; in a private recording show that non-allowlisted services have no lifecycle controls.-## 14–24 sec — project files+## 14–26 sec — project filesOpen Files and browse a sample project. Show one real file preview without exposing secrets.-## 24–34 sec — Code + terminal+## 26–36 sec — role boundary + Code-Open Code, then reveal its integrated Terminal. Run a harmless mock/read-only command so the-editor and terminal relationship is visible without implying a public demo has host access.+Briefly show Settings → Devices with Viewer / Operator / Owner, then open Code and its integrated+Terminal as Owner. Run a harmless mock/read-only command so the demo does not imply public host access.-## 34–44 sec — Alfa+## 36–46 sec — AlfaAsk Alfa a simple mock diagnosis question and show a read tool/activity row. If demonstratinga mutation in a private build, show the human Approve/Deny card rather than auto-approving.-## 44–52 sec — Browser / managed app+## 46–54 sec — Browser / managed appShow the Camoufox Browser power surface or a Hermes/OpenClaw Details panel. In a public demo,do not expose a real logged-in browser profile or vendor credentials.-## 52–60 sec — responsive switch + CTA+## 54–60 sec — responsive switch + CTASwitch to desktop/landscape, then show:diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.mdindex d71f78b1..d93b825e 100644--- a/docs/DEVELOPMENT.md+++ b/docs/DEVELOPMENT.md@@ -8,7 +8,7 @@ curl -fsSL https://bun.sh/install | bash # if bun is missing (see "Package manbun installcp .env.example .env.local # set OS_LOGIN_PASSWORD + OS_SESSION_SECRET (openssl rand -hex 32)bun run dev # http://localhost:3000-node scripts/approve-device.js <deviceId> "my laptop" # deviceId shows on the login screen+node scripts/approve-device.js <deviceId> "my laptop" --role owner # deviceId shows on login```## Layout@@ -17,7 +17,7 @@ Every feature is a self-contained **vertical slice** under `frontend/slices/<slu(its own components, hooks, and a `lib/host.ts` seam for host I/O). One manifest,`frontend/slices/os-shell/shell.manifest.ts`, wires slices into the shell — so**adding an app = one slice + one manifest entry**. Host access is bounded in-`lib/host` (Node `fs`/`child_process`, filesystem-jailed) behind signed-cookie auth+`lib/host` (Node `fs`/`child_process`, filesystem-jailed) behind signed-cookie plus live device-role auth(`lib/auth`). See [ARCHITECTURE.md](./ARCHITECTURE.md).## Quality gates@@ -32,12 +32,31 @@ actual `.git/hooks/pre-push` file is an intentionally tiny untracked shim; reinsidempotently with `bash scripts/gates.sh --install`.The gate runs typecheck/lint/test (shared sc-git runner when present, otherwise the-in-repo verify path), cycle checks, generated-changelog freshness, documentation/skill-checks, the high/critical dependency audit, and an out-of-tree production build.+in-repo verify path), cycle checks, generated-changelog freshness, documentation/skill checks,+comparison evidence/freshness, the high/critical dependency audit, and an out-of-tree production+build.`check-contrast.mjs` is informational. None of the build verification touches the livecheckout's `.next`. A healthy push ends with `audit: clean at high/critical.` and`build: HEAD compiles (out-of-tree).`++## Comparison governance++`docs/comparison-data.json` is the only hand-edited comparison source. It records criterion+definitions, per-product notes, official source URLs, and repository evidence for every MSO rating.+Do not hand-edit the generated README table or `docs/COMPARISON.md`. After an implementation or+source review:++```bash+node scripts/gen-comparison.mjs+node scripts/gen-comparison.mjs --check+```++The checker validates MSO evidence paths, restricts competitor links to reviewed official hosts,+and expires the comparison after 90 days. A rating may improve only after its repository evidence+exists. Specialist boundaries and the prioritized execution sequence live in+`docs/COMPETITIVE-ROADMAP.md`.+## Deploy — and the build hazard ⚠️mso deploys via **systemd on the VPS**, not `git push` (no webhook, no Dokploy/diff --git a/docs/FAQ.md b/docs/FAQ.mdindex dfe83872..9a7db3a3 100644--- a/docs/FAQ.md+++ b/docs/FAQ.md@@ -8,27 +8,52 @@ one responsive browser UI.### Is it safe to expose to the public internet?-Treat an authenticated owner session like SSH. MSO has signed sessions, device approval,+Treat an authenticated Owner session like SSH. MSO has signed sessions, device approval,filesystem bounds, rate limits and audits, but no third-party security audit. PreferTailscale/VPN or a tightly controlled HTTPS reverse proxy. Public showcases should use aseparate `NEXT_PUBLIC_OS_DEMO=1` mock-only build.### Why password plus device approval?-The password proves the owner knows the login secret; device approval prevents a new browser-from receiving an owner session until an existing trusted device or the server approves it.-It is a browser allowlist, not standards-based MFA.+The password proves the deployment secret; device approval prevents a new browser from receiving+any live role until an Owner device or the local server approves it. Approvals can be Viewer,+Operator, or Owner and are rechecked on every request. This is a browser/device allowlist, not+standards-based MFA or an independent identity provider.### I lost all approved devices. How do I get back in?-Use a trusted host-admin path to approve the device id shown on the login page with-`scripts/approve-device.js`, or inspect the allowlist on the server. Do not expose the+Use a trusted host-admin path and run `mso device approve <id> "recovery device" --role owner`+(or the underlying `scripts/approve-device.js`). Do not expose theallowlist through the normal Files API.### Can multiple people use one MSO installation?-It is single-owner by design. There is no multi-user RBAC for the cockpit. Do not hand out-sessions you would not hand a shell.+Yes, for a small trusted team, through **device-scoped** Viewer, Operator, and Owner roles. Viewer+gets bounded read surfaces; Operator adds explicit operational controls; Owner has shell-equivalent+host authority. This is not full multi-user RBAC: there are no named people, per-person passwords,+OIDC/SSO, Linux-account mapping, or tenant isolation yet. Every device belongs to one deployment+and one underlying Unix service account.+++### What can Viewer, Operator, and Owner do?++**Viewer** can use bounded files, telemetry, service inventory, cached package-update visibility,+docs and previews. **Operator** adds Camoufox, managed-app start/stop/restart/backup, status and logs, service logs and lifecycle+for units the owner explicitly allowlists. **Owner** adds file mutations, Terminal/exec, AI/MCP+credentials, device administration, self-update and install/update authority. New web approvals+default to Viewer; the local CLI can bootstrap an Owner. Unknown API mutations default to Owner. Appearance, Theme and Quicklink data are shared deployment preferences: delegated devices may use them, while only Owner may edit them.++### Can System Monitor restart any Linux service?++No. Service inventory is read-only by default. A lifecycle button appears only when the current+device is Operator/Owner and the exact `system:unit.service` or `user:unit.service` entry exists in+`OS_SERVICE_CONTROL_UNITS`. Wildcards, paths, flags and non-service units are rejected. System-scope+actions also need the process user's normal permission or narrowly configured non-interactive sudo.++### Does the Updates tab upgrade the server?++No. It reads the package manager's existing local cache with no refresh and has no install/upgrade+action. Use the Owner terminal or the host's normal maintenance process to review and apply updates.### Why no database?@@ -118,7 +143,7 @@ leave it off on small boxes when not needed.### How is the codebase checked?-Every normal push is expected to pass typecheck, lint, the full Vitest suite, cycle/doc/skill+Every normal push is expected to pass typecheck, lint, the full Vitest suite, cycle/doc/skill/comparison freshnesschecks, high/critical dependency audit and an out-of-tree production build. Dated audits arehistorical evidence; current behaviour is validated continuously by the gates and currentreference docs.@@ -126,7 +151,7 @@ reference docs.### Phone support?Mobile is a first-class surface. Portrait uses iOS/Android-style shells with safe-area and-single-owner navigation rules; phone landscape can resolve to the desktop surface. Current+role-aware navigation rules; phone landscape can resolve to the desktop surface. Currentshell E2E covers desktop, phone portrait and phone landscape.### Why is the repo called `mso` but product text says MSO / Manef Shell OS?diff --git a/docs/INSTALL.md b/docs/INSTALL.mdindex 358facb3..9088e818 100644--- a/docs/INSTALL.md+++ b/docs/INSTALL.md@@ -67,7 +67,7 @@ Run or resume it at any time:mso onboard```-It first approves the **local CLI device** in the owner allowlist (a process already running+It first approves the **local CLI device** as Owner in the device allowlist (a process already runningas the owning Unix account has equivalent host authority), then verifies the local serviceand session before asking for provider credentials. API keys are read with terminal echodisabled and posted from stdin; they are not placed in the CLI/curl argv.@@ -85,8 +85,8 @@ terminal status.## 2. Network exposure-The installer binds `127.0.0.1` by default. This is intentional: an authenticated MSO owner-session can execute host commands.+The installer binds `127.0.0.1` by default. This is intentional: an authenticated MSO Owner+session can execute host commands, and delegated roles still expose private server data.For an initial connection, use a localhost tunnel:@@ -112,7 +112,7 @@ deployment-owned authority.Do not bind `0.0.0.0` merely because a reverse proxy exists. Bind wider only when the hostfirewall/network design explicitly requires it.-## 3. Owner authentication+## 3. Authentication and device rolesIf installing manually, copy `.env.example` to `.env.local` and set at minimum:@@ -121,12 +121,25 @@ OS_LOGIN_PASSWORD=choose-a-strong-owner-passwordOS_SESSION_SECRET=<stable random 32+ byte secret>```-The first correct login from a browser creates a **pending device**. Approve the device id-shown on that login screen from the server with `scripts/approve-device.js`. After one-browser is approved, additional devices can be approved in Settings → Devices.+The first correct login from a browser creates a **pending device**. Bootstrap an Owner from the+server, then approve additional devices from Settings → Devices or the CLI:-Changing `OS_SESSION_SECRET` invalidates all existing browser sessions while leaving the-device allowlist intact.+```bash+mso device approve <device-id> "owner laptop" --role owner+mso device approve <device-id> "read-only tablet" --role viewer+mso device role <device-id> operator+```++Viewer is read-oriented; Operator adds bounded managed-app/Camoufox/service operations; Owner has+write, Terminal/exec, credential, device, MCP and update authority. Web approvals default to Viewer.+Role changes are resolved from the private device store on every request, so they do not wait for the+session cookie to expire. The local CLI remains the recovery path if browser Owners are lost.++These roles are tied to approved devices under one deployment password and one Unix service user.+They are not named-user accounts, Linux-user switching, OIDC/SSO, or tenant isolation. Shared Appearance, Theme and Quicklinks remain deployment-wide; delegated devices read/use them and Owner edits them.++Changing `OS_SESSION_SECRET` invalidates all existing browser sessions while leaving the device+allowlist and its roles intact.## 4. Filesystem roots@@ -158,6 +171,33 @@ Production health is:GET /api/health -> {status, buildId, uptime, version}```+### Service Center policy++System Monitor can inventory system and user services without extra configuration. Inventory is+read-only. Journal access needs Operator/Owner, and lifecycle is disabled until an Owner adds exact+entries—no wildcards—to `.env.local`:++```dotenv+OS_SERVICE_CONTROL_UNITS=user:mso.service,system:nginx.service+```++User-unit actions use the owner's user systemd bus. System-unit actions use the process user's+normal permission by default. Only when deliberately configured may MSO invoke non-interactive+sudo:++```dotenv+OS_SERVICE_CONTROL_USE_SUDO=1+```++If that flag is used, grant only the exact `systemctl` actions/units required; do not give the MSO+user broad passwordless sudo. The application allowlist is an additional control, not a replacement+for Unix/sudo policy. Advanced binary overrides (`MSO_SYSTEMCTL_BIN`, `MSO_JOURNALCTL_BIN`,+`MSO_SUDO_BIN`) exist for unusual installations/testing and should normally stay unset.++The Updates tab is visibility-only. It reads the supported package manager's **existing local+cache** and does not refresh repositories, install packages, or upgrade the host. Optional manager+and binary overrides are documented in `.env.example`; normal installations should use detection.+## 6. Optional Browser app — CamoufoxThe current Browser app is **Camoufox**, not the retired Playwright browser daemon.@@ -244,11 +284,10 @@ ChatGPT app; MSO's "Mark ChatGPT refreshed" button is only a local acknowledgeme## 10. Optional managed-app dashboards-Hermes, OpenClaw and 9Router lifecycle management works without a domain. 9Router is-domain-aware on the managed Docker/VPS path: a configured application domain is used as the-in-shell UI; otherwise, after health succeeds, its UI can be opened at `http://<public-ip>:20128`-when the host has a globally-routable IPv4. Hermes/OpenClaw-remain loopback-only unless an operator adds an external route.+Hermes, OpenClaw and 9Router lifecycle management works without a domain. A configured 9Router+application URL is preferred for its in-shell UI. Without one, 9Router stays loopback-only unless+the owner explicitly sets `NINE_ROUTER_EXPOSE_PUBLIC=1` and accepts the firewall/authentication+consequences. Hermes/OpenClaw remain loopback-only unless an operator adds an external route.The safe default is no vendor dashboard on the **MSO cockpit origin**. To opt intosplit-origin embedding, configure:@@ -311,7 +350,7 @@ owner user manager so replacing MSO cannot kill its own deploy controller.A Git push by itself is **not** a production deployment.-## 12. Rollback+## 13. RollbackPrefer an explicit known-good Git commit and the same verified rebuild/update machinery,not ad-hoc partial `.next` changes. Keep the old running process alive if the candidate@@ -321,11 +360,11 @@ For a live chunk mismatch after the source ref is already correct, `mso update ris the supported recovery path. Verify `/api/health` and `scripts/post-deploy-smoke.sh`afterward.-## 13. Backups and persistence+## 14. Backups and persistenceMSO owner-local state under `~/.mso/` includes:-- approved devices;+- approved devices and their Viewer/Operator/Owner roles;- AI/provider configuration;- MCP OAuth client/token hashes;- audit/activity/workflow memory;@@ -341,7 +380,7 @@ cookies.Rotate/retain `~/.mso/audit.log` with normal host log management. Inspect logs beforesharing them because command/path context may be private.-## 14. Uninstall+## 15. UninstallThe supported installer uninstall removes the MSO systemd unit but deliberately keeps thecheckout and `~/.mso` data:@@ -354,7 +393,7 @@ Delete code/private state only as a separate deliberate owner action after decidretain. Camoufox is a separate user service/profile and is not silently deleted by the MSOinstaller.-## 15. Verification checklist+## 16. Verification checklistAfter install/update:@@ -365,4 +404,6 @@ After install/update:5. if UI changed, test desktop + phone portrait + phone landscape;6. if MCP changed, compare Settings → MCP signature and refresh the external app/toolsnapshot;-7. if managed-app origins changed, sign in again and test each explicit app hostname.+7. if managed-app origins changed, sign in again and test each explicit app hostname;+8. test Viewer/Operator/Owner route behaviour on separate devices when authorization changed;+9. if Service Center changed, prove inventory, bounded logs, allowlist refusal/action and cache-only package visibility.diff --git a/docs/MANAGED-APPS.md b/docs/MANAGED-APPS.mdindex 6b784abd..85eaa378 100644--- a/docs/MANAGED-APPS.md+++ b/docs/MANAGED-APPS.md@@ -199,9 +199,10 @@ confirmation is still required for a real removal.**Lifecycle does not require a domain.** These are separate concerns:1. **Runtime management** — install/start/stop/update/backup/uninstall; no DNS required.-2. **Direct public access** — fallback for 9Router when no embeddable domain is configured; its server distribution is- deliberately published on host port `20128`; MSO derives a globally-routable IPv4 from- local network interfaces and returns `publicDashboardUrl`.+2. **Direct public access** — an explicit 9Router exception only when no embeddable domain is+ configured **and** `NINE_ROUTER_EXPOSE_PUBLIC=1`; only then is port `20128` published beyond+ loopback and MSO may derive a routable address for `publicDashboardUrl`. The normal install is+ loopback-only and has no direct-address fallback.3. **Embedded dashboard access** — preferred when configured: split-origin mode for a vendor UI shown insideMSO.@@ -266,8 +267,8 @@ the real secret verification.- app says "not installed" but you know it exists → check systemd-user visibility/detectionevidence 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 UI button has no public URL → the host has no globally-routable IPv4 on a local- interface, or the runtime was deliberately changed to loopback/private-only networking;+- 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 bydesign; Details and direct access (where defined) still work;- update refused → inspect the pre-update backup error first;diff --git a/docs/PRODUCT_HUNT.md b/docs/PRODUCT_HUNT.mdindex 93dde7bf..144693fd 100644--- a/docs/PRODUCT_HUNT.md+++ b/docs/PRODUCT_HUNT.md@@ -14,8 +14,9 @@ Manage your Linux server from any browser.## DescriptionMSO is an open-source, mobile-friendly visual shell for a Linux server you own. It combines-Files, real PTY Terminal, Code with an integrated terminal, live system metrics, a remote-Camoufox browser, media tools, optional BYOK Alfa AI, and managed Hermes/OpenClaw controls+Files, real PTY Terminal, Code with an integrated terminal, live metrics, a safe Service Center,+cached package-update visibility, a remote Camoufox browser, device-scoped roles, media tools,+optional BYOK Alfa AI, and managed Hermes/OpenClaw controlsinside one private browser workspace.## First comment draft@@ -27,9 +28,11 @@ transfer tools, metrics dashboards, docs and AI chat.MSO is not a Linux distribution, desktop environment or VPS provider. "OS" is the interfacemetaphor: a responsive workspace over a server you already own.-It is deliberately single-owner. An authenticated session can access files and run commands-as the Linux user that owns the process, so the recommended deployment is behind Tailscale-or another tightly controlled HTTPS path. The public demo uses mock data only.+It is owner-first, with live Viewer, Operator, and Owner roles assigned per approved device.+Owner remains shell-equivalent to the Linux service account; Operator is limited to bounded,+owner-allowlisted operations; Viewer is read-oriented. This is not enterprise identity or SSO,+so the recommended deployment is still behind Tailscale or another tightly controlled HTTPS path.+The public demo uses mock data only.The project is Public Alpha / Developer Preview and has not had a third-party securityaudit. I am looking for feedback on the core workflow before widening scope.@@ -44,7 +47,8 @@ audit. I am looking for feedback on the core workflow before widening scope.## Known limitations to disclose- Public Alpha / Developer Preview-- Single-owner, no multi-user RBAC+- Device-scoped roles, but no named-user directory, OIDC/SSO, Linux-account mapping, or tenant isolation- No third-party security audit- Private-network/TLS deployment strongly recommended+- Service actions are disabled until exact units are owner-allowlisted; package updates are visibility-only- Some integrations (Camoufox, Hermes/OpenClaw, MCP, model providers) are optionaldiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 2601a031..8e9adea0 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,7 +1,3 @@-# Ultimate assurance remediation — 2026-08-28--Codex Security completed all twenty explicit repository components and surfaced one High plus a set of Medium/Low findings. This remediation batch removes predictable shared-temporary session files, adds owner-only private shell state with symlink/ownership/mode checks and atomic writes, authenticates and byte-bounds MCP bodies before parsing, reapplies the deployment scope ceiling on every MCP dispatch, hardens custom-provider network destinations, skill discovery/cursors/search, approval disclosures, Camoufox isolation/revocation, media/project resource limits, security-store locking, and managed-app artifact identity. Dedicated adversarial regressions accompany each changed boundary. The release remains fail-closed until the final committed SHA completes repository verification, isolated production build, all Codex components, OWASP ZAP, hosted security workflows, deployment, and live health checks.-# mso — Progress LogRunning log of what shipped each phase. Newest at top.@@ -13,6 +9,33 @@ Running log of what shipped each phase. Newest at top.> [`docs/README.md`](./README.md) and [`docs/ARCHITECTURE.md`](./ARCHITECTURE.md); keep old> entries intact as historical evidence even when their commands/counts have been superseded.+## 2026-08-29 — evidence-backed comparison, delegated roles and Service Center (SHIPPED)++The old README comparison mixed unrelated tools into one hand-written scorecard. It is now generated+from `docs/comparison-data.json`: six defined criteria, official-source links for every comparison+product, an existing repository-evidence requirement for every MSO rating, and a 90-day review+freshness gate. The chosen category is deliberately narrow—mobile-first, AI-native private Linux+workspace for an owner or small trusted team—while specialist strengths and unfinished gaps remain+explicit in `docs/COMPARISON.md` and `docs/COMPETITIVE-ROADMAP.md`.++Device approval now carries a live Viewer, Operator or Owner role. The store migrates legacy+role-less devices to Owner, fails malformed roles down to Viewer, prevents browser self-demotion and+last-Owner removal, and re-resolves role/revocation on every request. The shell filters inaccessible+apps for clarity, while a centralized server policy makes the actual decision: explicit reads are Viewer and every unclassified route fails up to Owner; PTY/exec/config/MCP/update remain Owner, and only+explicit bounded operational surfaces are Operator.++System Monitor now includes Services and Updates beside live telemetry. It inventories system/user+`systemd` units, bounds journals, and permits start/stop/restart only for validated exact units in+`OS_SERVICE_CONTROL_UNITS`; no shell or wildcard path exists. Package visibility reads only the+existing local cache for apt/dnf/yum/pacman/zypper and exposes no refresh/install/upgrade action. The+same contracts are available through `mso units`, `mso unit ...`, `mso packages`, and role-aware+device CLI commands. Current-reference docs, env examples, generated CLI/comparison docs, Product+Hunt copy, contributor rules and security boundaries were synchronized in the same release.++Release contract: the exact commit must pass repository verification, an out-of-tree production+build, `bun run ship`, deployment, live health checks and the project security gate. The release+record below is generated from that immutable commit rather than from an uncommitted worktree.+## 2026-08-28 (security) — full-repository Codex remediation (DONE)The first terminal Codex Security component review completed all 20 tracked-repositorydiff --git a/docs/README.md b/docs/README.mdindex c3f65ab8..ce86ef9f 100644--- a/docs/README.md+++ b/docs/README.md@@ -12,14 +12,17 @@ cannot quietly become today's architecture documentation.5. Historical plans/audits for their dated context only.Run `node scripts/check-docs.mjs` to validate relative links plus selected-machine-verifiable facts. The repository quality gate runs it automatically.+machine-verifiable facts, and `node scripts/gen-comparison.mjs --check` to validate comparison+evidence and review freshness. The repository quality gate runs both automatically.## Current reference| Document | Contract ||---|---|| [`../README.md`](../README.md) | Product overview and quickstart |-| [`ARCHITECTURE.md`](./ARCHITECTURE.md) | Current runtime, shell, host, MCP and deployment architecture |+| [`ARCHITECTURE.md`](./ARCHITECTURE.md) | Current runtime, shell, role, host, MCP and deployment architecture |+| [`COMPARISON.md`](./COMPARISON.md) | Generated product comparison methodology, evidence and notes |+| [`COMPETITIVE-ROADMAP.md`](./COMPETITIVE-ROADMAP.md) | Executed comparison plan, deliberate specialist boundaries and next investments || [`INSTALL.md`](./INSTALL.md) | Owner installation, TLS, updates, backup and uninstall || [`DEVELOPMENT.md`](./DEVELOPMENT.md) | Development and release workflow || [`SECURITY-ASSURANCE.md`](./SECURITY-ASSURANCE.md) | Repeatable security verification lanes, public evidence, and claim boundaries |@@ -47,6 +50,7 @@ machine-verifiable facts. The repository quality gate runs it automatically.|---|---|| [`CLI.md`](./CLI.md) | `node scripts/gen-cli-docs.mjs` / `bin/mso --help` || [`CHANGELOG.md`](./CHANGELOG.md) | Git subjects via `scripts/gen-changelog.mjs`; never hand-edit |+| [`COMPARISON.md`](./COMPARISON.md) | `docs/comparison-data.json` via `scripts/gen-comparison.mjs`; never hand-edit || [`PROGRESS.md`](./PROGRESS.md) | Hand-written shipping rationale; newest first; canonical historical WHY |## Historical point-in-time documentsdiff --git a/docs/SLICE-CATALOG.md b/docs/SLICE-CATALOG.mdindex 93859123..5680a219 100644--- a/docs/SLICE-CATALOG.md+++ b/docs/SLICE-CATALOG.md@@ -32,7 +32,7 @@ shared API/host seam rather than reaching arbitrary Node host APIs from client c| `quicklinks` | Website shortcuts/favicons || `reel-editor` | Video/reel timeline editor || `shell-settings` | Shared shell settings UI primitives |-| `system-monitor` | CPU/memory/disk/process monitoring |+| `system-monitor` | Live metrics/processes plus service inventory/logs/allowlisted lifecycle and cache-only package updates |## AppShell feature directories (10)diff --git a/docs/comparison-data.json b/docs/comparison-data.jsonnew file mode 100644index 00000000..fc92dfb3--- /dev/null+++ b/docs/comparison-data.json@@ -0,0 +1,267 @@+{+ "schemaVersion": 1,+ "reviewedAt": "2026-08-29",+ "expiresAfterDays": 90,+ "positioning": "MSO is designed to be the most complete mobile-first, AI-native private Linux workspace for an owner or small trusted team. It does not claim to replace specialist products at their strongest specialty.",+ "legend": {+ "strong": "●",+ "partial": "◐",+ "none": "—"+ },+ "criteria": [+ {+ "id": "workspace",+ "label": "Workspace",+ "definition": "A unified browser workspace with mobile-aware navigation across files, terminal, editors, apps, and host views."+ },+ {+ "id": "hostOps",+ "label": "Host ops",+ "definition": "General Linux host operations such as services, logs, package visibility, network, storage, users, and system configuration."+ },+ {+ "id": "delivery",+ "label": "Delivery",+ "definition": "Application/container deployment, Git integration, previews, lifecycle, backups, and rollback."+ },+ {+ "id": "observability",+ "label": "Observability",+ "definition": "Metrics, history, alerting, anomaly detection, correlations, and incident analysis."+ },+ {+ "id": "delegation",+ "label": "Delegation",+ "definition": "Least-privilege roles, multiple identities/devices, auditability, and SSO or policy integration."+ },+ {+ "id": "aiControl",+ "label": "AI / MCP",+ "definition": "Built-in AI assistance plus structured remote tool/API control of the workspace."+ }+ ],+ "products": [+ {+ "id": "mso",+ "name": "MSO",+ "bestFor": "Mobile-first private Linux workspace",+ "sources": [+ {+ "label": "MSO repository",+ "url": "https://github.com/rahmanef63/mso"+ }+ ],+ "ratings": {+ "workspace": {+ "value": "strong",+ "note": "Files, real PTY, code/media editors, managed apps, responsive shells, PWA, and CLI share one API surface.",+ "evidence": [+ "app/os-root.tsx",+ "frontend/slices/files-manager/app.tsx",+ "frontend/slices/os-terminal/components/pty-terminal.tsx",+ "frontend/slices/appshell/responsive/responsive-provider.tsx"+ ]+ },+ "hostOps": {+ "value": "partial",+ "note": "Live metrics/processes, service inventory and logs, exact allowlisted systemd lifecycle, package-cache visibility, full owner shell. No first-class network/storage/user administration yet.",+ "evidence": [+ "lib/host/sys.ts",+ "lib/host/services.ts",+ "lib/host/package-updates.ts",+ "frontend/slices/system-monitor/app.tsx"+ ]+ },+ "delivery": {+ "value": "partial",+ "note": "Pinned managed-app install/update/backup/rollback paths exist, but MSO is not yet a general Git-to-container PaaS.",+ "evidence": [+ "lib/managed-apps/install.ts",+ "lib/managed-apps/update.ts",+ "lib/managed-apps/backups.ts"+ ]+ },+ "observability": {+ "value": "partial",+ "note": "Live host metrics and processes are built in; long-term history, alert rules, anomaly correlation, and RCA remain specialist gaps.",+ "evidence": [+ "frontend/slices/system-monitor/app.tsx",+ "frontend/slices/system-monitor/lib/use-stats-history.ts",+ "lib/host/sys.ts"+ ]+ },+ "delegation": {+ "value": "partial",+ "note": "Approved devices have live Viewer, Operator, and Owner roles with audit and immediate revocation. This is not a full user directory, Linux-account mapping, or SSO system.",+ "evidence": [+ "lib/auth/roles.ts",+ "lib/auth/device-store.ts",+ "app/api/auth/devices/route.ts",+ "app/os-root.tsx"+ ]+ },+ "aiControl": {+ "value": "strong",+ "note": "BYOK Alfa, structured host/editor tools, remote OAuth/PKCE MCP, CLI parity, and project-aware tool discovery are native product surfaces.",+ "evidence": [+ "app/api/assistant/route.ts",+ "app/mcp/route.ts",+ "lib/mcp/dispatch.ts",+ "frontend/slices/assistant/app.tsx"+ ]+ }+ }+ },+ {+ "id": "cockpit",+ "name": "Cockpit",+ "bestFor": "Deep graphical Linux administration",+ "sources": [+ {+ "label": "Cockpit project overview",+ "url": "https://cockpit-project.org/"+ }+ ],+ "ratings": {+ "workspace": { "value": "partial", "note": "Integrated browser administration and terminal, with optional applications; not an editor-centric mobile workspace." },+ "hostOps": { "value": "strong", "note": "Network, firewall, storage, logs, software updates, users, systemd, VMs, containers, and multi-server administration." },+ "delivery": { "value": "partial", "note": "Can administer containers and VMs, but is not primarily a Git-to-production PaaS." },+ "observability": { "value": "partial", "note": "Detailed host metrics and journal correlation, without Netdata-class alerting/anomaly depth." },+ "delegation": { "value": "strong", "note": "Uses normal Linux users and privileges and supports network-wide login/SSO approaches." },+ "aiControl": { "value": "none", "note": "No built-in AI assistant or remote MCP control plane in the core product." }+ }+ },+ {+ "id": "coolify",+ "name": "Coolify",+ "bestFor": "Self-hosted Git/PaaS delivery",+ "sources": [+ { "label": "Coolify features", "url": "https://coolify.io/docs" },+ { "label": "Coolify CI/CD", "url": "https://coolify.io/docs/applications/ci-cd" }+ ],+ "ratings": {+ "workspace": { "value": "partial", "note": "Dashboard and real-time terminal center on deployed resources rather than a general files/editors workspace." },+ "hostOps": { "value": "partial", "note": "Server setup automations, terminal, monitoring, and cleanup; not a general Linux administration cockpit." },+ "delivery": { "value": "strong", "note": "Git integrations, automatic and preview deployments, one-click services, SSL, databases, backups, webhooks, and API." },+ "observability": { "value": "partial", "note": "Deployment/server/container monitoring and notifications, but not deep per-second anomaly/RCA analytics." },+ "delegation": { "value": "strong", "note": "Team projects, roles, and permissions are first-class product features." },+ "aiControl": { "value": "none", "note": "No native AI workspace or MCP host control comparable to MSO." }+ }+ },+ {+ "id": "portainer",+ "name": "Portainer",+ "bestFor": "Container and stack operations",+ "sources": [+ { "label": "Portainer documentation", "url": "https://docs.portainer.io/" },+ { "label": "Portainer stack operations", "url": "https://docs.portainer.io/2.33-lts/user/docker/stacks/edit" }+ ],+ "ratings": {+ "workspace": { "value": "partial", "note": "Container consoles, logs, stack editors, and resource views; not a general host files/editor workspace." },+ "hostOps": { "value": "partial", "note": "Strong container-platform operations, but host systemd/network/storage administration is outside the core scope." },+ "delivery": { "value": "strong", "note": "Docker/Swarm/Kubernetes/Podman resources, stacks, GitOps updates, environment management, and migration/duplication." },+ "observability": { "value": "partial", "note": "Container state, logs, and resource inspection; not a Netdata-class observability system." },+ "delegation": { "value": "partial", "note": "Access controls are available; advanced RBAC is edition-dependent." },+ "aiControl": { "value": "none", "note": "No native AI/MCP workspace control plane." }+ }+ },+ {+ "id": "netdata",+ "name": "Netdata",+ "bestFor": "High-resolution observability and RCA",+ "sources": [+ { "label": "Netdata charts", "url": "https://learn.netdata.cloud/docs/dashboards-and-charts/charts" },+ { "label": "Netdata AI Insights", "url": "https://learn.netdata.cloud/docs/netdata-ai/insights" }+ ],+ "ratings": {+ "workspace": { "value": "partial", "note": "Rich monitoring dashboard rather than a files/terminal/editor workspace." },+ "hostOps": { "value": "none", "note": "Observes hosts and services; it is not a general administration shell." },+ "delivery": { "value": "none", "note": "Does not provide general application deployment workflows." },+ "observability": { "value": "strong", "note": "Per-second metrics, alerts, anomaly scores, correlation, cross-node analysis, and AI-generated incident insights." },+ "delegation": { "value": "partial", "note": "Cloud/team access exists, but identity and remote host access are not its primary comparison axis." },+ "aiControl": { "value": "partial", "note": "AI Insights explains telemetry and recommends actions; it does not expose a general host-action MCP surface." }+ }+ },+ {+ "id": "tailscale-ssh",+ "name": "Tailscale SSH",+ "bestFor": "Identity-aware private remote access",+ "sources": [+ { "label": "Tailscale SSH", "url": "https://tailscale.com/docs/features/tailscale-ssh" }+ ],+ "ratings": {+ "workspace": { "value": "none", "note": "An access layer, not a graphical workspace." },+ "hostOps": { "value": "partial", "note": "Carries SSH sessions to the host; administration remains command-line tooling on the target." },+ "delivery": { "value": "none", "note": "No application delivery control plane." },+ "observability": { "value": "none", "note": "Connection/audit data is not host observability." },+ "delegation": { "value": "strong", "note": "Identity, ACLs, SSH checks, session controls, revocation, and recording integrations are core strengths." },+ "aiControl": { "value": "none", "note": "No built-in AI/MCP host workspace." }+ }+ },+ {+ "id": "file-browser",+ "name": "File Browser",+ "bestFor": "Focused web file management",+ "sources": [+ { "label": "File Browser repository", "url": "https://github.com/filebrowser/filebrowser" }+ ],+ "ratings": {+ "workspace": { "value": "partial", "note": "Strong upload/delete/preview/edit file surface, without a complete server workspace." },+ "hostOps": { "value": "none", "note": "No general service, package, network, or storage administration." },+ "delivery": { "value": "none", "note": "No application deployment control plane." },+ "observability": { "value": "none", "note": "No host metrics/alerting system." },+ "delegation": { "value": "partial", "note": "File-focused users/scopes, not a complete host privilege model." },+ "aiControl": { "value": "none", "note": "No native AI/MCP control." }+ }+ },+ {+ "id": "ttyd",+ "name": "ttyd",+ "bestFor": "Small, focused web terminal",+ "sources": [+ { "label": "ttyd repository", "url": "https://github.com/tsl0922/ttyd" }+ ],+ "ratings": {+ "workspace": { "value": "partial", "note": "Excellent terminal transport, but intentionally only one command/terminal surface." },+ "hostOps": { "value": "none", "note": "Any operations come from the command it exposes, not from structured host controls." },+ "delivery": { "value": "none", "note": "No application deployment workflow." },+ "observability": { "value": "none", "note": "No host observability system." },+ "delegation": { "value": "partial", "note": "Basic/auth-proxy options and read-only mode, without a product-wide role model." },+ "aiControl": { "value": "none", "note": "No native AI/MCP workspace." }+ }+ },+ {+ "id": "casaos",+ "name": "CasaOS",+ "bestFor": "Friendly personal-cloud home server",+ "sources": [+ { "label": "CasaOS repository", "url": "https://github.com/IceWhaleTech/CasaOS" }+ ],+ "ratings": {+ "workspace": { "value": "partial", "note": "Friendly personal-cloud dashboard, files, widgets, and apps, but not a developer/operations workspace with full PTY/editor depth." },+ "hostOps": { "value": "partial", "note": "Home-server status and storage/app management rather than deep Linux administration." },+ "delivery": { "value": "partial", "note": "One-click Docker application ecosystem, not Git/preview-oriented PaaS delivery." },+ "observability": { "value": "partial", "note": "Dashboard status/widgets without specialist alerting and RCA depth." },+ "delegation": { "value": "none", "note": "Not positioned around least-privilege team administration." },+ "aiControl": { "value": "none", "note": "No native AI/MCP workspace control." }+ }+ },+ {+ "id": "runtipi",+ "name": "Runtipi",+ "bestFor": "Curated one-click self-hosted apps",+ "sources": [+ { "label": "Runtipi app store", "url": "https://runtipi.io/docs/learn/apps-and-app-store" },+ { "label": "Runtipi folder and backup model", "url": "https://runtipi.io/docs/reference/folder-structure" }+ ],+ "ratings": {+ "workspace": { "value": "partial", "note": "App-centric home-server dashboard rather than a unified developer/operations workspace." },+ "hostOps": { "value": "none", "note": "General Linux host administration is not the primary product surface." },+ "delivery": { "value": "strong", "note": "Curated/custom app stores, preconfigured Compose apps, lifecycle, logs, updates, persistence, and per-app backups." },+ "observability": { "value": "partial", "note": "App state/logs, not deep infrastructure observability." },+ "delegation": { "value": "none", "note": "Not positioned as a multi-admin identity/RBAC control plane." },+ "aiControl": { "value": "none", "note": "No native AI/MCP host workspace." }+ }+ }+ ]+}diff --git a/frontend/slices/appshell/index.ts b/frontend/slices/appshell/index.tsindex 020272ae..69f8a325 100644--- a/frontend/slices/appshell/index.ts+++ b/frontend/slices/appshell/index.ts@@ -66,8 +66,9 @@ export type { Activity } from "./lib/activity";// it in its own OsApiProvider). The OsApi type IS the portability contract.export { HostApiProvider, useOsApi } from "./lib/host-api";export type {- OsApi, Unsub, SysStats, FsEntry, FsRoot, FsList, FsUsage, FsHit,- UploadFile, UploadResult, UploadProgress, ExecResult, Process, AppManifest,+ OsApi, Unsub, HostAccessRole, HostAccess, SysStats, FsEntry, FsRoot, FsList, FsUsage, FsHit,+ UploadFile, UploadResult, UploadProgress, ExecResult, Process, ServiceScope, ServiceAction,+ SystemService, ServiceInventory, ServiceLogs, PackageUpdate, PackageUpdateSummary, AppManifest,} from "./lib/host-api";// F1–F20 window-manager + productivity libs (each module exports its own// public surface — commands/badges/layouts/recents/window-commands/window-title/diff --git a/frontend/slices/appshell/lib/host-api.tsx b/frontend/slices/appshell/lib/host-api.tsxindex ea61d612..d5136932 100644--- a/frontend/slices/appshell/lib/host-api.tsx+++ b/frontend/slices/appshell/lib/host-api.tsx@@ -12,6 +12,14 @@ import { createContext, useContext, type ReactNode } from "react";export type Unsub = () => void;+export type HostAccessRole = "viewer" | "operator" | "owner" | "demo";+export type HostAccess = {+ role: HostAccessRole;+ canRead: boolean;+ canOperate: boolean;+ canOwn: boolean;+};+export type SysStats = {cpu: { pct: number; cores: number };mem: { used: number; total: number };@@ -62,6 +70,47 @@ export type Process = {mem: number;};+export type ServiceScope = "system" | "user";+export type ServiceAction = "start" | "stop" | "restart";+export type SystemService = {+ unit: string;+ scope: ServiceScope;+ load: string;+ active: string;+ sub: string;+ description: string;+ controllable: boolean;+};+export type ServiceInventory = {+ services: SystemService[];+ diagnostics: string[];+ truncated: boolean;+ controlAllowlistConfigured: boolean;+ generatedAt: string;+};+export type ServiceLogs = {+ unit: string;+ scope: ServiceScope;+ entries: string[];+ available: boolean;+ diagnostic?: string;+};+export type PackageUpdate = {+ name: string;+ current?: string;+ candidate: string;+ architecture?: string;+};+export type PackageUpdateSummary = {+ manager: "apt" | "dnf" | "yum" | "pacman" | "zypper" | null;+ available: boolean;+ updates: PackageUpdate[];+ truncated: boolean;+ checkedAt: string;+ source: "local-cache";+ diagnostic?: string;+};+export type AppManifest = { name: string; slug: string; runtime: string; entry: string };/** A managed application on the host (hermes, openclaw) — the thing that actually@@ -72,6 +121,7 @@ export type BrowserState = { installed: boolean; running: boolean; autostart: boexport type OsApi = {mode: "mock" | "live";+ access: HostAccess;auth: {token: (u: string, p: string) => Promise<{ token: string; expires_at: number }>;me: () => Promise<{ user: { name: string; id: string } }>;@@ -105,6 +155,10 @@ export type OsApi = {stats: () => Promise<SysStats>;statsStream: (onEvent: (s: Partial<SysStats>) => void) => Unsub;processes: () => Promise<Process[]>;+ services: () => Promise<ServiceInventory>;+ serviceLogs: (scope: ServiceScope, unit: string, limit?: number) => Promise<ServiceLogs>;+ servicePower: (scope: ServiceScope, unit: string, action: ServiceAction) => Promise<SystemService>;+ packageUpdates: () => Promise<PackageUpdateSummary>;};// Managed apps, not the UI app list. `start`/`stop` used to sit here pointed at// /apps/:slug/start and /apps/:slug/stop — neither of which is a route — whilediff --git a/frontend/slices/auth/components/devices-panel.tsx b/frontend/slices/auth/components/devices-panel.tsxindex 105b2415..08edcd08 100644--- a/frontend/slices/auth/components/devices-panel.tsx+++ b/frontend/slices/auth/components/devices-panel.tsx@@ -1,143 +1,162 @@"use client";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import { Check, ShieldCheck, Trash2, Clock } from "lucide-react";import { Button } from "@/components/ui/button";import { Badge } from "@/components/ui/badge";-import { CopyButton, FormDrawer } from "@/features/os-shell";+import { CopyButton, FormDrawer, toast } from "@/features/os-shell";import { getOrCreateDeviceId } from "../lib/device";+import { DEVICE_ROLES, roleLabel, type DeviceRole } from "@/lib/auth/roles";-type Device = { deviceId: string; label: string; status: "approved" | "pending" };+type Device = {+ deviceId: string;+ label: string;+ status: "approved" | "pending";+ role?: DeviceRole;+};type DevicesResponse = {- approved?: Record<string, { label?: string }>;+ approved?: Record<string, { label?: string; role?: DeviceRole }>;pending?: Record<string, { label?: string }>;};-// Flatten the {approved,pending} maps from /api/auth/devices into one list.function flatten(r: DevicesResponse): Device[] {- const a = Object.entries(r.approved ?? {}).map(- ([deviceId, d]): Device => ({ deviceId, label: d.label || "device", status: "approved" }),+ const approved = Object.entries(r.approved ?? {}).map(+ ([deviceId, d]): Device => ({+ deviceId,+ label: d.label || "device",+ status: "approved",+ role: d.role || "owner",+ }),);- const p = Object.entries(r.pending ?? {}).map(+ const pending = Object.entries(r.pending ?? {}).map(([deviceId, d]): Device => ({ deviceId, label: d.label || "device", status: "pending" }),);- return [...a, ...p];+ return [...pending, ...approved];}-// Settings → Devices. Only reachable from an approved device (the OS is gated),-// so listing + approving the fleet here is the self-service path after the-// bootstrap device. Backed by the host JSON store via /api/auth/devices.export function DevicesPanel() {const [devices, setDevices] = useState<Device[] | null>(null);- // Revoke is destructive (other browsers lose sign-in); confirm before firing.+ const [pendingRoles, setPendingRoles] = useState<Record<string, DeviceRole>>({});const [pendingRevoke, setPendingRevoke] = useState<Device | null>(null);const thisId = typeof window !== "undefined" ? getOrCreateDeviceId() : "";- // Pure fetch (no setState) so the mount effect can use the .then form- // (react-hooks/set-state-in-effect).const fetchDevices = useCallback(async (): Promise<Device[]> => {- try {- const r = await fetch("/api/auth/devices", { cache: "no-store" });- if (r.ok) return flatten((await r.json()) as DevicesResponse);- return [];- } catch {- return [];- }+ const response = await fetch("/api/auth/devices", { cache: "no-store" });+ if (!response.ok) throw new Error("Owner role is required to manage devices");+ return flatten((await response.json()) as DevicesResponse);}, []);const load = useCallback(async () => {- setDevices(await fetchDevices());+ try {+ setDevices(await fetchDevices());+ } catch (error) {+ toast(error instanceof Error ? error.message : "Couldn't load devices", { tone: "error" });+ setDevices([]);+ }}, [fetchDevices]);useEffect(() => {let alive = true;- fetchDevices().then((d) => alive && setDevices(d));- return () => {- alive = false;- };+ fetchDevices()+ .then((rows) => alive && setDevices(rows))+ .catch(() => alive && setDevices([]));+ return () => { alive = false; };}, [fetchDevices]);- const act = useCallback(async (action: "approve" | "revoke", deviceId: string) => {+ const act = useCallback(async (+ action: "approve" | "revoke" | "set_role",+ deviceId: string,+ role?: DeviceRole,+ ) => {try {- const r = await fetch("/api/auth/devices", {+ const response = await fetch("/api/auth/devices", {method: "POST",headers: { "content-type": "application/json" },- body: JSON.stringify({ action, deviceId }),+ body: JSON.stringify({ action, deviceId, role }),});- if (r.ok) setDevices(flatten((await r.json()) as DevicesResponse));- } catch {- /* keep current list; user can retry */+ const body = (await response.json().catch(() => ({}))) as DevicesResponse & { error?: string };+ if (!response.ok) throw new Error(body.error || "Device change failed");+ setDevices(flatten(body));+ toast(action === "approve" ? "Device approved" : action === "revoke" ? "Device revoked" : "Device role updated");+ } catch (error) {+ toast(error instanceof Error ? error.message : "Device change failed", { tone: "error" });+ await load();}- }, []);+ }, [load]);++ const ownerCount = useMemo(+ () => devices?.filter((device) => device.status === "approved" && device.role === "owner").length ?? 0,+ [devices],+ );- if (devices === null) {- return <p className="text-xs text-muted-foreground">Loading devices…</p>;- }- if (devices.length === 0) {- return <p className="text-xs text-muted-foreground">No devices registered.</p>;- }+ if (devices === null) return <p className="text-xs text-muted-foreground">Loading devices…</p>;+ if (devices.length === 0) return <p className="text-xs text-muted-foreground">No devices registered.</p>;return (<>- <ul className="space-y-2">- {devices.map((d) => (- <li- key={d.deviceId}- className="flex items-center gap-3 rounded-lg border border-border bg-card/50 p-2.5"- >- <span className="grid size-8 shrink-0 place-items-center rounded-md bg-secondary text-muted-foreground">- {d.status === "approved" ? <ShieldCheck className="size-4" /> : <Clock className="size-4" />}- </span>- <div className="min-w-0 flex-1">- <p className="flex items-center gap-2 truncate text-sm font-medium">- {d.label}- {d.deviceId === thisId && <Badge variant="outline">This device</Badge>}- </p>- {/* Masked — a full ID on screen is a shoulder-surf/screenshot leak.- Click copies the full ID for CLI approval flows. */}- <span className="truncate font-mono text-[11px] text-muted-foreground">…{d.deviceId.slice(-6)}</span>- {/* history={false}: the ID is masked above on purpose, so filing the full- value into the persisted clipboard panel would undo that. */}- <CopyButton value={d.deviceId} label="full device ID" history={false} />- </div>- {d.status === "pending" ? (- <Button size="sm" onClick={() => void act("approve", d.deviceId)}>- <Check className="size-3.5" /> Approve- </Button>- ) : (- <Badge>approved</Badge>- )}- {d.deviceId !== thisId && (- <Button- size="icon"- variant="ghost"- aria-label="Revoke device"- onClick={() => setPendingRevoke(d)}- >- <Trash2 className="size-4 text-destructive" />- </Button>- )}- </li>- ))}- </ul>+ <div className="mb-3 rounded-lg border border-border/70 bg-muted/35 p-3 text-xs leading-relaxed text-muted-foreground">+ <strong className="text-foreground">Viewer</strong> reads files and telemetry. <strong className="text-foreground">Operator</strong> also runs bounded service/app actions. <strong className="text-foreground">Owner</strong> can write files, open shells, change credentials, and manage access.+ </div>+ <ul className="space-y-2">+ {devices.map((device) => {+ const pendingRole = pendingRoles[device.deviceId] ?? "viewer";+ const cannotDemoteLastOwner = device.role === "owner" && ownerCount <= 1;+ return (+ <li key={device.deviceId} className="flex flex-wrap items-center gap-3 rounded-lg border border-border bg-card/50 p-2.5">+ <span className="grid size-8 shrink-0 place-items-center rounded-md bg-secondary text-muted-foreground">+ {device.status === "approved" ? <ShieldCheck className="size-4" /> : <Clock className="size-4" />}+ </span>+ <div className="min-w-[9rem] flex-1">+ <p className="flex items-center gap-2 truncate text-sm font-medium">+ {device.label}+ {device.deviceId === thisId && <Badge variant="outline">This device</Badge>}+ </p>+ <span className="truncate font-mono text-[11px] text-muted-foreground">…{device.deviceId.slice(-6)}</span>+ <CopyButton value={device.deviceId} label="full device ID" history={false} />+ </div>- <FormDrawer- open={pendingRevoke !== null}- onOpenChange={(open) => !open && setPendingRevoke(null)}- size="sm"- >+ {device.status === "pending" ? (+ <div className="flex items-center gap-2">+ <RoleSelect+ value={pendingRole}+ onChange={(role) => setPendingRoles((current) => ({ ...current, [device.deviceId]: role }))}+ />+ <Button size="sm" onClick={() => void act("approve", device.deviceId, pendingRole)}>+ <Check className="size-3.5" /> Approve+ </Button>+ </div>+ ) : device.deviceId === thisId ? (+ <Badge>{roleLabel(device.role ?? "owner")}</Badge>+ ) : (+ <RoleSelect+ value={device.role ?? "owner"}+ disabled={cannotDemoteLastOwner}+ title={cannotDemoteLastOwner ? "Approve another owner before changing this role" : undefined}+ onChange={(role) => void act("set_role", device.deviceId, role)}+ />+ )}++ {device.deviceId !== thisId && (+ <Button size="icon" variant="ghost" aria-label="Revoke device" onClick={() => setPendingRevoke(device)}>+ <Trash2 className="size-4 text-destructive" />+ </Button>+ )}+ </li>+ );+ })}+ </ul>++ <FormDrawer open={pendingRevoke !== null} onOpenChange={(open) => !open && setPendingRevoke(null)} size="sm"><FormDrawer.Header><FormDrawer.Title>{pendingRevoke ? `Revoke device "${pendingRevoke.label}"?` : "Revoke device?"}</FormDrawer.Title><FormDrawer.Description>- This device will need re-approval to sign in again. Existing sessions stay valid until they expire.+ New requests are rejected immediately. Any live Camoufox viewer is terminated; the device must be approved again before it can sign in.</FormDrawer.Description></FormDrawer.Header><FormDrawer.Footer>- <Button type="button" variant="ghost" onClick={() => setPendingRevoke(null)}>- Cancel- </Button>+ <Button type="button" variant="ghost" onClick={() => setPendingRevoke(null)}>Cancel</Button><Buttontype="button"variant="destructive"@@ -146,11 +165,35 @@ export function DevicesPanel() {setPendingRevoke(null);}}>- <Trash2 className="size-4" />- Revoke+ <Trash2 className="size-4" /> Revoke</Button></FormDrawer.Footer></FormDrawer></>);}++function RoleSelect({+ value,+ onChange,+ disabled,+ title,+}: {+ value: DeviceRole;+ onChange: (role: DeviceRole) => void;+ disabled?: boolean;+ title?: string;+}) {+ return (+ <select+ aria-label="Device role"+ value={value}+ disabled={disabled}+ title={title}+ onChange={(event) => onChange(event.target.value as DeviceRole)}+ className="min-h-9 rounded-md border border-input bg-background px-2 text-xs text-foreground disabled:cursor-not-allowed disabled:opacity-60"+ >+ {DEVICE_ROLES.map((role) => <option key={role} value={role}>{roleLabel(role)}</option>)}+ </select>+ );+}diff --git a/frontend/slices/auth/index.ts b/frontend/slices/auth/index.tsindex fc882117..116c3174 100644--- a/frontend/slices/auth/index.ts+++ b/frontend/slices/auth/index.ts@@ -4,3 +4,4 @@ export { openOnboarding } from "./components/auth-gate";export { LoginScreen, LoginCard } from "./components/login-screen";export { DevicesPanel } from "./components/devices-panel";export { SessionProvider, useSession, type SessionStatus } from "./lib/use-session";+export type { DeviceRole } from "@/lib/auth/roles";diff --git a/frontend/slices/auth/lib/use-session.tsx b/frontend/slices/auth/lib/use-session.tsxindex f93aa538..8e4c8bf3 100644--- a/frontend/slices/auth/lib/use-session.tsx+++ b/frontend/slices/auth/lib/use-session.tsx@@ -3,51 +3,54 @@import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from "react";import { AUTHED_EVENT } from "@/lib/prefs/use-prefs-sync";import { IS_DEMO } from "@/lib/demo";+import type { DeviceRole } from "@/lib/auth/roles";export type SessionStatus = "loading" | "out" | "in";-type SessionValue = {- status: SessionStatus;+type SessionSnapshot = { status: SessionStatus; role: DeviceRole | null };+type SessionValue = SessionSnapshot & {refresh: () => Promise<void>;signOut: () => Promise<void>;};-// ONE shared session probe for the whole app. The public shell, the OsApi-// mock↔live switch, and the Settings sign-in all read this single source of-// truth — so there's no double /api/auth/me and no mock→live flash on the-// owner's cold load. `refresh()` re-checks after login; `signOut()` clears it.const SessionContext = createContext<SessionValue>({status: "out",+ role: null,refresh: async () => {},signOut: async () => {},});-export function SessionProvider({ initialStatus, children }: { initialStatus?: SessionStatus; children: ReactNode }) {- // Server-injected status (app/[[...slug]]/page.tsx → OsRoot) is the first render- // on BOTH sides, so hydration matches and the shell paints with no Splash and no- // /api/auth/me round-trip. IS_DEMO is a build-inlined NEXT_PUBLIC var (identical- // server/client) → still forces "out". "loading" only applies to a prop-less- // mount (e.g. tests), which keeps the old probe path.- const [status, setStatus] = useState<SessionStatus>(IS_DEMO ? "out" : (initialStatus ?? "loading"));+export function SessionProvider({+ initialStatus,+ initialRole,+ children,+}: {+ initialStatus?: SessionStatus;+ initialRole?: DeviceRole | null;+ children: ReactNode;+}) {+ const [snapshot, setSnapshot] = useState<SessionSnapshot>(() => ({+ status: IS_DEMO ? "out" : (initialStatus ?? "loading"),+ role: IS_DEMO || initialStatus !== "in" ? null : (initialRole ?? "viewer"),+ }));- const probe = useCallback(async (): Promise<SessionStatus> => {- if (IS_DEMO) return "out"; // demo makes no /api calls+ const probe = useCallback(async (): Promise<SessionSnapshot> => {+ if (IS_DEMO) return { status: "out", role: null };try {- const r = await fetch("/api/auth/me", { cache: "no-store" });- const d = (await r.json()) as { authenticated?: boolean };- return d.authenticated ? "in" : "out";+ const response = await fetch("/api/auth/me", { cache: "no-store" });+ const body = (await response.json()) as { authenticated?: boolean; role?: DeviceRole | null };+ return body.authenticated+ ? { status: "in", role: body.role ?? "viewer" }+ : { status: "out", role: null };} catch {- return "out";+ return { status: "out", role: null };}}, []);const refresh = useCallback(async () => {- const s = await probe();- setStatus(s);- // Providers mounted above the shell (appearance/quicklinks) 401'd their- // initial GET /api/prefs while signed out; announce the login so prefs-sync- // re-pulls with the fresh cookie.- if (s === "in") window.dispatchEvent(new Event(AUTHED_EVENT));+ const next = await probe();+ setSnapshot(next);+ if (next.status === "in") window.dispatchEvent(new Event(AUTHED_EVENT));}, [probe]);const signOut = useCallback(async () => {@@ -56,20 +59,38 @@ export function SessionProvider({ initialStatus, children }: { initialStatus?: S} catch {/* best-effort — clear locally regardless */}- setStatus("out");+ setSnapshot({ status: "out", role: null });}, []);+ useEffect(() => {+ if (IS_DEMO || initialStatus !== undefined) return;+ let alive = true;+ probe().then((next) => alive && setSnapshot(next));+ return () => { alive = false; };+ }, [probe, initialStatus]);+useEffect(() => {if (IS_DEMO) return;- if (initialStatus !== undefined) return; // server already resolved it — no cold-load probelet alive = true;- probe().then((s) => alive && setStatus(s));+ const sync = () => {+ if (document.visibilityState !== "visible") return;+ probe().then((next) => { if (alive) setSnapshot(next); });+ };+ const timer = window.setInterval(sync, 60_000);+ window.addEventListener("focus", sync);+ document.addEventListener("visibilitychange", sync);return () => {alive = false;+ window.clearInterval(timer);+ window.removeEventListener("focus", sync);+ document.removeEventListener("visibilitychange", sync);};- }, [probe, initialStatus]);+ }, [probe]);- const value = useMemo(() => ({ status, refresh, signOut }), [status, refresh, signOut]);+ const value = useMemo(+ () => ({ ...snapshot, refresh, signOut }),+ [snapshot, refresh, signOut],+ );return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;}diff --git a/frontend/slices/docs/docs.test.ts b/frontend/slices/docs/docs.test.tsindex d3d0ceb3..bbede783 100644--- a/frontend/slices/docs/docs.test.ts+++ b/frontend/slices/docs/docs.test.ts@@ -18,7 +18,7 @@ describe("docs app", () => {it("is promoted while signed out, so the menu matches the state", () => {const osRoot = read("../../../app/os-root.tsx");expect(osRoot).toContain('status === "out"');- expect(osRoot).toContain('a.id === "docs"');+ expect(osRoot).toContain('app.id === "docs"');});it("leads with the install guide this instance serves itself", () => {diff --git a/frontend/slices/os-settings/components/sections.tsx b/frontend/slices/os-settings/components/sections.tsxindex cb8a747c..d67c8582 100644--- a/frontend/slices/os-settings/components/sections.tsx+++ b/frontend/slices/os-settings/components/sections.tsx@@ -3,7 +3,7 @@import { Lock, ShieldCheck } from "lucide-react";import { ScrollArea } from "@/components/ui/scroll-area";import { cn } from "@/lib/utils";-import { DevicesPanel } from "@/features/auth";+import { DevicesPanel, useSession } from "@/features/auth";import { useActiveShell } from "@/features/os-shell";import { SettingsSection } from "@/features/shell-settings";import { SECTIONS, type SectionId } from "../lib/sections";@@ -22,7 +22,20 @@ import { AboutSection } from "./about-section";// The section content — one functional panel per SectionId, shared verbatim by// every shell's Settings layout (the per-shell seam only swaps the navigation// chrome around these, never the bodies).+const OWNER_ONLY = new Set<SectionId>(["appearance", "theme", "ai", "quicklinks", "mcp", "devices", "cleanup", "backup"]);+export function SettingsSectionBody({ id }: { id: SectionId }) {+ const { status, role } = useSession();+ if (status === "in" && role !== "owner" && OWNER_ONLY.has(id)) {+ return (+ <SettingsSection icon={<Lock />} title="Owner access required">+ <p className="text-sm leading-relaxed text-muted-foreground">+ This section changes shared workspace preferences, credentials, host state, access policy, or owner backups.+ The current <strong className="text-foreground">{role ?? "viewer"}</strong> device can use read-only workspace features but cannot open this control surface.+ </p>+ </SettingsSection>+ );+ }switch (id) {case "appearance":return <AppearanceSection />;diff --git a/frontend/slices/system-monitor/app.tsx b/frontend/slices/system-monitor/app.tsxindex 6fcb6ea1..34e8829e 100644--- a/frontend/slices/system-monitor/app.tsx+++ b/frontend/slices/system-monitor/app.tsx@@ -1,119 +1,88 @@"use client";+import { useState } from "react";import { Activity, AlertCircle, Loader2, RotateCw } from "lucide-react";import { Button } from "@/components/ui/button";-import {- usePublishInspector,- useOsApi,- useResponsive,- ResponsiveToolbar,- type ToolbarItem,-} from "./lib/host";+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { usePublishInspector, useOsApi, useResponsive, ResponsiveToolbar, type ToolbarItem } from "./lib/host";import { AppFrame } from "./components/host-frame";import { GaugeGrid } from "./components/gauge-grid";import { GlassPanel } from "./components/glass-panel";import { Sparkline } from "./components/sparkline";import { ProcessTable } from "./components/process-table";+import { ServicesPanel } from "./components/services-panel";+import { PackageUpdatesPanel } from "./components/package-updates-panel";import { useStatsHistory } from "./lib/use-stats-history";import { MONITOR_VARS, type MonitorVar } from "./lib/palette";import { fmtGiBPair, fmtMBs, fmtPct } from "./lib/format";-// Default export so os-shell can lazy-load it as a window app.+type MonitorTab = "overview" | "services" | "updates";+export default function SystemMonitor() {const api = useOsApi();const { isMobile } = useResponsive();- // Mobile shell navigation owns the feature title on both iOS and Android.- const { stats, procs, cpuSeries, netSeries, gpu, error, refresh } = useStatsHistory();-- usePublishInspector(- "system-monitor",- {- subject: "VPS host",- props: [- { label: "CPU", value: stats ? fmtPct(stats.cpu.pct) : "—" },- { label: "Memory", value: stats ? fmtGiBPair(stats.mem.used, stats.mem.total) : "—" },- { label: "Disk", value: stats ? fmtGiBPair(stats.disk.used, stats.disk.total) : "—" },- { label: "Processes", value: String(procs.length) },- { label: "Mode", value: api.mode },- ],- actions: [{ id: "refresh", label: "Refresh", run: refresh }],- context: stats- ? `System monitor: cpu ${fmtPct(stats.cpu.pct)}, mem ${fmtGiBPair(stats.mem.used, stats.mem.total)} (${api.mode})`- : "System monitor: reading host telemetry…",- suggestions: ["Why is CPU high?", "What's using memory?", "Recommend cleanup"],- },- [stats, procs.length, api.mode, refresh],- );-- // Error path: telemetry never landed AND the poll keeps failing — surface a- // retry tile so the user can act instead of staring at a frozen spinner.- if (!stats && error) {- return (- <div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center">- <AlertCircle className="size-6 text-destructive" />- <div className="space-y-1">- <p className="text-sm font-medium text-foreground">Couldn't load stats</p>- <p className="max-w-xs text-xs text-muted-foreground">{error}</p>- </div>- <Button variant="outline" size="sm" onClick={refresh} className="gap-1.5">- <RotateCw className="size-3.5" /> Retry- </Button>- </div>- );- }+ const [tab, setTab] = useState<MonitorTab>("overview");+ const { stats, procs, cpuSeries, netSeries, gpu, error, refresh } = useStatsHistory(tab === "overview");- if (!stats) {- return (- <div className="flex h-full items-center justify-center gap-2 text-xs text-[color:var(--text-faint)]">- <Loader2 className="size-4 animate-spin" /> Reading host telemetry…- </div>- );- }+ usePublishInspector("system-monitor", {+ subject: tab === "overview" ? "VPS host" : tab === "services" ? "systemd services" : "package updates",+ props: [+ { label: "View", value: tab },+ { label: "Role", value: api.access.role },+ { label: "CPU", value: stats ? fmtPct(stats.cpu.pct) : "—" },+ { label: "Memory", value: stats ? fmtGiBPair(stats.mem.used, stats.mem.total) : "—" },+ { label: "Processes", value: String(procs.length) },+ { label: "Mode", value: api.mode },+ ],+ actions: tab === "overview" ? [{ id: "refresh", label: "Refresh", run: refresh }] : [],+ context: `System Monitor ${tab}; role=${api.access.role}; mode=${api.mode}`,+ suggestions: tab === "overview" ? ["Why is CPU high?", "What's using memory?"] : tab === "services" ? ["Which service is failing?"] : ["Summarize cached updates"],+ }, [tab, stats, procs.length, api.mode, api.access.role, refresh]);- const lastNet = netSeries[netSeries.length - 1] ?? 0;- // Toolbar actions live as data; ResponsiveToolbar collapses non-primary items- // into a ⋯ menu on compact form factors. Refresh stays primary (always inline).- const toolbarItems: ToolbarItem[] = [- { id: "refresh", label: "Refresh", icon: RotateCw, onClick: refresh, primary: true },- ];- const chipLabel = isMobile- ? `${stats.cpu.cores}c`- : `${stats.cpu.cores} cores · ${api.mode}`;+ const toolbarItems: ToolbarItem[] = tab === "overview"+ ? [{ id: "refresh", label: "Refresh", icon: RotateCw, onClick: refresh, primary: true }]+ : [];+ const chipLabel = isMobile ? api.access.role : `${api.mode} · ${api.access.role}`;return (- <AppFrame- header={- <header className="flex items-center justify-between gap-2 px-3 py-2">- <div className="flex min-w-0 items-center gap-2">- {!isMobile && <Activity className="size-4 shrink-0 text-primary" />}- {!isMobile && <h2 className="truncate text-sm font-semibold">System Monitor</h2>}- <span className="shrink-0 rounded-full bg-[color:var(--inset)] px-2 py-0.5 font-mono text-[10px] text-[color:var(--text-dim)]">- {chipLabel}- </span>- </div>- <ResponsiveToolbar items={toolbarItems} />- </header>- }- >- <div- className="space-y-3.5 p-4"- style={MONITOR_VARS as React.CSSProperties}- >- <GaugeGrid stats={stats} gpu={gpu} />-- <div className="grid grid-cols-2 gap-3 @max-[440px]:grid-cols-1">- <GlassPanel title="CPU load" right={fmtPct(stats.cpu.pct)}>- <Sparkline data={cpuSeries} accent={"--mon-cpu" as MonitorVar} max={100} />- </GlassPanel>- <GlassPanel title="Network" right={fmtMBs(lastNet)}>- <Sparkline data={netSeries} accent={"--mon-net" as MonitorVar} />- </GlassPanel>+ <AppFrame header={+ <header className="flex flex-wrap items-center justify-between gap-2 px-3 py-2">+ <div className="flex min-w-0 items-center gap-2">+ {!isMobile && <Activity className="size-4 shrink-0 text-primary" />}+ {!isMobile && <h2 className="truncate text-sm font-semibold">System Monitor</h2>}+ <span className="shrink-0 rounded-full bg-[color:var(--inset)] px-2 py-0.5 font-mono text-[10px] text-[color:var(--text-dim)]">{chipLabel}</span>+ </div>+ <div className="flex min-w-0 flex-1 items-center justify-end gap-2">+ <Tabs className="min-w-0">+ <TabsList className="max-w-full overflow-x-auto">+ {(["overview", "services", "updates"] as const).map((value) => (+ <TabsTrigger key={value} active={tab === value} onClick={() => setTab(value)} className="capitalize">{value}</TabsTrigger>+ ))}+ </TabsList>+ </Tabs>+ {toolbarItems.length > 0 && <ResponsiveToolbar items={toolbarItems} />}</div>+ </header>+ }>+ {tab === "overview" ? <Overview stats={stats} procs={procs} cpuSeries={cpuSeries} netSeries={netSeries} gpu={gpu} error={error} refresh={refresh} /> : null}+ {tab === "services" ? <ServicesPanel /> : null}+ {tab === "updates" ? <PackageUpdatesPanel /> : null}+ </AppFrame>+ );+}- <GlassPanel title="Processes">- <ProcessTable processes={procs} />- </GlassPanel>+function Overview({ stats, procs, cpuSeries, netSeries, gpu, error, refresh }: ReturnType<typeof useStatsHistory>) {+ if (!stats && error) return <div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center"><AlertCircle className="size-6 text-destructive" /><p className="max-w-xs text-xs text-muted-foreground">{error}</p><Button variant="outline" size="sm" onClick={refresh}><RotateCw className="size-3.5" /> Retry</Button></div>;+ if (!stats) return <div className="flex h-full items-center justify-center gap-2 text-xs text-[color:var(--text-faint)]"><Loader2 className="size-4 animate-spin" /> Reading host telemetry…</div>;+ const lastNet = netSeries[netSeries.length - 1] ?? 0;+ return (+ <div className="space-y-3.5 p-4" style={MONITOR_VARS as React.CSSProperties}>+ <GaugeGrid stats={stats} gpu={gpu} />+ <div className="grid grid-cols-2 gap-3 @max-[440px]:grid-cols-1">+ <GlassPanel title="CPU load" right={fmtPct(stats.cpu.pct)}><Sparkline data={cpuSeries} accent={"--mon-cpu" as MonitorVar} max={100} /></GlassPanel>+ <GlassPanel title="Network" right={fmtMBs(lastNet)}><Sparkline data={netSeries} accent={"--mon-net" as MonitorVar} /></GlassPanel></div>- </AppFrame>+ <GlassPanel title="Processes"><ProcessTable processes={procs} /></GlassPanel>+ </div>);}diff --git a/frontend/slices/system-monitor/components/package-updates-panel.tsx b/frontend/slices/system-monitor/components/package-updates-panel.tsxnew file mode 100644index 00000000..63bab12a--- /dev/null+++ b/frontend/slices/system-monitor/components/package-updates-panel.tsx@@ -0,0 +1,72 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { AlertCircle, Loader2, PackageSearch, RotateCw, Search } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Badge } from "@/components/ui/badge";+import { useOsApi, type PackageUpdateSummary } from "../lib/host";++export function PackageUpdatesPanel() {+ const api = useOsApi();+ const [summary, setSummary] = useState<PackageUpdateSummary | null>(null);+ const [query, setQuery] = useState("");+ const [error, setError] = useState<string | null>(null);++ const load = useCallback(async () => {+ try {+ setError(null);+ setSummary(await api.sys.packageUpdates());+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ }+ }, [api]);+ useEffect(() => {+ let alive = true;+ api.sys.packageUpdates()+ .then((value) => { if (alive) setSummary(value); })+ .catch((cause) => { if (alive) setError(cause instanceof Error ? cause.message : String(cause)); });+ return () => { alive = false; };+ }, [api]);++ const rows = useMemo(() => {+ const needle = query.trim().toLowerCase();+ return (summary?.updates ?? []).filter((item) => !needle || `${item.name} ${item.current ?? ""} ${item.candidate}`.toLowerCase().includes(needle));+ }, [summary, query]);++ if (!summary && !error) return <div className="flex h-full items-center justify-center gap-2 p-8 text-xs text-muted-foreground"><Loader2 className="size-4 animate-spin" />Reading local package cache…</div>;+ if (error) return <div className="flex h-full flex-col items-center justify-center gap-3 p-8 text-center"><AlertCircle className="size-6 text-destructive" /><p className="text-xs text-muted-foreground">{error}</p><Button size="sm" variant="outline" onClick={() => void load()}>Retry</Button></div>;++ return (+ <div className="space-y-3.5 p-4">+ <div className="rounded-lg border border-border bg-muted/35 p-3 text-xs leading-relaxed text-muted-foreground">+ Visibility only. MSO reads the package manager's existing local cache and never runs refresh, install, or upgrade from this panel.+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <div className="relative min-w-[12rem] flex-1">+ <Search className="pointer-events-none absolute left-2.5 top-2 size-4 text-muted-foreground" />+ <Input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search package updates" className="pl-8" />+ </div>+ <Button size="sm" variant="outline" onClick={() => void load()}><RotateCw className="size-3.5" /> Check cache</Button>+ </div>+ <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">+ <PackageSearch className="size-4" />+ <strong className="text-foreground">{summary?.updates.length ?? 0}</strong> updates+ <Badge variant="outline">{summary?.manager ?? "unsupported"}</Badge>+ <Badge variant="outline">local cache</Badge>+ </div>+ {summary?.diagnostic && <p className="rounded-lg border border-destructive/30 bg-destructive/5 p-2.5 text-xs text-destructive">{summary.diagnostic}</p>}+ <div className="divide-y divide-border overflow-hidden rounded-xl border border-border bg-card/45">+ {rows.map((item) => (+ <div key={`${item.name}:${item.architecture ?? ""}`} className="grid gap-1 p-3 text-xs sm:grid-cols-[minmax(8rem,1fr)_minmax(9rem,auto)_auto] sm:items-center">+ <div className="min-w-0"><p className="truncate font-mono font-semibold text-foreground">{item.name}</p>{item.architecture && <p className="text-[10px] text-muted-foreground">{item.architecture}</p>}</div>+ <p className="break-all font-mono text-[11px] text-muted-foreground">{item.current || "installed version unavailable"} → <span className="text-foreground">{item.candidate}</span></p>+ <Badge variant="secondary">available</Badge>+ </div>+ ))}+ {!rows.length && <p className="p-8 text-center text-xs text-muted-foreground">{summary?.available ? "No matching cached updates." : "Package cache is unavailable."}</p>}+ </div>+ {summary?.truncated && <p className="text-xs text-muted-foreground">Result capped for safety. Narrow the search or use the owner terminal for a full listing.</p>}+ </div>+ );+}diff --git a/frontend/slices/system-monitor/components/services-panel.tsx b/frontend/slices/system-monitor/components/services-panel.tsxnew file mode 100644index 00000000..eecbb6d4--- /dev/null+++ b/frontend/slices/system-monitor/components/services-panel.tsx@@ -0,0 +1,174 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { AlertCircle, FileText, Loader2, Play, RotateCw, Search, Square } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Badge } from "@/components/ui/badge";+import { FormDrawer, toast } from "@/features/os-shell";+import { GlassPanel } from "./glass-panel";+import { useOsApi, type ServiceAction, type ServiceInventory, type ServiceLogs, type SystemService } from "../lib/host";++export function ServicesPanel() {+ const api = useOsApi();+ const [inventory, setInventory] = useState<ServiceInventory | null>(null);+ const [query, setQuery] = useState("");+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState<string | null>(null);+ const [logs, setLogs] = useState<ServiceLogs | null>(null);+ const [pending, setPending] = useState<{ service: SystemService; action: ServiceAction } | null>(null);++ const load = useCallback(async () => {+ try {+ setError(null);+ setInventory(await api.sys.services());+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ }+ }, [api]);++ useEffect(() => {+ let alive = true;+ api.sys.services()+ .then((value) => { if (alive) setInventory(value); })+ .catch((cause) => { if (alive) setError(cause instanceof Error ? cause.message : String(cause)); });+ return () => { alive = false; };+ }, [api]);++ const rows = useMemo(() => {+ const needle = query.trim().toLowerCase();+ if (!needle) return inventory?.services ?? [];+ return (inventory?.services ?? []).filter((service) =>+ `${service.unit} ${service.description} ${service.scope} ${service.active} ${service.sub}`.toLowerCase().includes(needle),+ );+ }, [inventory, query]);++ const power = useCallback(async (service: SystemService, action: ServiceAction) => {+ const key = `${service.scope}:${service.unit}`;+ setBusy(key);+ try {+ await api.sys.servicePower(service.scope, service.unit, action);+ toast(`${service.unit}: ${action} completed`);+ await load();+ } catch (cause) {+ toast(cause instanceof Error ? cause.message : "Service action failed", { tone: "error" });+ } finally {+ setBusy(null);+ }+ }, [api, load]);++ const readLogs = useCallback(async (service: SystemService) => {+ setBusy(`logs:${service.scope}:${service.unit}`);+ try {+ setLogs(await api.sys.serviceLogs(service.scope, service.unit, 160));+ } catch (cause) {+ toast(cause instanceof Error ? cause.message : "Couldn't read service logs", { tone: "error" });+ } finally {+ setBusy(null);+ }+ }, [api]);++ if (!inventory && !error) {+ return <Loading label="Reading systemd inventory…" />;+ }+ if (error) {+ return <Failure message={error} retry={load} />;+ }++ return (+ <div className="space-y-3.5 p-4">+ <div className="flex flex-wrap items-center gap-2">+ <div className="relative min-w-[12rem] flex-1">+ <Search className="pointer-events-none absolute left-2.5 top-2 size-4 text-muted-foreground" />+ <Input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search services" className="pl-8" />+ </div>+ <Button size="sm" variant="outline" onClick={() => void load()}><RotateCw className="size-3.5" /> Refresh</Button>+ </div>++ {!inventory?.controlAllowlistConfigured && (+ <div className="rounded-lg border border-border bg-muted/35 p-3 text-xs leading-relaxed text-muted-foreground">+ Inventory is read-only. An owner can enable exact units with <code>OS_SERVICE_CONTROL_UNITS=user:mso.service,system:nginx.service</code>. Wildcards are rejected.+ </div>+ )}+ {api.mode === "live" && !api.access.canOperate && (+ <div className="rounded-lg border border-border bg-muted/35 p-3 text-xs text-muted-foreground">+ Current role: <strong className="text-foreground">{api.access.role}</strong>. Service logs and allowlisted lifecycle actions require Operator or Owner.+ </div>+ )}+ {inventory?.diagnostics.map((diagnostic) => (+ <p key={diagnostic} className="rounded-lg border border-destructive/30 bg-destructive/5 p-2.5 text-xs text-destructive">{diagnostic}</p>+ ))}++ <div className="space-y-2">+ {rows.map((service) => {+ const key = `${service.scope}:${service.unit}`;+ const running = service.active === "active";+ const canOperate = service.controllable && api.access.canOperate;+ return (+ <div key={key} className="rounded-xl border border-[color:var(--sep)] bg-[color:var(--glass-panel)] p-3">+ <div className="flex flex-wrap items-start gap-3">+ <span className={`mt-1 size-2.5 shrink-0 rounded-full ${running ? "bg-emerald-500" : service.active === "failed" ? "bg-destructive" : "bg-muted-foreground/45"}`} />+ <div className="min-w-[11rem] flex-1">+ <p className="break-all font-mono text-xs font-semibold text-foreground">{service.unit}</p>+ <p className="mt-1 line-clamp-2 text-xs text-muted-foreground">{service.description || "No description"}</p>+ <div className="mt-2 flex flex-wrap gap-1.5">+ <Badge variant="outline">{service.scope}</Badge>+ <Badge variant={running ? "default" : "secondary"}>{service.active}/{service.sub}</Badge>+ {service.controllable && <Badge variant="outline">allowlisted</Badge>}+ </div>+ </div>+ <div className="flex flex-wrap items-center justify-end gap-1.5">+ {api.access.canOperate && (+ <Button size="sm" variant="ghost" disabled={busy !== null} onClick={() => void readLogs(service)}>+ {busy === `logs:${key}` ? <Loader2 className="size-3.5 animate-spin" /> : <FileText className="size-3.5" />} Logs+ </Button>+ )}+ {canOperate && !running && (+ <Button size="sm" disabled={busy === key} onClick={() => void power(service, "start")}><Play className="size-3.5" /> Start</Button>+ )}+ {canOperate && running && (+ <>+ <Button size="sm" variant="outline" disabled={busy === key} onClick={() => setPending({ service, action: "restart" })}><RotateCw className="size-3.5" /> Restart</Button>+ <Button size="sm" variant="destructive" disabled={busy === key} onClick={() => setPending({ service, action: "stop" })}><Square className="size-3.5" /> Stop</Button>+ </>+ )}+ </div>+ </div>+ </div>+ );+ })}+ {!rows.length && <p className="py-8 text-center text-xs text-muted-foreground">No matching services.</p>}+ </div>++ {logs && (+ <GlassPanel title={`${logs.scope}:${logs.unit}`} right={logs.available ? `${logs.entries.length} lines` : "unavailable"}>+ {logs.available ? (+ <pre className="max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-lg bg-background/60 p-3 font-mono text-[11px] leading-relaxed text-foreground">{logs.entries.join("\n") || "No journal entries."}</pre>+ ) : <p className="text-xs text-destructive">{logs.diagnostic || "Journal unavailable"}</p>}+ </GlassPanel>+ )}++ <FormDrawer open={pending !== null} onOpenChange={(open) => !open && setPending(null)} size="sm">+ <FormDrawer.Header>+ <FormDrawer.Title>{pending ? `${pending.action} ${pending.service.unit}?` : "Service action"}</FormDrawer.Title>+ <FormDrawer.Description>This exact unit is owner-allowlisted. The action is audited and runs without a shell.</FormDrawer.Description>+ </FormDrawer.Header>+ <FormDrawer.Footer>+ <Button variant="ghost" onClick={() => setPending(null)}>Cancel</Button>+ <Button variant={pending?.action === "stop" ? "destructive" : "default"} onClick={() => {+ if (pending) void power(pending.service, pending.action);+ setPending(null);+ }}>{pending?.action || "Confirm"}</Button>+ </FormDrawer.Footer>+ </FormDrawer>+ </div>+ );+}++function Loading({ label }: { label: string }) {+ return <div className="flex h-full items-center justify-center gap-2 p-8 text-xs text-muted-foreground"><Loader2 className="size-4 animate-spin" />{label}</div>;+}++function Failure({ message, retry }: { message: string; retry: () => Promise<void> }) {+ return <div className="flex h-full flex-col items-center justify-center gap-3 p-8 text-center"><AlertCircle className="size-6 text-destructive" /><p className="text-xs text-muted-foreground">{message}</p><Button size="sm" variant="outline" onClick={() => void retry()}>Retry</Button></div>;+}diff --git a/frontend/slices/system-monitor/lib/host.ts b/frontend/slices/system-monitor/lib/host.tsindex df0e8f64..5f7a1d99 100644--- a/frontend/slices/system-monitor/lib/host.ts+++ b/frontend/slices/system-monitor/lib/host.ts@@ -7,7 +7,18 @@export type { AppDescriptor } from "@/features/os-shell";export { usePublishInspector } from "@/features/os-shell";-export { useOsApi, type SysStats, type Process } from "@/features/os-shell";+export {+ useOsApi,+ type SysStats,+ type Process,+ type HostAccess,+ type ServiceScope,+ type ServiceAction,+ type SystemService,+ type ServiceInventory,+ type ServiceLogs,+ type PackageUpdateSummary,+} from "@/features/os-shell";export { useResponsive, ResponsiveToolbar } from "@/features/os-shell";export type { ToolbarItem } from "@/features/os-shell";export { useActiveShell } from "@/features/os-shell";diff --git a/frontend/slices/system-monitor/lib/use-stats-history.ts b/frontend/slices/system-monitor/lib/use-stats-history.tsindex 7ae8874d..afe2f324 100644--- a/frontend/slices/system-monitor/lib/use-stats-history.ts+++ b/frontend/slices/system-monitor/lib/use-stats-history.ts@@ -22,7 +22,7 @@ export type StatsHistory = {// Polls sys.stats on an interval, accumulating a ~40-point rolling history for// the CPU + network sparklines, plus a local GPU mock walk (GPU isn't in the// contract). Refs avoid re-subscribing the interval on every tick.-export function useStatsHistory(): StatsHistory {+export function useStatsHistory(enabled = true): StatsHistory {const api = useOsApi();const [stats, setStats] = useState<SysStats | null>(null);const [procs, setProcs] = useState<Process[]>([]);@@ -61,6 +61,7 @@ export function useStatsHistory(): StatsHistory {useEffect(() => {aliveRef.current = true;+ if (!enabled) return () => { aliveRef.current = false; };// Poll only while the tab is visible. Minimizing the window unmounts this, but// BACKGROUNDING the tab does not — and hydrateBoot restores the window on reload,// so an untended cockpit otherwise fires 80 authenticated requests/min at its own@@ -80,7 +81,7 @@ export function useStatsHistory(): StatsHistory {clearInterval(iv);document.removeEventListener("visibilitychange", onVis);};- }, [pull]);+ }, [pull, enabled]);return { stats, procs, cpuSeries, netSeries, gpu, error, refresh: pull };}diff --git a/lib/agent/server-role.test.ts b/lib/agent/server-role.test.tsnew file mode 100644index 00000000..875baf66--- /dev/null+++ b/lib/agent/server-role.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";+import { requiredRoleForRequest } from "./server";++const req = (method: string, path: string) => new Request(`https://mso.example${path}`, { method });++describe("host API role policy", () => {+ it("allows only explicit viewer reads and fails every unknown route up to owner", () => {+ for (const path of [+ "/api/v1/fs/list",+ "/api/v1/apps",+ "/api/v1/stock/search",+ "/api/v1/sys/stats",+ "/api/v1/sys/processes",+ "/api/v1/temp-share/abc",+ ]) expect(requiredRoleForRequest(req("GET", path)), path).toBe("viewer");+ expect(requiredRoleForRequest(req("GET", "/api/v1/future-feature"))).toBe("owner");+ expect(requiredRoleForRequest(req("GET", "/api/v1/sys/stats-private"))).toBe("owner");+ expect(requiredRoleForRequest(req("GET", "/api/v1/sys/services-private"))).toBe("owner");+ expect(requiredRoleForRequest(req("POST", "/api/v1/future-feature"))).toBe("owner");+ expect(requiredRoleForRequest(req("DELETE", "/api/v1/fs/delete"))).toBe("owner");+ });++ it("keeps shells, audit, cleanup and self-update owner-only on every verb", () => {+ for (const path of [+ "/api/v1/exec/run",+ "/api/v1/editor/exec",+ "/api/v1/term/stream",+ "/api/v1/sys/audit",+ "/api/v1/sys/cleanup",+ "/api/v1/sys/update",+ ]) expect(requiredRoleForRequest(req("GET", path))).toBe("owner");+ });++ it("gives operators only the bounded operational surfaces", () => {+ expect(requiredRoleForRequest(req("GET", "/api/v1/camoufox/service"))).toBe("operator");+ expect(requiredRoleForRequest(req("POST", "/api/v1/managed-apps/openclaw"))).toBe("operator");+ expect(requiredRoleForRequest(req("GET", "/api/v1/managed-apps/openclaw/logs"))).toBe("operator");+ expect(requiredRoleForRequest(req("GET", `/api/v1/managed-apps/openclaw/jobs/${"a".repeat(24)}`))).toBe("operator");+ expect(requiredRoleForRequest(req("DELETE", `/api/v1/managed-apps/openclaw/jobs/${"a".repeat(24)}`))).toBe("owner");+ expect(requiredRoleForRequest(req("DELETE", "/api/v1/managed-apps/openclaw/jobs/not-a-job-id"))).toBe("operator");+ expect(requiredRoleForRequest(req("POST", "/api/v1/managed-apps/openclaw/update"))).toBe("owner");+ expect(requiredRoleForRequest(req("POST", "/api/v1/managed-apps/openclaw/install"))).toBe("owner");+ });++ it("treats service inventory and package visibility as reads, actions/logs as operator", () => {+ expect(requiredRoleForRequest(req("GET", "/api/v1/sys/services"))).toBe("viewer");+ expect(requiredRoleForRequest(req("POST", "/api/v1/sys/services"))).toBe("operator");+ expect(requiredRoleForRequest(req("GET", "/api/v1/sys/services/logs"))).toBe("operator");+ expect(requiredRoleForRequest(req("GET", "/api/v1/sys/packages"))).toBe("viewer");+ });+});diff --git a/lib/agent/server.ts b/lib/agent/server.tsindex 76ff2b67..ded86352 100644--- a/lib/agent/server.ts+++ b/lib/agent/server.ts@@ -1,14 +1,68 @@-// SERVER-ONLY. Session gate for /api/v1 routes. Host fs/exec/sys are handled-// locally in @/lib/host (mso runs on the host). The former headless-browser-// bridge (OS_BROWSER_URL + OS_AGENT_TOKEN) was retired with the os-browser-// service — the Browser app renders pages in a client-side iframe now.+// SERVER-ONLY. Session + live device-role gate for /api/v1 routes. Host fs/exec/sys+// are handled locally in @/lib/host (mso runs on the host).import { requireSession } from "@/lib/auth/require-session";+import type { DeviceRole } from "@/lib/auth/roles";import { IS_DEMO } from "@/lib/demo";-// Cookie-only auth. Used by every /api/v1 route (fs, exec, term, sys, editor,-// apps, stock).-export async function verifyAuth(req?: Request): Promise<boolean> {- void req; // kept for call-site symmetry+const READ_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);+const VIEWER_READ_PATHS = new Set([+ "/api/v1/apps",+ "/api/v1/sys/stats",+ "/api/v1/sys/processes",+]);+const VIEWER_READ_PREFIXES = [+ "/api/v1/fs/",+ "/api/v1/stock/",+ "/api/v1/temp-share/",+];+const OWNER_PREFIXES = [+ "/api/v1/exec/",+ "/api/v1/editor/",+ "/api/v1/term/",+ "/api/v1/sys/audit",+ "/api/v1/sys/cleanup",+ "/api/v1/sys/update",+];++/**+ * Default-deny policy for the host API.+ *+ * - Viewer reads are explicit. A newly-added GET cannot silently expose host data.+ * - Every unclassified route requires owner. A new POST cannot become an operator+ * action just because its author forgot to add a policy row.+ * - Operator exceptions are narrow product surfaces with their own allowlists or+ * bounded lifecycle contracts.+ */+export function requiredRoleForRequest(req?: Request): DeviceRole {+ if (!req) return "viewer";+ let pathname = "";+ try { pathname = new URL(req.url).pathname; } catch { return "owner"; }+ const method = req.method.toUpperCase();++ if (pathname === "/api/v1/sys/services/logs") return "operator";+ if (pathname === "/api/v1/sys/services") return READ_METHODS.has(method) ? "viewer" : "operator";+ if (pathname === "/api/v1/sys/packages") return "viewer";++ if (pathname.startsWith("/api/v1/camoufox/")) return "operator";+ if (pathname.startsWith("/api/v1/managed-apps/")) {+ if (pathname.includes("/install") || pathname.includes("/update")) return "owner";+ // A job may be an install/update/rollback/uninstall started by Owner. Reading+ // its progress is operational; terminating it changes an Owner-authorized flow.+ if (method === "DELETE" && /\/jobs\/[a-f0-9]{24}$/.test(pathname)) return "owner";+ return "operator";+ }+ if (pathname === "/api/v1/managed-apps") return "operator";++ if (OWNER_PREFIXES.some((prefix) => pathname.startsWith(prefix))) return "owner";+ if (READ_METHODS.has(method) && (+ VIEWER_READ_PATHS.has(pathname) || VIEWER_READ_PREFIXES.some((prefix) => pathname.startsWith(prefix))+ )) return "viewer";+ return "owner";+}++// Cookie-only auth. An explicit role is allowed for unusual callers; ordinary+// /api/v1 routes rely on the policy above so new mutations fail closed.+export async function verifyAuth(req?: Request, minimumRole?: DeviceRole): Promise<boolean> {if (IS_DEMO) return false;- return requireSession();+ return requireSession(minimumRole ?? requiredRoleForRequest(req));}diff --git a/lib/auth/app-access.test.ts b/lib/auth/app-access.test.tsnew file mode 100644index 00000000..95b3445a--- /dev/null+++ b/lib/auth/app-access.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { appAllowedForRole } from "./app-access";++describe("role-aware app catalog", () => {+ it("keeps Viewer on read-oriented workspace surfaces", () => {+ for (const id of ["files-manager", "system-monitor", "media-viewer", "quicklinks", "docs", "os-settings"]) {+ expect(appAllowedForRole(id, "viewer"), id).toBe(true);+ }+ for (const id of ["os-terminal", "code-editor", "assistant", "hermes", "camoufox-browser"]) {+ expect(appAllowedForRole(id, "viewer"), id).toBe(false);+ }+ });++ it("adds only bounded operational apps for Operator", () => {+ for (const id of ["camoufox-browser", "hermes", "openclaw", "9router"]) {+ expect(appAllowedForRole(id, "operator"), id).toBe(true);+ }+ for (const id of ["os-terminal", "code-editor", "assistant", "app-store", "create-app"]) {+ expect(appAllowedForRole(id, "operator"), id).toBe(false);+ }+ });++ it("allows every app for Owner and fails unknown apps closed otherwise", () => {+ expect(appAllowedForRole("future-runtime-app", "owner")).toBe(true);+ expect(appAllowedForRole("future-runtime-app", "operator")).toBe(false);+ expect(appAllowedForRole("future-runtime-app", "viewer")).toBe(false);+ expect(appAllowedForRole("future-runtime-app", null)).toBe(false);+ });+});diff --git a/lib/auth/app-access.ts b/lib/auth/app-access.tsnew file mode 100644index 00000000..d4706dc8--- /dev/null+++ b/lib/auth/app-access.ts@@ -0,0 +1,24 @@+import type { DeviceRole } from "./roles";++const VIEWER_APPS = new Set([+ "files-manager",+ "system-monitor",+ "media-viewer",+ "quicklinks",+ "docs",+ "os-settings",+]);+const OPERATOR_APPS = new Set([+ ...VIEWER_APPS,+ "camoufox-browser",+ "hermes",+ "openclaw",+ "9router",+]);++/** Unknown/runtime apps fail closed for delegated devices until explicitly classified. */+export function appAllowedForRole(appId: string, role: DeviceRole | null): boolean {+ if (role === "owner") return true;+ if (role === "operator") return OPERATOR_APPS.has(appId);+ return VIEWER_APPS.has(appId);+}diff --git a/lib/auth/device-store.test.ts b/lib/auth/device-store.test.tsindex d264ee8e..b14b99ea 100644--- a/lib/auth/device-store.test.ts+++ b/lib/auth/device-store.test.ts@@ -61,6 +61,7 @@ describe("device-store — an unreadable file must never look like an empty one"const s = await listDevices();expect(Object.keys(s.approved)).toEqual([DEV]); // survived the second write+ expect(s.approved[DEV].role).toBe("owner");expect(s.pending[OTHER].ip).toBe("203.0.113.2");await expect(isApproved(DEV)).resolves.toBe(true);await expect(isApproved(OTHER)).resolves.toBe(false);@@ -69,6 +70,7 @@ describe("device-store — an unreadable file must never look like an empty one"it("keeps a device revoked when login touches race the kill switch", async () => {const { approveDevice, revokeDevice, touchApproved, isApproved } = await load();await approveDevice(DEV, "my laptop");+ await approveDevice(OTHER, "recovery owner");await Promise.all([...Array.from({ length: 16 }, () => touchApproved(DEV)),revokeDevice(DEV),@@ -83,3 +85,45 @@ describe("device-store — an unreadable file must never look like an empty one"expect((await fs.stat(path.dirname(store))).mode & 0o777).toBe(0o700);});});++describe("device-store — delegated roles", () => {+ it("treats a pre-role approved entry as owner for backward compatibility", async () => {+ await fs.writeFile(store, JSON.stringify({+ approved: { [DEV]: { label: "legacy laptop", approvedAt: 1 } },+ pending: {},+ }));+ const { getApprovedDevice, listDevices } = await load();+ await expect(getApprovedDevice(DEV)).resolves.toMatchObject({ role: "owner" });+ expect((await listDevices()).approved[DEV].role).toBe("owner");+ });++ it("approves a least-privilege viewer and changes its role live", async () => {+ const { approveDevice, getApprovedDevice, setDeviceRole } = await load();+ await approveDevice(DEV, "guest phone", "viewer");+ await expect(getApprovedDevice(DEV)).resolves.toMatchObject({ role: "viewer" });+ await setDeviceRole(DEV, "operator");+ await expect(getApprovedDevice(DEV)).resolves.toMatchObject({ role: "operator" });+ });++ it("refuses approval as a role-change bypass for an existing device", async () => {+ const { approveDevice, getApprovedDevice } = await load();+ await approveDevice(DEV, "owner laptop", "owner");+ await expect(approveDevice(DEV, "same laptop", "viewer")).rejects.toThrow("already approved");+ await expect(getApprovedDevice(DEV)).resolves.toMatchObject({ role: "owner", label: "owner laptop" });+ });++ it("never lets the web role API remove the last owner", async () => {+ const { approveDevice, revokeDevice, setDeviceRole } = await load();+ await approveDevice(DEV, "only owner", "owner");+ await expect(setDeviceRole(DEV, "viewer")).rejects.toThrow("at least one owner");+ await expect(revokeDevice(DEV)).rejects.toThrow("at least one owner");+ });++ it("allows owner demotion after another owner exists", async () => {+ const { approveDevice, getApprovedDevice, setDeviceRole } = await load();+ await approveDevice(DEV, "owner one", "owner");+ await approveDevice(OTHER, "owner two", "owner");+ await setDeviceRole(DEV, "viewer");+ await expect(getApprovedDevice(DEV)).resolves.toMatchObject({ role: "viewer" });+ });+});diff --git a/lib/auth/device-store.ts b/lib/auth/device-store.tsindex e1dcc951..2ed6e950 100644--- a/lib/auth/device-store.ts+++ b/lib/auth/device-store.ts@@ -2,17 +2,24 @@ import { promises as fs } from "fs";import os from "os";import path from "path";import { withSecurityStoreLock } from "@/lib/security-store-lock";+import {+ DeviceRoleError,+ isDeviceRole,+ storedDeviceRole,+ type DeviceRole,+} from "./roles";// Server-side device allowlist, ported from the VPS Control Room. The login// password is a weak/memorable factor; the strong factor is a 128-bit device// id that must be pre-approved here. A new device with the right password is// NOT let in — it lands in `pending` until an approved device (or the CLI)-// promotes it. This is the "something you have" leg.+// promotes it. A role then constrains the approved browser at every API call.export interface ApprovedDevice {label: string;approvedAt: number;lastSeen?: number;+ role: DeviceRole;}export interface PendingDevice {@@ -23,7 +30,7 @@ export interface PendingDevice {attempts: number;}-interface DeviceStore {+export interface DeviceStore {approved: Record<string, ApprovedDevice>;pending: Record<string, PendingDevice>;}@@ -42,16 +49,48 @@ export function isValidDeviceId(id: unknown): id is string {return typeof id === "string" && DEVICE_ID_RE.test(id);}+function finiteTime(value: unknown, fallback: number): number {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++function normalizeApproved(raw: unknown): Record<string, ApprovedDevice> {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};+ const out: Record<string, ApprovedDevice> = {};+ for (const [id, value] of Object.entries(raw)) {+ if (!isValidDeviceId(id) || !value || typeof value !== "object" || Array.isArray(value)) continue;+ const row = value as Record<string, unknown>;+ out[id] = {+ label: typeof row.label === "string" && row.label ? row.label.slice(0, 80) : "approved device",+ approvedAt: finiteTime(row.approvedAt, 0),+ ...(typeof row.lastSeen === "number" && Number.isFinite(row.lastSeen) ? { lastSeen: row.lastSeen } : {}),+ // Stores written before delegated roles had no role field. Preserve their+ // historical full access, while malformed future values fail down to viewer.+ role: storedDeviceRole(row.role),+ };+ }+ return out;+}++function normalizePending(raw: unknown): Record<string, PendingDevice> {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};+ const out: Record<string, PendingDevice> = {};+ for (const [id, value] of Object.entries(raw)) {+ if (!isValidDeviceId(id) || !value || typeof value !== "object" || Array.isArray(value)) continue;+ const row = value as Record<string, unknown>;+ out[id] = {+ label: typeof row.label === "string" && row.label ? row.label.slice(0, 80) : "unknown device",+ firstSeen: finiteTime(row.firstSeen, Date.now()),+ lastSeen: finiteTime(row.lastSeen, Date.now()),+ ip: typeof row.ip === "string" ? row.ip.slice(0, 120) : "unknown",+ attempts: Math.max(1, Math.floor(finiteTime(row.attempts, 1))),+ };+ }+ return out;+}+// "No file yet" is the ONLY failure that may look like an empty store. Anything else-// — corrupt JSON, EACCES, EIO — must throw.-//-// This used to `catch { return {…empty} }` for every error, and that was a silent way-// to lose every approved device: read() feeds a read-modify-write, and two callers-// (recordPending, approveDevice) write unconditionally. So one unparseable byte in-// auth-devices.json meant the next login from an unapproved device read "no devices",-// then PERSISTED that — wiping the allowlist and locking the owner out of their own-// host. recordPending is reachable from the internet by anyone holding the password.-// Failing loudly here costs a 500 on login; failing quietly cost the allowlist.+// — corrupt JSON, EACCES, EIO — must throw. A normalized read also migrates legacy+// role-less entries in memory; the next legitimate mutation persists the role field.async function read(): Promise<DeviceStore> {let raw: string;try {@@ -60,8 +99,11 @@ async function read(): Promise<DeviceStore> {if ((e as NodeJS.ErrnoException).code === "ENOENT") return { approved: {}, pending: {} };throw e;}- const parsed = JSON.parse(raw) as Partial<DeviceStore>;- return { approved: parsed.approved ?? {}, pending: parsed.pending ?? {} };+ const parsed = JSON.parse(raw) as Record<string, unknown>;+ return {+ approved: normalizeApproved(parsed.approved),+ pending: normalizePending(parsed.pending),+ };}async function write(store: DeviceStore): Promise<void> {@@ -82,9 +124,17 @@ function mutate<T>(fn: () => Promise<T>): Promise<T> {return run;}-export async function isApproved(deviceId: string): Promise<boolean> {+function ownerCount(store: DeviceStore): number {+ return Object.values(store.approved).filter((entry) => entry.role === "owner").length;+}++export async function getApprovedDevice(deviceId: string): Promise<ApprovedDevice | null> {const store = await read();- return deviceId in store.approved;+ return store.approved[deviceId] ?? null;+}++export async function isApproved(deviceId: string): Promise<boolean> {+ return (await getApprovedDevice(deviceId)) !== null;}/** Mark an approved device as just-seen (best effort). */@@ -103,25 +153,47 @@ export async function listDevices(): Promise<DeviceStore> {return read();}-/** Approve a device (moves it out of pending). Used by the in-app panel + CLI. */-export function approveDevice(deviceId: string, label?: string): Promise<void> {+/** Approve a device (moves it out of pending). Omitted role preserves legacy owner semantics. */+export function approveDevice(deviceId: string, label?: string, role: DeviceRole = "owner"): Promise<void> {+ if (!isDeviceRole(role)) return Promise.reject(new DeviceRoleError("invalid device role"));return mutate(async () => {const store = await read();+ if (store.approved[deviceId]) throw new DeviceRoleError("device is already approved; use set_role");const pending = store.pending[deviceId];store.approved[deviceId] = {label: (label && label.slice(0, 80)) || pending?.label || "approved device",approvedAt: Date.now(),+ role,};delete store.pending[deviceId];await write(store);});}+/** Change an approved device's live role. Demotion takes effect on its next request. */+export function setDeviceRole(deviceId: string, role: DeviceRole): Promise<void> {+ if (!isDeviceRole(role)) return Promise.reject(new DeviceRoleError("invalid device role"));+ return mutate(async () => {+ const store = await read();+ const entry = store.approved[deviceId];+ if (!entry) throw new DeviceRoleError("device is not approved");+ if (entry.role === "owner" && role !== "owner" && ownerCount(store) <= 1) {+ throw new DeviceRoleError("at least one owner device must remain approved");+ }+ entry.role = role;+ await write(store);+ });+}+/** Un-trust a device (and clear any pending record for the same id). */export function revokeDevice(deviceId: string): Promise<void> {return mutate(async () => {const store = await read();- if (!(deviceId in store.approved) && !(deviceId in store.pending)) return;+ const approved = store.approved[deviceId];+ if (!approved && !(deviceId in store.pending)) return;+ if (approved?.role === "owner" && ownerCount(store) <= 1) {+ throw new DeviceRoleError("at least one owner device must remain approved");+ }delete store.approved[deviceId];delete store.pending[deviceId];await write(store);diff --git a/lib/auth/require-session.test.ts b/lib/auth/require-session.test.tsindex 441838e2..0a2a92a2 100644--- a/lib/auth/require-session.test.ts+++ b/lib/auth/require-session.test.ts@@ -14,7 +14,11 @@ vi.mock("next/headers", () => ({getAll: (name: string) => jar.filter((cookie) => cookie.name === name),}),}));-vi.mock("./device-store", () => ({ isApproved: async (id: string) => id === "dev-1" }));+vi.mock("./device-store", () => ({+ getApprovedDevice: async (id: string) => id === "dev-1"+ ? { label: "device", approvedAt: 1, role: "operator" }+ : null,+}));const valid = () => signSession({ issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "dev-1" }, SECRET);@@ -44,4 +48,13 @@ describe("getSession with a shadowed cookie", () => {});expect(await getSession()).toBeNull();});++ it("rechecks the live device role for every authorization decision", async () => {+ const { getSessionContext, requireSession } = await import("./require-session");+ jar.push({ name: "session", value: valid() });+ await expect(getSessionContext()).resolves.toMatchObject({ role: "operator" });+ await expect(requireSession("viewer")).resolves.toBe(true);+ await expect(requireSession("operator")).resolves.toBe(true);+ await expect(requireSession("owner")).resolves.toBe(false);+ });});diff --git a/lib/auth/require-session.ts b/lib/auth/require-session.tsindex ea51b107..fac2a130 100644--- a/lib/auth/require-session.ts+++ b/lib/auth/require-session.ts@@ -1,6 +1,7 @@import { cookies } from "next/headers";import { verifySession, type SessionPayload } from "./session";-import { isApproved } from "./device-store";+import { getApprovedDevice, type ApprovedDevice } from "./device-store";+import { roleAtLeast, type DeviceRole } from "./roles";import { IS_DEMO } from "@/lib/demo";export const SESSION_COOKIE = "session";@@ -9,40 +10,40 @@ function secret(): string {return process.env.OS_SESSION_SECRET ?? "";}-// Reads + verifies the signed session cookie. Returns the payload or null.-// Server-only (uses next/headers cookies()).-//-// Revocation: a valid HMAC is not enough — the session is only honoured while-// its device is STILL in the approved allowlist. Without this re-check, revoking-// a lost/stolen device wouldn't kill its live sessions until natural expiry-// (the very case revoke exists for). A session carrying no device_id is also-// rejected (login always stamps one; a payload without it is legacy/forged).-// Cookies are not isolated by port or path (RFC 6265 §8.5), and `document.cookie`-// on the same host can add a SECOND `session=` cookie that sorts ahead of the real-// one. Reading only the first match would then hand every request a forged value-// and lock the user out of their own cockpit with the valid cookie still in the-// jar. So verify EVERY candidate and take the first that holds up.-export async function getSession(): Promise<SessionPayload | null> {+export type SessionContext = {+ session: SessionPayload;+ device: ApprovedDevice;+ role: DeviceRole;+};++// Reads + verifies every signed-session candidate, then resolves the device record+// live. Role changes and revocation therefore take effect on the next request; no+// authorization claim is cached in a cookie that can remain stale for 24 hours.+export async function getSessionContext(): Promise<SessionContext | null> {if (IS_DEMO) return null;const jar = await cookies();for (const { value } of jar.getAll(SESSION_COOKIE)) {- const payload = verifySession(value, secret());- if (!payload?.device_id) continue;- if (!(await isApproved(payload.device_id))) continue;- return payload;+ const session = verifySession(value, secret());+ if (!session?.device_id) continue;+ const device = await getApprovedDevice(session.device_id);+ if (!device) continue;+ return { session, device, role: device.role };}return null;}-// True when the caller holds a valid session. Used by /api/v1 routes in place-// of the old Convex Bearer check (verifyAuth). The session cookie is sent-// automatically on same-origin requests (incl. <img>, fetch).-export async function requireSession(): Promise<boolean> {- return (await getSession()) !== null;+/** Compatibility payload accessor for existing callers that do not need role data. */+export async function getSession(): Promise<SessionPayload | null> {+ return (await getSessionContext())?.session ?? null;+}++export async function requireSession(minimumRole: DeviceRole = "viewer"): Promise<boolean> {+ const context = await getSessionContext();+ return context !== null && roleAtLeast(context.role, minimumRole);}-// The approved device id behind the current session, or null. Used to attribute-// audit-log entries to an actor without re-reading the cookie in every route.+// Approved device id behind the current session, or null. Audit attribution remains+// stable across role changes; role is recorded separately by security-sensitive routes.export async function getSessionActor(): Promise<string | null> {- return (await getSession())?.device_id ?? null;+ return (await getSessionContext())?.session.device_id ?? null;}diff --git a/lib/auth/roles.test.ts b/lib/auth/roles.test.tsnew file mode 100644index 00000000..3043fe67--- /dev/null+++ b/lib/auth/roles.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from "vitest";+import { isDeviceRole, roleAtLeast, storedDeviceRole } from "./roles";++describe("device roles", () => {+ it("orders viewer < operator < owner", () => {+ expect(roleAtLeast("viewer", "viewer")).toBe(true);+ expect(roleAtLeast("viewer", "operator")).toBe(false);+ expect(roleAtLeast("operator", "viewer")).toBe(true);+ expect(roleAtLeast("operator", "owner")).toBe(false);+ expect(roleAtLeast("owner", "operator")).toBe(true);+ });++ it("migrates missing legacy roles up, but malformed values down", () => {+ expect(storedDeviceRole(undefined)).toBe("owner");+ expect(storedDeviceRole("operator")).toBe("operator");+ expect(storedDeviceRole("admin")).toBe("viewer");+ expect(isDeviceRole("owner")).toBe(true);+ expect(isDeviceRole("root")).toBe(false);+ });+});diff --git a/lib/auth/roles.ts b/lib/auth/roles.tsnew file mode 100644index 00000000..a47333d0--- /dev/null+++ b/lib/auth/roles.ts@@ -0,0 +1,43 @@+/**+ * Device-scoped access levels for the owner-first cockpit.+ *+ * These are not Linux users, an identity directory, or SSO. They constrain what an+ * already-approved browser device may ask the MSO web/API layer to do. The process+ * still runs as one Unix account, so an owner session remains equivalent to that+ * account and an operator must still be treated as trusted with operational data.+ */+export const DEVICE_ROLES = ["viewer", "operator", "owner"] as const;+export type DeviceRole = (typeof DEVICE_ROLES)[number];++const ROLE_RANK: Record<DeviceRole, number> = {+ viewer: 0,+ operator: 1,+ owner: 2,+};++export function isDeviceRole(value: unknown): value is DeviceRole {+ return typeof value === "string" && (DEVICE_ROLES as readonly string[]).includes(value);+}++/** Missing means a legacy pre-role owner device. An invalid stored value fails down. */+export function storedDeviceRole(value: unknown): DeviceRole {+ if (value === undefined) return "owner";+ return isDeviceRole(value) ? value : "viewer";+}++export function roleAtLeast(actual: DeviceRole, required: DeviceRole): boolean {+ return ROLE_RANK[actual] >= ROLE_RANK[required];+}++export function roleLabel(role: DeviceRole): string {+ if (role === "owner") return "Owner";+ if (role === "operator") return "Operator";+ return "Viewer";+}++export class DeviceRoleError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "DeviceRoleError";+ }+}diff --git a/lib/host/audit.ts b/lib/host/audit.tsindex c8c21cb5..97c1741c 100644--- a/lib/host/audit.ts+++ b/lib/host/audit.ts@@ -24,6 +24,7 @@ export type AuditAction =| "fs.upload"| "fs.zip"| "sys.cleanup"+ | "sys.service"/** The cockpit replacing its own code (Settings → About, or `mso update run`). */| "sys.update"| "managed-app.action"@@ -40,6 +41,7 @@ export type AuditAction =| "auth.denied"| "auth.ratelimited"| "auth.logout"+ | "auth.device"| "framework.error";export interface AuditEntry {diff --git a/lib/host/package-updates.test.ts b/lib/host/package-updates.test.tsnew file mode 100644index 00000000..3ee2b0ce--- /dev/null+++ b/lib/host/package-updates.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it, vi } from "vitest";+vi.mock("server-only", () => ({}));+import { parseAptUpdates, parsePacmanUpdates, parseRpmUpdates, parseZypperUpdates } from "./package-updates";++describe("package update parsers", () => {+ it("parses apt cache output", () => {+ expect(parseAptUpdates("Listing... Done\nopenssl/jammy-updates 3.0.2-1ubuntu1.18 amd64 [upgradable from: 3.0.2-1ubuntu1]\n"))+ .toEqual([{ name: "openssl", candidate: "3.0.2-1ubuntu1.18", architecture: "amd64", current: "3.0.2-1ubuntu1" }]);+ });++ it("parses rpm, pacman, and zypper output without repository text becoming a package", () => {+ expect(parseRpmUpdates("Last metadata expiration check: 0:01 ago\nopenssl.x86_64 3.2.2 updates\n"))+ .toEqual([{ name: "openssl", architecture: "x86_64", candidate: "3.2.2" }]);+ expect(parsePacmanUpdates("curl 8.1.0-1 -> 8.2.0-1\n"))+ .toEqual([{ name: "curl", current: "8.1.0-1", candidate: "8.2.0-1" }]);+ expect(parseZypperUpdates("v | Name | Current Version | Available Version | Arch\n--+------+-----------------+-------------------+-----\nv | git | 2.40 | 2.41 | x86_64\n"))+ .toEqual([{ name: "git", current: "2.40", candidate: "2.41", architecture: "x86_64" }]);+ });+});diff --git a/lib/host/package-updates.ts b/lib/host/package-updates.tsnew file mode 100644index 00000000..e79f6446--- /dev/null+++ b/lib/host/package-updates.ts@@ -0,0 +1,113 @@+import "server-only";+import { execFile } from "node:child_process";+import { existsSync } from "node:fs";+import { promisify } from "node:util";+import type { PackageUpdate, PackageUpdateSummary } from "@/lib/os-api/types";+import { childEnv } from "./child-env";++const execFileAsync = promisify(execFile);+const MAX_UPDATES = 250;+type Manager = NonNullable<PackageUpdateSummary["manager"]>;++const candidates: Array<{ manager: Manager; paths: string[]; args: string[]; accepted?: number[] }> = [+ { manager: "apt", paths: ["/usr/bin/apt", "/bin/apt"], args: ["list", "--upgradable"] },+ { manager: "dnf", paths: ["/usr/bin/dnf", "/bin/dnf"], args: ["-q", "check-update", "--cacheonly"], accepted: [100] },+ { manager: "yum", paths: ["/usr/bin/yum", "/bin/yum"], args: ["-q", "check-update", "-C"], accepted: [100] },+ { manager: "pacman", paths: ["/usr/bin/pacman", "/bin/pacman"], args: ["-Qu"], accepted: [1] },+ { manager: "zypper", paths: ["/usr/bin/zypper", "/bin/zypper"], args: ["--no-refresh", "--non-interactive", "list-updates"], accepted: [100] },+];++function forcedManager(): Manager | null {+ const value = process.env.MSO_PACKAGE_MANAGER;+ return candidates.some((candidate) => candidate.manager === value) ? value as Manager : null;+}++function managerCommand(): { manager: Manager; program: string; args: string[]; accepted: number[] } | null {+ const forced = forcedManager();+ for (const candidate of candidates) {+ if (forced && candidate.manager !== forced) continue;+ const override = process.env[`MSO_${candidate.manager.toUpperCase()}_BIN`];+ const program = override || candidate.paths.find(existsSync);+ if (program) return { ...candidate, program, accepted: candidate.accepted ?? [] };+ }+ return null;+}++export function parseAptUpdates(stdout: string): PackageUpdate[] {+ const updates: PackageUpdate[] = [];+ for (const line of stdout.split("\n")) {+ if (!line || line.startsWith("Listing") || !line.includes("/")) continue;+ const match = line.match(/^([^/\s]+)\/\S+\s+(\S+)\s+(\S+)(?:\s+\[upgradable from: ([^\]]+)\])?/);+ if (!match) continue;+ updates.push({ name: match[1], candidate: match[2], architecture: match[3], ...(match[4] ? { current: match[4] } : {}) });+ }+ return updates;+}++export function parseRpmUpdates(stdout: string): PackageUpdate[] {+ const updates: PackageUpdate[] = [];+ for (const raw of stdout.split("\n")) {+ const line = raw.trim();+ if (!line || line.startsWith("Last metadata") || line.startsWith("Obsoleting")) continue;+ const parts = line.split(/\s+/);+ if (parts.length < 2 || !parts[0]?.includes(".")) continue;+ const split = parts[0].lastIndexOf(".");+ updates.push({ name: parts[0].slice(0, split), architecture: parts[0].slice(split + 1), candidate: parts[1] });+ }+ return updates;+}++export function parsePacmanUpdates(stdout: string): PackageUpdate[] {+ return stdout.split("\n").map((line) => line.trim()).filter(Boolean).flatMap((line) => {+ const match = line.match(/^(\S+)\s+(\S+)\s+->\s+(\S+)/);+ return match ? [{ name: match[1], current: match[2], candidate: match[3] }] : [];+ });+}++export function parseZypperUpdates(stdout: string): PackageUpdate[] {+ const updates: PackageUpdate[] = [];+ for (const raw of stdout.split("\n")) {+ const cols = raw.split("|").map((part) => part.trim());+ if (cols.length < 5 || !cols[1] || cols[1] === "Name" || /^[-+]+$/.test(cols[1])) continue;+ updates.push({ name: cols[1], current: cols[2] || undefined, candidate: cols[3], architecture: cols[4] || undefined });+ }+ return updates;+}++function parse(manager: Manager, stdout: string): PackageUpdate[] {+ if (manager === "apt") return parseAptUpdates(stdout);+ if (manager === "dnf" || manager === "yum") return parseRpmUpdates(stdout);+ if (manager === "pacman") return parsePacmanUpdates(stdout);+ return parseZypperUpdates(stdout);+}++export async function packageUpdates(): Promise<PackageUpdateSummary> {+ const command = managerCommand();+ const checkedAt = new Date().toISOString();+ if (!command) return { manager: null, available: false, updates: [], truncated: false, checkedAt, source: "local-cache", diagnostic: "No supported package manager found" };+ try {+ const result = await execFileAsync(command.program, command.args, {+ env: childEnv() as NodeJS.ProcessEnv,+ timeout: 20_000,+ maxBuffer: 1024 * 1024,+ windowsHide: true,+ });+ const updates = parse(command.manager, result.stdout);+ return { manager: command.manager, available: true, updates: updates.slice(0, MAX_UPDATES), truncated: updates.length > MAX_UPDATES, checkedAt, source: "local-cache" };+ } catch (error) {+ const e = error as NodeJS.ErrnoException & { code?: number; stdout?: string; stderr?: string };+ if (typeof e.code === "number" && command.accepted.includes(e.code)) {+ const updates = parse(command.manager, e.stdout || "");+ return { manager: command.manager, available: true, updates: updates.slice(0, MAX_UPDATES), truncated: updates.length > MAX_UPDATES, checkedAt, source: "local-cache" };+ }+ return {+ manager: command.manager,+ available: false,+ updates: [],+ truncated: false,+ checkedAt,+ source: "local-cache",+ diagnostic: (e.stderr || e.message || "Package update check failed").trim().slice(0, 320),+ };+ }+}diff --git a/lib/host/services.test.ts b/lib/host/services.test.tsnew file mode 100644index 00000000..2c1e6e52--- /dev/null+++ b/lib/host/services.test.ts@@ -0,0 +1,41 @@+import { afterEach, describe, expect, it, vi } from "vitest";+vi.mock("server-only", () => ({}));+import { parseSystemctlServices, serviceControlAllowlist, validServiceUnit } from "./services";++afterEach(() => vi.unstubAllEnvs());++describe("systemd service inventory", () => {+ it("parses stable systemctl columns and marks only exact allowlist matches controllable", () => {+ const allow = new Set(["user:mso.service"]);+ const rows = parseSystemctlServices([+ "mso.service loaded active running Manef Shell OS",+ "[email protected] loaded failed failed Queue worker one",+ "not-a-unit.socket loaded active listening Socket",+ ].join("\n"), "user", allow);+ expect(rows).toEqual([+ {+ unit: "mso.service", scope: "user", load: "loaded", active: "active", sub: "running",+ description: "Manef Shell OS", controllable: true,+ },+ {+ unit: "[email protected]", scope: "user", load: "loaded", active: "failed", sub: "failed",+ description: "Queue worker one", controllable: false,+ },+ ]);+ });++ it("fails malformed allowlist entries closed instead of broadening control", () => {+ vi.stubEnv("OS_SERVICE_CONTROL_UNITS", "user:mso.service,system:nginx.service,*.service,user:../bad.service");+ const parsed = serviceControlAllowlist();+ expect([...parsed.units]).toEqual(["user:mso.service", "system:nginx.service"]);+ expect(parsed.diagnostics).toHaveLength(2);+ });++ it("accepts ordinary and template units but no spaces, slash, or flags", () => {+ expect(validServiceUnit("nginx.service")).toBe(true);+ expect(validServiceUnit("[email protected]")).toBe(true);+ for (const bad of ["../nginx.service", "nginx service", "nginx\\evil.service", "--help.service", "nginx.socket", ""]) {+ expect(validServiceUnit(bad)).toBe(false);+ }+ });+});diff --git a/lib/host/services.ts b/lib/host/services.tsnew file mode 100644index 00000000..0d4f6e24--- /dev/null+++ b/lib/host/services.ts@@ -0,0 +1,197 @@+import "server-only";+import { execFile } from "node:child_process";+import { promisify } from "node:util";+import type {+ ServiceAction,+ ServiceInventory,+ ServiceLogs,+ ServiceScope,+ SystemService,+} from "@/lib/os-api/types";+import { userBusEnv } from "@/lib/managed-apps/user-bus";+import { childEnv } from "./child-env";+import { HostError } from "./host-error";++const execFileAsync = promisify(execFile);+const MAX_SERVICES = 300;+const MAX_LOG_LINES = 200;+const UNIT_RE = /^[A-Za-z0-9_][A-Za-z0-9_.@:-]{0,179}\.service$/;+const ACTIONS = new Set<ServiceAction>(["start", "stop", "restart"]);++const systemctlBin = () => process.env.MSO_SYSTEMCTL_BIN || "/usr/bin/systemctl";+const journalctlBin = () => process.env.MSO_JOURNALCTL_BIN || "/usr/bin/journalctl";++function assertScope(scope: unknown): asserts scope is ServiceScope {+ if (scope !== "system" && scope !== "user") throw new HostError("scope must be system or user");+}++function assertUnit(unit: unknown): asserts unit is string {+ if (typeof unit !== "string" || !UNIT_RE.test(unit)) throw new HostError("invalid systemd service unit");+}++function commandEnv(scope: ServiceScope): NodeJS.ProcessEnv {+ return { ...childEnv(), ...(scope === "user" ? userBusEnv() : undefined) } as NodeJS.ProcessEnv;+}++async function run(+ program: string,+ args: string[],+ scope: ServiceScope,+ timeout = 10_000,+): Promise<{ stdout: string; stderr: string }> {+ try {+ const result = await execFileAsync(program, args, {+ env: commandEnv(scope),+ timeout,+ maxBuffer: 1024 * 1024,+ windowsHide: true,+ });+ return { stdout: result.stdout, stderr: result.stderr };+ } catch (error) {+ const e = error as NodeJS.ErrnoException & { stdout?: string; stderr?: string };+ const detail = (e.stderr || e.stdout || e.message || "command failed").trim().slice(0, 320);+ throw new HostError(detail);+ }+}++export function validServiceUnit(unit: string): boolean {+ return UNIT_RE.test(unit);+}++export function serviceControlAllowlist(raw = process.env.OS_SERVICE_CONTROL_UNITS ?? ""): {+ units: Set<string>;+ diagnostics: string[];+} {+ const units = new Set<string>();+ const diagnostics: string[] = [];+ for (const item of raw.split(/[\s,]+/).map((part) => part.trim()).filter(Boolean).slice(0, 64)) {+ const colon = item.indexOf(":");+ const scope = item.slice(0, colon);+ const unit = item.slice(colon + 1);+ if ((scope !== "system" && scope !== "user") || !validServiceUnit(unit)) {+ diagnostics.push(`Ignored invalid service allowlist entry: ${item.slice(0, 120)}`);+ continue;+ }+ units.add(`${scope}:${unit}`);+ }+ return { units, diagnostics };+}++export function parseSystemctlServices(+ stdout: string,+ scope: ServiceScope,+ controllable: ReadonlySet<string>,+): SystemService[] {+ const rows: SystemService[] = [];+ for (const raw of stdout.split("\n")) {+ const line = raw.trim().replace(/^●\s*/, "");+ if (!line) continue;+ const parts = line.split(/\s+/);+ if (parts.length < 4 || !validServiceUnit(parts[0] ?? "")) continue;+ const [unit, load, active, sub, ...description] = parts;+ rows.push({+ unit,+ scope,+ load,+ active,+ sub,+ description: description.join(" "),+ controllable: controllable.has(`${scope}:${unit}`),+ });+ }+ return rows;+}++async function listScope(scope: ServiceScope, allowlist: ReadonlySet<string>): Promise<SystemService[]> {+ const args = [+ ...(scope === "user" ? ["--user"] : ["--system"]),+ "list-units",+ "--type=service",+ "--all",+ "--no-legend",+ "--no-pager",+ "--plain",+ ];+ const { stdout } = await run(systemctlBin(), args, scope);+ return parseSystemctlServices(stdout, scope, allowlist);+}++export async function listSystemServices(): Promise<ServiceInventory> {+ const allow = serviceControlAllowlist();+ const diagnostics = [...allow.diagnostics];+ const services: SystemService[] = [];+ for (const scope of ["user", "system"] as const) {+ try {+ services.push(...await listScope(scope, allow.units));+ } catch (error) {+ diagnostics.push(`${scope} services unavailable: ${error instanceof Error ? error.message : String(error)}`);+ }+ }+ services.sort((a, b) => a.scope.localeCompare(b.scope) || a.unit.localeCompare(b.unit));+ const truncated = services.length > MAX_SERVICES;+ return {+ services: services.slice(0, MAX_SERVICES),+ diagnostics,+ truncated,+ controlAllowlistConfigured: allow.units.size > 0,+ generatedAt: new Date().toISOString(),+ };+}++async function readService(scope: ServiceScope, unit: string, controllable: boolean): Promise<SystemService> {+ const args = [+ ...(scope === "user" ? ["--user"] : ["--system"]),+ "show",+ unit,+ "--no-pager",+ "--property=LoadState,ActiveState,SubState,Description",+ ];+ const { stdout } = await run(systemctlBin(), args, scope);+ const values = Object.fromEntries(stdout.split("\n").map((line) => line.split(/=(.*)/s).slice(0, 2)).filter((row) => row.length === 2));+ return {+ unit,+ scope,+ load: values.LoadState || "unknown",+ active: values.ActiveState || "unknown",+ sub: values.SubState || "unknown",+ description: values.Description || "",+ controllable,+ };+}++export async function servicePower(scope: ServiceScope, unit: string, action: ServiceAction): Promise<SystemService> {+ assertScope(scope);+ assertUnit(unit);+ if (!ACTIONS.has(action)) throw new HostError("action must be start, stop, or restart");+ const allow = serviceControlAllowlist();+ const key = `${scope}:${unit}`;+ if (!allow.units.has(key)) throw new HostError("service action is not allowlisted by OS_SERVICE_CONTROL_UNITS");++ if (scope === "system" && process.env.OS_SERVICE_CONTROL_USE_SUDO === "1") {+ const sudo = process.env.MSO_SUDO_BIN || "/usr/bin/sudo";+ await run(sudo, ["-n", systemctlBin(), "--system", action, unit], scope, 30_000);+ } else {+ const args = [...(scope === "user" ? ["--user"] : ["--system"]), action, unit];+ await run(systemctlBin(), args, scope, 30_000);+ }+ return readService(scope, unit, true);+}++export async function serviceLogs(scope: ServiceScope, unit: string, limit = 120): Promise<ServiceLogs> {+ assertScope(scope);+ assertUnit(unit);+ const lines = Math.min(Math.max(Math.floor(limit) || 120, 1), MAX_LOG_LINES);+ const args = ["--no-pager", "--output=short-iso", `--lines=${lines}`, scope === "user" ? `--user-unit=${unit}` : `--unit=${unit}`];+ try {+ const { stdout } = await run(journalctlBin(), args, scope, 15_000);+ return { unit, scope, entries: stdout.split("\n").filter(Boolean).slice(-lines), available: true };+ } catch (error) {+ return {+ unit,+ scope,+ entries: [],+ available: false,+ diagnostic: error instanceof Error ? error.message : String(error),+ };+ }+}diff --git a/lib/os-api/http-adapter.ts b/lib/os-api/http-adapter.tsindex 32f85664..7691ed8d 100644--- a/lib/os-api/http-adapter.ts+++ b/lib/os-api/http-adapter.ts@@ -1,4 +1,4 @@-import { API_VERSION, type OsApi, type SysStats } from "./types";+import { API_VERSION, type HostAccessRole, type OsApi, type SysStats } from "./types";import type { ManagedAppView } from "@/lib/managed-apps/types";import { uploadChunked } from "./upload";@@ -44,7 +44,14 @@ const toSummary = (a: ManagedAppWire): ManagedApp => ({// {baseUrl}/api/v1. Auth = the signed session cookie, sent automatically on// same-origin requests (no Bearer token). Host actions stay allowlisted// server-side; this is just the client.-export function HttpAdapter(cfg: { url?: string }): OsApi {+export function HttpAdapter(cfg: { url?: string; role?: Exclude<HostAccessRole, "demo"> }): OsApi {+ const role = cfg.role ?? "viewer";+ const access = {+ role,+ canRead: true,+ canOperate: role === "operator" || role === "owner",+ canOwn: role === "owner",+ } as const;const root = (cfg.url || "").replace(/\/$/, "") + "/api/" + API_VERSION;async function req<T>(@@ -85,6 +92,7 @@ export function HttpAdapter(cfg: { url?: string }): OsApi {return {mode: "live",+ access,auth: {token: (username, password) =>req("POST", "/auth/token", { body: { username, password } }),@@ -113,6 +121,12 @@ export function HttpAdapter(cfg: { url?: string }): OsApi {statsStream: (onEvent) =>sse("/sys/stats/stream", {}, (d) => onEvent(d as Partial<SysStats>)),processes: () => req("GET", "/sys/processes"),+ services: () => req("GET", "/sys/services"),+ serviceLogs: (scope, unit, limit = 120) => req("GET", "/sys/services/logs", {+ query: { scope, unit, limit: String(limit) },+ }),+ servicePower: (scope, unit, action) => req("POST", "/sys/services", { body: { scope, unit, action } }),+ packageUpdates: () => req("GET", "/sys/packages"),},apps: {// UNWRAP, then TRANSLATE. Both managed-app routes answer in an envelope —diff --git a/lib/os-api/index.tsx b/lib/os-api/index.tsxindex 82e2e861..2bc519d8 100644--- a/lib/os-api/index.tsx+++ b/lib/os-api/index.tsx@@ -40,15 +40,15 @@ export function zipUrl(// with the gateway secret (server-side only). Demo never touches the host.export function OsApiProvider({ children }: { children: ReactNode }) {const { tweaks } = useAppearance();- const { status } = useSession();+ const { status, role } = useSession();// Live only when signed in. A public/signed-out visitor stays on mock (the// /api host routes would 401 them anyway — this just avoids the error spray// and gives a clean mock experience); live activates the moment the owner// signs in (Settings → Server), since the shared session flips `status`.const mode = IS_DEMO || status !== "in" ? "mock" : tweaks.server.mode;const api = useMemo(- () => (mode === "live" ? HttpAdapter({ url: "" }) : MockAdapter()),- [mode],+ () => (mode === "live" ? HttpAdapter({ url: "", role: role ?? "viewer" }) : MockAdapter()),+ [mode, role],);return <HostApiProvider api={api}>{children}</HostApiProvider>;}@@ -68,4 +68,6 @@ export type {UploadResult,ExecResult,Process,+ HostAccess,+ HostAccessRole,} from "./types";diff --git a/lib/os-api/mock-adapter.ts b/lib/os-api/mock-adapter.tsindex 2618198d..7ccb696e 100644--- a/lib/os-api/mock-adapter.ts+++ b/lib/os-api/mock-adapter.ts@@ -9,9 +9,15 @@ import { makeMockFs } from "./mock-fs";export function MockAdapter(): OsApi {const tree = loadDemoTree();const persist = () => saveDemoTree(tree);+ const services = [+ { unit: "mso.service", scope: "user" as const, load: "loaded", active: "active", sub: "running", description: "Manef Shell OS", controllable: true },+ { unit: "demo-worker.service", scope: "user" as const, load: "loaded", active: "failed", sub: "failed", description: "Demo background worker", controllable: true },+ { unit: "ssh.service", scope: "system" as const, load: "loaded", active: "active", sub: "running", description: "OpenBSD Secure Shell server", controllable: false },+ ];return {mode: "mock",+ access: { role: "demo", canRead: true, canOperate: true, canOwn: true },auth: {token: (u) => delay({ token: "mock." + btoa(u || "root"), expires_at: Date.now() + 36e5 }),me: () => delay({ user: { name: "root", id: "u_local" } }),@@ -54,6 +60,33 @@ export function MockAdapter(): OsApi {{ pid: 201, name: "background-worker", status: "restarted 2m ago", cpu: 7, mem: 142 },{ pid: 318, name: "preview-proxy", status: "running", cpu: 3, mem: 88 },]),+ services: () => delay({+ services: services.map((service) => ({ ...service })),+ diagnostics: [],+ truncated: false,+ controlAllowlistConfigured: true,+ generatedAt: new Date().toISOString(),+ }),+ serviceLogs: (scope, unit) => delay({+ unit, scope, available: true, entries: [+ `[mock] ${unit}: started successfully`,+ `[mock] ${unit}: health check passed`,+ ],+ }),+ servicePower: (scope, unit, action) => {+ const service = services.find((entry) => entry.scope === scope && entry.unit === unit);+ if (!service || !service.controllable) return Promise.reject(new Error("service action is not allowlisted"));+ service.active = action === "stop" ? "inactive" : "active";+ service.sub = action === "stop" ? "dead" : "running";+ return delay({ ...service }, 250);+ },+ packageUpdates: () => delay({+ manager: "apt" as const, available: true, truncated: false, checkedAt: new Date().toISOString(), source: "local-cache" as const,+ updates: [+ { name: "openssl", current: "3.0.2-0ubuntu1", candidate: "3.0.2-0ubuntu1.18", architecture: "amd64" },+ { name: "curl", current: "8.5.0-2", candidate: "8.5.0-2ubuntu10", architecture: "amd64" },+ ],+ }),},apps: {list: () =>diff --git a/lib/os-api/types.ts b/lib/os-api/types.tsindex b9f0bd46..25fb1295 100644--- a/lib/os-api/types.ts+++ b/lib/os-api/types.ts@@ -7,6 +7,8 @@ export const API_VERSION = "v1";export type {Unsub,+ HostAccessRole,+ HostAccess,SysStats,FsEntry,FsRoot,@@ -18,6 +20,13 @@ export type {UploadProgress,ExecResult,Process,+ ServiceScope,+ ServiceAction,+ SystemService,+ ServiceInventory,+ ServiceLogs,+ PackageUpdate,+ PackageUpdateSummary,AppManifest,OsApi,} from "@/features/appshell";diff --git a/package.json b/package.jsonindex 0c65d821..8626ad2d 100644--- a/package.json+++ b/package.json@@ -13,7 +13,7 @@"typecheck": "tsc --noEmit","test": "vitest run","coverage": "vitest run --coverage",- "check": "node scripts/check-cycles.mjs && node scripts/check-docs.mjs && node scripts/check-contrast.mjs && node scripts/check-skill-flows.mjs",+ "check": "node scripts/check-cycles.mjs && node scripts/check-docs.mjs && node scripts/gen-comparison.mjs --check && node scripts/check-contrast.mjs && node scripts/check-skill-flows.mjs","audit": "node scripts/audit.mjs","verify": "bun run typecheck && bun run lint && bun run coverage && bun run check && bun run audit","security:ultimate": "bash scripts/security-ultimate.sh",@@ -24,7 +24,8 @@"smoke": "E2E_BASE_URL=http://localhost:4005 vitest run scripts/e2e/smoke.test.ts","icons:app": "node scripts/gen-app-icons.mjs && python3 scripts/gen-remaining-platform-icons.py","skill:new": "node scripts/create-skill-flow.mjs",- "skill:check": "node scripts/check-skill-flows.mjs"+ "skill:check": "node scripts/check-skill-flows.mjs",+ "comparison": "node scripts/gen-comparison.mjs"},"dependencies": {"@anthropic-ai/sdk": "^0.100.1",diff --git a/proxy-websocket.test.ts b/proxy-websocket.test.tsindex 91693f4d..a613fa97 100644--- a/proxy-websocket.test.ts+++ b/proxy-websocket.test.ts@@ -6,8 +6,12 @@ import { describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import { signSession } from "./lib/auth/session";-const approved = vi.hoisted(() => ({ value: true }));-vi.mock("@/lib/auth/device-store", () => ({ isApproved: async () => approved.value }));+const approved = vi.hoisted(() => ({ value: true, role: "owner" as "viewer" | "operator" | "owner" }));+vi.mock("@/lib/auth/device-store", () => ({+ getApprovedDevice: async () => approved.value+ ? { label: "test device", approvedAt: 1, role: approved.role }+ : null,+}));const TEMPLATE = "{id}.mso.rahmanef.com";@@ -52,6 +56,7 @@ describe("WebSocket upgrade on an app host", () => {vi.stubEnv("OS_SESSION_SECRET", SECRET);vi.stubEnv("OPENCLAW_DASHBOARD_URL", GATEWAY);approved.value = true;+ approved.role = "owner";return loadProxy(TEMPLATE);}@@ -62,6 +67,14 @@ describe("WebSocket upgrade on an app host", () => {expect(rewriteOf(res)).toBe(`${GATEWAY}/chat?tab=1`);});+ it("requires operator or owner for a managed-app upgrade", async () => {+ const proxy = await load();+ approved.role = "viewer";+ expect((await proxy(upgradeReq("openclaw.mso.rahmanef.com", "/chat", session()))).status).toBe(404);+ approved.role = "operator";+ expect(rewriteOf(await proxy(upgradeReq("openclaw.mso.rahmanef.com", "/chat", session())))).toBe(`${GATEWAY}/chat`);+ });+it("refuses an upgrade carrying no session — nothing downstream would have", async () => {const proxy = await load();const res = await proxy(upgradeReq("openclaw.mso.rahmanef.com"));@@ -183,6 +196,7 @@ describe("the Camoufox split-origin VNC bridge", () => {vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.rahmanef.com");vi.stubEnv("CAMOUFOX_NOVNC_URL", novnc);approved.value = true;+ approved.role = "owner";return loadProxy(TEMPLATE);}@@ -218,6 +232,14 @@ describe("the Camoufox split-origin VNC bridge", () => {expect(res.headers.get("referrer-policy")).toBe("no-referrer");});+ it("requires operator or owner for the live browser viewer", async () => {+ const proxy = await load();+ approved.role = "viewer";+ expect((await proxy(vnc(session()))).status).toBe(404);+ approved.role = "operator";+ expect(new URL(rewriteOf(await proxy(vnc(session())))!).origin).toBe(NOVNC);+ });+it("maps the viewer-host root to the full noVNC UI", async () => {const proxy = await load();expect(new URL(rewriteOf(await proxy(vnc(session(), "/")))!).pathname).toBe("/vnc.html");diff --git a/proxy.ts b/proxy.tsindex 243a0200..79e08644 100644--- a/proxy.ts+++ b/proxy.ts@@ -26,7 +26,8 @@ import { proxyPrefix, upstreamSocketHeaders } from "@/lib/managed-apps/proxy-heaimport { getManagedAppDefinition } from "@/lib/managed-apps/catalog";import { projectIngressDecision } from "@/lib/managed-apps/project-ingress";import { verifySession } from "@/lib/auth/session";-import { isApproved } from "@/lib/auth/device-store";+import { getApprovedDevice } from "@/lib/auth/device-store";+import { roleAtLeast, type DeviceRole } from "@/lib/auth/roles";import { IS_DEMO } from "@/lib/demo";import {camoufoxViewerCsp,@@ -58,13 +59,14 @@ const CAMOUFOX_NOVNC_URL = process.env.CAMOUFOX_NOVNC_URL ?? "http://127.0.0.1:6// same host can add a second one that sorts ahead of the real one; checking only the// first would let a forged value decide. Revocation is re-checked here too — a valid// HMAC alone must not outlive the device being removed.-async function hasApprovedSession(request: NextRequest): Promise<boolean> {+async function hasApprovedSession(request: NextRequest, minimumRole: DeviceRole = "viewer"): Promise<boolean> {if (IS_DEMO) return false;const secret = process.env.OS_SESSION_SECRET ?? "";for (const { value } of request.cookies.getAll(SESSION_COOKIE)) {const payload = verifySession(value, secret);if (!payload?.device_id) continue;- if (await isApproved(payload.device_id)) return true;+ const device = await getApprovedDevice(payload.device_id);+ if (device && roleAtLeast(device.role, minimumRole)) return true;}return false;}@@ -159,7 +161,7 @@ export async function proxy(request: NextRequest) {// loopback viewer; no cockpit route exists there. The Domain session cookie is// used solely at this edge gate and is stripped before noVNC receives the request.if (isCamoufoxViewerHost(host)) {- if (!(await hasApprovedSession(request))) return notFound();+ if (!(await hasApprovedSession(request, "operator"))) return notFound();if (request.method !== "GET" && request.method !== "HEAD") return notFound();let base: URL;try {@@ -232,7 +234,7 @@ export async function proxy(request: NextRequest) {// in feature-cli.ts. The query string is passed verbatim — Hermes' `?ticket=` is// that socket's entire credential.if (WEBSOCKET_UPGRADE.test(request.headers.get("upgrade") ?? "")) {- if (!(await hasApprovedSession(request))) return notFound();+ if (!(await hasApprovedSession(request, "operator"))) return notFound();const base = new URL(getManagedAppDefinition(managedApp).dashboardUrl);if (!LOOPBACK_HOST.test(base.hostname)) return notFound();return NextResponse.rewrite(new URL(`${pathname}${request.nextUrl.search}`, base), {diff --git a/scripts/approve-device-lock.test.ts b/scripts/approve-device-lock.test.tsindex 86156787..f50220d7 100644--- a/scripts/approve-device-lock.test.ts+++ b/scripts/approve-device-lock.test.ts@@ -1,4 +1,6 @@-import { readFileSync } from "node:fs";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { spawnSync } from "node:child_process";+import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";@@ -15,4 +17,23 @@ describe("approve-device cross-process lock protocol", () => {expect(acquire).toContain("return openExclusive(LOCK, token)");expect(source).not.toContain("function recoverAbandonedLock");});++ it("refuses approval as a role-change bypass for an existing device", () => {+ const root = mkdtempSync(path.join(os.tmpdir(), "mso-approve-role-"));+ const store = path.join(root, "devices.json");+ const device = "e".repeat(32);+ const run = (args: string[]) => spawnSync(process.execPath, [SCRIPT, ...args], {+ env: { ...process.env, OS_DEVICE_STORE: store }, encoding: "utf8",+ });+ try {+ expect(run([device, "owner laptop", "--role", "owner"]).status).toBe(0);+ const second = run([device, "same laptop", "--role", "viewer"]);+ expect(second.status).not.toBe(0);+ expect(second.stderr).toContain("already approved");+ const parsed = JSON.parse(readFileSync(store, "utf8"));+ expect(parsed.approved[device]).toMatchObject({ label: "owner laptop", role: "owner" });+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });});diff --git a/scripts/approve-device.js b/scripts/approve-device.jsindex 3bd2f990..78523a27 100755--- a/scripts/approve-device.js+++ b/scripts/approve-device.js@@ -2,7 +2,7 @@// Seed / list / revoke trusted login devices for mso (no Convex — flat JSON,// same model as the VPS Control Room).//-// node scripts/approve-device.js <deviceId> [label] # approve a device+// node scripts/approve-device.js <deviceId> [label] [--role viewer|operator|owner]// node scripts/approve-device.js --list # show approved + pending// node scripts/approve-device.js --revoke <deviceId> # un-trust a device//@@ -14,6 +14,7 @@ const os = require("os");const path = require("path");const { randomUUID } = require("crypto");const { spawnSync } = require("child_process");+const { DEVICE_ROLES, normalizeApproved, parseApprovalArgs, roleOf, setRoleResult } = require("./lib/device-role-cli");const STORE =process.env.OS_DEVICE_STORE || path.join(os.homedir(), ".mso", "auth-devices.json");@@ -22,7 +23,8 @@ const DEVICE_ID_RE = /^[a-f0-9-]{16,128}$/i;function read() {try {const p = JSON.parse(fs.readFileSync(STORE, "utf8"));- return { approved: p.approved || {}, pending: p.pending || {} };+ const approved = normalizeApproved(p.approved);+ return { approved, pending: p.pending || {} };} catch (error) {if (error && error.code === "ENOENT") return { approved: {}, pending: {} };throw error;@@ -132,7 +134,7 @@ const ts = (t) => (t ? new Date(t).toISOString() : "—");// Two ways to act on a device: copy the bare id (compose your own command), or// copy the whole line below it and paste it. JSON.stringify does the quoting, so// a label containing a quote or a space still pastes as ONE argument.-const approveCmd = (id, label) => ` mso device approve ${id} ${JSON.stringify(label || "my device")}`;+const approveCmd = (id, label) => ` mso device approve ${id} ${JSON.stringify(label || "my device")} --role viewer`;const revokeCmd = (id) => ` mso device revoke ${id}`;// A live VNC WebSocket has already passed its session check, so changing the@@ -154,7 +156,7 @@ function terminateCamoufoxSessions() {const listApproved = (ap) => {if (!ap.length) return void console.log(" (none)");for (const [id, d] of ap) {- console.log(` ${id} "${d.label}" approved=${ts(d.approvedAt)} lastSeen=${ts(d.lastSeen)}`);+ console.log(` ${id} "${d.label}" role=${roleOf(d)} approved=${ts(d.approvedAt)} lastSeen=${ts(d.lastSeen)}`);console.log(revokeCmd(id));}};@@ -184,6 +186,13 @@ if (args[0] === "--pending") {process.exit(0);}++if (args[0] === "--set-role") {+ const result = setRoleResult({ args, deviceIdRe: DEVICE_ID_RE, withMutation, read, write });+ for (const line of result.lines) (result.error ? console.error : console.log)(line);+ process.exit(result.code);+}+if (args[0] === "--revoke-all") {// Locks every browser out at once. Recoverable — approving is a local file// write that needs no session — but the confirmation is not optional, because@@ -240,23 +249,24 @@ if (args[0] === "--revoke") {process.exit(0);}-const id = args[0];-const label = args.slice(1).join(" ") || "seeded device";-if (!id || !DEVICE_ID_RE.test(id)) {- console.error("usage: approve-device.js <deviceId> [label] | --list | --revoke <id>");- console.error("deviceId must be 16-128 hex/uuid chars");+const { id, label, role } = parseApprovalArgs(args);+if (!id || !DEVICE_ID_RE.test(id) || !DEVICE_ROLES.has(role)) {+ console.error("usage: approve-device.js <deviceId> [label] [--role viewer|operator|owner] | --list | --set-role <id> <role> | --revoke <id>");+ console.error("deviceId must be 16-128 hex/uuid chars; role must be viewer, operator, or owner");process.exit(1);}-const approvedLabel = withMutation(() => {+const approved = withMutation(() => {const store = read();+ if (store.approved[id]) throw new Error("device is already approved; use --set-role");const pending = store.pending[id];store.approved[id] = {label: label !== "seeded device" ? label : (pending && pending.label) || label,approvedAt: Date.now(),+ role,};delete store.pending[id];write(store);- return store.approved[id].label;+ return store.approved[id];});-console.log(`approved ${id} "${approvedLabel}"`);+console.log(`approved ${id} "${approved.label}" role=${approved.role}`);console.log("-> that device can now sign in with the password.");diff --git a/scripts/device-role-cli.test.ts b/scripts/device-role-cli.test.tsnew file mode 100644index 00000000..76b272e3--- /dev/null+++ b/scripts/device-role-cli.test.ts@@ -0,0 +1,30 @@+import { createRequire } from "node:module";+import { describe, expect, it } from "vitest";++const require = createRequire(import.meta.url);+const { normalizeApproved, parseApprovalArgs, roleOf } = require("./lib/device-role-cli") as {+ normalizeApproved: (raw: unknown) => Record<string, { role: string }>;+ parseApprovalArgs: (args: string[]) => { id: string; label: string; role: string };+ roleOf: (entry: unknown) => string;+};++describe("local device role CLI helpers", () => {+ it("keeps legacy role-less approvals as owner but fails malformed roles down to viewer", () => {+ expect(roleOf({ label: "legacy" })).toBe("owner");+ expect(roleOf({ role: "operator" })).toBe("operator");+ expect(roleOf({ role: "admin" })).toBe("viewer");+ expect(normalizeApproved({ a: { label: "legacy" }, b: { role: "root" } })).toEqual({+ a: { label: "legacy", role: "owner" },+ b: { role: "viewer" },+ });+ });++ it("parses a quoted label independently from the explicit role option", () => {+ expect(parseApprovalArgs(["abc", "my phone", "--role", "viewer"])).toEqual({+ id: "abc", label: "my phone", role: "viewer",+ });+ expect(parseApprovalArgs(["abc", "recovery owner"])).toEqual({+ id: "abc", label: "recovery owner", role: "owner",+ });+ });+});diff --git a/scripts/gen-comparison.mjs b/scripts/gen-comparison.mjsnew file mode 100755index 00000000..a63b148a--- /dev/null+++ b/scripts/gen-comparison.mjs@@ -0,0 +1,150 @@+#!/usr/bin/env node+import fs from "node:fs";+import path from "node:path";+import process from "node:process";+import { fileURLToPath } from "node:url";++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+const dataPath = path.join(root, "docs/comparison-data.json");+const readmePath = path.join(root, "README.md");+const detailPath = path.join(root, "docs/COMPARISON.md");+const check = process.argv.includes("--check");+const allowedRatings = new Set(["strong", "partial", "none"]);+const officialHosts = new Set([+ "github.com",+ "cockpit-project.org",+ "coolify.io",+ "next.coolify.io",+ "docs.portainer.io",+ "learn.netdata.cloud",+ "tailscale.com",+ "runtipi.io"+]);++const data = JSON.parse(fs.readFileSync(dataPath, "utf8"));+const fail = (message) => { console.error(`comparison: ${message}`); process.exit(1); };+const escape = (value) => String(value).replaceAll("|", "\\|").replaceAll("\n", " ");++if (data.schemaVersion !== 1) fail("unsupported schemaVersion");+if (!Array.isArray(data.criteria) || !data.criteria.length) fail("criteria are required");+if (!Array.isArray(data.products) || !data.products.length) fail("products are required");+const reviewed = new Date(`${data.reviewedAt}T00:00:00Z`);+if (!Number.isFinite(reviewed.getTime())) fail("reviewedAt must be YYYY-MM-DD");+const ageDays = Math.floor((Date.now() - reviewed.getTime()) / 86_400_000);+if (ageDays < -1) fail("reviewedAt is in the future");+if (ageDays > data.expiresAfterDays) fail(`comparison review is ${ageDays} days old; refresh official sources and reviewedAt`);++const criteria = data.criteria.map((criterion) => criterion.id);+const productIds = new Set();+for (const product of data.products) {+ if (!product.id || productIds.has(product.id)) fail(`duplicate/missing product id: ${product.id}`);+ productIds.add(product.id);+ for (const criterion of criteria) {+ const rating = product.ratings?.[criterion];+ if (!rating || !allowedRatings.has(rating.value)) fail(`${product.id}.${criterion} has no valid rating`);+ if (product.id === "mso") {+ for (const evidence of rating.evidence ?? []) {+ if (path.isAbsolute(evidence) || evidence.includes("..") || !fs.existsSync(path.join(root, evidence))) {+ fail(`missing/unsafe MSO evidence: ${evidence}`);+ }+ }+ if (!(rating.evidence ?? []).length) fail(`MSO rating ${criterion} requires repository evidence`);+ }+ }+ if (!Array.isArray(product.sources) || !product.sources.length) fail(`${product.id} requires official sources`);+ for (const source of product.sources) {+ let url;+ try { url = new URL(source.url); } catch { fail(`${product.id} has invalid source URL`); }+ if (url.protocol !== "https:" || !officialHosts.has(url.hostname)) fail(`${product.id} source is not on an approved official host: ${source.url}`);+ }+}++const symbol = (value) => data.legend[value];+const tableHeader = `| Product | Best fit | ${data.criteria.map((criterion) => escape(criterion.label)).join(" | ")} |`;+const tableRule = `|---|---|${data.criteria.map(() => ":---:").join("|")}|`;+const tableRows = data.products.map((product) =>+ `| **${escape(product.name)}** | ${escape(product.bestFor)} | ${data.criteria.map((criterion) => symbol(product.ratings[criterion.id].value)).join(" | ")} |`+);+const compact = [+ `**Positioning:** ${data.positioning}`,+ "",+ `${data.legend.strong} strong · ${data.legend.partial} partial/scope-limited · ${data.legend.none} not a product surface`,+ "",+ tableHeader,+ tableRule,+ ...tableRows,+ "",+ `Reviewed against official product documentation on **${data.reviewedAt}**. Ratings describe product scope, not benchmark scores. See [methodology, evidence, and per-cell notes](docs/COMPARISON.md) and the [execution roadmap](docs/COMPETITIVE-ROADMAP.md).`,+].join("\n");++const start = "<!-- comparison:start -->";+const end = "<!-- comparison:end -->";+const readme = fs.readFileSync(readmePath, "utf8");+const startIndex = readme.indexOf(start);+const endIndex = readme.indexOf(end);+if (startIndex < 0 || endIndex < startIndex) fail("README comparison markers are missing");+const nextReadme = `${readme.slice(0, startIndex + start.length)}\n${compact}\n${readme.slice(endIndex)}`;++const details = [+ "<!-- Generated by scripts/gen-comparison.mjs from docs/comparison-data.json. Do not edit by hand. -->",+ "# Product comparison",+ "",+ `Last reviewed: **${data.reviewedAt}** · freshness gate: **${data.expiresAfterDays} days**`,+ "",+ data.positioning,+ "",+ "## Method",+ "",+ "- Ratings describe the documented product surface, not speed, popularity, or a universal winner.",+ "- `●` means a first-class strength, `◐` means partial or deliberately narrow scope, and `—` means it is not a meaningful product surface.",+ "- MSO cells must point to repository evidence that exists at build time.",+ "- Competitor claims use official project documentation only and must be manually re-reviewed before the freshness window expires.",+ "- Edition-dependent or adjacent capabilities are marked partial unless they are consistently core to the product.",+ "",+ "## Criteria",+ "",+ ...data.criteria.flatMap((criterion) => [`### ${criterion.label}`, "", criterion.definition, ""]),+ "## Matrix",+ "",+ tableHeader,+ tableRule,+ ...tableRows,+ "",+ "## Notes and evidence",+ "",+ ...data.products.flatMap((product) => [+ `### ${product.name}`,+ "",+ `**Best fit:** ${product.bestFor}`,+ "",+ ...data.criteria.flatMap((criterion) => {+ const rating = product.ratings[criterion.id];+ const evidence = (rating.evidence ?? []).length+ ? ` Evidence: ${(rating.evidence ?? []).map((entry) => `\`${entry}\``).join(", ")}.`+ : "";+ return [`- **${criterion.label} ${symbol(rating.value)}:** ${rating.note}${evidence}`];+ }),+ "",+ "Official sources:",+ ...product.sources.map((source) => `- [${source.label}](${source.url})`),+ "",+ ]),+ "## Interpretation",+ "",+ "MSO can lead its chosen category by integrating daily work that otherwise requires several tools: files, PTY, editors, service/package visibility, managed apps, device-scoped roles, AI, MCP, and CLI parity. It should not dilute that advantage by pretending to be a deeper Linux administrator than Cockpit, a broader PaaS than Coolify, a stronger container control plane than Portainer, a richer observability platform than Netdata, or a stronger identity network than Tailscale.",+ "",+].join("\n");++function writeOrCheck(file, next) {+ const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";+ if (check) {+ if (current !== next) fail(`${path.relative(root, file)} is stale; run node scripts/gen-comparison.mjs`);+ } else {+ fs.writeFileSync(file, next);+ console.log(`wrote ${path.relative(root, file)}`);+ }+}++writeOrCheck(readmePath, nextReadme);+writeOrCheck(detailPath, details);+if (check) console.log(`comparison: current — ${data.products.length} products, ${data.criteria.length} criteria, reviewed ${data.reviewedAt}`);diff --git a/scripts/lib/device-role-cli.js b/scripts/lib/device-role-cli.jsnew file mode 100644index 00000000..a80b61c6--- /dev/null+++ b/scripts/lib/device-role-cli.js@@ -0,0 +1,55 @@+"use strict";++const DEVICE_ROLES = new Set(["viewer", "operator", "owner"]);++function roleOf(entry) {+ if (!entry || typeof entry !== "object") return "viewer";+ if (entry.role === undefined) return "owner"; // legacy approved device+ return DEVICE_ROLES.has(entry.role) ? entry.role : "viewer";+}++function normalizeApproved(raw) {+ const approved = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};+ for (const entry of Object.values(approved)) {+ if (entry && typeof entry === "object") entry.role = roleOf(entry);+ }+ return approved;+}++function parseApprovalArgs(args) {+ const id = args[0];+ let role = "owner";+ const labelParts = [];+ for (let index = 1; index < args.length; index += 1) {+ if (args[index] === "--role") {+ role = args[index + 1] || "";+ index += 1;+ } else labelParts.push(args[index]);+ }+ return { id, role, label: labelParts.join(" ") || "seeded device" };+}++function setRoleResult({ args, deviceIdRe, withMutation, read, write }) {+ const id = args[1];+ const role = args[2];+ if (!id || !deviceIdRe.test(id) || !DEVICE_ROLES.has(role)) {+ return { code: 1, error: true, lines: ["usage: --set-role <deviceId> <viewer|operator|owner>"] };+ }+ const result = withMutation(() => {+ const store = read();+ const entry = store.approved[id];+ if (!entry) return null;+ const owners = Object.values(store.approved).filter((device) => roleOf(device) === "owner").length;+ if (roleOf(entry) === "owner" && role !== "owner" && owners <= 1) {+ throw new Error("at least one owner device must remain approved");+ }+ entry.role = role;+ write(store);+ return { label: entry.label, role };+ });+ return result+ ? { code: 0, error: false, lines: [`updated ${id} "${result.label}" role=${result.role}`] }+ : { code: 1, error: true, lines: [`not approved: ${id}`] };+}++module.exports = { DEVICE_ROLES, normalizeApproved, parseApprovalArgs, roleOf, setRoleResult };diff --git a/vitest.config.mts b/vitest.config.mtsindex ba7d4531..0627e046 100644--- a/vitest.config.mts+++ b/vitest.config.mts@@ -28,7 +28,7 @@ export default defineConfig({"frontend/slices/**/*.test.{ts,tsx}","lib/**/*.test.{ts,tsx}","bin/**/*.test.{ts,tsx}",- "scripts/e2e/**/*.test.{ts,tsx}",+ "scripts/**/*.test.{ts,tsx}","instrumentation.test.ts",// Root-level modules Next requires by name (middleware is `proxy.ts` in 16),// so their tests are colocated at the root and named one by one. NAMED, not