Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
fix(security): bound code-scanning filesystem paths and CLI test execution
Rahman98beb9d6f1f4
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex a60ce378..6e3851dd 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -13,6 +13,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Fixed**+- `security` bound code-scanning filesystem paths and CLI test execution- `organization` memoize focused groups and retain group search- `deps` update brace-expansion within supported major lines- `reconciliation` close combined environment and fixture contractsdiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 9b19f6db..7c35729b 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,7 @@+## 2026-09-30 — Code-scanning filesystem boundary fixes++Closed the shared bounded-reader gap with lexical and real-parent containment against configured read roots (or the explicit root of an already-authorized internal store/skill scan) while retaining final-component O_NOFOLLOW and pre-allocation size limits. Repository-memory project roots use the host read guard and reject a symlinked memory parent before reads or writes. Project knowledge rejects redirected metadata directories, and linked-worktree lookup checks lexical containment before probing a caller path. The memory-backup CLI fixture now executes a fixed Bash file instead of dynamic shell code. Regression fixtures explicitly authorize their temporary roots and exercise traversal, out-of-root access, symlink parents and preserved valid reads. The current lockfile already contains brace-expansion 1.1.21 and 5.0.12, which cover the three advisory IDs in Scorecard alert 118; scanner closure must be verified against the released SHA.+## 2026-09-30 — Reconciliation takeover verificationRecovered the interrupted reconciliation in a separate worktree while preserving the original conflicted checkout and verified all-ref backup. The split CLI dispatcher retains the exclusive service-start/restart lock from the rescue branch, and Hostinger wildcard owner validation is recovered with its existing bounded-payload regression. Local-agent lifecycle initialization remains within the source-size gate without disabling lint. The combined candidate passed 3,723 tests across 649 files, all 16 CI runner contracts, typecheck, lint, architecture/docs/contrast checks and dependency audit. Native-host physical acceptance and unrelated legacy histories remain preserved; these are not claimed completed by this integration. Runtime release is verified separately through the official ship gates.diff --git a/lib/forge/store.ts b/lib/forge/store.tsindex 6fd0d7b7..61bf2ee3 100644--- a/lib/forge/store.ts+++ b/lib/forge/store.ts@@ -36,7 +36,7 @@ async function ensureRoot(): Promise<void> {async function readCandidateFile(file: string): Promise<ForgeCandidate | null> {try {- const data = await readBoundedRegularBufferOrThrow(file, 256 * 1024);+ const data = await readBoundedRegularBufferOrThrow(file, 256 * 1024, candidatesDir());if (!data.length) throw new Error("invalid forge candidate file");return JSON.parse(data.toString("utf8")) as ForgeCandidate;} catch (error) {diff --git a/lib/host/bounded-read.test.ts b/lib/host/bounded-read.test.tsindex b77bcde4..3a2f07b3 100644--- a/lib/host/bounded-read.test.ts+++ b/lib/host/bounded-read.test.ts@@ -1,4 +1,4 @@-import { afterAll, describe, expect, it } from "vitest";+import { afterAll, describe, expect, it, vi } from "vitest";import { promises as fs } from "fs";import os from "os";import path from "path";@@ -9,7 +9,8 @@ import { BOUNDED_READ, readBoundedRegularFile } from "./bounded-read";// attacker-influenced checkout must cost one fstat, not 2 GiB of heap, and a// read-scope projects_list must not be a memory-exhaustion primitive.const dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-bounded-"));-afterAll(async () => { await fs.rm(dir, { recursive: true, force: true }); });+vi.stubEnv("OS_FS_READ_ROOTS", dir);+afterAll(async () => { vi.unstubAllEnvs(); await fs.rm(dir, { recursive: true, force: true }); });describe("readBoundedRegularFile", () => {it("reads a regular file within the cap", async () => {@@ -39,6 +40,20 @@ describe("readBoundedRegularFile", () => {await expect(readBoundedRegularFile(path.join(dir, "nope"), 1024)).resolves.toBeNull();});+ it("rejects outside roots and parent symlink escapes before opening", async () => {+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), "mso-bounded-outside-"));+ try {+ const file = path.join(outside, "secret");+ await fs.writeFile(file, "secret");+ await expect(readBoundedRegularFile(file, 1024)).resolves.toBeNull();+ await expect(readBoundedRegularFile(file, 1024, outside)).resolves.toBe("secret");+ await expect(readBoundedRegularFile(file, 1024, dir)).resolves.toBeNull();+ await expect(readBoundedRegularFile(path.join(dir, "..", path.basename(outside), "secret"), 1024)).resolves.toBeNull();+ await fs.symlink(outside, path.join(dir, "redirect"));+ await expect(readBoundedRegularFile(path.join(dir, "redirect", "secret"), 1024)).resolves.toBeNull();+ } finally { await fs.rm(outside, { recursive: true, force: true }); }+ });+it("publishes a cap for every discovery read", () => {for (const key of ["packageJson", "skillMd", "gitHead", "gitRef", "packedRefs"] as const) {expect(BOUNDED_READ[key], key).toBeGreaterThan(0);diff --git a/lib/host/bounded-read.ts b/lib/host/bounded-read.tsindex 2dde020e..483986dd 100644--- a/lib/host/bounded-read.ts+++ b/lib/host/bounded-read.ts@@ -15,6 +15,29 @@// Returns null — never throws and never partially reads. A file that fails any check// is simply "no metadata", which every caller already handles.import { constants, promises as fs } from "fs";+import path from "node:path";+import { readRootList } from "./path-roots";++async function openReadableFile(file: string, trustedRoot?: string) {+ const absolute = path.resolve(file);+ for (const configured of trustedRoot ? [trustedRoot] : readRootList()) {+ const root = path.resolve(configured);+ const relative = path.relative(root, absolute);+ if (relative === ".." || relative.startsWith(".." + path.sep) || path.isAbsolute(relative)) {+ continue;+ } else {+ const parent = await fs.realpath(path.dirname(absolute));+ const realRoot = await fs.realpath(root);+ const realRelative = path.relative(realRoot, parent);+ if (realRelative === ".." || realRelative.startsWith(".." + path.sep) || path.isAbsolute(realRelative)) {+ throw new Error("bounded read outside readable roots");+ }+ // Keep O_NOFOLLOW on the original final component; only resolve its parent.+ return fs.open(path.join(parent, path.basename(absolute)), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);+ }+ }+ throw new Error("bounded read outside readable roots");+}/** Per-artifact caps. Generous enough for real files, small enough that the worst* case of a full scan is bounded arithmetic rather than "whatever is on disk". */@@ -28,9 +51,10 @@ export const BOUNDED_READ = {projectMcpConfig: 256 * 1024,} as const;-export async function readBoundedRegularBufferOrThrow(file: string, maxBytes: number): Promise<Buffer> {+// Internal stores/skill scans may supply their already-authorized root; host reads default to configured read roots.+export async function readBoundedRegularBufferOrThrow(file: string, maxBytes: number, trustedRoot?: string): 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);+ const handle = await openReadableFile(file, trustedRoot);try {const before = await handle.stat();if (!before.isFile() || before.size > maxBytes) throw new Error("not a bounded regular file");@@ -47,12 +71,12 @@ export async function readBoundedRegularBufferOrThrow(file: string, maxBytes: nu} finally { await handle.close(); }}-export async function readBoundedRegularBuffer(file: string, maxBytes: number): Promise<Buffer | null> {- try { return await readBoundedRegularBufferOrThrow(file, maxBytes); }+export async function readBoundedRegularBuffer(file: string, maxBytes: number, trustedRoot?: string): Promise<Buffer | null> {+ try { return await readBoundedRegularBufferOrThrow(file, maxBytes, trustedRoot); }catch { return null; }}-export async function readBoundedRegularFile(file: string, maxBytes: number): Promise<string | null> {- const buffer = await readBoundedRegularBuffer(file, maxBytes);+export async function readBoundedRegularFile(file: string, maxBytes: number, trustedRoot?: string): Promise<string | null> {+ const buffer = await readBoundedRegularBuffer(file, maxBytes, trustedRoot);return buffer === null ? null : buffer.toString("utf8");}diff --git a/lib/host/project-candidate-index.test.ts b/lib/host/project-candidate-index.test.tsindex 58aeb3a1..ce2e0856 100644--- a/lib/host/project-candidate-index.test.ts+++ b/lib/host/project-candidate-index.test.ts@@ -1,9 +1,10 @@-import { afterAll, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";import { promises as fs } from "node:fs";import os from "node:os";import path from "node:path";const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-candidate-index-"));+vi.stubEnv("OS_FS_READ_ROOTS", root);const cache = path.join(root, "cache");process.env.MSO_CANDIDATE_INDEX_DIR = cache;const { searchProjectCandidateIndex } = await import("./project-candidate-index");@@ -27,6 +28,7 @@ describe("project candidate index", () => {await fs.rm(cache, { recursive: true, force: true });});afterAll(async () => {+ vi.unstubAllEnvs();delete process.env.MSO_CANDIDATE_INDEX_DIR;await fs.rm(root, { recursive: true, force: true });});diff --git a/lib/host/project-capabilities.test.ts b/lib/host/project-capabilities.test.tsindex ee106ba7..4c3b8a90 100644--- a/lib/host/project-capabilities.test.ts+++ b/lib/host/project-capabilities.test.ts@@ -1,15 +1,16 @@-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { promises as fs } from "fs";import os from "os";import path from "path";import { projectCapabilities, runProjectFunction } from "./project-capabilities";const roots: string[] = [];-afterEach(async () => { await Promise.all(roots.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true }))); });+afterEach(async () => { vi.unstubAllEnvs(); await Promise.all(roots.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true }))); });async function project() {const dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-project-cap-"));roots.push(dir);+ vi.stubEnv("OS_FS_READ_ROOTS", roots.join(path.delimiter));await fs.mkdir(path.join(dir, ".mso"));return dir;}diff --git a/lib/host/project-experience.test.ts b/lib/host/project-experience.test.tsindex 861d415a..2db4b684 100644--- a/lib/host/project-experience.test.ts+++ b/lib/host/project-experience.test.ts@@ -1,4 +1,4 @@-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { execFileSync } from "node:child_process";import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";import os from "node:os";@@ -6,6 +6,7 @@ import path from "node:path";import { detectProjectConvex, projectGitDiff, projectGitEdits, projectGitSnapshot, readProjectKnowledge } from "./project-experience";const root = await mkdtemp(path.join(os.tmpdir(), "mso-project-exp-"));+vi.stubEnv("OS_FS_READ_ROOTS", root);const project = path.join(root, "app");beforeAll(async () => {@@ -24,7 +25,7 @@ beforeAll(async () => {await writeFile(path.join(project, "a.txt"), "one\ntwo\nworking\n");});-afterAll(async () => rm(root, { recursive: true, force: true }));+afterAll(async () => { vi.unstubAllEnvs(); await rm(root, { recursive: true, force: true }); });describe("project experience host helpers", () => {it("returns bounded Git snapshot, history and working-tree diff", async () => {@@ -59,6 +60,15 @@ describe("project experience host helpers", () => {await expect(readProjectKnowledge(project)).rejects.toThrow(/regular non-symlink/i);});+ it("refuses a symlinked knowledge directory inside readable roots", async () => {+ const outside = path.join(root, "other-project");+ await mkdir(outside);+ await writeFile(path.join(outside, "KNOWLEDGE.md"), "other project's knowledge");+ await rm(path.join(project, ".mso"), { recursive: true });+ await symlink(outside, path.join(project, ".mso"));+ await expect(readProjectKnowledge(project)).rejects.toThrow(/real directory/i);+ });+it("detects Convex without returning deployment values", async () => {await writeFile(path.join(project, ".env.local"), "CONVEX_SELF_HOSTED_URL=https://secret.example\n");const detected = await detectProjectConvex(project);diff --git a/lib/host/project-experience.ts b/lib/host/project-experience.tsindex 1ccb0e7b..670ff497 100644--- a/lib/host/project-experience.ts+++ b/lib/host/project-experience.ts@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";import { promises as fs } from "node:fs";import path from "node:path";import { BOUNDED_READ, readBoundedRegularFile } from "./bounded-read";+import { resolveReadable } from "./paths";import { childEnv } from "./child-env";const GIT_TIMEOUT_MS = 8_000;@@ -104,7 +105,13 @@ export async function projectGitDiff(projectPath: string, options: { sha?: strin}export async function readProjectKnowledge(projectPath: string) {- const file = path.join(projectPath, KNOWLEDGE_REL);+ const root = await resolveReadable(projectPath);+ const directory = path.join(root, ".mso");+ const directoryStat = await fs.lstat(directory).catch(() => null);+ if (directoryStat && (!directoryStat.isDirectory() || directoryStat.isSymbolicLink())) {+ throw new Error(`${KNOWLEDGE_REL} must be a regular non-symlink file in a real directory`);+ }+ const file = path.join(root, KNOWLEDGE_REL);const stat = await fs.lstat(file).catch(() => null);if (!stat) return { exists: false, path: KNOWLEDGE_REL, content: "", bytes: 0, sha256: undefined };if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`${KNOWLEDGE_REL} must be a regular non-symlink file`);diff --git a/lib/host/project-mcp.test.ts b/lib/host/project-mcp.test.tsindex 498988d2..1d26e033 100644--- a/lib/host/project-mcp.test.ts+++ b/lib/host/project-mcp.test.ts@@ -1,9 +1,10 @@-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";const root = await mkdtemp(path.join(os.tmpdir(), "mso-project-mcp-"));+vi.stubEnv("OS_FS_READ_ROOTS", root);const fixture = path.join(root, "fixture.mjs");const project = path.join(root, "project");await import("node:fs/promises").then(({ mkdir }) => mkdir(project, { recursive: true }));@@ -17,7 +18,7 @@ rl.on('line',(line)=>{const m=JSON.parse(line); if(m.method==='initialize') retu`);await writeFile(path.join(project, ".mcp.json"), JSON.stringify({ mcpServers: { projectFixture: { command: process.execPath, args: [fixture], env: { PROJECT_VISIBLE: "ok", SECRET_REF: "${OS_SESSION_SECRET}" } } } }));});-afterAll(async () => rm(root, { recursive: true, force: true }));+afterAll(async () => { vi.unstubAllEnvs(); await rm(root, { recursive: true, force: true }); });describe("dynamic project MCP boundary", () => {it("returns only safe server aliases, never config/env values", async () => {diff --git a/lib/host/project-worktree.test.ts b/lib/host/project-worktree.test.tsindex db0980fb..758946f6 100644--- a/lib/host/project-worktree.test.ts+++ b/lib/host/project-worktree.test.ts@@ -55,6 +55,7 @@ describe("task-owned project worktrees", () => {const workspace = await prepareProjectWorktree(repo);await expect(linkedWorkflowWorktreeCanonicalPath(workspace.workspacePath)).resolves.toBe(repo);await expect(linkedWorkflowWorktreeCanonicalPath(repo)).resolves.toBeNull();+ await expect(linkedWorkflowWorktreeCanonicalPath(path.join(workspace.workspacePath, "..", "..", "project"))).resolves.toBeNull();});it("rolls back only a still-clean fresh worktree and preserves changed work", async () => {diff --git a/lib/host/project-worktree.ts b/lib/host/project-worktree.tsindex b6bba270..16bc171e 100644--- a/lib/host/project-worktree.ts+++ b/lib/host/project-worktree.ts@@ -143,17 +143,23 @@ function insideRoot(root: string, candidate: string): boolean {* workspace without making arbitrary hidden directories globally resolvable. */export async function linkedWorkflowWorktreeCanonicalPath(candidatePath: string): Promise<string | null> {const root = await fs.realpath(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ worktreeRoot())).catch(() => null);- const candidate = await fs.realpath(candidatePath).catch(() => null);- if (!root || !candidate || candidate === root || !insideRoot(root, candidate)) return null;- const marker = await fs.lstat(path.join(candidate, ".git")).catch(() => null);- if (!marker?.isFile() || marker.isSymbolicLink()) return null;- const commonRaw = await git(candidate, ["rev-parse", "--git-common-dir"]).catch(() => "");- if (!commonRaw) return null;- const common = await fs.realpath(path.resolve(candidate, commonRaw)).catch(() => null);- if (!common || path.basename(common) !== ".git") return null;- const canonical = await fs.realpath(path.dirname(common)).catch(() => null);- if (!canonical || canonical === candidate) return null;- const canonicalMarker = await fs.lstat(path.join(canonical, ".git")).catch(() => null);- if (!canonicalMarker?.isDirectory() || canonicalMarker.isSymbolicLink()) return null;- return canonical;+ if (!root) return null;+ const absolute = path.resolve(candidatePath);+ const relative = path.relative(root, absolute);+ if (relative === "" || relative === ".." || relative.startsWith(".." + path.sep) || path.isAbsolute(relative)) return null;+ else {+ const candidate = await fs.realpath(absolute).catch(() => null);+ if (!candidate || candidate === root || !insideRoot(root, candidate)) return null;+ const marker = await fs.lstat(path.join(candidate, ".git")).catch(() => null);+ if (!marker?.isFile() || marker.isSymbolicLink()) return null;+ const commonRaw = await git(candidate, ["rev-parse", "--git-common-dir"]).catch(() => "");+ if (!commonRaw) return null;+ const common = await fs.realpath(path.resolve(candidate, commonRaw)).catch(() => null);+ if (!common || path.basename(common) !== ".git") return null;+ const canonical = await fs.realpath(path.dirname(common)).catch(() => null);+ if (!canonical || canonical === candidate) return null;+ const canonicalMarker = await fs.lstat(path.join(canonical, ".git")).catch(() => null);+ if (!canonicalMarker?.isDirectory() || canonicalMarker.isSymbolicLink()) return null;+ return canonical;+ }}diff --git a/lib/host/skill-market-api.ts b/lib/host/skill-market-api.tsindex 9d5858f8..08ea8634 100644--- a/lib/host/skill-market-api.ts+++ b/lib/host/skill-market-api.ts@@ -33,8 +33,8 @@ async function installation(row: SkillMarketRow, root: string, catalogDigest: stconst names = (await fs.readdir(target)).sort();signature += ":" + names.join(",");if (names.length === 2 && names.includes("SKILL.md") && names.includes(".mso-market.json")) {- const body = await readBoundedRegularFile(path.join(target, "SKILL.md"), 256 * 1024);- const raw = await readBoundedRegularFile(path.join(target, ".mso-market.json"), 64 * 1024);+ const body = await readBoundedRegularFile(path.join(target, "SKILL.md"), 256 * 1024, root);+ const raw = await readBoundedRegularFile(path.join(target, ".mso-market.json"), 64 * 1024, root);signature += ":" + sha((body ?? "") + "\0" + (raw ?? ""));let marker; try { marker = JSON.parse(raw ?? "null"); } catch { marker = null; }if (body && marker?.id === row.id && typeof marker.sha256 === "string") {@@ -54,7 +54,7 @@ export async function listSkillMarket(): Promise<SkillMarketSnapshot> {const pin = await pinSecurityStorePath(path.join(root, ".market-state"));try {const data = JSON.parse(await marketCommand(["list", "--json"])) as SkillMarketSnapshot;- const catalog = await readBoundedRegularFile(path.join(process.cwd(), "skill-market/catalog.json"), 512 * 1024);+ const catalog = await readBoundedRegularFile(path.join(process.cwd(), "skill-market/catalog.json"), 512 * 1024, path.join(process.cwd(), "skill-market"));if (!catalog) throw new Error("Reviewed skill catalog unavailable");if (!Array.isArray(data.skills) || data.skills.length > 200 || data.root !== root || data.skills.some(row => !idPattern.test(row.id))) throw new Error("Invalid skill market response");return { ...data, skills: await Promise.all(data.skills.map(row => installation(row, root, sha(catalog)))) };diff --git a/lib/orchestration/repo-memory-insights.test.ts b/lib/orchestration/repo-memory-insights.test.tsindex befbadf5..081230e1 100644--- a/lib/orchestration/repo-memory-insights.test.ts+++ b/lib/orchestration/repo-memory-insights.test.ts@@ -1,4 +1,4 @@-import { afterAll, describe, expect, it } from "vitest";+import { afterAll, describe, expect, it, vi } from "vitest";import { promises as fs } from "node:fs";import os from "node:os";import path from "node:path";@@ -7,12 +7,13 @@ import { relatedRepoMemory, repoMemoryTimeline } from "./repo-memory-insights";import { upsertRepoMemory } from "./repo-memory";const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-memory-insights-"));+vi.stubEnv("OS_FS_READ_ROOTS", root);const project = path.join(root, "source");const target = path.join(root, "target");await fs.mkdir(project);await fs.mkdir(target);-afterAll(() => fs.rm(root, { recursive: true, force: true }));+afterAll(async () => { vi.unstubAllEnvs(); await fs.rm(root, { recursive: true, force: true }); });describe("repo memory insights and portable sync", () => {it("derives explicit and conflict relations without an embedding/model call", async () => {diff --git a/lib/orchestration/repo-memory-storage.ts b/lib/orchestration/repo-memory-storage.tsindex 302c048f..c44c0872 100644--- a/lib/orchestration/repo-memory-storage.ts+++ b/lib/orchestration/repo-memory-storage.ts@@ -1,4 +1,5 @@import { readBoundedRegularFile } from "@/lib/host/bounded-read";+import { resolveReadable } from "@/lib/host/paths";import { randomUUID } from "node:crypto";import { promises as fs } from "node:fs";import path from "node:path";@@ -23,10 +24,10 @@ async function assertDirectoryNoSymlink(dir: string): Promise<void> {}export async function projectRoot(projectPath: string): Promise<string> {- const absolute = path.resolve(projectPath);+ const absolute = await resolveReadable(projectPath);const stat = await fs.lstat(absolute).catch(() => null);- if (!stat?.isDirectory() || stat.isSymbolicLink()) throw new Error("project path must be a real directory");- return fs.realpath(absolute);+ if (absolute !== path.resolve(projectPath) || !stat?.isDirectory() || stat.isSymbolicLink()) throw new Error("project path must be a real directory");+ return absolute;}export async function existingRepoMemoryLayout(projectPath: string): Promise<string | null> {@@ -35,6 +36,7 @@ export async function existingRepoMemoryLayout(projectPath: string): Promise<strconst stat = await fs.lstat(agent).catch(() => null);if (!stat) return null;if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("repo memory .agent path is not a safe directory");+ await assertDirectoryNoSymlink(path.join(agent, "memory"));for (const relative of LAYOUT) {const candidate = path.join(agent, relative);const nested = await fs.lstat(candidate).catch(() => null);@@ -50,6 +52,7 @@ export async function ensureRepoMemoryLayout(projectPath: string): Promise<strinconst agent = path.join(root, ".agent");await assertDirectoryNoSymlink(agent);await fs.mkdir(agent, { recursive: true, mode: 0o700 });+ await assertDirectoryNoSymlink(path.join(agent, "memory"));for (const relative of LAYOUT) {const dir = path.join(agent, relative);await assertDirectoryNoSymlink(dir);diff --git a/lib/orchestration/repo-memory.test.ts b/lib/orchestration/repo-memory.test.tsindex dda10afc..b9fbaabe 100644--- a/lib/orchestration/repo-memory.test.ts+++ b/lib/orchestration/repo-memory.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { promises as fs } from "node:fs";import os from "node:os";import path from "node:path";@@ -13,11 +13,13 @@ const roots: string[] = [];async function project() {const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-rasmic-memory-"));roots.push(root);+ vi.stubEnv("OS_FS_READ_ROOTS", roots.join(path.delimiter));await fs.writeFile(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));return root;}afterEach(async () => {+ vi.unstubAllEnvs();await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));});@@ -152,6 +154,17 @@ describe("repo-local structured memory", () => {expect(files).toHaveLength(1);});+ it("refuses an unauthorized project and a symlinked memory parent before writes", async () => {+ const root = await project();+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), "mso-memory-outside-"));+ roots.push(outside);+ await expect(searchRepoMemory(outside, { query: "secret" })).rejects.toThrow(/outside readable roots/i);+ await fs.mkdir(path.join(root, ".agent"));+ await fs.symlink(outside, path.join(root, ".agent", "memory"));+ await expect(upsertRepoMemory(root, { kind: "task", title: "escape", summary: "blocked", source: "agent" })).rejects.toThrow(/not a safe directory/i);+ expect(await fs.readdir(outside)).toEqual([]);+ });+it("refuses nested symlink escapes during read-only retrieval", async () => {const root = await project();const outside = await fs.mkdtemp(path.join(os.tmpdir(), "mso-rasmic-outside-"));diff --git a/lib/skills/catalog-scan.ts b/lib/skills/catalog-scan.tsindex 0cb8be8e..864f4fed 100644--- a/lib/skills/catalog-scan.ts+++ b/lib/skills/catalog-scan.ts@@ -36,7 +36,7 @@ export type RootSpec = {*/export async function readSkillFile(file: string): Promise<string | null> {if (path.basename(file) !== SKILL_FILE) return null;- return readBoundedRegularFile(file, SKILL_SCAN_LIMITS.maxSkillBytes);+ return readBoundedRegularFile(file, SKILL_SCAN_LIMITS.maxSkillBytes, path.dirname(file));}export function skillDescription(md: string): string {@@ -54,7 +54,7 @@ type ClawHubOrigin = {};async function verifiedBundledSkill(dir: string, md: string): Promise<Pick<SkillInfo, "trust" | "provenance">> {- const raw = await readBoundedRegularFile(path.join(dir, ".clawhub/origin.json"), 64 * 1024);+ const raw = await readBoundedRegularFile(path.join(dir, ".clawhub/origin.json"), 64 * 1024, dir);if (!raw) return { trust: "untrusted" };let origin: ClawHubOrigin;try {diff --git a/lib/skills/skill-contract.ts b/lib/skills/skill-contract.tsindex 45cfb6d6..fc7b1654 100644--- a/lib/skills/skill-contract.ts+++ b/lib/skills/skill-contract.ts@@ -94,7 +94,7 @@ export function parseSkillContract(value: unknown): SkillContract {}export async function readSkillContract(skillDir: string): Promise<SkillContract | undefined> {- const raw = await readBoundedRegularFile(path.join(skillDir, CONTRACT_FILE), CONTRACT_MAX_BYTES);+ const raw = await readBoundedRegularFile(path.join(skillDir, CONTRACT_FILE), CONTRACT_MAX_BYTES, skillDir);if (!raw) return undefined;return parseSkillContract(parseYaml(raw));}diff --git a/scripts/cli/memory-backup-test.sh b/scripts/cli/memory-backup-test.shnew file mode 100644index 00000000..3eb42c61--- /dev/null+++ b/scripts/cli/memory-backup-test.sh@@ -0,0 +1,7 @@+#!/usr/bin/env bash+set -euo pipefail+source scripts/cli/memory-backup.sh+jget() { printf "%s" "$1"; }+jpost() { printf "%s" "$2"; }+die() { exit 2; }+mso_memory_backup "$@"diff --git a/scripts/cli/memory-backup.test.ts b/scripts/cli/memory-backup.test.tsindex 6667beaa..12d02f72 100644--- a/scripts/cli/memory-backup.test.ts+++ b/scripts/cli/memory-backup.test.ts@@ -1,9 +1,7 @@import { describe, expect, it } from "vitest";import { spawnSync } from "node:child_process";-import path from "node:path";-const script = path.resolve("scripts/cli/memory-backup.sh");function run(...args: string[]) {- return spawnSync("bash", ["-c", 'source "$1"; shift; jget() { printf "%s" "$1"; }; jpost() { printf "%s" "$2"; }; die() { exit 2; }; mso_memory_backup "$@"', "test", script, ...args], { encoding: "utf8" });+ return spawnSync("bash", ["scripts/cli/memory-backup-test.sh", ...args], { encoding: "utf8" });}describe("memory backup history CLI", () => {it("reads the first and subsequent pages using the existing transport", () => {