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
fix(security): close 3 of 4 rm -rf bypasses, and stop a corrupt file wiping the device allowlist
Rahman6482d0e20337
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 6505861b..5c587b44 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -8,6 +8,56 @@ 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-03 (later) — the two open items closed, and the health lens finds a silent way to lose the device allowlist (DONE)++Clearing both items the entry below left open.++**Three of the four `rm -rf /` bypasses are closed.** The patterns anchor the catastrophic+argument on `\s`, `$` or `*`, so a `/` followed by `;`, `)` or `"` walked straight past them.+Rather than widen each regex — which leaks a new way in for every character you forget —+`matchDestructive` now splits the command on shell separators (`[;&|()"'\`\n]+`) and tests+each segment, so `echo hi; rm -rf /`, `(rm -rf /) &`, `bash -c "rm -rf /"` and+`echo $(rm -rf /)` all land on a segment where the trailing `/` sits at end-of-string.+**Ordering inside that function is load-bearing and pinned by a test:** the whole string is+tested BEFORE the segments, because the fork-bomb pattern is built out of `(){}|&;:` — the+very characters being split on — so segment-only testing would silently stop detecting it.++The fourth (`HOME=/ rm -rf "$HOME"`) stays an `it.fails()`: the destructive argument only+exists after the shell expands the variable, which no static filter can see. Expected-fails+went 4 → 1 and the suite turns red if that ever starts being caught.++Accepted cost, pinned as its own test: quoted prose is now refused too —+`git commit -m "never run rm -rf / on prod"` is indistinguishable from+`bash -c "rm -rf /"` except by program name. Erring toward refusal; the escape hatch is+`OS_EXEC_ALLOW_DESTRUCTIVE=1`. Ordinary commands (`ls -la /`, `cd / && ls`, `find / -name x`,+`systemctl status mso`) were checked and still pass.++**The health lens (the one that died) found a real data-loss path.**+`lib/auth/device-store.ts`'s `read()` returned an empty store for EVERY failure — and it+feeds a read-modify-write whose callers `recordPending` and `approveDevice` write+unconditionally. So one unparseable byte in `~/.mso/auth-devices.json` meant the next login+attempt from an unapproved device read "no devices", then **persisted that** — wiping every+approved device and locking the owner out of their own host. `recordPending` is reachable+from the internet by anyone holding the password. Now only `ENOENT` (legit first run) yields+an empty store; corrupt JSON or EACCES throws. Costs a 500 on login; the old behaviour cost+the allowlist. `device-store.test.ts` is new (it had none) and its two key cases were+verified to fail against the old code.++**`lib/host/fs-upload.ts` had zero tests** despite being a write boundary behind+`/api/v1/fs/upload`. `fs-upload.test.ts` now pins the two things that matter: a part cannot+escape the destination (parent/deep/mid-path traversal, absolute paths, segment-only inputs)+and the 100 MiB cap stops bytes reaching disk, leaving no `.tmp` behind.++**The rest of the health lens came back clean**, and it is worth recording so nobody re-runs+it: 1 `@ts-expect-error` in total (in a test, justified), **zero** real `any` in non-test code,+1 empty `catch` (the inline theme script in `app/layout.tsx`, where a corrupt localStorage+must not block render), and 21 files with `eslint-disable` — all narrow, single-rule, and+carrying a reason. No secret has ever been committed: the two `OS_SESSION_SECRET=` hits in+git history are `$(openssl …)`, `$SECRET` and a regex, not values. `exec.ts` is NOT untested+as a filename scan suggests — `exec-filter.test.ts` covers it.++1136 tests / 115 files (was 1115 / 113).+## 2026-08-03 — pnpm→bun, a 5-lens audit, and the gates that were never actually gating (DONE)Four commits: `268747f` (bun + audit fixes), `844eef3` (−836 lines), `674455b` (dependency@@ -107,6 +157,7 @@ the deleted `check-slices.mjs` line, which would block every push.human-approval-gated and an authenticated owner has full shell anyway, so this degrades theDANGER badge rather than being RCE — but a regex over shell strings is the wrong shape; the fixis to split on shell metacharacters and check each segment. (2) The repo-health lens above.+→ **Both closed the same day; see the entry above this one.**## 2026-07-30 — v0.2.0: Alfa can act on the host, and a release gate that found four reasons it should not ship yet (DONE)diff --git a/lib/auth/device-store.test.ts b/lib/auth/device-store.test.tsnew file mode 100644index 00000000..aface498--- /dev/null+++ b/lib/auth/device-store.test.ts@@ -0,0 +1,75 @@+import { promises as fs } from "fs";+import os from "os";+import path from "path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// STORE_PATH is read at module load from OS_DEVICE_STORE, so each case points it at+// a fresh temp file and re-imports the module.+let dir: string;+let store: string;++async function load() {+ vi.resetModules();+ vi.stubEnv("OS_DEVICE_STORE", store);+ return import("./device-store");+}++beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-devstore-"));+ store = path.join(dir, "auth-devices.json");+});++afterEach(async () => {+ vi.unstubAllEnvs();+ await fs.rm(dir, { recursive: true, force: true });+});++const DEV = "a".repeat(32);+const OTHER = "b".repeat(32);++describe("device-store — an unreadable file must never look like an empty one", () => {+ it("treats a MISSING file as an empty store (legit first run)", async () => {+ const { listDevices } = await load();+ await expect(listDevices()).resolves.toEqual({ approved: {}, pending: {} });+ });++ it("THROWS on corrupt JSON instead of reporting an empty store", async () => {+ await fs.writeFile(store, "{ this is not json");+ const { listDevices } = await load();+ await expect(listDevices()).rejects.toThrow();+ });++ // The regression this file exists for. read() feeds a read-modify-write, and+ // recordPending writes unconditionally — so while read() swallowed every error,+ // one unparseable byte plus a single login attempt from an unapproved device+ // silently replaced the whole allowlist with {}, locking the owner out. That path+ // is reachable from the internet by anyone holding the password.+ it("does not WIPE approved devices when the file is corrupt", async () => {+ await fs.writeFile(store, "{ corrupt");+ const { recordPending } = await load();++ await expect(recordPending(OTHER, "attacker", "203.0.113.1")).rejects.toThrow();++ // The corrupt bytes must still be there — NOT overwritten with an empty store.+ expect(await fs.readFile(store, "utf8")).toBe("{ corrupt");+ });++ it("still records a pending device normally when the file is readable", async () => {+ const { approveDevice, recordPending, listDevices, isApproved } = await load();+ await approveDevice(DEV, "my laptop");+ await recordPending(OTHER, "new phone", "203.0.113.2");++ const s = await listDevices();+ expect(Object.keys(s.approved)).toEqual([DEV]); // survived the second write+ expect(s.pending[OTHER].ip).toBe("203.0.113.2");+ await expect(isApproved(DEV)).resolves.toBe(true);+ await expect(isApproved(OTHER)).resolves.toBe(false);+ });++ it("writes the store 0600 inside a 0700 dir", async () => {+ const { approveDevice } = await load();+ await approveDevice(DEV, "my laptop");+ expect((await fs.stat(store)).mode & 0o777).toBe(0o600);+ expect((await fs.stat(path.dirname(store))).mode & 0o777).toBe(0o700);+ });+});diff --git a/lib/auth/device-store.ts b/lib/auth/device-store.tsindex 6c8adbf9..1f5c1293 100644--- a/lib/auth/device-store.ts+++ b/lib/auth/device-store.ts@@ -41,13 +41,26 @@ export function isValidDeviceId(id: unknown): id is string {return typeof id === "string" && DEVICE_ID_RE.test(id);}+// "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.async function read(): Promise<DeviceStore> {+ let raw: string;try {- const parsed = JSON.parse(await fs.readFile(STORE_PATH, "utf8")) as Partial<DeviceStore>;- return { approved: parsed.approved ?? {}, pending: parsed.pending ?? {} };- } catch {- return { approved: {}, pending: {} };+ raw = await fs.readFile(STORE_PATH, "utf8");+ } catch (e) {+ 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 ?? {} };}async function write(store: DeviceStore): Promise<void> {diff --git a/lib/host/destructive-patterns.ts b/lib/host/destructive-patterns.tsindex e2abfd21..ddfe2285 100644--- a/lib/host/destructive-patterns.ts+++ b/lib/host/destructive-patterns.ts@@ -23,9 +23,27 @@ export const DESTRUCTIVE: { re: RegExp; why: string }[] = [{ re: /\bkill\s+(?:-(?:9|KILL|SIGKILL)\s+)?1(?:\s|$)/, why: "kill PID 1" },];+// Shell metacharacters that start a new command, open a subshell, or open/close a+// quoted string. The patterns above anchor the catastrophic argument on `\s`, `$` or+// `*`, so a `/` followed by `;`, `)` or `"` used to slip straight past them:+// echo hi; rm -rf /; echo bye `/` then `;`+// (rm -rf /) & `/` then `)`+// bash -c "rm -rf /" `/` then `"`+// Splitting on these puts each command on its own, where the trailing `/` lands at+// end-of-segment and the existing patterns can see it. Widening every regex instead+// was the alternative and is the wrong shape — a regex over a shell string leaks a+// new way in for every character you forget.+const SEPARATORS = /[;&|()"'`\n]+/;+// The reason a command matches the denylist, or null. Pure (no env override —// that's exec.ts's job); safe to call from the browser.export function matchDestructive(cmd: string): string | null {- for (const d of DESTRUCTIVE) if (d.re.test(cmd)) return d.why;+ // WHOLE STRING FIRST, and it must stay first: the fork-bomb pattern is built out+ // of `(){}|&;:` — the very characters SEPARATORS splits on — so testing only the+ // segments would stop detecting it.+ for (const part of [cmd, ...cmd.split(SEPARATORS)]) {+ if (!part) continue;+ for (const d of DESTRUCTIVE) if (d.re.test(part)) return d.why;+ }return null;}diff --git a/lib/host/exec-filter.test.ts b/lib/host/exec-filter.test.tsindex 5b967d34..7c85f726 100644--- a/lib/host/exec-filter.test.ts+++ b/lib/host/exec-filter.test.ts@@ -96,24 +96,46 @@ describe("destructiveReason — adversarial encodings", () => {expect(destructiveReason("\\rm -rf /")).toMatch(/rm -rf on \//);});- // KNOWN GAPS — documented so the next hardening pass knows where to focus.- // These slip past the current regex set. Not catastrophic in isolation- // because the cockpit is owner-only AND the operator must be aware enough- // to wrap a destructive cmd in shell trickery — but real polish targets.- // Each `it.fails` PASSES the suite when the assertion fails (Vitest spec),- // so when these are fixed the suite turns RED — a built-in regression alarm.- it.fails("GAP: chained `;` form — `/` followed by `;` slips past `\\/(?:\\s|$|\\*)`", () => {+ // These three were `it.fails()` GAPs until 2026-08-03. matchDestructive now splits+ // the command on shell separators and tests each segment, so a `/` followed by+ // `;`, `)` or `"` no longer hides the argument from patterns anchored on \s|$|\*.+ it("blocks the chained `;` form", () => {expect(destructiveReason("echo hi; rm -rf /; echo bye")).toMatch(/rm -rf on \//);});- it.fails("GAP: subshell form — `/` followed by `)` slips past `\\/(?:\\s|$|\\*)`", () => {+ it("blocks the subshell form", () => {expect(destructiveReason("(rm -rf /) &")).toMatch(/rm -rf on \//);});- it.fails("GAP: `bash -c \"rm -rf /\"` — `/` followed by `\"` slips past", () => {+ it("blocks `bash -c \"rm -rf /\"` (quoted payload)", () => {expect(destructiveReason('bash -c "rm -rf /"')).toMatch(/rm -rf on \//);});+ it("blocks a command-substitution payload", () => {+ expect(destructiveReason("echo $(rm -rf /)")).toMatch(/rm -rf on \//);+ });++ it("still detects the fork bomb, which is BUILT from the separator characters", () => {+ // Regression pin for the ordering inside matchDestructive: this pattern spans+ // `(){}|&;:`, so it only survives because the WHOLE string is tested before the+ // split segments. Test segments alone and this silently stops matching.+ expect(destructiveReason(":(){ :|:& };:")).toMatch(/fork bomb/);+ });++ it("ACCEPTED FALSE POSITIVE: refuses a destructive string inside quoted prose", () => {+ // The cost of segment-splitting: a quoted mention is indistinguishable from a+ // quoted payload, because `bash -c "rm -rf /"` and `git commit -m "rm -rf /"`+ // differ only in the program name. Deliberately erring toward refusal — the+ // escape hatch is OS_EXEC_ALLOW_DESTRUCTIVE=1, and the failure mode is an+ // annoying refusal rather than a wiped disk. Pinned so the trade is a decision+ // rather than a surprise.+ expect(destructiveReason('git commit -m "never run rm -rf / on prod"')).toMatch(/rm -rf on \//);+ });++ // REMAINING GAP, and not fixable by a static filter: the destructive argument+ // only exists after the shell expands the variable. `it.fails` PASSES while the+ // assertion fails, so this turns the suite RED if it ever starts being caught —+ // a built-in alarm that the note below has gone stale.it.fails("GAP: variable-expansion form `HOME=/ rm -rf \"$HOME\"` — no literal `/` after -rf", () => {expect(destructiveReason('HOME=/ rm -rf "$HOME"')).toMatch(/rm -rf on \//);});diff --git a/lib/host/fs-upload.test.ts b/lib/host/fs-upload.test.tsnew file mode 100644index 00000000..63bde483--- /dev/null+++ b/lib/host/fs-upload.test.ts@@ -0,0 +1,95 @@+import { promises as fs } from "fs";+import os from "os";+import path from "path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// The upload writer had no test at all. It is a write boundary reachable from+// /api/v1/fs/upload, so the two things pinned here are the two that matter:+// a part must not escape the destination dir, and the size cap must actually stop+// bytes from landing on disk.+let dir: string;++async function load() {+ vi.resetModules();+ vi.stubEnv("OS_FS_WRITE_ROOTS", dir);+ vi.stubEnv("OS_FS_READ_ROOTS", dir);+ return import("./fs-upload");+}++// A body that yields `n` bytes in 1 MiB chunks without allocating them all at once.+async function* bytes(n: number): AsyncIterable<Uint8Array> {+ const CHUNK = 1024 * 1024;+ let sent = 0;+ while (sent < n) {+ const size = Math.min(CHUNK, n - sent);+ yield new Uint8Array(size);+ sent += size;+ }+}++async function* text(s: string): AsyncIterable<Uint8Array> {+ yield new TextEncoder().encode(s);+}++beforeEach(async () => {+ dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "mso-upload-")));+});++afterEach(async () => {+ vi.unstubAllEnvs();+ await fs.rm(dir, { recursive: true, force: true });+});++describe("streamFileInto — the upload write boundary", () => {+ it("writes a normal file, including into a nested folder", async () => {+ const { resolveUploadDest, streamFileInto } = await load();+ const destReal = await resolveUploadDest(dir);++ expect(await streamFileInto(destReal, "imgs/a.txt", text("hello"))).toBe("ok");+ expect(await fs.readFile(path.join(dir, "imgs", "a.txt"), "utf8")).toBe("hello");+ });++ it.each([+ ["../escape.txt", "parent traversal"],+ ["../../etc/cron.d/pwn", "deep traversal"],+ ["a/../../../escape.txt", "traversal in the middle"],+ ["/etc/cron.d/pwn", "absolute path"],+ ["./././", "no usable segment"],+ ["", "empty"],+ ])("refuses %s (%s) and writes nothing outside dest", async (relPath) => {+ const { resolveUploadDest, streamFileInto } = await load();+ const destReal = await resolveUploadDest(dir);++ const res = await streamFileInto(destReal, relPath, text("pwned"));+ // Either rejected outright, or the ".." segments were stripped so it landed+ // INSIDE dest. What must never happen is a write above dest.+ if (res === "ok") {+ const escaped = path.resolve(dir, "..", "escape.txt");+ await expect(fs.access(escaped)).rejects.toThrow();+ } else {+ expect(res).toBe("bad-path");+ }+ await expect(fs.access("/etc/cron.d/pwn")).rejects.toThrow();+ });++ it("stops at the 100 MiB cap and leaves no file or .tmp behind", async () => {+ const { resolveUploadDest, streamFileInto } = await load();+ const destReal = await resolveUploadDest(dir);++ expect(await streamFileInto(destReal, "big.bin", bytes(101 * 1024 * 1024))).toBe("too-large");+ await expect(fs.access(path.join(dir, "big.bin"))).rejects.toThrow();+ expect((await fs.readdir(dir)).filter((f) => f.includes(".tmp-"))).toEqual([]);+ });++ it("rejects a destination outside the WRITE roots", async () => {+ const { resolveUploadDest } = await load();+ await expect(resolveUploadDest("/etc")).rejects.toThrow();+ });++ it("rejects a destination that is a file, not a directory", async () => {+ const file = path.join(dir, "notadir.txt");+ await fs.writeFile(file, "x");+ const { resolveUploadDest } = await load();+ await expect(resolveUploadDest(file)).rejects.toThrow(/not a directory/i);+ });+});