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): pin store paths and eliminate unsafe file-read patterns

Rahman006029617a15
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5cce8be2..554f34fb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2,7 +2,7 @@ name: CI
on:
push:
- branches: [main]
+ branches: [main, "security/**"]
pull_request:
branches: [main]
workflow_dispatch:
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index a7253460..1f0d3d57 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -2,7 +2,7 @@ name: CodeQL
on:
push:
- branches: [main]
+ branches: [main, "security/**"]
pull_request:
branches: [main]
schedule:
@@ -38,3 +38,7 @@ jobs:
uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4
with:
category: /language:javascript-typescript
+ output: ${{ runner.temp }}/mso-codeql-results
+
+ - name: Report every result from this exact CodeQL analysis
+ run: node scripts/codeql-report.mjs "$RUNNER_TEMP/mso-codeql-results"
diff --git a/.github/workflows/security-alerts.yml b/.github/workflows/security-alerts.yml
index b4284ec6..001e0a6c 100644
--- a/.github/workflows/security-alerts.yml
+++ b/.github/workflows/security-alerts.yml
@@ -4,7 +4,7 @@ on:
push:
branches: [main, "security/**"]
workflow_run:
- workflows: [CodeQL, Scorecard]
+ workflows: [CodeQL, OpenSSF Scorecard]
types: [completed]
branches: [main]
workflow_dispatch:
diff --git a/.github/workflows/security-core.yml b/.github/workflows/security-core.yml
index 15c642da..158f90ee 100644
--- a/.github/workflows/security-core.yml
+++ b/.github/workflows/security-core.yml
@@ -2,7 +2,7 @@ name: Security Core
on:
push:
- branches: [main]
+ branches: [main, "security/**"]
pull_request:
branches: [main]
schedule:
diff --git a/bun.lock b/bun.lock
index 24007713..8c9ed4ed 100644
--- a/bun.lock
+++ b/bun.lock
@@ -45,6 +45,7 @@
"eslint": "^9.39.4",
"eslint-config-next": "^16.3.2",
"fast-check": "^4.9.0",
+ "parse5": "8.0.1",
"postcss": "^8.5.26",
"tailwindcss": "^4.3.0",
"typescript": "^5.9.3",
@@ -623,6 +624,8 @@
"enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A=="],
+ "entities": ["[email protected]", "", {}, "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA=="],
+
"es-abstract": ["[email protected]", "", { "dependencies": { "array-buffer-byte-length": "^1.0.2", "arraybuffer.prototype.slice": "^1.0.4", "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "call-bound": "^1.0.4", "data-view-buffer": "^1.0.2", "data-view-byte-length": "^1.0.2", "data-view-byte-offset": "^1.0.1", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "es-set-tostringtag": "^2.1.0", "es-to-primitive": "^1.3.0", "function.prototype.name": "^1.1.8", "get-intrinsic": "^1.3.0", "get-proto": "^1.0.1", "get-symbol-description": "^1.1.0", "globalthis": "^1.0.4", "gopd": "^1.2.0", "has-property-descriptors": "^1.0.2", "has-proto": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "internal-slot": "^1.1.0", "is-array-buffer": "^3.0.5", "is-callable": "^1.2.7", "is-data-view": "^1.0.2", "is-negative-zero": "^2.0.3", "is-regex": "^1.2.1", "is-set": "^2.0.3", "is-shared-array-buffer": "^1.0.4", "is-string": "^1.1.1", "is-typed-array": "^1.1.15", "is-weakref": "^1.1.1", "math-intrinsics": "^1.1.0", "object-inspect": "^1.13.4", "object-keys": "^1.1.1", "object.assign": "^4.1.7", "own-keys": "^1.0.1", "regexp.prototype.flags": "^1.5.4", "safe-array-concat": "^1.1.3", "safe-push-apply": "^1.0.0", "safe-regex-test": "^1.1.0", "set-proto": "^1.0.0", "stop-iteration-iterator": "^1.1.0", "string.prototype.trim": "^1.2.10", "string.prototype.trimend": "^1.0.9", "string.prototype.trimstart": "^1.0.8", "typed-array-buffer": "^1.0.3", "typed-array-byte-length": "^1.0.3", "typed-array-byte-offset": "^1.0.4", "typed-array-length": "^1.0.7", "unbox-primitive": "^1.1.0", "which-typed-array": "^1.1.19" } }, "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg=="],
"es-abstract-get": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "es-object-atoms": "^1.1.2", "is-callable": "^1.2.7", "object-inspect": "^1.13.4" } }, "sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg=="],
@@ -985,6 +988,8 @@
"parent-module": ["[email protected]", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="],
+ "parse5": ["[email protected]", "", { "dependencies": { "entities": "^8.0.0" } }, "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw=="],
+
"path-exists": ["[email protected]", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
"path-key": ["[email protected]", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index b8f6d7d0..3d715abf 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,7 @@
+## 2026-09-05 — Resolve actual CodeQL findings and restore the demo
+
+The actual GitHub alert inventory exposed 22 default-branch findings, unlike the previously green scanner-completion jobs. Security-store locks now use an owner-root-validated pinned directory while preserving adjacent CLI lock names; bounded no-follow reads replace file check/reopen pairs. HTML fixture extraction uses parse5; the terminal picker opens its device once. Owner facts and activity logs now have explicit field/byte limits, private no-follow storage, concurrency and rejection tests. Diagnostic logging failures remain isolated from authorized tool execution. Security branches receive real CodeQL, CI and independent scanners; unfiltered SARIF summaries and a separate actual-alert inventory make pending evidence visible. README restores the existing real GIF inline and has a regression test for animation and screenshot presence. No alert is automatically dismissed by these changes.
+
## 2026-09-05 — MCP Page preview lifecycle
diff --git a/lib/agent/legacy-owner-memory.test.ts b/lib/agent/legacy-owner-memory.test.ts
index b24dafb9..009de739 100644
--- a/lib/agent/legacy-owner-memory.test.ts
+++ b/lib/agent/legacy-owner-memory.test.ts
@@ -1,25 +1,47 @@
-import { describe, it, expect } from "vitest";
+import { afterAll, beforeEach, describe, it, expect } from "vitest";
+import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
-process.env.OS_MEMORY_STORE = path.join(os.tmpdir(), `mso-memory-test-${process.pid}.json`);
+const directory = await fs.mkdtemp(path.join(os.tmpdir(), "mso-memory-test-"));
+const file = path.join(directory, "memory.json");
+process.env.OS_MEMORY_STORE = file;
const { addMemory, recall, listMemories, removeMemory } = await import("./legacy-owner-memory");
+beforeEach(async () => { await fs.rm(file, { force: true }); });
+afterAll(async () => { delete process.env.OS_MEMORY_STORE; await fs.rm(directory, { recursive: true, force: true }); });
-describe("memory store + recall", () => {
+describe("owner memory store + recall", () => {
it("adds, recalls by word overlap, and removes", async () => {
- const a = await addMemory("I deploy mso with bun run build then restart");
+ const a = await addMemory("I deploy mso with the guarded release command");
await addMemory("My favorite color is blue");
-
- const hits = await recall("how do I deploy?");
- const joined = hits.map((m) => m.text).join();
- expect(joined).toMatch(/deploy/);
- expect(joined).not.toMatch(/color/); // "deploy" doesn't overlap the color fact
-
- await removeMemory(a.id);
- expect((await listMemories()).some((m) => m.id === a.id)).toBe(false);
+ const joined = (await recall("how do I deploy?")).map((m) => m.text).join();
+ expect(joined).toMatch(/deploy/); expect(joined).not.toMatch(/color/);
+ await removeMemory(a.id); expect((await listMemories()).some((m) => m.id === a.id)).toBe(false);
});
-
- it("falls back to recent facts when the query has no ≥3-char words", async () => {
- expect(Array.isArray(await recall("a b"))).toBe(true);
+ it("falls back to recent facts when the query has no long words", async () => {
+ await addMemory("Keep this user fact as data"); expect(await recall("a b")).toHaveLength(1);
+ });
+ it("serializes parallel additions without losing a fact", async () => {
+ await Promise.all(Array.from({ length: 12 }, (_, i) => addMemory(`Concurrent fact ${i}`)));
+ const rows = await listMemories(); expect(rows).toHaveLength(12); expect(new Set(rows.map((x) => x.id)).size).toBe(12);
+ });
+ it("refuses malformed existing state rather than overwriting it", async () => {
+ await fs.writeFile(file, "invalid existing content", { mode: 0o600 });
+ await expect(addMemory("new data")).rejects.toThrow();
+ expect(await fs.readFile(file, "utf8")).toBe("invalid existing content");
+ });
+ it("refuses symlinked state without changing the target", async () => {
+ const victim = path.join(directory, "victim.json"); await fs.writeFile(victim, "[]", { mode: 0o600 });
+ await fs.symlink(victim, file);
+ await expect(addMemory("do not follow symlinks")).rejects.toThrow();
+ expect(await fs.readFile(victim, "utf8")).toBe("[]");
+ });
+ it("rejects empty or control-character input and keeps arbitrary text non-executable", async () => {
+ await expect(addMemory(" ")).rejects.toThrow(); await expect(addMemory("bad\0text")).rejects.toThrow();
+ const literal = "User fact: <script>example()</script>; $(not-executed)";
+ const memory = await addMemory(literal); expect((await listMemories())[0].text).toBe(literal);
+ const stored = JSON.parse(await fs.readFile(file, "utf8"));
+ expect(Object.keys(stored[0]).sort()).toEqual(["createdAt", "id", "text"]);
+ expect(stored[0].id).toBe(memory.id);
});
});
diff --git a/lib/agent/legacy-owner-memory.ts b/lib/agent/legacy-owner-memory.ts
index 3170c443..f1d8f03d 100644
--- a/lib/agent/legacy-owner-memory.ts
+++ b/lib/agent/legacy-owner-memory.ts
@@ -1,61 +1,91 @@
-import { promises as fs } from "node:fs";
+import { randomUUID } from "node:crypto";
+import { constants, promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
+import { pinSecurityStorePath } from "@/lib/security-store-path";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
-// Durable cross-session facts recalled into Alfa's system prompt. One JSON file in
-// ~/.mso (small structured records, chmod 600). Recall is substring scoring for
-// now. ponytail: substring recall — swap for embeddings if it gets noisy at scale.
-export interface Memory {
- id: string;
- text: string;
- createdAt: number;
-}
-
+// Owner-authenticated facts, persisted as bounded JSON data, never executable source.
+export interface Memory { id: string; text: string; createdAt: number; }
const FILE = process.env.OS_MEMORY_STORE || path.join(os.homedir(), ".mso", "memory.json");
+const MAX_BYTES = 2 * 1024 * 1024;
+const MAX_RECORDS = 1000;
+
+function records(value: unknown): Memory[] {
+ if (!Array.isArray(value) || value.length > MAX_RECORDS) throw new Error("Invalid or oversized memory store");
+ return value.map((row) => {
+ if (!row || typeof row !== "object" || Array.isArray(row)
+ || typeof row.id !== "string" || !/^mem_[a-zA-Z0-9_-]{1,80}$/.test(row.id)
+ || typeof row.text !== "string" || row.text.length > 500
+ || !Number.isSafeInteger(row.createdAt) || row.createdAt < 0) throw new Error("Invalid memory record");
+ // Deliberate projection: persisted objects cannot inject additional fields.
+ return { id: row.id, text: row.text, createdAt: row.createdAt };
+ });
+}
async function read(): Promise<Memory[]> {
+ const pinned = await pinSecurityStorePath(FILE);
+ let handle;
try {
- const j = JSON.parse(await fs.readFile(FILE, "utf8"));
- return Array.isArray(j) ? j : [];
- } catch {
- return [];
- }
+ handle = await fs.open(pinned.file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || stat.nlink !== 1 || (stat.mode & 0o077) || stat.size > MAX_BYTES) throw new Error("Unsafe memory store");
+ const bytes = Buffer.alloc(Number(stat.size));
+ let offset = 0;
+ while (offset < bytes.length) {
+ const read = await handle.read(bytes, offset, bytes.length - offset, offset);
+ if (!read.bytesRead) throw new Error("Memory store changed during read");
+ offset += read.bytesRead;
+ }
+ const after = await handle.stat();
+ if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) throw new Error("Memory store changed during read");
+ return records(JSON.parse(bytes.toString("utf8")));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
+ throw error; // Never overwrite corrupt/unreadable existing state with an empty list.
+ } finally { await handle?.close(); await pinned.directory.close(); }
}
async function write(list: Memory[]): Promise<void> {
- await fs.mkdir(path.dirname(FILE), { recursive: true, mode: 0o700 });
- const tmp = `${FILE}.tmp`;
- await fs.writeFile(tmp, JSON.stringify(list, null, 2), { encoding: "utf8", mode: 0o600 });
- await fs.rename(tmp, FILE);
+ const body = JSON.stringify(records(list), null, 2) + "\n";
+ if (Buffer.byteLength(body) > MAX_BYTES) throw new Error("Memory store exceeds its byte limit");
+ const pinned = await pinSecurityStorePath(FILE);
+ const temporary = `${pinned.file}.${randomUUID()}.tmp`;
+ try {
+ const handle = await fs.open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
+ try { await handle.writeFile(body, "utf8"); await handle.sync(); }
+ finally { await handle.close(); }
+ await fs.rename(temporary, pinned.file);
+ } finally {
+ await fs.unlink(temporary).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; });
+ await pinned.directory.close();
+ }
}
-export async function listMemories(): Promise<Memory[]> {
- return (await read()).sort((a, b) => b.createdAt - a.createdAt);
-}
+export async function listMemories(): Promise<Memory[]> { return (await read()).sort((a, b) => b.createdAt - a.createdAt); }
export async function addMemory(text: string): Promise<Memory> {
- const m: Memory = { id: `mem_${Date.now().toString(36)}`, text: text.trim().slice(0, 500), createdAt: Date.now() };
- const list = await read();
- list.push(m);
- await write(list);
- return m;
+ if (typeof text !== "string") throw new Error("Memory text must be a string");
+ const clean = text.trim().slice(0, 500);
+ if (!clean || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(clean)) throw new Error("Memory text is empty or contains control characters");
+ const memory: Memory = { id: `mem_${randomUUID()}`, text: clean, createdAt: Date.now() };
+ return withSecurityStoreLock(FILE, async () => {
+ const list = await read();
+ if (list.length >= MAX_RECORDS) throw new Error("Memory store is full; remove an old record first");
+ await write([...list, memory]);
+ return memory;
+ });
}
export async function removeMemory(id: string): Promise<void> {
- await write((await read()).filter((m) => m.id !== id));
+ await withSecurityStoreLock(FILE, async () => { await write((await read()).filter((memory) => memory.id !== id)); });
}
-// Recall facts relevant to `query` (scored by how many of its ≥3-char words appear),
-// capped. No query signal → the most recent facts.
+// Bounded substring recall, not a claim of semantic retrieval or trusted instructions.
export async function recall(query: string, limit = 8): Promise<Memory[]> {
- const all = await read();
- if (all.length === 0) return [];
+ const all = await read(), count = Math.max(1, Math.min(100, Math.floor(limit) || 8));
const words = query.toLowerCase().match(/[a-z0-9]{3,}/g) ?? [];
- if (words.length === 0) return all.slice(-limit);
- return all
- .map((m) => ({ m, hits: words.filter((w) => m.text.toLowerCase().includes(w)).length }))
- .filter((s) => s.hits > 0)
- .sort((a, b) => b.hits - a.hits)
- .slice(0, limit)
- .map((s) => s.m);
+ if (!words.length) return all.slice(-count);
+ return all.map((memory) => ({ memory, hits: words.filter((word) => memory.text.toLowerCase().includes(word)).length }))
+ .filter((row) => row.hits > 0).sort((a, b) => b.hits - a.hits).slice(0, count).map((row) => row.memory);
}
diff --git a/lib/capabilities/activity-security.test.ts b/lib/capabilities/activity-security.test.ts
new file mode 100644
index 00000000..c29d2c12
--- /dev/null
+++ b/lib/capabilities/activity-security.test.ts
@@ -0,0 +1,35 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+const directory = await fs.mkdtemp(path.join(os.tmpdir(), "mso-activity-security-"));
+const file = path.join(directory, "activity.jsonl");
+process.env.OS_MCP_ACTIVITY_LOG = file;
+const { recordCapabilityActivity, readCapabilityActivity } = await import("./activity");
+beforeEach(async () => { await fs.rm(file, { force: true }); });
+afterAll(async () => { delete process.env.OS_MCP_ACTIVITY_LOG; await fs.rm(directory, { recursive: true, force: true }); });
+
+describe("private activity metadata persistence", () => {
+ it("projects approved fields and redacts text without persisting request bodies", async () => {
+ const entry = { id: "test", tool: "fs_write", state: "completed" as const, target: "token=synthetic-value", detail: "password=synthetic-value", content: "request-body-not-for-log", arbitrary: "do-not-keep" };
+ await recordCapabilityActivity(entry);
+ const raw = await fs.readFile(file, "utf8");
+ expect(raw).not.toContain("synthetic-value"); expect(raw).not.toContain("request-body-not-for-log"); expect(raw).not.toContain("arbitrary");
+ expect((await readCapabilityActivity(1))[0].target).toBe("token=[redacted]");
+ });
+ it("leaves symlink destinations untouched and isolates diagnostic failures", async () => {
+ const victim = path.join(directory, "victim"); await fs.writeFile(victim, "untouched", { mode: 0o600 }); await fs.symlink(victim, file);
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
+ try {
+ await recordCapabilityActivity({ id: "refused", tool: "fs_write", state: "completed" });
+ expect(await fs.readFile(victim, "utf8")).toBe("untouched"); expect(log).toHaveBeenCalled();
+ await expect(readCapabilityActivity()).rejects.toThrow();
+ } finally { log.mockRestore(); }
+ });
+ it("rejects invalid identities and oversized metadata cannot grow an unbounded record", async () => {
+ expect(() => recordCapabilityActivity({ id: "bad\nrow", tool: "fs_write", state: "completed" })).toThrow();
+ await recordCapabilityActivity({ id: "bounded", tool: "fs_write", state: "completed", detail: "x".repeat(20000) });
+ expect(Buffer.byteLength(await fs.readFile(file))).toBeLessThan(1024);
+ });
+});
diff --git a/lib/capabilities/activity.ts b/lib/capabilities/activity.ts
index 2960dcdc..ef829385 100644
--- a/lib/capabilities/activity.ts
+++ b/lib/capabilities/activity.ts
@@ -1,93 +1,100 @@
-import { promises as fs } from "fs";
-import os from "os";
-import path from "path";
-import { randomUUID } from "crypto";
+import { constants, promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { randomUUID } from "node:crypto";
+import { pinSecurityStorePath } from "@/lib/security-store-path";
export type CapabilityActivityState = "started" | "completed" | "failed" | "denied" | "rate_limited" | "invalid_args";
-
export interface CapabilityActivityEntry {
- id: string;
- ts: string;
- actor?: string | null;
- tool: string;
- state: CapabilityActivityState;
- scope?: string;
- workflowId?: string;
- workflowIntent?: string;
- workflowProject?: string;
- target?: string;
- durationMs?: number;
- detail?: string;
+ id: string; ts: string; actor?: string | null; tool: string;
+ state: CapabilityActivityState; scope?: string; workflowId?: string;
+ workflowIntent?: string; workflowProject?: string; target?: string;
+ durationMs?: number; detail?: string;
}
-
+const STATES = new Set(["started", "completed", "failed", "denied", "rate_limited", "invalid_args"]);
+const TAIL_BYTES = 4 * 1024 * 1024;
function activityPath(): string {
const env = process.env.OS_MCP_ACTIVITY_LOG;
- if (env && env.trim()) return env.replace(/^~(?=$|\/)/, os.homedir());
- return path.join(os.homedir(), ".mso", "mcp-activity.log");
-}
-
-function trunc(v: string | undefined, max = 180): string | undefined {
- if (!v) return undefined;
- return v.length > max ? v.slice(0, max) + "…" : v;
+ return env?.trim() ? env.replace(/^~(?=$|\/)/, os.homedir()) : path.join(os.homedir(), ".mso", "mcp-activity.log");
}
-
function safeActivityText(value: string): string {
- return value
+ return value.replace(/[\u0000-\u001f\u007f]/gu, " ")
.replace(/([?&](?:token|key|secret|password|code)=)[^&\s]+/gi, "$1[redacted]")
.replace(/\b(password|token|secret|api[_-]?key)\s*[:=]\s*\S+/gi, "$1=[redacted]")
.replace(/\b(?:bearer\s+)?(?:sk|pk|ghp|mso_mcp)_[a-z0-9_-]{8,}\b/gi, "[redacted]")
.replace(/\b[a-f0-9]{48,}\b/gi, "[opaque-id]");
}
-
-let chain: Promise<void> = Promise.resolve();
-
-export function newActivityId(): string {
- return randomUUID();
+function text(value: unknown, limit = 180): string | undefined {
+ if (value == null || value === "") return undefined;
+ if (typeof value !== "string") throw new Error("Activity metadata must be text");
+ const safe = safeActivityText(value);
+ return safe.length > limit ? safe.slice(0, limit) + "…" : safe;
}
-
+function normalized(entry: Omit<CapabilityActivityEntry, "ts"> & { ts?: string }): CapabilityActivityEntry {
+ if (typeof entry.id !== "string" || !/^[A-Za-z0-9_.:-]{1,180}$/.test(entry.id)
+ || typeof entry.tool !== "string" || !/^[A-Za-z][A-Za-z0-9_.:-]{0,119}$/.test(entry.tool)
+ || !STATES.has(entry.state)) throw new Error("Invalid activity identity or state");
+ if (entry.scope != null && !["read", "write", "exec"].includes(entry.scope)) throw new Error("Invalid activity scope");
+ if (entry.durationMs != null && (!Number.isFinite(entry.durationMs) || entry.durationMs < 0)) throw new Error("Invalid activity duration");
+ if (entry.ts != null && (!Number.isFinite(Date.parse(entry.ts)) || entry.ts.length > 40)) throw new Error("Invalid activity timestamp");
+ // Never spread a caller's object: request bodies/unknown keys must not reach disk.
+ return {
+ id: entry.id, tool: entry.tool, state: entry.state, ts: entry.ts ?? new Date().toISOString(),
+ actor: text(entry.actor), scope: entry.scope, workflowId: text(entry.workflowId),
+ workflowIntent: text(entry.workflowIntent, 500), workflowProject: text(entry.workflowProject, 240),
+ target: text(entry.target), detail: text(entry.detail, 220), durationMs: entry.durationMs,
+ };
+}
+let chain: Promise<void> = Promise.resolve();
+export function newActivityId(): string { return randomUUID(); }
export function activityTarget(args: Record<string, unknown>): string | undefined {
- // Never serialize fs_write.content or arbitrary payloads. Prefer the one field
- // that explains what the tool is acting on without leaking the body.
for (const key of ["path", "id", "target", "query", "intent", "project", "from", "command", "on", "workflow_id"] as const) {
- const v = args[key];
- if (typeof v === "string" && v) return trunc(safeActivityText(v));
- if (typeof v === "boolean") return String(v);
+ const value = args[key];
+ if (typeof value === "string" && value) return text(value);
+ if (typeof value === "boolean") return String(value);
}
return undefined;
}
-
export function recordCapabilityActivity(entry: Omit<CapabilityActivityEntry, "ts"> & { ts?: string }): Promise<void> {
if (process.env.VITEST && !process.env.OS_MCP_ACTIVITY_LOG) return Promise.resolve();
- const line = JSON.stringify({
- ...entry,
- ts: entry.ts ?? new Date().toISOString(),
- workflowIntent: trunc(entry.workflowIntent ? safeActivityText(entry.workflowIntent) : undefined, 500),
- workflowProject: trunc(entry.workflowProject ? safeActivityText(entry.workflowProject) : undefined, 240),
- target: trunc(entry.target),
- detail: trunc(entry.detail, 220),
- }) + "\n";
- chain = chain.then(async () => {
- const file = activityPath();
+ const line = JSON.stringify(normalized(entry)) + "\n";
+ if (Buffer.byteLength(line) > 8192) return Promise.reject(new Error("Activity record exceeds limit"));
+ chain = chain.catch(() => undefined).then(async () => {
+ const pinned = await pinSecurityStorePath(activityPath());
+ let handle;
try {
- await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
- await fs.appendFile(file, line, { mode: 0o600 });
- } catch (e) {
- console.error("[capability-activity] write failed:", e instanceof Error ? e.message : e);
- }
+ handle = await fs.open(pinned.file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || stat.nlink !== 1 || (stat.mode & 0o077)) throw new Error("Unsafe activity log");
+ await handle.writeFile(line, "utf8");
+ } finally { await handle?.close(); await pinned.directory.close(); }
});
- return chain;
+ // Activity is diagnostic metadata, not the mandatory security audit trail.
+ // Record failures without crashing an otherwise authorized tool call.
+ return chain.catch(() => { console.error("[capability-activity] bounded private log write failed"); });
}
-
export async function readCapabilityActivity(limit = 80): Promise<CapabilityActivityEntry[]> {
- const raw = await fs.readFile(activityPath(), "utf8").catch(() => "");
- return raw
- .split("\n")
- .filter(Boolean)
- .slice(-800)
- .map((line) => {
- try { return JSON.parse(line) as CapabilityActivityEntry; } catch { return null; }
- })
- .filter((v): v is CapabilityActivityEntry => Boolean(v?.id && v?.tool && v?.state))
- .slice(-Math.min(Math.max(limit, 1), 200))
- .reverse();
+ const pinned = await pinSecurityStorePath(activityPath());
+ let handle;
+ try {
+ handle = await fs.open(pinned.file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || stat.nlink !== 1 || (stat.mode & 0o077)) throw new Error("Unsafe activity log");
+ const start = Math.max(0, Number(stat.size) - TAIL_BYTES), buffer = Buffer.alloc(Math.min(Number(stat.size), TAIL_BYTES));
+ let offset = 0;
+ while (offset < buffer.length) {
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, start + offset);
+ if (!bytesRead) break;
+ offset += bytesRead;
+ }
+ const lines = buffer.subarray(0, offset).toString("utf8").split("\n");
+ if (start) lines.shift(); // the first tail fragment may start inside a JSON string
+ return lines.filter(Boolean).slice(-800).map((line) => {
+ try { return normalized(JSON.parse(line)); } catch { return null; }
+ }).filter((value): value is CapabilityActivityEntry => value !== null)
+ .slice(-Math.min(Math.max(Math.floor(limit) || 80, 1), 200)).reverse();
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
+ throw error;
+ } finally { await handle?.close(); await pinned.directory.close(); }
}
diff --git a/lib/forge/evaluate.ts b/lib/forge/evaluate.ts
index 3f54d261..eee29ed4 100644
--- a/lib/forge/evaluate.ts
+++ b/lib/forge/evaluate.ts
@@ -1,3 +1,4 @@
+import { forgeTargetHash } from "./target-hash";
import { createHash } from "node:crypto";
import { promises as fs } from "node:fs";
import path from "node:path";
@@ -34,10 +35,7 @@ async function currentTargetHash(candidate: ForgeCandidate): Promise<string> {
const target = candidate.kind === "skill"
? path.join(candidate.projectPath, ".mso", "skills", candidate.skill!.name, "SKILL.md")
: path.join(candidate.projectPath, ".mso", "functions.json");
- const stat = await fs.lstat(target).catch(() => null);
- if (!stat) return "absent";
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 512 * 1024) return "invalid";
- return createHash("sha256").update(await fs.readFile(target)).digest("hex");
+ return forgeTargetHash(target);
}
function recipeChecks(candidate: ForgeCandidate, checks: ForgeCheck[]): void {
diff --git a/lib/forge/promote.ts b/lib/forge/promote.ts
index a70226ba..401d3013 100644
--- a/lib/forge/promote.ts
+++ b/lib/forge/promote.ts
@@ -1,3 +1,4 @@
+import { forgeTargetHash } from "./target-hash";
import { createHash } from "node:crypto";
import { promises as fs } from "node:fs";
import path from "node:path";
@@ -22,12 +23,6 @@ async function safeMsoDir(projectPath: string): Promise<string> {
return real;
}
-async function targetHash(file: string): Promise<string> {
- const stat = await fs.lstat(file).catch(() => null);
- if (!stat) return "absent";
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 512 * 1024) return "invalid";
- return hash(await fs.readFile(file));
-}
function assertEvaluated(candidate: ForgeCandidate): void {
const evaluation = candidate.evaluation;
@@ -57,7 +52,7 @@ async function promoteFunction(candidate: ForgeCandidate): Promise<ForgePromotio
if (!candidate.evaluation?.sourceHash || candidate.evaluation.sourceHash !== sourceHash) throw new Error("project function source changed after evaluation; evaluate again");
const mso = await safeMsoDir(candidate.projectPath), file = path.join(mso, "functions.json");
const expected = candidate.evaluation?.targetHash ?? "";
- if (await targetHash(file) !== expected) throw new Error("project functions manifest changed after evaluation; evaluate again");
+ if (await forgeTargetHash(file) !== expected) throw new Error("project functions manifest changed after evaluation; evaluate again");
const current = await readProjectFunctionsManifest(candidate.projectPath);
if (current.found && !current.functions) throw new Error(current.error ?? "existing functions manifest is invalid");
const functions = current.found ? (current.functions ?? []) : [];
diff --git a/lib/forge/store.ts b/lib/forge/store.ts
index 3ab594f4..6fd0d7b7 100644
--- a/lib/forge/store.ts
+++ b/lib/forge/store.ts
@@ -1,3 +1,4 @@
+import { readBoundedRegularBufferOrThrow } from "@/lib/host/bounded-read";
import { createHash, randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
import os from "node:os";
@@ -34,10 +35,14 @@ async function ensureRoot(): Promise<void> {
}
async function readCandidateFile(file: string): Promise<ForgeCandidate | null> {
- const stat = await fs.lstat(file).catch(() => null);
- if (!stat) return null;
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size <= 0 || stat.size > 256 * 1024) throw new Error("invalid forge candidate file");
- return JSON.parse(await fs.readFile(file, "utf8")) as ForgeCandidate;
+ try {
+ const data = await readBoundedRegularBufferOrThrow(file, 256 * 1024);
+ if (!data.length) throw new Error("invalid forge candidate file");
+ return JSON.parse(data.toString("utf8")) as ForgeCandidate;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw new Error("invalid forge candidate file", { cause: error });
+ }
}
async function writeCandidateFile(file: string, candidate: ForgeCandidate): Promise<void> {
diff --git a/lib/forge/target-hash.ts b/lib/forge/target-hash.ts
new file mode 100644
index 00000000..11f58207
--- /dev/null
+++ b/lib/forge/target-hash.ts
@@ -0,0 +1,11 @@
+import { createHash } from "node:crypto";
+import { readBoundedRegularBufferOrThrow } from "@/lib/host/bounded-read";
+
+export async function forgeTargetHash(file: string): Promise<string> {
+ try {
+ const data = await readBoundedRegularBufferOrThrow(file, 512 * 1024);
+ return createHash("sha256").update(data).digest("hex");
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : "invalid";
+ }
+}
diff --git a/lib/host/bounded-read.ts b/lib/host/bounded-read.ts
index 894593bc..2dde020e 100644
--- a/lib/host/bounded-read.ts
+++ b/lib/host/bounded-read.ts
@@ -28,29 +28,28 @@ export const BOUNDED_READ = {
projectMcpConfig: 256 * 1024,
} as const;
-export async function readBoundedRegularBuffer(file: string, maxBytes: number): Promise<Buffer | null> {
- let handle: Awaited<ReturnType<typeof fs.open>>;
- try {
- // O_NOFOLLOW: ELOOP if `file` itself is a symlink. Intermediate directories are
- // the caller's problem — they are realpath-contained before we get here.
- handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
- } catch {
- return null;
- }
+export async function readBoundedRegularBufferOrThrow(file: string, maxBytes: number): Promise<Buffer> {
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes > 64 * 1024 * 1024) throw new Error("invalid bounded-read limit");
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
try {
- const stat = await handle.stat();
- if (!stat.isFile()) return null;
- if (stat.size > maxBytes) return null;
- const size = Number(stat.size);
- if (size === 0) return Buffer.alloc(0);
- const buffer = Buffer.allocUnsafe(size);
- const { bytesRead } = await handle.read(buffer, 0, size, 0);
- return buffer.subarray(0, bytesRead);
- } catch {
- return null;
- } finally {
- await handle.close().catch(() => undefined);
- }
+ const before = await handle.stat();
+ if (!before.isFile() || before.size > maxBytes) throw new Error("not a bounded regular file");
+ const buffer = Buffer.alloc(Number(before.size));
+ let offset = 0;
+ while (offset < buffer.length) {
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
+ if (!bytesRead) throw new Error("file changed during bounded read");
+ offset += bytesRead;
+ }
+ const after = await handle.stat();
+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs) throw new Error("file changed during bounded read");
+ return buffer;
+ } finally { await handle.close(); }
+}
+
+export async function readBoundedRegularBuffer(file: string, maxBytes: number): Promise<Buffer | null> {
+ try { return await readBoundedRegularBufferOrThrow(file, maxBytes); }
+ catch { return null; }
}
export async function readBoundedRegularFile(file: string, maxBytes: number): Promise<string | null> {
diff --git a/lib/infra/setup-capability.test.ts b/lib/infra/setup-capability.test.ts
index 0ceedf37..03c6a9b5 100644
--- a/lib/infra/setup-capability.test.ts
+++ b/lib/infra/setup-capability.test.ts
@@ -20,8 +20,11 @@ describe("native integration setup capabilities", () => {
const grant = await api.openIntegrationSetup("composio", "test-owner", "project");
expect(grant.token).toMatch(/^[A-Za-z0-9_-]{43}$/);
const file = path.join(root, "integration-setup", createHash("sha256").update(grant.token).digest("hex") + ".json");
- expect((await fs.stat(file)).mode & 0o777).toBe(0o600);
- const stored = await fs.readFile(file, "utf8"); expect(stored).not.toContain(grant.token); expect(stored).toContain("test-owner");
+ const handle = await fs.open(file, "r");
+ try {
+ expect((await handle.stat()).mode & 0o777).toBe(0o600);
+ const stored = await handle.readFile("utf8"); expect(stored).not.toContain(grant.token); expect(stored).toContain("test-owner");
+ } finally { await handle.close(); }
expect(grant.setup.fields.map(f => f.key)).toEqual(["apiKey"]);
expect(grant.setup.expiresAt - Date.now()).toBeLessThanOrEqual(600000);
await expect(api.consumeIntegrationSetup(grant.token, { orgApiKey: KEY })).rejects.toMatchObject({ code: "invalid_fields" });
diff --git a/lib/infra/setup-hub.test.ts b/lib/infra/setup-hub.test.ts
index c1c9a367..3f58d102 100644
--- a/lib/infra/setup-hub.test.ts
+++ b/lib/infra/setup-hub.test.ts
@@ -1,3 +1,4 @@
+import { inlineScripts } from "../../scripts/test-support/inline-scripts";
import { expect, it } from "vitest";
import { integrationCatalog } from "./setup-catalog";
import { INTEGRATION_PICKER_SCRIPT } from "./setup-picker";
@@ -10,7 +11,7 @@ it("derives the complete native setup catalog from the same provider registry",
});
it("keeps guidance before login and preserves explicit role/expiry recovery", () => {
const page = integrationSetupPage();
- expect(() => new Function(page.html.match(/<script[^>]*>([\s\S]*?)<\/script>/)![1])).not.toThrow();
+ expect(() => new Function(inlineScripts(page.html)[0])).not.toThrow();
for (const marker of ['"/api/auth/me"', 'session.role!=="owner"', '"visibilitychange"', '"How to get this credential"', 'Open a new setup session']) expect(page.html).toContain(marker);
expect(INTEGRATION_PICKER_SCRIPT).not.toContain('localStorage'); expect(page.csp).toContain("form-action 'none'");
});
diff --git a/lib/mcp/ui-page-lifecycle.test.ts b/lib/mcp/ui-page-lifecycle.test.ts
index 2f8f2df0..cf73a8d9 100644
--- a/lib/mcp/ui-page-lifecycle.test.ts
+++ b/lib/mcp/ui-page-lifecycle.test.ts
@@ -1,3 +1,4 @@
+import { inlineScripts } from "../../scripts/test-support/inline-scripts";
import { describe, expect, it } from "vitest";
import { LEGACY_PAGE_V2_URI, LEGACY_PAGE_V3_URI, MSO_PAGE_URI, listUiResources, readUiResource } from "./ui-resources";
@@ -11,7 +12,7 @@ describe("MCP Page lifecycle and cached resource migration", () => {
});
it("includes the Apps handshake and readiness contract in valid self-contained JavaScript", () => {
const html = readUiResource(MSO_PAGE_URI)?.text ?? "";
- const script = html.match(/<script>([\s\S]*)<\/script>/)?.[1];
+ const script = inlineScripts(html)[0];
expect(script).toBeTruthy();
expect(() => new Function(script ?? "")).not.toThrow();
for (const marker of [
diff --git a/lib/mcp/ui-resources.test.ts b/lib/mcp/ui-resources.test.ts
index 8bfafa8e..0927a076 100644
--- a/lib/mcp/ui-resources.test.ts
+++ b/lib/mcp/ui-resources.test.ts
@@ -1,3 +1,4 @@
+import { inlineScripts } from "../../scripts/test-support/inline-scripts";
import { describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
@@ -111,7 +112,7 @@ describe("MCP Apps Block and Page contract", () => {
expect(content.text).toContain("slice(0,12000)");
expect(content.text).toContain("MSO block submission");
expect(content.text).toContain("workflowFallback");
- const script = content.text.match(/<script>([\s\S]*)<\/script>/)?.[1];
+ const script = inlineScripts(content.text)[0];
expect(script).toBeTruthy();
expect(() => new Function(script!)).not.toThrow();
expect(content.text).not.toContain("fetch(");
diff --git a/lib/orchestration/repo-memory-artifacts.ts b/lib/orchestration/repo-memory-artifacts.ts
index 50d21cde..732f0c49 100644
--- a/lib/orchestration/repo-memory-artifacts.ts
+++ b/lib/orchestration/repo-memory-artifacts.ts
@@ -1,3 +1,4 @@
+import { readBoundedRegularFile } from "@/lib/host/bounded-read";
import { promises as fs } from "node:fs";
import path from "node:path";
import {
@@ -40,10 +41,10 @@ export async function readAutomationScript(projectPath: string, id: string): Pro
const safeId = safeArtifactId(id);
for (const name of [`${safeId}.json`, `${safeId}.candidate.json`]) {
const file = path.join(agent, "scripts", name);
- const stat = await fs.lstat(file).catch(() => null);
- if (!stat?.isFile() || stat.isSymbolicLink() || stat.size <= 0 || stat.size > MAX_RECORD_BYTES) continue;
+ const raw = await readBoundedRegularFile(file, MAX_RECORD_BYTES);
+ if (!raw) continue;
try {
- const parsed = JSON.parse(await fs.readFile(file, "utf8")) as AutomationScriptManifest;
+ const parsed = JSON.parse(raw) as AutomationScriptManifest;
if (parsed?.schemaVersion !== 1 || parsed.id !== id || !Array.isArray(parsed.steps) || !parsed.steps.length) continue;
if (parsed.status !== "candidate" && parsed.status !== "tested") continue;
return parsed;
diff --git a/lib/orchestration/repo-memory-storage.ts b/lib/orchestration/repo-memory-storage.ts
index 445e3d30..302c048f 100644
--- a/lib/orchestration/repo-memory-storage.ts
+++ b/lib/orchestration/repo-memory-storage.ts
@@ -1,3 +1,4 @@
+import { readBoundedRegularFile } from "@/lib/host/bounded-read";
import { randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
import path from "node:path";
@@ -72,10 +73,10 @@ export async function atomicWriteJson(file: string, value: unknown): Promise<voi
}
export async function readRecordFile(file: string): Promise<RepoMemoryRecord | null> {
- const stat = await fs.lstat(file).catch(() => null);
- if (!stat?.isFile() || stat.isSymbolicLink() || stat.size <= 0 || stat.size > MAX_RECORD_BYTES) return null;
+ const raw = await readBoundedRegularFile(file, MAX_RECORD_BYTES);
+ if (!raw) return null;
try {
- const parsed = JSON.parse(await fs.readFile(file, "utf8")) as RepoMemoryRecord;
+ const parsed = JSON.parse(raw) as RepoMemoryRecord;
if (parsed?.schemaVersion !== 1 || typeof parsed.id !== "string" || !KIND_DIR[parsed.kind]) return null;
return parsed;
} catch {
diff --git a/lib/security-store-lock.ts b/lib/security-store-lock.ts
index 6586d044..f9d3793a 100644
--- a/lib/security-store-lock.ts
+++ b/lib/security-store-lock.ts
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { promises as fs, constants as fsConstants } from "node:fs";
-import path from "node:path";
+import { pinSecurityStorePath } from "./security-store-path";
// Cross-process lock for the tiny JSON files that carry security decisions.
// Atomic rename protects one write, but not a whole read-modify-write transaction.
@@ -32,9 +32,9 @@ function pidIsGone(pid: number): boolean {
async function abandoned(lockPath: string, staleMs: number): Promise<boolean> {
let handle;
try {
- handle = await fs.open(lockPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
+ handle = await fs.open(lockPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
const stat = await handle.stat();
- if (!stat.isFile()) return false; // fail closed: never auto-break an unexpected object
+ if (!stat.isFile() || stat.size > 256 || stat.uid !== process.getuid?.() || (stat.mode & 0o077)) return false; // fail closed: never auto-break an unexpected object
const owner = await handle.readFile("utf8");
const pid = Number(owner.split(":", 1)[0]);
// A valid, live PID wins over age: never break mutual exclusion merely because
@@ -86,13 +86,19 @@ async function openRecoveryGuard(lockPath: string, token: string): Promise<HeldL
}
async function release(lockPath: string, held: HeldLock): Promise<void> {
- const owner = await fs.readFile(lockPath, "utf8").catch(() => "");
- // Never remove a lock that a recovery path may have handed to another process.
- if (owner === held.token) await fs.unlink(lockPath).catch(() => undefined);
+ let handle;
+ try {
+ handle = await fs.open(lockPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size > 256 || stat.uid !== process.getuid?.() || (stat.mode & 0o077)) return;
+ const owner = await handle.readFile("utf8");
+ // All supported lock publishers serialize under the recovery gate.
+ if (owner === held.token) await fs.unlink(lockPath).catch(() => undefined);
+ } catch { /* never remove an unreadable or replaced lock */ }
+ finally { await handle?.close().catch(() => undefined); }
}
async function acquire(lockPath: string, timings: Required<SecurityStoreLockTimings>): Promise<HeldLock> {
- await fs.mkdir(path.dirname(lockPath), { recursive: true, mode: 0o700 });
const token = `${process.pid}:${randomUUID()}`;
const recoveryPath = `${lockPath}.recovery`;
const deadline = Date.now() + timings.busyTimeoutMs;
@@ -158,11 +164,11 @@ export async function withSecurityStoreLock<T>(
busyTimeoutMs: options.busyTimeoutMs ?? DEFAULTS.busyTimeoutMs,
staleMs: options.staleMs ?? DEFAULTS.staleMs,
};
- const lockPath = `${storePath}.lock`;
- const held = await acquire(lockPath, timings);
+ const pinned = await pinSecurityStorePath(storePath);
+ const lockPath = `${pinned.file}.lock`;
try {
- return await fn();
- } finally {
- await release(lockPath, held);
- }
+ const held = await acquire(lockPath, timings);
+ try { return await fn(); }
+ finally { await release(lockPath, held); }
+ } finally { await pinned.directory.close(); }
}
diff --git a/lib/security-store-path.test.ts b/lib/security-store-path.test.ts
new file mode 100644
index 00000000..680dec71
--- /dev/null
+++ b/lib/security-store-path.test.ts
@@ -0,0 +1,45 @@
+import { constants, promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { pinSecurityStorePath } from "./security-store-path";
+import { withSecurityStoreLock } from "./security-store-lock";
+
+const roots: string[] = [];
+async function fixture() { const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-pinned-store-")); roots.push(root); return root; }
+afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });
+
+describe("pinned owner security-store paths", () => {
+ it("rejects traversal and non-canonical symlink ancestors before creating a target", async () => {
+ const root = await fixture(), outside = await fixture();
+ await fs.symlink(outside, path.join(root, "alias"));
+ await expect(pinSecurityStorePath(path.join(root, "alias/new/store.json"))).rejects.toThrow();
+ await expect(fs.stat(path.join(outside, "new"))).rejects.toMatchObject({ code: "ENOENT" });
+ await expect(pinSecurityStorePath("../../etc/store.json")).rejects.toThrow(/absolute path/);
+ await expect(pinSecurityStorePath("/etc/unauthorized-store.json")).rejects.toThrow(/outside configured/);
+ });
+ it("refuses shared writable store parents", async () => {
+ const root = await fixture(); await fs.chmod(root, 0o777);
+ await expect(pinSecurityStorePath(path.join(root, "store.json"))).rejects.toThrow(/not writable by others/);
+ });
+ it("keeps operations on the pinned inode after the pathname is replaced", async () => {
+ const root = await fixture(), original = path.join(root, "original"), moved = path.join(root, "moved");
+ await fs.mkdir(original, { mode: 0o700 });
+ const pinned = await pinSecurityStorePath(path.join(original, "store.json"));
+ try {
+ await fs.rename(original, moved); await fs.mkdir(original, { mode: 0o700 });
+ const handle = await fs.open(pinned.file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
+ try { await handle.writeFile("owned"); } finally { await handle.close(); }
+ expect(await fs.readFile(path.join(moved, "store.json"), "utf8")).toBe("owned");
+ await expect(fs.stat(path.join(original, "store.json"))).rejects.toMatchObject({ code: "ENOENT" });
+ } finally { await pinned.directory.close(); }
+ });
+ it("will not follow a malicious lock symlink or enter the transaction", async () => {
+ const root = await fixture(), store = path.join(root, "store.json"), external = path.join(root, "untouched");
+ await fs.writeFile(external, "private", { mode: 0o600 }); await fs.symlink(external, `${store}.lock`);
+ let entered = false;
+ await expect(withSecurityStoreLock(store, async () => { entered = true; }, { waitMs: 1, busyTimeoutMs: 15 })).rejects.toThrow(/busy/);
+ expect(entered).toBe(false); expect(await fs.readFile(external, "utf8")).toBe("private");
+ expect((await fs.lstat(`${store}.lock`)).isSymbolicLink()).toBe(true);
+ });
+});
diff --git a/lib/security-store-path.ts b/lib/security-store-path.ts
new file mode 100644
index 00000000..9d5c7bb9
--- /dev/null
+++ b/lib/security-store-path.ts
@@ -0,0 +1,66 @@
+import { constants, promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+// A kernel-pinned parent keeps lock/file operations on one directory even if its
+// pathname is replaced. Linux /proc/self/fd is the supported VPS/WSL runtime.
+// Store filenames remain adjacent and compatible with the independent device CLI.
+const STORE_ENV = [
+ "OS_DEVICE_STORE", "OS_MCP_STORE", "OS_INFRA_STORE", "OS_MEMORY_STORE", "OS_MCP_ACTIVITY_LOG",
+ "OS_A2A_STORE", "OS_A2A_TASK_STORE", "OS_A2A_CREDENTIAL_STORE", "OS_A2A_INBOUND_TOKEN_STORE",
+ "OS_A2A_LOCAL_AUTH_STORE", "OS_LOCAL_AGENT_MESSAGE_STORE", "OS_LOCAL_AGENT_PRESENCE_STORE",
+ "OS_CONFIG_STORE", "OS_PREFS_PATH", "OS_SKILL_MEMORY_STORE",
+] as const;
+const DIRECTORY_ENV = ["OS_TOOL_FORGE_DIR", "OS_AGENT_MEMORY_DIR", "OS_AGENT_SESSIONS_DIR", "OS_PROJECT_AGENT_TASKS_DIR"] as const;
+const expand = (value: string) => path.resolve(value.replace(/^~(?=$|\/)/, os.homedir()));
+
+export async function pinSecurityStorePath(storePath: string) {
+ if (process.platform !== "linux") throw new Error("Pinned security-store operations require Linux or WSL");
+ if (typeof storePath !== "string" || storePath.includes("\0") || !path.isAbsolute(storePath)) throw new Error("Security store needs an absolute path");
+ const absolute = path.resolve(storePath);
+ const name = path.basename(absolute);
+ if (!/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,220}$/.test(name)) throw new Error("Invalid security-store filename");
+ const allowed = [os.homedir(), ...(process.env.OS_FS_WRITE_ROOTS ?? "").split(":").filter(Boolean),
+ ...STORE_ENV.flatMap((key) => process.env[key] ? [path.dirname(expand(process.env[key]!))] : []),
+ ...DIRECTORY_ENV.flatMap((key) => process.env[key] ? [expand(process.env[key]!)] : []),
+ // Test sandboxes are private mkdtemp directories, never the shared temp root itself.
+ ...(process.env.VITEST ? [os.tmpdir()] : [])];
+ if (!allowed.some((root) => absolute.startsWith(`${expand(root)}${path.sep}`))) throw new Error("Security store is outside configured owner roots");
+ const parent = path.dirname(absolute);
+ const directory = await openDirectoryChain(parent);
+ try {
+ const stat = await directory.stat();
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 0o022)) throw new Error("Security-store parent must be owned and not writable by others");
+ const pinnedRoot = `/proc/self/fd/${directory.fd}`;
+ // Reject all symlinked ancestor spellings as well as a swapped parent inode.
+ if (await fs.realpath(pinnedRoot) !== parent) throw new Error("Security-store parent is not canonical");
+ return { file: `${pinnedRoot}/${name}`, directory, absolute };
+ } catch (error) {
+ await directory.close();
+ throw error;
+ }
+}
+
+// Walk from a stable descriptor, opening one basename at a time with O_NOFOLLOW.
+// Creating a missing parent must not follow an attacker-controlled intermediate link.
+async function openDirectoryChain(parent: string) {
+ let directory = await fs.open("/", constants.O_RDONLY | constants.O_DIRECTORY);
+ try {
+ const parts = parent.split(path.sep).filter(Boolean);
+ if (parts.length > 128) throw new Error("Security-store path is too deep");
+ for (const part of parts) {
+ if (!part || part === "." || part === ".." || /[/\\\0]/.test(part)) throw new Error("Invalid store directory component");
+ const child = `/proc/self/fd/${directory.fd}/${path.basename(part)}`;
+ let next;
+ try { next = await fs.open(child, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ await fs.mkdir(child, { mode: 0o700 }).catch((cause: NodeJS.ErrnoException) => { if (cause.code !== "EEXIST") throw cause; });
+ next = await fs.open(child, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
+ }
+ await directory.close();
+ directory = next;
+ }
+ return directory;
+ } catch (error) { await directory.close(); throw error; }
+}
diff --git a/package.json b/package.json
index 7be2af34..4548e0a7 100644
--- a/package.json
+++ b/package.json
@@ -92,6 +92,7 @@
"eslint": "^9.39.4",
"eslint-config-next": "^16.3.2",
"fast-check": "^4.9.0",
+ "parse5": "8.0.1",
"postcss": "^8.5.26",
"tailwindcss": "^4.3.0",
"typescript": "^5.9.3",
diff --git a/scripts/codeql-report.mjs b/scripts/codeql-report.mjs
new file mode 100644
index 00000000..0cbf0b80
--- /dev/null
+++ b/scripts/codeql-report.mjs
@@ -0,0 +1,24 @@
+#!/usr/bin/env node
+// Read-only evidence: report every SARIF result without filtering/deleting diagnostics.
+import fs from "node:fs";
+import path from "node:path";
+const directory = process.argv[2];
+if (!directory) throw new Error("usage: node scripts/codeql-report.mjs <SARIF directory>");
+const files = fs.readdirSync(directory).filter((name) => name.endsWith(".sarif"));
+if (!files.length) throw new Error("CodeQL produced no SARIF file");
+let count = 0;
+for (const name of files) {
+ const data = JSON.parse(fs.readFileSync(path.join(directory, name), "utf8"));
+ if (!Array.isArray(data.runs) || !data.runs.length) throw new Error("Missing CodeQL run");
+ for (const run of data.runs) {
+ if (run.tool?.driver?.name !== "CodeQL" || !Array.isArray(run.results)) throw new Error("Unexpected SARIF tool/result shape");
+ for (const row of run.results) {
+ const rule = run.tool.driver.rules?.find((rule) => rule.id === row.ruleId);
+ const locations = (row.locations ?? []).map(({ physicalLocation: p }) => ({ path: p?.artifactLocation?.uri, line: p?.region?.startLine }));
+ console.log(`CODEQL_FINDING ${JSON.stringify({ rule: row.ruleId, severity: rule?.properties?.["security-severity"], message: row.message?.text, locations })}`);
+ count++;
+ }
+ }
+}
+console.log(`CODEQL_RESULT_COUNT ${count}`);
+console.log("This is a diagnostic inventory, not a clearance decision; GitHub open-alert checks are separate.");
diff --git a/scripts/mso-tui-select.mjs b/scripts/mso-tui-select.mjs
index 0b4e1db4..07c32439 100755
--- a/scripts/mso-tui-select.mjs
+++ b/scripts/mso-tui-select.mjs
@@ -83,10 +83,10 @@ async function run() {
const items = parsePickerItems(fs.readFileSync(0, "utf8"));
if (!items.length) process.exit(2);
- const inFd = fs.openSync("/dev/tty", "r");
- const outFd = fs.openSync("/dev/tty", "w");
- const input = new tty.ReadStream(inFd);
- const output = new tty.WriteStream(outFd);
+ // One read/write descriptor: no separate pathname check/open or truncating open.
+ const terminalFd = fs.openSync("/dev/tty", fs.constants.O_RDWR);
+ const input = new tty.ReadStream(terminalFd);
+ const output = new tty.WriteStream(terminalFd);
readline.emitKeypressEvents(input);
const wasRaw = Boolean(input.isRaw);
let query = "";
diff --git a/scripts/test-support/inline-scripts.ts b/scripts/test-support/inline-scripts.ts
new file mode 100644
index 00000000..c4df7a70
--- /dev/null
+++ b/scripts/test-support/inline-scripts.ts
@@ -0,0 +1,14 @@
+import { parse, type DefaultTreeAdapterTypes } from "parse5";
+
+// Parse generated HTML as a browser does. This is test extraction, not an HTML sanitizer.
+export function inlineScripts(html: string): string[] {
+ const scripts: string[] = [];
+ const walk = (node: DefaultTreeAdapterTypes.Node): void => {
+ if ("tagName" in node && node.tagName === "script" && !node.attrs.some((attr) => attr.name === "src")) {
+ scripts.push(node.childNodes.map((child) => "value" in child ? child.value : "").join(""));
+ }
+ if ("childNodes" in node) node.childNodes.forEach(walk);
+ };
+ walk(parse(html));
+ return scripts;
+}