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(heartbeat): integrate security guards and quote cron paths for POSIX shells

rahmanefb8da465d58dc
diff --cc docs/PROGRESS.md
index ee07d349,ef8425ec..0811be58
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@@ -1,9 -1,19 +1,25 @@@
+ ## 2026-10-08: Complete the scan hardening audit and repair verification
+
+ The three Codex Security Cloud scans overlap across authority, credentials, ingress, resource ceilings and installation provenance. The security branch now includes webhook authentication, distinct PAT principals, refresh-family replay revocation, explicit exec authority for loopback discovery, immutable managed-app update targets, provider environment SecretRefs, proven gateway ownership, bounded audit tails, backup retention and pinned NodeSource bootstrap bytes.
+
+ Independent verification additionally found that archive admission ended before its unlinked output descriptor closed, temporary-directory failure could strand admission, and delegated write could replace user-local launchers or their parent directories. The shared guards now cover those paths and managed-runtime trees; archive admission lasts until stream closure with a bounded lifetime. Backups recheck file/byte limits during copying and remove incomplete snapshots on failure. Installer bootstrap checksums were refreshed after the core hardening. Gateway test launchers now emit valid JavaScript, and the equivalent listener-port comparison parses correctly under strict Semgrep. OAuth and workflow fixtures explicitly exercise replay revocation and live approved-device authority.
+
+ These are source and verification changes. Production deployment and scan closure require the verified main revision and live runtime evidence; local tests alone do not establish either.
+
+ ## 2026-10-07: Harden delegated workflow, ingress and credential boundaries
+
+ Two repository security scans (October 2 and October 7) exposed overlapping authority and ingress gaps. Project dotenv files are now credential material everywhere, recursive archives exclude them, exact-loopback A2A is opt-in, and pre-auth A2A traffic cannot evict authenticated rate-limit state. Project ingress requires bounded framing and forwards only protocol headers, not cockpit cookies or Authorization.
+
+ Workflow Graph execution now treats stored definitions as data rather than grants: live web-device role and deployment scope are rechecked before execution, Operator authority caps at write, unattended stored non-web principals fail closed, error workflows carry ancestry, and typed/short secret variables are redacted from receipts. Public JSON/form readers used by login, OAuth, Discord and setup enforce actual byte ceilings and deadlines before parsing; login admission is reserved before password comparison so a distributed source cannot continue the password oracle past the global budget. OAuth consent now describes the real breadth of write authority.
+
+ Regression coverage was added for these boundaries. This entry does not claim closure of the remaining archive-size, backup-retention, audit-growth, installer-supply-chain, OpenClaw argv, workflow-webhook authentication, or write-to-control-plane findings; those require separate verified changes.
+
+## 2026-10-06: Optional one-shot fallback heartbeat
+
+A named connector can remain alive while its public connection is unavailable. The opt-in `mso heartbeat` checks structured gateway local/public identity and recovers only MSO-owned fallback processes through the existing lifecycle. It is disabled unless `OS_HEARTBEAT_ENABLED=1`, needs an explicit validated named-gateway recipe before stopping a managed connector, and leaves external supervisors report-only. An idempotent optional cron installer schedules 30-minute and cron-startup checks without adding a monitoring daemon or replacing unrelated cron entries. Private scoped locks prevent overlapping recovery and status retains no credentials. Platform startup and workspace suspension remain host responsibilities.
+
+Focused regressions cover disabled behavior, consecutive failures, public health, managed recipe preflight, external ownership, malformed observations, private env files, local fallback recovery and cron preservation. This is a PR candidate; no production installation or main branch is changed.
+
## 2026-10-06: Patch source-map-js and retain the 9Router proposal
Hosted Verify and OSV identified GHSA-68fv-2mgg-jv7q in the locked source-map-js 1.2.1 dependency. The targeted update resolves it to the patched 1.2.2 without changing package ranges, audit policy or existing dependency patches. A fresh frozen install loads the native PTY module, and both strict and native Bun audits are clean. Full combined-head repository, build, browser and security verification remains required before integration.
diff --cc scripts/lib/heartbeat-cron.sh
index 43f9704e,00000000..4eb53272
mode 100644,000000..100644
--- a/scripts/lib/heartbeat-cron.sh
+++ b/scripts/lib/heartbeat-cron.sh
@@@ -1,28 -1,0 +1,30 @@@
+#!/usr/bin/env bash
+# Install/remove only this checkout's cron entries; do not start/install cron itself.
++heartbeat_cron_quote() { printf "'%s'" "${1//\'/\'\\\'\'}"; }
+heartbeat_cron() {
+ local action="$1" minutes="${OS_HEARTBEAT_INTERVAL_MINUTES:-30}" schedule marker old entry cron_path
+ command -v crontab >/dev/null || gateway_fail 'crontab is unavailable; use the host supervisor to schedule heartbeat'
+ case "$minutes" in 1|2|3|5|10|15|20|30) schedule="*/$minutes * * * *" ;; 60) schedule='0 * * * *' ;; *) gateway_fail 'interval must divide an hour (1,2,3,5,10,15,20,30,60)' ;; esac
+ [[ "$ROOT$ENVF$PATH" != *$'\n'* ]] || gateway_fail 'cron paths must not contain newlines'
+ marker="# mso-heartbeat:$KEY"
+ old="$(crontab -l 2>/dev/null)" || {
+ # Missing crontab is expected; other errors must not overwrite an existing table.
+ local error
+ error="$(crontab -l 2>&1 || true)"
+ [[ "$error" == *'no crontab for'* ]] || gateway_fail 'could not read existing crontab'
+ old=''
+ }
+ old="$(printf '%s\n' "$old" | grep -Fv -- "$marker" || true)"
+ if [ "$action" = install-cron ]; then
+ cron_path="$(dirname "$(command -v node)"):/usr/local/bin:/usr/bin:/bin"
- printf -v entry 'env PATH=%q MSO_GATEWAY_ENV=%q /bin/bash %q once >/dev/null' "$cron_path" "$ENVF" "$ROOT/scripts/mso-heartbeat"
++ # Cron's command shell is POSIX sh; Bash %q can emit unsupported $'...' syntax.
++ printf -v entry 'env PATH=%s MSO_GATEWAY_ENV=%s /bin/bash %s once >/dev/null' "$(heartbeat_cron_quote "$cron_path")" "$(heartbeat_cron_quote "$ENVF")" "$(heartbeat_cron_quote "$ROOT/scripts/mso-heartbeat")"
+ # Cron interprets percent even inside shell quotes. Escape it after shell quoting.
+ entry="${entry//%/\\%}"
+ { [ -z "$old" ] || printf '%s\n' "$old"; printf '%s %s %s\n' "$schedule" "$entry" "$marker"; printf '@reboot %s %s\n' "$entry" "$marker"; } | crontab -
+ echo "heartbeat: installed cron every $minutes minutes and at cron startup"
+ else
+ { [ -z "$old" ] || printf '%s\n' "$old"; } | crontab -
+ echo 'heartbeat: removed this checkout cron entries'
+ fi
+}
diff --cc scripts/mso-heartbeat.test.ts
index 7d525b27,00000000..cb4c68b7
mode 100644,000000..100644
--- a/scripts/mso-heartbeat.test.ts
+++ b/scripts/mso-heartbeat.test.ts
@@@ -1,153 -1,0 +1,153 @@@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { spawnSync } from "node:child_process";
+import { afterEach, describe, expect, it } from "vitest";
+
+const source = path.resolve(__dirname, "..");
+const roots: string[] = [];
+afterEach(() => roots.splice(0).forEach(root => fs.rmSync(root, { recursive: true, force: true })));
+function fixture() {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "mso-heartbeat-")); roots.push(home);
- const root = path.join(home, "repo with spaces %"), bin = path.join(home, "bin");
++ const root = path.join(home, "repo with spaces % ' café\t"), bin = path.join(home, "bin");
+ fs.mkdirSync(path.join(root, "scripts/lib"), { recursive: true, mode: 0o700 });
+ fs.mkdirSync(bin, { mode: 0o700 });
+ for (const file of ["gateway-config.sh", "gateway-common.sh", "private-state.sh", "heartbeat-cron.sh", "gateway-provider.sh", "gateway-tool.sh", "gateway-tunnel.sh", "gateway-cloudflare-edge.sh"])
+ fs.copyFileSync(path.join(source, "scripts/lib", file), path.join(root, "scripts/lib", file));
+ fs.copyFileSync(path.join(source, "scripts/mso-heartbeat"), path.join(root, "scripts/mso-heartbeat"));
+ fs.mkdirSync(path.join(root, "security"));
+ fs.copyFileSync(path.join(source, "security/gateway-artifacts.env"), path.join(root, "security/gateway-artifacts.env"));
+ fs.mkdirSync(path.join(root, "node_modules"));
+ fs.symlinkSync(path.join(source, "node_modules/yaml"), path.join(root, "node_modules/yaml"));
+ const config = path.join(home, "cloudflared.yml"), credential = path.join(home, "credential.json");
+ fs.writeFileSync(credential, "{}", { mode: 0o600 });
+ fs.writeFileSync(config, `credentials-file: ${credential}\ningress:\n - hostname: fixture.example\n service: http://127.0.0.1:4005\n - service: http_status:404\n`, { mode: 0o600 });
+ const envFile = path.join(root, ".env.local"), observation = path.join(home, "observation.json");
+ fs.writeFileSync(envFile, "", { mode: 0o600 });
+ fs.writeFileSync(path.join(root, "scripts/mso-gateway"), `#!/bin/bash
+if [ "$1" = status ]; then cat "$HOME/observation.json"; exit 2; fi
+printf '%s\\n' "$*" >>"$HOME/actions"
+if [ "$1" = start ] || [ "$1" = local-start ]; then
+ printf '%s' '{"ownership":"mso","localHealth":"healthy","publicHealth":"healthy","public":"https://fixture.example","supervisor":"mso-lifecycle"}' >"$HOME/observation.json"
+fi
+`, { mode: 0o700 });
+ fs.writeFileSync(path.join(bin, "crontab"), `#!/bin/bash
+if [ "$1" = -l ]; then
+ if [ -f "$HOME/table" ]; then cat "$HOME/table"; else echo 'no crontab for fixture' >&2; exit 1; fi
+else cat >"$HOME/table"; fi
+`, { mode: 0o700 });
+ const env = { ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}`, MSO_GATEWAY_ROOT: root,
+ MSO_GATEWAY_ENV: envFile, OS_HEARTBEAT_ENABLED: "1", OS_HEARTBEAT_FAILURE_THRESHOLD: "1",
+ OS_PUBLIC_ORIGIN: "", MSO_GATEWAY_LOCAL_URL: "http://127.0.0.1:4005" };
+ function state(ownership = "mso", healthy = false, supervisor = "mso-lifecycle") {
+ fs.writeFileSync(observation, JSON.stringify({ ownership, supervisor,
+ localHealth: healthy ? "healthy" : "unhealthy", publicHealth: healthy ? "healthy" : "unhealthy", public: null }));
+ }
+ state();
+ const run = (args: string[] = [], extra = {}) => spawnSync("bash", [path.join(root, "scripts/mso-heartbeat"), ...args], { env: { ...env, ...extra }, encoding: "utf8" });
+ const actions = () => fs.existsSync(path.join(home, "actions")) ? fs.readFileSync(path.join(home, "actions"), "utf8") : "";
+ return { home, root, config, envFile, observation, env, state, run, actions };
+}
+describe("optional one-shot heartbeat", () => {
+ it("is disabled by default and does not create runtime state", () => {
+ const f = fixture(); const result = f.run([], { OS_HEARTBEAT_ENABLED: "0" });
+ expect(result.status).toBe(0); expect(result.stdout).toContain("disabled");
+ expect(fs.existsSync(path.join(f.home, ".mso"))).toBe(false); expect(f.actions()).toBe("");
+ });
+ it("resets failures on valid health without changing any process", () => {
+ const f = fixture(); f.state("mso", true);
+ expect(f.run().status).toBe(0); expect(f.actions()).toBe("");
+ });
+ it("counts consecutive failures and recovers only the explicit managed recipe", () => {
+ const f = fixture(); const extra = { OS_HEARTBEAT_FAILURE_THRESHOLD: "2",
+ OS_HEARTBEAT_GATEWAY_CONFIG: f.config, OS_HEARTBEAT_GATEWAY_TUNNEL: "fixture", OS_PUBLIC_ORIGIN: "https://fixture.example" };
+ expect(f.run([], extra).status).toBe(2); expect(f.actions()).toBe("");
+ const result = f.run([], extra);
+ expect(result.stderr).toBe(""); expect(result.status).toBe(0);
+ expect(f.actions()).toBe(`stop\nstart --config ${f.config} --tunnel fixture\n`);
+ expect(result.stdout).toContain("recovered");
+ });
+ it("validates the recovery recipe before stopping a degraded managed connector", () => {
+ const f = fixture();
+ expect(f.run([], { OS_HEARTBEAT_GATEWAY_CONFIG: "/missing/config", OS_HEARTBEAT_GATEWAY_TUNNEL: "fixture" }).status).toBe(1);
+ expect(f.actions()).toBe("");
+ });
+ it("checks public health even when the local runtime is healthy", () => {
+ const f = fixture();
+ fs.writeFileSync(f.observation, JSON.stringify({ ownership: "mso", supervisor: "mso-lifecycle",
+ localHealth: "healthy", publicHealth: "unhealthy", public: "https://fixture.example" }));
+ expect(f.run().status).toBe(2); expect(f.actions()).toBe("");
+ });
+ it("loads the opt-in from the installation env file", () => {
+ const f = fixture(); f.state("mso", true);
+ fs.writeFileSync(f.envFile, "OS_HEARTBEAT_ENABLED=1\n");
+ expect(f.run([], { OS_HEARTBEAT_ENABLED: "0" }).stdout).toContain("healthy");
+ fs.writeFileSync(f.envFile, "OS_HEARTBEAT_ENABLED=0\n");
+ expect(f.run().stdout).toContain("disabled");
+ });
+ it("does not replace a named gateway with a quick tunnel", () => {
+ const f = fixture(); expect(f.run().status).toBe(2); expect(f.actions()).toBe("");
+ });
+ it.each(["external", "systemd", "s6", "docker", "kubernetes"])("preserves %s supervision", supervisor => {
+ const f = fixture(); f.state("mso", false, supervisor);
+ expect(f.run().status).toBe(2); expect(f.actions()).toBe("");
+ });
+ it("never adopts an externally owned connector", () => {
+ const f = fixture(); f.state("external", false, "unknown");
+ expect(f.run().status).toBe(2); expect(f.actions()).toBe("");
+ });
+ it("recovers an absent loopback fallback without creating a public connector", () => {
+ const f = fixture(); f.state("none", false, "unknown");
+ expect(f.run().status).toBe(0); expect(f.actions()).toBe("local-start\n");
+ });
+ it("rejects a corrupt observation before lifecycle actions", () => {
+ const f = fixture(); fs.writeFileSync(f.observation, '{"stateError":"unsafe-or-corrupt"}');
+ expect(f.run().status).toBe(1); expect(f.actions()).toBe("");
+ });
+ it("rejects an unsafe env file", () => {
+ const f = fixture(); fs.chmodSync(f.envFile, 0o644);
+ expect(f.run().status).toBe(1); expect(f.actions()).toBe("");
+ });
+ it("installs idempotent 30-minute and reboot entries, preserving other jobs", () => {
+ const f = fixture(); fs.writeFileSync(path.join(f.home, "table"), "5 * * * * /unrelated/job\n");
+ expect(f.run(["install-cron"]).status).toBe(0);
+ expect(f.run(["install-cron"]).status).toBe(0);
+ const table = fs.readFileSync(path.join(f.home, "table"), "utf8");
+ expect(table).toContain("*/30 * * * *"); expect(table).toContain("@reboot");
+ expect(table.match(/# mso-heartbeat:/g)).toHaveLength(2); expect(table).toContain("/unrelated/job");
+ expect(f.run(["remove-cron"], { OS_HEARTBEAT_ENABLED: "0" }).status).toBe(0);
+ expect(fs.readFileSync(path.join(f.home, "table"), "utf8")).toBe("5 * * * * /unrelated/job\n");
+ });
+ it("resets consecutive failures after a healthy observation", () => {
+ const f = fixture(), extra = { OS_HEARTBEAT_FAILURE_THRESHOLD: "2" };
+ expect(f.run([], extra).status).toBe(2);
+ f.state("mso", true); expect(f.run([], extra).status).toBe(0);
+ f.state(); expect(f.run([], extra).status).toBe(2); expect(f.actions()).toBe("");
+ });
+ it("serializes checks without inheriting its lock into lifecycle children", () => {
+ const f = fixture(); f.state("mso", true); expect(f.run().status).toBe(0);
+ const base = path.join(f.home, ".mso/private/heartbeat");
+ const lock = path.join(base, fs.readdirSync(base)[0], "check.lock");
+ const result = spawnSync("flock", [lock, "bash", path.join(f.root, "scripts/mso-heartbeat")], { env: f.env, encoding: "utf8" });
+ expect(result.status).toBe(0); expect(result.stdout).toContain("already running"); expect(f.actions()).toBe("");
+ });
- it("runs the installed cron command correctly with spaces and percent in paths", () => {
++ it("runs cron under POSIX sh with quoted, Unicode, tab and percent paths", () => {
+ const f = fixture(); f.state("mso", true); expect(f.run(["install-cron"]).status).toBe(0);
+ const line = fs.readFileSync(path.join(f.home, "table"), "utf8").split("\n")[0];
+ const command = line.replace(/^\S+ \S+ \S+ \S+ \S+ /, "").replace(/ # mso-heartbeat:.*$/, "").replace(/\\%/g, "%");
- const result = spawnSync("bash", ["-c", command], { env: { ...f.env, MSO_GATEWAY_ROOT: "" }, encoding: "utf8" });
++ const result = spawnSync("sh", ["-c", command], { env: { ...f.env, MSO_GATEWAY_ROOT: "" }, encoding: "utf8" });
+ expect(result.stderr).toBe(""); expect(result.status).toBe(0); expect(f.actions()).toBe("");
+ });
+ it("does not overwrite crontab when reading it fails", () => {
+ const f = fixture(); fs.writeFileSync(path.join(f.home, "table"), "5 * * * * /unrelated/job\n");
+ fs.writeFileSync(path.join(f.home, "bin/crontab"), "#!/bin/bash\necho 'permission denied' >&2\nexit 1\n", { mode: 0o700 });
+ expect(f.run(["install-cron"]).status).toBe(1);
+ expect(fs.readFileSync(path.join(f.home, "table"), "utf8")).toContain("/unrelated/job");
+ });
+ it("does not install cron while disabled or with an invalid interval", () => {
+ const f = fixture(); expect(f.run(["install-cron"], { OS_HEARTBEAT_ENABLED: "0" }).status).toBe(0);
+ expect(fs.existsSync(path.join(f.home, "table"))).toBe(false);
+ expect(f.run(["install-cron"], { OS_HEARTBEAT_INTERVAL_MINUTES: "31" }).status).toBe(1);
+ expect(fs.existsSync(path.join(f.home, "table"))).toBe(false);
+ });
+});