Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(update): remove passwordless sudo requirement

Rahmana9b932f118f0
diff --git a/README.md b/README.md
index 15dfde44..cfc5b9da 100644
--- a/README.md
+++ b/README.md
@@ -52,7 +52,7 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
- **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.
-- **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. Same thing from a shell: `mso update run`.
+- **Update itself** — Settings → About shows what is on `origin/main`, lists the incoming commits, and runs the whole deploy (pull → verify the build out-of-tree → build → restart) from a button. The verification runs first on purpose: a commit that does not compile becomes a refusal, not an outage. The updater runs in the owner's systemd user manager and does not require passwordless sudo. Same thing from a shell: `mso update 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), driven through their own CLIs and systemd units. Each app's own dashboard opens in a window; give each one its own hostname and it is served from its own origin (opt-in, two env vars). See [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md).
**Work** — code/text editor, browser, and media tools in the same workspace.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 3a946467..bce42e81 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -8,6 +8,34 @@ Running log of what shipped each phase. Newest at top.
> Read those phases as history. **This file is the source of truth for what exists** —
> `ARCHITECTURE.md` is no longer maintained and carries a stale-warning banner.
+## 2026-08-19 — v0.2.1: self-update stopped assuming passwordless sudo (DONE)
+
+A real 0.2.0 installation exposed the gap: Settings found the incoming commits, but
+pressing Update failed immediately with `sudo: a password is required`. Nothing had
+been pulled or built, so the running copy stayed safe; the button was nevertheless
+unusable on an ordinary VPS account. The installer never created a passwordless
+sudo rule — correctly — while `startUpdate()` had silently required one.
+
+The updater is non-root now. `startUpdate()` launches an owner-scoped transient unit
+with `systemd-run --user`, which gives the build its own cgroup so it survives
+replacing `mso.service`. At the end, the script reads the service's `MainPID`, proves
+that PID belongs to the same uid as the updater, sends it `SIGTERM`, and waits for a
+new active PID. The installed system unit's existing `Restart=always` starts the
+fresh build; no sudo credential or broad sudoers exception is needed.
+
+The preflight also refuses clearly when the per-user systemd manager is unavailable,
+when `mso.service` is missing, or when the service belongs to another user. The
+installer now starts `[email protected]` after enabling linger and verifies that the
+user bus answers, so a fresh install can use the update button immediately. Argument
+construction has regression tests that explicitly reject `sudo` and a root-capable
+`User=` property. Typecheck, lint, the architecture/contrast checks, dependency audit,
+and the full 1,336-test coverage suite passed before release; the final rebuild-only
+path was exercised against the live service and ended in `UPDATE OK`.
+
+Existing 0.2.0 installations need one interactive installer run to receive this fix,
+because the broken updater cannot bootstrap its own replacement. After that one-time
+migration, future Settings updates run without a sudo prompt.
+
## 2026-08-17 (audit) — a codebase pass: what was duplicated, what had drifted, what was undefended (DONE)
Not a UI pass. Scanned for dead exports, parallel implementations, unguarded
@@ -102,12 +130,14 @@ deploy.
Three things about it are load-bearing:
-- **The work does not run in `mso.service`.** Its last step is `systemctl restart
- mso.service`, and systemd's default KillMode kills the whole cgroup — a detached
- child included. It would die mid-`next build`, with `.next` already deleted (the
- build's first act) and nothing to restart into. So `startUpdate()` hands the job to
- a TRANSIENT unit via `sudo systemd-run --collect --unit=mso-self-update`, which
- lives in its own cgroup and survives the restart it performs.
+- **The work does not run in `mso.service`.** Replacing that service makes systemd
+ kill its whole cgroup — a detached child included. It would die mid-`next build`,
+ with `.next` already deleted and nothing to restart into. `startUpdate()` now hands
+ the job to the owner's TRANSIENT user unit via `systemd-run --user`; that separate
+ cgroup survives while the script signals the same-uid service PID and lets
+ `Restart=always` bring MSO back. The original 0.2.0 implementation used a system
+ transient unit through `sudo -n`, which failed on normal password-protected sudo
+ accounts and was replaced in 0.2.1.
- **It verifies out-of-tree BEFORE building in place.** `scripts/ship.sh` is run by a
person who is watching; this is run by an operator who pressed a button and walked
away. `scripts/verify-build.sh` proves the pulled HEAD compiles without touching
diff --git a/lib/host/self-update.test.ts b/lib/host/self-update.test.ts
index 37ade5a5..1a170d05 100644
--- a/lib/host/self-update.test.ts
+++ b/lib/host/self-update.test.ts
@@ -7,7 +7,7 @@ import { describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
-const { parseCommits, blockingReason } = await import("./self-update");
+const { parseCommits, blockingReason, updateUnitArgs } = await import("./self-update");
const status = (over: Partial<Parameters<typeof blockingReason>[0]> = {}) => ({
supported: true,
@@ -47,6 +47,25 @@ describe("parseCommits", () => {
});
});
+describe("updateUnitArgs", () => {
+ it("runs in the owner's user manager without sudo or a root User property", () => {
+ const args = updateUnitArgs("/srv/mso", "/home/alice/.mso/self-update.log");
+
+ expect(args.slice(0, 2)).toEqual(["--user", "--collect"]);
+ expect(args).toContain("--unit=mso-self-update");
+ expect(args).toContain("--property=WorkingDirectory=/srv/mso");
+ expect(args).toContain("/srv/mso/scripts/self-update.sh");
+ expect(args).not.toContain("--rebuild-only");
+ expect(args.some((arg) => arg.startsWith("--property=User="))).toBe(false);
+ expect(args.join(" ")).not.toContain("sudo");
+ });
+
+ it("exposes only the rebuild boolean as the optional operation", () => {
+ const args = updateUnitArgs("/srv/mso", "/tmp/update.log", true);
+ expect(args.at(-1)).toBe("--rebuild-only");
+ });
+});
+
describe("blockingReason", () => {
it("lets a normal update through", () => {
expect(blockingReason(status(), false)).toBeNull();
diff --git a/lib/host/self-update.ts b/lib/host/self-update.ts
index 6416fc7c..84e458c4 100644
--- a/lib/host/self-update.ts
+++ b/lib/host/self-update.ts
@@ -14,12 +14,13 @@ import { HostError } from "./host-error";
// it a button.
//
// THE UPDATE DOES NOT RUN IN THIS PROCESS, and that is not a style choice: the last
-// step is `systemctl restart mso.service`, and systemd's default KillMode kills
-// everything in the unit's cgroup — including a child we spawned. A detached child
-// is still in that cgroup, so it would be killed mid-`next build`, with `.next`
-// already deleted (the build's first act) and nothing to restart into. So the work
-// is handed to a TRANSIENT unit via `systemd-run`, which lives in its own cgroup and
-// survives the restart it performs.
+// step replaces the process serving MSO, and systemd's default KillMode kills every
+// child in mso.service's cgroup. A detached child is still in that cgroup, so it
+// would die mid-`next build`, with `.next` already deleted and nothing to restart
+// into. The job is therefore handed to the OWNER'S transient user unit via
+// `systemd-run --user`. That gives it a separate cgroup without granting the web app
+// passwordless root. At the end the updater signals mso.service's same-UID MainPID;
+// Restart=always brings the system unit back on the freshly-built checkout.
const UNIT = "mso-self-update";
const LOG_TAIL = 12_000;
const GIT_TIMEOUT_MS = 20_000;
@@ -63,6 +64,25 @@ export const updateLogPath = (): string => {
const repoRoot = (): string => process.cwd();
+/** Arguments are pure/testable because this boundary is security-sensitive: the
+ * request may choose only update vs rebuild. No path, command, ref, or root-capable
+ * argument comes from the client. */
+export function updateUnitArgs(root: string, logPath: string, rebuildOnly = false): string[] {
+ return [
+ "--user",
+ "--collect",
+ `--unit=${UNIT}`,
+ `--property=WorkingDirectory=${root}`,
+ // A build on a small VPS is minutes, not seconds; the default 90s start
+ // timeout would kill it exactly at the point of no return.
+ "--property=TimeoutStartSec=3600",
+ `--setenv=MSO_UPDATE_LOG=${logPath}`,
+ "/bin/bash",
+ path.join(root, "scripts", "self-update.sh"),
+ ...(rebuildOnly ? ["--rebuild-only"] : []),
+ ];
+}
+
interface Ran {
code: number;
stdout: string;
@@ -122,9 +142,13 @@ export function blockingReason(status: UpdateStatus, rebuildOnly: boolean): stri
async function isRunning(): Promise<boolean> {
// `is-active` on a transient unit that has been collected exits non-zero, which
// is the same answer as "never ran" — both mean "not running", so the code is
- // all we need here.
- const result = await run("systemctl", ["is-active", `${UNIT}.service`], 10_000);
- return result.code === 0;
+ // all we need here. Check the old system-unit location too while installations
+ // migrate from the pre-0.2.1 sudo-based updater.
+ const [userUnit, legacySystemUnit] = await Promise.all([
+ run("systemctl", ["--user", "is-active", `${UNIT}.service`], 10_000),
+ run("systemctl", ["is-active", `${UNIT}.service`], 10_000),
+ ]);
+ return userUnit.code === 0 || legacySystemUnit.code === 0;
}
async function readLog(): Promise<string> {
@@ -161,6 +185,40 @@ export async function getUpdateStatus(fetchRemote = true): Promise<UpdateStatus>
return { ...base, reason: "this deployment is not a git checkout, so there is nothing to pull" };
}
+ // The installer enables linger and gives mso.service XDG_RUNTIME_DIR precisely
+ // so the service can reach this per-user manager. Unlike the old sudo path, this
+ // is both non-interactive and non-root.
+ const userManager = await run("systemctl", ["--user", "show-environment"], 10_000);
+ if (userManager.code !== 0) {
+ return {
+ ...base,
+ reason:
+ "the per-user systemd manager is unavailable — re-run scripts/install.sh once to restore linger and the user bus",
+ };
+ }
+
+ const [loadState, serviceUser, restartPolicy] = await Promise.all([
+ run("systemctl", ["show", "-p", "LoadState", "--value", "mso.service"], 10_000),
+ run("systemctl", ["show", "-p", "User", "--value", "mso.service"], 10_000),
+ run("systemctl", ["show", "-p", "Restart", "--value", "mso.service"], 10_000),
+ ]);
+ if (loadState.code !== 0 || loadState.stdout.trim() !== "loaded") {
+ return { ...base, reason: "mso.service is not installed as a systemd service, so it cannot safely restart itself" };
+ }
+ if (restartPolicy.code !== 0 || restartPolicy.stdout.trim() === "no") {
+ return {
+ ...base,
+ reason: "mso.service has no automatic restart policy; refusing to stop the running process during self-update",
+ };
+ }
+ const owner = os.userInfo().username;
+ if (serviceUser.code !== 0 || serviceUser.stdout.trim() !== owner) {
+ return {
+ ...base,
+ reason: `mso.service runs as ${serviceUser.stdout.trim() || "an unknown user"}, not ${owner}; refusing a cross-user update`,
+ };
+ }
+
const running = await isRunning();
const [head, subject, status] = await Promise.all([
git(["rev-parse", "--short", "HEAD"]),
@@ -214,29 +272,13 @@ export async function startUpdate(rebuildOnly = false): Promise<UpdateStatus> {
if (!(await fs.stat(script).catch(() => null))) throw new HostError(`missing ${script}`);
const started = await run(
- "sudo",
- [
- "-n",
- "systemd-run",
- "--collect",
- `--unit=${UNIT}`,
- `--property=User=${os.userInfo().username}`,
- `--property=WorkingDirectory=${repoRoot()}`,
- // A build on a small VPS is minutes, not seconds; the default 90s start
- // timeout would kill it exactly at the point of no return.
- "--property=TimeoutStartSec=3600",
- `--setenv=MSO_UPDATE_LOG=${updateLogPath()}`,
- "/bin/bash",
- script,
- ...(rebuildOnly ? ["--rebuild-only"] : []),
- ],
+ "systemd-run",
+ updateUnitArgs(repoRoot(), updateLogPath(), rebuildOnly),
30_000,
);
if (started.code !== 0) {
- // The common causes are both fixable and neither is obvious from "exit 1":
- // no passwordless sudo, or no systemd-run on the host.
throw new HostError(
- `could not start the updater: ${(started.stderr || started.stdout).trim().slice(0, 300) || `exit ${started.code}`}`,
+ `could not start the updater: ${(started.stderr || started.stdout).trim().slice(0, 300) || `exit ${started.code}`}. Re-run scripts/install.sh once if the user systemd manager is unavailable`,
);
}
return { ...status, running: true };
diff --git a/package.json b/package.json
index 954d790a..7a698942 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "mso",
- "version": "0.2.0",
+ "version": "0.2.1",
"private": true,
"engines": {
"node": ">=20.9"
diff --git a/scripts/install.sh b/scripts/install.sh
index 93972e6d..6b6807ff 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -297,7 +297,15 @@ EOF
# Idempotent; failure is not fatal, it only means managed-app installs will say
# so plainly when they preflight the bus.
sudo_do loginctl enable-linger "$(id -un)" >/dev/null 2>&1 \
- || warn "could not enable linger for $(id -un) — managed-app installs may not be able to create user services"
+ || warn "could not enable linger for $(id -un) — self-update and managed-app user services may stop after logout"
+ # `enable-linger` makes the manager persistent, but some minimal images do not
+ # start [email protected] until the next login. Start it now so the first update
+ # button works immediately, then prove the bus MSO will use actually answers.
+ sudo_do systemctl start "user@$(id -u).service" >/dev/null 2>&1 \
+ || warn "could not start the per-user systemd manager — self-update may be unavailable"
+ if ! XDG_RUNTIME_DIR="/run/user/$(id -u)" systemctl --user show-environment >/dev/null 2>&1; then
+ warn "per-user systemd bus is unavailable — self-update and managed-app services will not work until user@$(id -u).service is running"
+ fi
sudo_do systemctl daemon-reload
sudo_do systemctl enable "$SERVICE"
diff --git a/scripts/self-update.sh b/scripts/self-update.sh
index 5b30029b..59e88102 100755
--- a/scripts/self-update.sh
+++ b/scripts/self-update.sh
@@ -2,9 +2,10 @@
# self-update.sh — pull main, prove it compiles, build, restart. The body of the
# Settings → About update button.
#
-# RUN BY systemd-run, NOT by mso.service (lib/host/self-update.ts explains why: the
-# last step restarts mso.service, and systemd kills the whole cgroup — a child of the
-# service would die mid-build with .next already deleted).
+# RUN BY systemd-run --user, NOT by mso.service (lib/host/self-update.ts explains
+# why: replacing mso.service kills that service's whole cgroup, so an updater child
+# would die mid-build with .next already deleted). The user unit survives, signals
+# mso.service's same-UID MainPID, and Restart=always starts the freshly-built app.
#
# Order is the same load-bearing order as scripts/ship.sh, with ONE addition: the
# out-of-tree verification. ship.sh is run by a human who is watching; this is run by
@@ -58,15 +59,59 @@ bash scripts/verify-build.sh >/dev/null || die "HEAD does not compile — nothin
step "building in place"
bun run build >/dev/null || die "build failed after it had already passed out-of-tree — check disk space"
-step "restarting mso.service"
-sudo -n systemctl restart mso.service || die "could not restart mso.service"
-sleep 4
+step "restarting mso.service (same-user signal; no sudo)"
+# mso.service runs as the owner and has Restart=always. Signalling its MainPID is
+# therefore the least-privilege equivalent of `systemctl restart`: systemd cleans
+# the rest of that service cgroup and starts it again, while this updater lives in a
+# separate USER-manager cgroup and survives. Verify the uid before signalling so a
+# hand-edited unit can never turn this into a cross-user kill.
+RESTART_POLICY="$(systemctl show -p Restart --value mso.service 2>/dev/null || true)"
+[ -n "$RESTART_POLICY" ] && [ "$RESTART_POLICY" != "no" ] \
+ || die "mso.service has no automatic restart policy"
+OLD_PID="$(systemctl show -p MainPID --value mso.service 2>/dev/null || true)"
+case "$OLD_PID" in
+ ""|*[!0-9]*) die "could not read mso.service MainPID" ;;
+esac
+[ "$OLD_PID" -gt 1 ] || die "mso.service has no running MainPID"
+SELF_UID="$(id -u)"
+PID_UID="$(stat -c %u "/proc/$OLD_PID" 2>/dev/null || true)"
+[ "$PID_UID" = "$SELF_UID" ] || die "mso.service MainPID $OLD_PID belongs to uid ${PID_UID:-unknown}, not $SELF_UID"
+kill -TERM "$OLD_PID" || die "could not signal mso.service MainPID $OLD_PID"
+
+NEW_PID=""
+for _ in $(seq 1 40); do
+ CANDIDATE="$(systemctl show -p MainPID --value mso.service 2>/dev/null || true)"
+ case "$CANDIDATE" in
+ ""|*[!0-9]*) ;;
+ *)
+ if [ "$CANDIDATE" -gt 1 ] && [ "$CANDIDATE" != "$OLD_PID" ] && systemctl is-active --quiet mso.service; then
+ NEW_PID="$CANDIDATE"
+ break
+ fi
+ ;;
+ esac
+ sleep 1
+done
+[ -n "$NEW_PID" ] || die "mso.service did not come back with a new MainPID"
+printf 'restarted %s -> %s\n' "$OLD_PID" "$NEW_PID"
# The chunk-mismatch check CLAUDE.md warns about, verified rather than remembered —
-# the same check scripts/ship.sh ends with. If the HTML references a chunk the
-# restarted process does not serve, every asset 404s and the UI comes up unstyled.
-PORT="${PORT:-4005}"
-CSS=$(curl -fsS --max-time 10 "http://127.0.0.1:$PORT/" | grep -o '/_next/static/[^"]*\.css' | head -1)
+# the same check scripts/ship.sh ends with. `active` only means npm has started, not
+# that Next is already accepting connections, so wait for real HTML before checking
+# its referenced CSS chunk.
+# The user transient unit intentionally does not inherit arbitrary service env.
+# Read the fixed numeric PORT from the installed unit instead; fall back to the
+# installer's default for older or hand-written units.
+SERVICE_PORT="$(systemctl show -p Environment --value mso.service 2>/dev/null \
+ | tr ' ' '\n' | sed -n 's/^PORT=//p' | head -1)"
+PORT="${PORT:-${SERVICE_PORT:-4005}}"
+HTML=""
+for _ in $(seq 1 30); do
+ HTML="$(curl -fsS --max-time 3 "http://127.0.0.1:$PORT/" 2>/dev/null || true)"
+ [ -n "$HTML" ] && break
+ sleep 1
+done
+CSS=$(printf '%s' "$HTML" | grep -o '/_next/static/[^"]*\.css' | head -1)
if [ -z "$CSS" ]; then
die "no CSS reference in the served HTML — recover with: rm -rf .next && bun run build && sudo systemctl restart mso.service"
fi