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(security): close resource and launcher gaps and repair gates

rahmanef3550458b453a
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 7bd4e889..77770618 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -4,6 +4,40 @@
Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;
this is the *what*, and it is what Settings → Account → About shows as “What's new”.
+## 2026-10-08
+
+**Fixed**
+
+- `security` close resource and launcher gaps and repair gates
+- `security` inspect ZIP output through pinned descriptor
+- `ci` close gateway typing and audit file races
+- `security` pin NodeSource bootstrap bytes
+- `security` bound managed-app backup retention
+- `security` bound audit growth and tail reads
+- `security` bind gateway tunnels to proven local runtime
+- `security` fail closed on mutable managed-app updates
+- `security` keep OpenClaw provider keys out of argv
+- `security` serialize managed-app lifecycle cross-process
+- `security` bound archive generation resources
+- `security` serialize bounded image imports
+- `security` require exec for A2A loopback discovery
+- `security` isolate PAT principals and revoke refresh replay
+- `ci` clear typecheck, OSV, and reviewed history gates
+- `security` require authenticated workflow webhooks
+- `security` block delegated writes to control plane
+
+## 2026-10-07
+
+**Fixed**
+
+- `security` bound public ingress bodies
+- `security` enforce live workflow authority
+- `security` harden credential and A2A boundaries
+
+**Docs**
+
+- `security` record scan hardening boundaries
+
## 2026-10-06
**Added**
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 86168a06..ef8425ec 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,11 @@
+## 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.
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index 2dfa8f52..8809c4a9 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -14,6 +14,8 @@ It is additive: existing deterministic project flows, RASMIC scripts and learned
Graphs, versions, variables and execution receipts are private per authenticated principal. Source and builtin templates contain no operator-specific user, credential, path or seeded workflow.
+Delegated write authority excludes the live MSO checkout, Git control files, user-systemd units, user-local CLI launchers, Hermes/OpenClaw runtime trees and parent directories that could replace them. These control-plane mutations require exec authority; canonical symlink targets are checked as well.
+
## Node catalog
### Triggers
diff --git a/lib/host/audit.ts b/lib/host/audit.ts
index aa17c68e..555234b1 100644
--- a/lib/host/audit.ts
+++ b/lib/host/audit.ts
@@ -1,11 +1,6 @@
// Host-owned runtime data is not a build asset; tracing exclusions preserve runtime guards.
-// SERVER-ONLY. Append-only audit trail for privileged actions (shell exec, file
-// mutations, cleanup runs, auth events). Single-owner tool that can run shell
-// commands MUST keep a tamper-evident record — if something goes wrong, this is
-// the only forensic trail. JSONL, one event per line, flushed best-effort.
-//
-// Location: $OS_AUDIT_LOG, else ~/.mso/audit.log. Reads are NOT audited
-// (bounded + high-volume); only state-changing actions are.
+// SERVER-ONLY. Bounded best-effort JSONL trail for privileged mutations.
+// Location: $OS_AUDIT_LOG, else ~/.mso/audit.log; reads are not audited.
import { constants, promises as fs } from "fs";
import os from "os";
import path from "path";
@@ -42,10 +37,7 @@ function trunc(s: string | undefined, max = 512): string | undefined {
return s.length > max ? s.slice(0, max) + "…" : s;
}
-// Clamp meta values defensively: a caller could pass an unbounded string (a
-// user-supplied URL, a stack-trace fragment), and one bloated meta would
-// torpedo the whole forensic line. Scalars pass through; strings cap at 256;
-// anything else is dropped (the type already forbids it, but defense in depth).
+// Keep caller-supplied metadata bounded and scalar-only.
function clampMeta(
meta: Record<string, string | number | boolean> | undefined,
): Record<string, string | number | boolean> | undefined {
@@ -102,10 +94,7 @@ export async function readAuditTail(opts?: {
.reverse();
}
-// Internal: serialize writes onto a single chained promise so bursty parallel
-// callers land in submission order. The chain NEVER rejects (each link
-// swallows + logs its own failure), otherwise one bad write would poison every
-// subsequent audit call for the lifetime of the process.
+// Preserve submission order; a failed write must not poison later writes.
let _writeChain: Promise<void> = Promise.resolve();
const AUDIT_MAX_BYTES = 8 * 1024 * 1024;
const AUDIT_READ_TAIL_BYTES = 256 * 1024;
@@ -163,11 +152,7 @@ async function copyHandle(source: Awaited<ReturnType<typeof fs.open>>, dest: Awa
}
async function writeLine(line: string): Promise<void> {
- // A test run must never append to the OWNER's forensic trail. This is not
- // hypothetical: on 2026-08-10 two `mcp.denied` lines from lib/mcp/dispatch.test.ts
- // landed in a real ~/.mso/audit.log, because that suite exercises the dispatcher
- // and the dispatcher audits. audit.test.ts always stubs OS_AUDIT_LOG at a temp
- // path, so this only silences the callers that forgot to.
+ // Tests require an explicit synthetic trail; never append to the owner's log.
if (process.env.VITEST && !process.env.OS_AUDIT_LOG) return;
const file = auditPath();
let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
@@ -206,10 +191,7 @@ async function writeLine(line: string): Promise<void> {
}
}
-// Append an audit entry. Returns a promise that resolves AFTER this entry's
-// write completes (or fails — failures are swallowed; the trail is best-effort
-// and must never break the caller). Callers may fire-and-forget the returned
-// promise; ordering across concurrent callers is preserved via _writeChain.
+// Resolves after the best-effort write; failures never break the caller.
export function audit(entry: AuditEntry): Promise<void> {
if (!allowRateLimitAudit(entry.action)) return Promise.resolve();
// Drop `meta` from the serialized line when it's empty so existing greps that
diff --git a/lib/host/delegated-write.test.ts b/lib/host/delegated-write.test.ts
index 86e68d0e..577eb255 100644
--- a/lib/host/delegated-write.test.ts
+++ b/lib/host/delegated-write.test.ts
@@ -19,4 +19,10 @@ describe("delegated write control-plane guard", () => {
it("allows ordinary project content", async () => {
await expect(assertDelegatedWritePath(path.join(os.tmpdir(), "project", "src", "index.ts"))).resolves.toBeUndefined();
});
+ it("blocks CLI launchers used by managed-app probes", async () => {
+ for (const dir of [".local/bin", ".bun/bin", ".hermes", ".openclaw"]) {
+ await expect(assertDelegatedWritePath(path.join(os.homedir(), dir, "hermes"))).rejects.toThrow(/control-plane/);
+ }
+ await expect(assertDelegatedWritePath(path.join(os.homedir(), ".local"))).rejects.toThrow(/control-plane/);
+ });
});
diff --git a/lib/host/delegated-write.ts b/lib/host/delegated-write.ts
index fa2d2752..89c5eb7c 100644
--- a/lib/host/delegated-write.ts
+++ b/lib/host/delegated-write.ts
@@ -34,15 +34,15 @@ function containsGitControl(target: string): boolean {
}
export async function assertDelegatedWritePath(raw: string): Promise<void> {
+ const requested = absolute(raw);
const target = await canonicalProspective(raw);
- const app = appDir();
- const systemdUser = path.join(os.homedir(), ".config", "systemd", "user");
+ const controls = [appDir(), ...[".config/systemd/user", ".local/bin", ".bun/bin", ".hermes", ".openclaw"].map(dir => path.join(os.homedir(), dir))];
+ const canonical = await Promise.all(controls.map(canonicalProspective));
if (
- target === app ||
- isUnderRoot(target, app) ||
containsGitControl(target) ||
- target === systemdUser ||
- isUnderRoot(target, systemdUser)
+ containsGitControl(requested) ||
+ [...controls, ...canonical].some(control =>
+ [requested, target].some(candidate => isUnderRoot(candidate, control) || isUnderRoot(control, candidate)))
) {
throw new HostError("write scope cannot modify executable control-plane inputs; exec authority required");
}
diff --git a/lib/host/fs-zip.test.ts b/lib/host/fs-zip.test.ts
index c16aa8d3..eda43712 100644
--- a/lib/host/fs-zip.test.ts
+++ b/lib/host/fs-zip.test.ts
@@ -1,8 +1,9 @@
import path from "path";
import os from "os";
-import { chmodSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, truncateSync, writeFileSync } from "fs";
+import { chmodSync, mkdirSync, mkdtempSync, promises as fsp, readdirSync, realpathSync, rmSync, truncateSync, writeFileSync } from "fs";
import type { Readable } from "stream";
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { once } from "node:events";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { appSecretExcludes, assertSafeName, zipStream } from "./fs-zip";
describe("assertSafeName", () => {
@@ -78,6 +79,13 @@ describe("zipStream against the real zip binary", () => {
expect(names).toContain("keep.txt");
expect(names).toContain("proj/src.txt");
});
+ it("releases admission when temporary directory creation fails", async () => {
+ const temporary = vi.spyOn(fsp, "mkdtemp").mockRejectedValueOnce(new Error("disk unavailable"));
+ try {
+ await expect(zipStream(base, ["keep.txt"])).rejects.toThrow(/disk unavailable/);
+ expect(entries(await read(await zipStream(base, ["keep.txt"])))).toContain("keep.txt");
+ } finally { temporary.mockRestore(); }
+ });
it("force-strips nested loose private keys from recursive archives", async () => {
const dir = path.join(base, "secrets-fixture");
@@ -119,10 +127,12 @@ describe("zipStream against the real zip binary", () => {
const before = stale();
const abandoned = await zipStream(base, ["keep.txt"]);
expect(stale()).toBe(before);
+ await expect(zipStream(base, ["keep.txt"])).rejects.toThrow(/already/);
+ abandoned.destroy();
+ await once(abandoned, "close");
const drained = await read(await zipStream(base, ["keep.txt"]));
expect(entries(drained)).toContain("keep.txt"); // unlinked bytes still readable
expect(stale()).toBe(before);
- abandoned.destroy();
});
});
@@ -132,6 +142,7 @@ describe("zip resource ceilings", () => {
const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), "mso-zip-budget-")));
process.env.OS_FS_READ_ROOTS = root;
const huge = path.join(root, "huge.bin");
+ writeFileSync(huge, "");
truncateSync(huge, 513 * 1024 * 1024);
try {
await expect(zipStream(root, ["huge.bin"])).rejects.toThrow(/512 MiB input limit/);
diff --git a/lib/host/fs-zip.ts b/lib/host/fs-zip.ts
index e8f9c15c..c2d72696 100644
--- a/lib/host/fs-zip.ts
+++ b/lib/host/fs-zip.ts
@@ -92,13 +92,14 @@ export async function zipStream(
for (const n of exclude) assertSafeName(n);
if (zipGate.__msoZipActive) throw new HostError("Another archive is already being generated");
zipGate.__msoZipActive = true;
+ let tmpDir: string;
try {
await assertArchiveBudget(real, names, exclude);
+ tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), "os-zip-"));
} catch (error) {
zipGate.__msoZipActive = false;
throw error;
}
- const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), "os-zip-"));
const out = path.join(tmpDir, "archive.zip");
// `-y` = store symlinks AS links, never follow. Without it `zip -r` archives a
// link's TARGET content, escaping the realpath/credential bounds checked above
@@ -167,13 +168,14 @@ export async function zipStream(
throw new HostError("Generated archive exceeds the 600 MiB output limit");
}
- zipGate.__msoZipActive = false;
// ponytail: staged on disk, not streamed as zip runs — correctness over the
// buffer-free ideal, since a piped zip won't extract. Opened, then unlinked
// BEFORE the stream is handed back: the open fd keeps bytes readable while the
// directory entry is already gone, so abandoned responses cannot strand /tmp.
await fsp.rm(tmpDir, { recursive: true, force: true });
const stream = handle.createReadStream({ autoClose: true });
+ const timer = setTimeout(() => stream.destroy(), ZIP_PROCESS_TIMEOUT_MS).unref();
+ stream.once("close", () => { clearTimeout(timer); zipGate.__msoZipActive = false; });
handle = undefined; // stream now owns the descriptor
return stream;
} catch (error) {
diff --git a/lib/managed-apps/backups-quota.test.ts b/lib/managed-apps/backups-quota.test.ts
index 6434c6ca..0beda54e 100644
--- a/lib/managed-apps/backups-quota.test.ts
+++ b/lib/managed-apps/backups-quota.test.ts
@@ -4,6 +4,7 @@ import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ManagedAppDefinition } from "./types";
import { createBackup, listBackups } from "./backups";
+vi.mock("server-only", () => ({}));
const roots: string[] = [];
function definition(root: string): ManagedAppDefinition {
@@ -15,6 +16,20 @@ afterEach(async () => {
});
describe("managed-app backup quotas", () => {
+ it("rejects growth after preflight and removes the incomplete snapshot", async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-backup-growth-")); roots.push(root);
+ vi.spyOn(os, "homedir").mockReturnValue(root);
+ await fs.mkdir(path.join(root, "state"));
+ await fs.writeFile(path.join(root, "state", "config.json"), "{}");
+ const copy = fs.cp;
+ vi.spyOn(fs, "cp").mockImplementationOnce(async (source, target, options) => {
+ const huge = await fs.open(path.join(root, "state", "huge.bin"), "w");
+ try { await huge.truncate(513 * 1024 * 1024); } finally { await huge.close(); }
+ return copy(source, target, options);
+ });
+ await expect(createBackup(definition(root), "pre-update")).rejects.toThrow(/backup changed/);
+ expect(await listBackups("openclaw")).toEqual([]);
+ });
it("rate-limits manual snapshots", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-backup-quota-")); roots.push(root);
vi.spyOn(os, "homedir").mockReturnValue(root);
diff --git a/lib/managed-apps/backups.ts b/lib/managed-apps/backups.ts
index f9845282..8eb620d8 100644
--- a/lib/managed-apps/backups.ts
+++ b/lib/managed-apps/backups.ts
@@ -117,10 +117,11 @@ export async function createBackup(definition: ManagedAppDefinition, reason: Man
if (stat.isFile()) {
files += 1;
bytes += stat.size;
+ if (files > BACKUP_MAX_FILES || bytes > BACKUP_MAX_BYTES) throw new Error("backup changed beyond the 512 MiB/100000 file limit");
}
return true;
},
- });
+ }).catch(async error => { await fs.rm(target, { recursive: true, force: true }); throw error; });
const manifest: ManagedAppBackup = {
id,
applicationId: definition.id,
diff --git a/lib/managed-apps/install-secret-argv.test.ts b/lib/managed-apps/install-secret-argv.test.ts
new file mode 100644
index 00000000..30b6c1a8
--- /dev/null
+++ b/lib/managed-apps/install-secret-argv.test.ts
@@ -0,0 +1,13 @@
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+describe("OpenClaw provider secrets stay out of child argv", () => {
+ const script = readFileSync(path.join(process.cwd(), "scripts", "managed-app-install"), "utf8");
+ it("uses provider env SecretRefs instead of provider key flags", () => {
+ const openclaw = script.slice(script.indexOf("install_openclaw() {"), script.indexOf("openclaw_bin() {"));
+ expect(openclaw).toContain("--secret-input-mode ref");
+ expect(openclaw).not.toMatch(/--(?:anthropic|openai|openrouter|gemini|groq|xai|deepseek)-api-key/);
+ expect(openclaw.slice(openclaw.indexOf('"$openclaw" onboard'))).not.toContain('"$KEY"');
+ });
+});
diff --git a/lib/managed-apps/install.test.ts b/lib/managed-apps/install.test.ts
index 1854f925..6510ce02 100644
--- a/lib/managed-apps/install.test.ts
+++ b/lib/managed-apps/install.test.ts
@@ -217,14 +217,3 @@ describe("the provider table and the install script agree", () => {
expect(script).not.toMatch(/\bread -[rp]\b/);
});
});
-
-
-describe("OpenClaw provider secrets stay out of child argv", () => {
- const script = readFileSync(path.join(process.cwd(), "scripts", "managed-app-install"), "utf8");
- it("uses provider env SecretRefs instead of provider key flags", () => {
- const openclaw = script.slice(script.indexOf("install_openclaw() {"), script.indexOf("openclaw_bin() {"));
- expect(openclaw).toContain("--secret-input-mode ref");
- expect(openclaw).not.toMatch(/--(?:anthropic|openai|openrouter|gemini|groq|xai|deepseek)-api-key/);
- expect(openclaw).not.toContain('"$KEY"');
- });
-});
diff --git a/lib/managed-apps/jobs.test.ts b/lib/managed-apps/jobs.test.ts
index 7350e99c..cdc3441e 100644
--- a/lib/managed-apps/jobs.test.ts
+++ b/lib/managed-apps/jobs.test.ts
@@ -11,7 +11,6 @@ vi.mock("server-only", () => ({}));
const { startManagedAppJob, readManagedAppJob, listManagedAppJobs } = await import("./jobs");
const { MANAGED_APP_JOB_LOG_CAP, liveRecord } = await import("./job-runner");
const { performManagedAppAction } = await import("./manager");
-const { withManagedAppOperationLease } = await import("./lock");
import type { ManagedAppJob } from "./types";
let home: string;
@@ -217,18 +216,3 @@ describe("what never reaches a shell, and what never spawns", () => {
expect(latest).not.toHaveProperty("log"); // history rows carry no transcript
});
});
-
-
-describe("cross-process managed-app operation lease", () => {
- it("refuses a second contender while the durable lease is held", async () => {
- let entered!: () => void, release!: () => void;
- const inside = new Promise<void>((resolve) => { entered = resolve; });
- const hold = new Promise<void>((resolve) => { release = resolve; });
- const first = withManagedAppOperationLease("hermes", async () => { entered(); await hold; });
- await inside;
- await expect(withManagedAppOperationLease("hermes", async () => undefined)).rejects.toThrow("another operation is already running");
- release();
- await first;
- await expect(withManagedAppOperationLease("hermes", async () => "ok")).resolves.toBe("ok");
- });
-});
diff --git a/lib/managed-apps/operation-lease.test.ts b/lib/managed-apps/operation-lease.test.ts
new file mode 100644
index 00000000..46d2865c
--- /dev/null
+++ b/lib/managed-apps/operation-lease.test.ts
@@ -0,0 +1,26 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+const { withManagedAppOperationLease } = await import("./lock");
+let home: string;
+beforeEach(async () => {
+ home = await fs.mkdtemp(path.join(os.tmpdir(), "mapp-lease-"));
+ vi.spyOn(os, "homedir").mockReturnValue(home);
+});
+afterEach(async () => { vi.restoreAllMocks(); await fs.rm(home, { recursive: true, force: true }); });
+
+describe("cross-process managed-app operation lease", () => {
+ it("refuses a second contender while the durable lease is held", async () => {
+ let entered!: () => void, release!: () => void;
+ const inside = new Promise<void>((resolve) => { entered = resolve; });
+ const hold = new Promise<void>((resolve) => { release = resolve; });
+ const first = withManagedAppOperationLease("hermes", async () => { entered(); await hold; });
+ await inside;
+ await expect(withManagedAppOperationLease("hermes", async () => undefined)).rejects.toThrow("another operation is already running");
+ release();
+ await first;
+ await expect(withManagedAppOperationLease("hermes", async () => "ok")).resolves.toBe("ok");
+ });
+});
diff --git a/lib/managed-apps/update.test.ts b/lib/managed-apps/update.test.ts
index 12ff32cb..a5f9d928 100644
--- a/lib/managed-apps/update.test.ts
+++ b/lib/managed-apps/update.test.ts
@@ -130,7 +130,14 @@ describe("mutable upstream updates fail closed", () => {
});
it("still permits the reviewed 9Router update path", async () => {
- await expect(startUpdate("9router")).rejects.not.toThrow(/immutable artifact target and digest/);
+ await recorder("9router");
+ await fs.mkdir(path.join(home, ".9router"));
+ const catalog = await import("./catalog");
+ const definition = catalog.getManagedAppDefinition("9router");
+ vi.spyOn(catalog, "getManagedAppDefinition").mockReturnValue({ ...definition, command: path.join(bin, "9router") });
+ const job = await settle(await startUpdate("9router"));
+ expect(job.status).toBe("succeeded");
+ expect(await recorded("9router")).toEqual(["update", "--yes"]);
});
});
diff --git a/lib/managed-apps/update.ts b/lib/managed-apps/update.ts
index 6f8174b5..54520b51 100644
--- a/lib/managed-apps/update.ts
+++ b/lib/managed-apps/update.ts
@@ -11,11 +11,7 @@ import type { ManagedAppDefinition, ManagedAppId, ManagedAppJob } from "./types"
import { assertChannel, updateAdapter, UNINSTALL_PREVIEW_FLAG } from "./update-cli";
import type { ManagedAppBackup, ManagedAppUpdateOptions, ManagedAppUpdateStatus } from "./update-types";
-// The update service. Four destructive flows, one shape: validate, take a
-// backup INSIDE the operation, then hand a validated argv array to the job
-// layer. INSTALL is not one of them — both installers are interactive
-// (`hermes setup`, `openclaw update wizard`), so MSO reports the command for a
-// human to run and never fakes it (`capabilities.installCommand`).
+// Validate, snapshot inside the operation, then submit guarded fixed argv.
/** OpenClaw's own per-STEP timeout is 1800 s and a run has several steps, so a
* 30-minute wall clock would kill a healthy update mid-step. An hour is the
@@ -43,14 +39,9 @@ function assertVerifiedUpdatePath(id: ManagedAppId): void {
}
}
-/** Absolute path to the app's CLI. Resolved rather than trusted to PATH so the
- * argv the job records is the exact binary that ran, and a missing CLI fails
- * here with a readable message instead of as a child-process ENOENT. */
+/** Resolve the exact CLI or fail before creating a job. */
async function resolveProgram(command: string): Promise<string> {
- // Shared with detection (runner.ts) rather than a second `which` of its own:
- // under systemd the unit's PATH has no ~/.local/bin, so a bare `which` reported
- // "hermes is not installed" for an installed Hermes and disabled the whole
- // update centre — the same fault that made the app read as absent.
+ // Share detection's fallback for user-local CLIs outside systemd PATH.
const resolved = await resolveCommand(command);
if (!resolved || !path.isAbsolute(resolved)) throw new Error(`${command} is not installed`);
return resolved;
@@ -68,12 +59,7 @@ function unavailable(id: ManagedAppId, error: string): ManagedAppUpdateStatus {
detail: null,
channel: { value: null, kind: null, available: [], switchable: false, reason: null },
installKind: null,
- // Nothing that needs the CLI can be driven right now; `installCommand`
- // survives because it is exactly what the operator needs when the answer is
- // "not installed". `rollback` is the deliberate exception, spelled out so
- // the omission cannot read as one: a rollback is `restore.ts` copying files
- // in-process, so it needs no CLI and stays available precisely when a
- // broken install makes it most useful.
+ // File-based rollback survives a missing CLI; execution controls do not.
capabilities: { ...safeCapabilities(id, capabilities), check: false, apply: false, dryRun: false, channel: false, uninstall: false, rollback: true },
checkedAt: new Date().toISOString(),
error,
@@ -169,10 +155,7 @@ export async function startUpdate(id: ManagedAppId, options: ManagedAppUpdateOpt
});
}
-/** OpenClaw only. Upstream persists a channel ONLY after a successful core
- * update (`--channel` is a flag on `update`, not a setting), and MSO will not
- * write into ~/.openclaw itself — so switching a channel IS an update run,
- * backup and all. The returned job is a normal update job. */
+/** A channel switch executes an update, so it needs the same immutable target. */
export async function setChannel(id: ManagedAppId, channel: string): Promise<ManagedAppJob> {
const adapter = updateAdapter(id);
if (!adapter.capabilities.channel) throw new Error(`channel switching is not supported for ${id}`);
diff --git a/lib/mcp/store-security.test.ts b/lib/mcp/store-security.test.ts
new file mode 100644
index 00000000..8e2180b6
--- /dev/null
+++ b/lib/mcp/store-security.test.ts
@@ -0,0 +1,70 @@
+import { describe, it, expect, beforeEach, afterAll } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const DIR = path.join(os.tmpdir(), `mso-mcp-security-test-${process.pid}`);
+process.env.OS_MCP_STORE = path.join(DIR, "mcp.json");
+
+const store = await import("./store");
+
+beforeEach(async () => {
+ await fs.rm(DIR, { recursive: true, force: true });
+});
+afterAll(async () => {
+ await fs.rm(DIR, { recursive: true, force: true });
+});
+
+
+describe("durable MCP credential isolation", () => {
+ it("assigns every PAT a distinct durable client principal", async () => {
+ const first = await store.mintPatToken({ label: "client one", scope: "read", ttlDays: 1 });
+ const second = await store.mintPatToken({ label: "client two", scope: "read", ttlDays: 1 });
+ const a = await store.validateToken(first.rawToken);
+ const b = await store.validateToken(second.rawToken);
+ expect(a?.clientId).toMatch(/^manual:pat:[a-f0-9]{24}$/);
+ expect(b?.clientId).toMatch(/^manual:pat:[a-f0-9]{24}$/);
+ expect(a?.clientId).not.toBe(b?.clientId);
+ });
+
+ it("treats refresh-token replay as grant-family compromise", async () => {
+ await store.storeOAuthGrant({
+ accessToken: "initial-access",
+ refreshToken: "initial-refresh",
+ label: "oauth",
+ clientId: "client-replay",
+ scope: "exec",
+ resource: "https://mso.example/mcp",
+ offlineAccess: true,
+ grantId: "grant-replay",
+ });
+ expect(await store.rotateOAuthGrant({
+ oldRefreshToken: "initial-refresh",
+ accessToken: "successor-access",
+ refreshToken: "successor-refresh",
+ label: "oauth",
+ clientId: "client-replay",
+ resource: "https://mso.example/mcp",
+ })).not.toBeNull();
+ expect(await store.validateToken("successor-access")).not.toBeNull();
+
+ expect(await store.rotateOAuthGrant({
+ oldRefreshToken: "initial-refresh",
+ accessToken: "replay-access",
+ refreshToken: "replay-refresh",
+ label: "oauth",
+ clientId: "client-replay",
+ resource: "https://mso.example/mcp",
+ })).toBeNull();
+
+ expect(await store.validateToken("successor-access")).toBeNull();
+ expect(await store.rotateOAuthGrant({
+ oldRefreshToken: "successor-refresh",
+ accessToken: "after-replay-access",
+ refreshToken: "after-replay-refresh",
+ label: "oauth",
+ clientId: "client-replay",
+ resource: "https://mso.example/mcp",
+ })).toBeNull();
+ });
+});
diff --git a/lib/mcp/store.test.ts b/lib/mcp/store.test.ts
index 09cd567e..c72ae6e9 100644
--- a/lib/mcp/store.test.ts
+++ b/lib/mcp/store.test.ts
@@ -186,8 +186,9 @@ describe("OAuth refresh grants", () => {
const rotated = await store.rotateOAuthGrant({ oldRefreshToken: "refresh-one", accessToken: "access-two", refreshToken: "refresh-two", label: "oauth", clientId: "chatgpt-client", resource: "https://mso.example/mcp" });
expect(rotated).toMatchObject({ grantId: "grant-one", scope: "exec", offlineAccess: true });
- expect(await store.rotateOAuthGrant({ oldRefreshToken: "refresh-one", accessToken: "replay", refreshToken: "replay-r", label: "oauth", clientId: "chatgpt-client", resource: "https://mso.example/mcp" })).toBeNull();
expect(await store.validateToken("access-two")).toMatchObject({ grantId: "grant-one", profile: "chatgpt" });
+ expect(await store.rotateOAuthGrant({ oldRefreshToken: "refresh-one", accessToken: "replay", refreshToken: "replay-r", label: "oauth", clientId: "chatgpt-client", resource: "https://mso.example/mcp" })).toBeNull();
+ expect(await store.validateToken("access-two")).toBeNull();
});
it("binds refresh to client/resource and revoking one access token kills the grant family", async () => {
@@ -198,57 +199,3 @@ describe("OAuth refresh grants", () => {
await expect(store.rotateOAuthGrant({ oldRefreshToken: "family-refresh", accessToken: "after-revoke", refreshToken: "after-revoke-r", label: "oauth", clientId: "client-a", resource: "https://mso.example/mcp" })).resolves.toBeNull();
});
});
-
-
-describe("durable MCP credential isolation", () => {
- it("assigns every PAT a distinct durable client principal", async () => {
- const first = await store.mintPatToken({ label: "client one", scope: "read", ttlDays: 1 });
- const second = await store.mintPatToken({ label: "client two", scope: "read", ttlDays: 1 });
- const a = await store.validateToken(first.rawToken);
- const b = await store.validateToken(second.rawToken);
- expect(a?.clientId).toMatch(/^manual:pat:[a-f0-9]{24}$/);
- expect(b?.clientId).toMatch(/^manual:pat:[a-f0-9]{24}$/);
- expect(a?.clientId).not.toBe(b?.clientId);
- });
-
- it("treats refresh-token replay as grant-family compromise", async () => {
- await store.storeOAuthGrant({
- accessToken: "initial-access",
- refreshToken: "initial-refresh",
- label: "oauth",
- clientId: "client-replay",
- scope: "exec",
- resource: "https://mso.example/mcp",
- offlineAccess: true,
- grantId: "grant-replay",
- });
- expect(await store.rotateOAuthGrant({
- oldRefreshToken: "initial-refresh",
- accessToken: "successor-access",
- refreshToken: "successor-refresh",
- label: "oauth",
- clientId: "client-replay",
- resource: "https://mso.example/mcp",
- })).not.toBeNull();
- expect(await store.validateToken("successor-access")).not.toBeNull();
-
- expect(await store.rotateOAuthGrant({
- oldRefreshToken: "initial-refresh",
- accessToken: "replay-access",
- refreshToken: "replay-refresh",
- label: "oauth",
- clientId: "client-replay",
- resource: "https://mso.example/mcp",
- })).toBeNull();
-
- expect(await store.validateToken("successor-access")).toBeNull();
- expect(await store.rotateOAuthGrant({
- oldRefreshToken: "successor-refresh",
- accessToken: "after-replay-access",
- refreshToken: "after-replay-refresh",
- label: "oauth",
- clientId: "client-replay",
- resource: "https://mso.example/mcp",
- })).toBeNull();
- });
-});
diff --git a/lib/mcp/tenant-grant-lifecycle.test.ts b/lib/mcp/tenant-grant-lifecycle.test.ts
index 9dfef42c..fcd42123 100644
--- a/lib/mcp/tenant-grant-lifecycle.test.ts
+++ b/lib/mcp/tenant-grant-lifecycle.test.ts
@@ -102,7 +102,7 @@ describe("actual OAuth store with synthetic tenant grants", () => {
const results = await Promise.all([rotate("fixture-refresh", "one"), rotate("fixture-refresh", "two")]);
expect(results.filter(Boolean)).toHaveLength(1);
const replacements = await Promise.all(["fixture-access-one", "fixture-access-two"].map(store.validateToken));
- expect(replacements.filter(Boolean)).toHaveLength(1);
+ expect(replacements.filter(Boolean)).toHaveLength(0); // replay revokes the winning grant family
});
it("never acquires a tenant marker added after an unbound queued call", async () => {
enabled = false;
diff --git a/lib/workflow/organization-agent-routing.test.ts b/lib/workflow/organization-agent-routing.test.ts
index 649af5cd..4522e9c5 100644
--- a/lib/workflow/organization-agent-routing.test.ts
+++ b/lib/workflow/organization-agent-routing.test.ts
@@ -10,6 +10,8 @@ vi.mock("@/lib/capabilities/execute", () => ({ executeCapabilityCall: async ({ t
const dir = await mkdtemp(path.join(os.tmpdir(), "mso-org-routing-"));
process.env.OS_AGENT_SESSIONS_DIR = path.join(dir, "sessions");
process.env.OS_ORGANIZATION_STORE = path.join(dir, "organization.json");
+process.env.OS_DEVICE_STORE = path.join(dir, "devices.json");
+const devices = await import("@/lib/auth/device-store");
const org = await import("@/lib/agent/organization-store");
const graphs = await import("./graph-store");
const engine = await import("./graph-engine");
@@ -35,18 +37,19 @@ describe("workflow organization seat routing", () => {
expect(done.nodes.find((node) => node.id === "agent")?.logs.join(" ")).toContain("Organization seat CTO routed to project agent");
});
it("bridges a Web workflow principal to the same device's native Local Agent namespace", async () => {
+ await devices.approveDevice("aabbccddeeff00112233445566778899", "fixture", "owner");
let chart = await org.getOrganizationChart();
chart = await org.upsertOrganizationSeat(chart.revision, { id: "seat_local", unitId: "unit_product", name: "Operator", title: "Operator", role: "operator", state: "active", seatMode: "on_demand", target: { kind: "local-agent", ref: "milo" } });
- const graph = await graphs.createWorkflowGraph("web:device-1", { name: "Local route", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ const graph = await graphs.createWorkflowGraph("web:aabbccddeeff00112233445566778899", { name: "Local route", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
{ id: "start-local", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
{ id: "agent-local", name: "Operator", type: "agent", position: { x: 120, y: 0 }, config: { orgSeatId: "seat_local", message: "Inspect" } },
], edges: [{ id: "local-e", source: "start-local", target: "agent-local" }] });
let seenPrincipal = "";
const tool: CapabilityTool = { name: "local_agent_request", description: "fixture", scope: "exec", inputSchema: { type: "object", properties: {} }, run: async (_args, ctx) => { seenPrincipal = ctx.principal ?? ""; return { ok: true }; } };
- const context = { principal: "web:device-1", actor: "web:device-1", sessionId: "session", scope: "exec" as const };
+ const context = { principal: "web:aabbccddeeff00112233445566778899", actor: "web:aabbccddeeff00112233445566778899", sessionId: "session", scope: "exec" as const };
const started = await engine.startWorkflowGraph(graph, {}, "org-local-once", context, (name) => name === tool.name ? tool : undefined);
- const done = await engine.workflowGraphRunStatus("web:device-1", started.id, 5000);
- expect(done.state).toBe("completed"); expect(seenPrincipal).toBe("cli:device-1");
+ const done = await engine.workflowGraphRunStatus("web:aabbccddeeff00112233445566778899", started.id, 5000);
+ expect(done.state).toBe("completed"); expect(seenPrincipal).toBe("cli:aabbccddeeff00112233445566778899");
});
});
diff --git a/scripts/install-core.sh b/scripts/install-core.sh
index 0d5c5d3e..1b37e3dd 100755
--- a/scripts/install-core.sh
+++ b/scripts/install-core.sh
@@ -3,32 +3,17 @@
#
# curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash
#
-# Idempotent: re-running updates the checkout, rebuilds, and restarts the
-# service. The bootstrap never needs stdin, so curl|bash stays safe. After a
-# FRESH install it uses /dev/tty (when present) for guided onboarding; CI/headless
-# installs never hang and can run `mso onboard` later. Existing .env.local is preserved.
+# Idempotent update; preserves .env.local. Fresh interactive installs use /dev/tty.
set -Eeuo pipefail
-# ---- config: env override > flag > default ----
CANONICAL_REPO_URL="https://github.com/rahmanef63/mso.git"
REPO_URL="${MSO_REPO:-$CANONICAL_REPO_URL}"
DIR="${MSO_DIR:-$HOME/mso}"
DIR_EXPLICIT=0
REF="${MSO_REF:-main}"
PORT="${MSO_PORT:-4005}"
-# Address the server listens on. Loopback by DEFAULT, for two reasons that point
-# the same way:
-# 1. It cannot log in otherwise. sessionCookieAttrs() sets `secure: true`
-# (lib/auth/session-cookie.ts), and a browser only accepts a Secure cookie
-# over plain http on a trustworthy origin — localhost / 127.0.0.1 / ::1. So
-# http://<lan-or-public-ip>:PORT returns 200 on login and then silently
-# drops the cookie: an endless login loop. A 0.0.0.0 bind buys no working
-# access it did not already have.
-# 2. It is a shell. An authenticated session runs commands as this user, and a
-# fresh VPS has ufw installed but disabled — so the old default published
-# that shell to the whole internet about two minutes into a curl|bash.
-# Reach it over an SSH tunnel, `tailscale serve`, or a reverse proxy on this host
-# (all three land the browser on a trustworthy origin, so the cookie sticks).
+# Loopback protects the host shell and supports Secure session cookies over HTTP.
+# Remote access uses SSH, tailscale serve or a trusted HTTPS reverse proxy.
BIND="${MSO_BIND:-127.0.0.1}"
SERVICE="mso.service"
DO_SERVICE=1
diff --git a/scripts/install-termux.sh b/scripts/install-termux.sh
index 2f6206ce..6689b82c 100755
--- a/scripts/install-termux.sh
+++ b/scripts/install-termux.sh
@@ -7,7 +7,7 @@ DISTRO="${MSO_TERMUX_DISTRO:-mso-ubuntu}"
GUEST_USER="${MSO_TERMUX_USER:-mso}"
IMAGE="${MSO_TERMUX_IMAGE:-ubuntu:24.04}"
GUEST_INSTALL_URL_DEFAULT="https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install-core.sh"
-GUEST_INSTALL_SHA256_DEFAULT="d56a6ed0f1330e53d18d796caf272ac47a1b1abc0ee86c92b4eff5cd2a5bb206"
+GUEST_INSTALL_SHA256_DEFAULT="d796e29308685f21dcccb3ab72a2e39fde698fdf3f33170940335977e5dee46d"
INSTALL_URL="${MSO_TERMUX_INSTALL_URL:-$GUEST_INSTALL_URL_DEFAULT}"
INSTALL_SHA256="${MSO_TERMUX_INSTALL_SHA256:-$GUEST_INSTALL_SHA256_DEFAULT}"
GUEST_REF="${MSO_TERMUX_REF:-main}"
diff --git a/scripts/install.sh b/scripts/install.sh
index 6c3344e1..5f6a1174 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -11,10 +11,10 @@ umask 077
RAW_BASE="${MSO_INSTALL_RAW_BASE:-https://raw.githubusercontent.com/rahmanef63/mso/main/scripts}"
CORE_URL="${MSO_INSTALL_CORE_URL:-https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install-core.sh}"
-CORE_SHA256="d56a6ed0f1330e53d18d796caf272ac47a1b1abc0ee86c92b4eff5cd2a5bb206"
+CORE_SHA256="d796e29308685f21dcccb3ab72a2e39fde698fdf3f33170940335977e5dee46d"
CORE_EOF='# MSO_INSTALLER_CORE_EOF'
MACOS_SHA256="668ec3c8bbf3ee36dc2ae70952c3ba43c6f73ebc3acd6956fa4be2f65a076bfe"
-TERMUX_SHA256="12a979b6ef9a8dc62253e059e612cd1f6201014b7a4c20f5a6dc3d46d0436f10"
+TERMUX_SHA256="eb634d1ec3d5aec0bea6e34243b4b8664ecb2af0df0fd30df196b4a89b0f96f0"
TMP_INSTALLER=''
TMP_PLATFORM=''
diff --git a/scripts/lib/gateway-runtime.sh b/scripts/lib/gateway-runtime.sh
index 5311b351..a30a6ea4 100644
--- a/scripts/lib/gateway-runtime.sh
+++ b/scripts/lib/gateway-runtime.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
# Runtime/state lifecycle used by the public tunnel and local `mso web` fallback.
-GATEWAY_EXPECTED_VERSION="$(node -p "require('$ROOT/package.json').version")" || gateway_fail "cannot read MSO version"
+GATEWAY_EXPECTED_VERSION="$(node -p 'require(process.argv[1]).version' "$ROOT/package.json")" || gateway_fail "cannot read MSO version"
gateway_runtime_from_state() {
local state="$1" identity owned instance stored_env
@@ -42,7 +42,7 @@ NODE
set -- $line; [ "$#" -ge 10 ] || continue
addr="${2:-}"; state="${4:-}"
[ "$state" = 0A ] || continue
- case "$addr" in *:"$hex") inode="${10:-}"; [ -n "$inode" ] && break 2;; esac
+ if [[ "$addr" = *:"$hex" ]]; then inode="${10:-}"; [ -n "$inode" ] && break 2; fi
done <"$file"
done
[[ "$inode" =~ ^[0-9]+$ ]] || return 1
diff --git a/scripts/mso-gateway-test-fixture.ts b/scripts/mso-gateway-test-fixture.ts
index 52e5b22c..649544ce 100644
--- a/scripts/mso-gateway-test-fixture.ts
+++ b/scripts/mso-gateway-test-fixture.ts
@@ -61,7 +61,7 @@ export function fixture() {
if (process.argv.includes('--version')) { console.log('cloudflared version fixture'); process.exit(0); }
if (process.env.OS_SESSION_SECRET || process.env.OS_LOGIN_PASSWORD) require('fs').writeFileSync(process.env.HOME + '/cloudflared-secret-env', 'leaked');
if (process.argv.includes('--url')) {
- require('fs').appendFileSync(process.env.HOME + '/gateway-fake-starts', 'start\n');
+ require('fs').appendFileSync(process.env.HOME + '/gateway-fake-starts', 'start\\n');
console.error('INF https://mso-gateway-fixture.trycloudflare.com');
}
process.on('SIGTERM', () => process.exit(0));