From 80d8fb1b7070982f8bdcbaf6eca56f56210d86a4 Mon Sep 17 00:00:00 2001 From: soovwv Date: Wed, 15 Jul 2026 23:22:28 +0900 Subject: [PATCH 1/7] fix: enforce strict state and write boundaries --- src/fsutil.js | 60 +++++++++++++++++++++++++++++++++++++++++++++ test/fsutil.test.js | 42 ++++++++++++++++++++++++++++++- 2 files changed, 101 insertions(+), 1 deletion(-) diff --git a/src/fsutil.js b/src/fsutil.js index 40b8ae2..ec87d12 100644 --- a/src/fsutil.js +++ b/src/fsutil.js @@ -19,6 +19,25 @@ export async function readJson(file, fallback = null) { } } +export async function readJsonStrict(file, fallback = null) { + let raw; + try { + raw = await fs.readFile(file, "utf8"); + } catch (error) { + if (error?.code === "ENOENT") return fallback; + throw error; + } + try { + return JSON.parse(stripBom(raw)); + } catch (cause) { + const error = new Error(`${path.basename(file)} contains invalid JSON; repair or remove the artifact before continuing`); + error.code = "AIENVMAP_INVALID_JSON"; + error.file = file; + error.cause = cause; + throw error; + } +} + export function stripBom(value) { return String(value).replace(/^\uFEFF/, ""); } @@ -28,6 +47,7 @@ export async function writeJson(file, data) { } export async function writeTextAtomic(file, content) { + await assertAienvmapWriteBoundary(file); await fs.mkdir(path.dirname(file), { recursive: true }); const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`); try { @@ -43,6 +63,7 @@ export async function writeTextAtomic(file, content) { } export async function appendJsonLine(file, data) { + await assertAienvmapWriteBoundary(file); await fs.mkdir(path.dirname(file), { recursive: true }); await withFileLock(file, async () => { await fs.appendFile(file, `${JSON.stringify(data)}\n`, "utf8"); @@ -58,6 +79,7 @@ export async function jsonlRevision(file) { } export async function appendJsonLinesChecked(file, entries, expectedRevision) { + await assertAienvmapWriteBoundary(file); await fs.mkdir(path.dirname(file), { recursive: true }); return withFileLock(file, async () => { let raw = ""; @@ -162,3 +184,41 @@ export async function removeMarkerBlock(file, begin, end) { await writeTextAtomic(file, next); return { changed: true, action: "remove-marker" }; } + +export async function assertWritePathInsideWorkspace(workspace, target) { + const root = await fs.realpath(path.resolve(workspace)); + const absolute = path.resolve(target); + let probe = absolute; + const remainder = []; + let resolved; + while (true) { + try { + resolved = await fs.realpath(probe); + break; + } catch (error) { + if (error?.code !== "ENOENT") throw error; + const parent = path.dirname(probe); + if (parent === probe) throw error; + remainder.unshift(path.basename(probe)); + probe = parent; + } + } + const candidate = path.resolve(resolved, ...remainder); + const relative = path.relative(root, candidate); + if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) { + const error = new Error("write target must stay inside the workspace after resolving symbolic links"); + error.code = "AIENVMAP_WRITE_OUTSIDE_WORKSPACE"; + throw error; + } + return absolute; +} + +async function assertAienvmapWriteBoundary(file) { + const absolute = path.resolve(file); + const parts = absolute.split(path.sep); + const index = parts.lastIndexOf(".aienvmap"); + if (index < 1) return; + const state = parts.slice(0, index + 1).join(path.sep) || path.parse(absolute).root; + const workspace = path.dirname(state); + await assertWritePathInsideWorkspace(workspace, absolute); +} diff --git a/test/fsutil.test.js b/test/fsutil.test.js index 45e476d..d86eff3 100644 --- a/test/fsutil.test.js +++ b/test/fsutil.test.js @@ -6,7 +6,7 @@ import os from "node:os"; import path from "node:path"; import { spawn } from "node:child_process"; import { fileURLToPath } from "node:url"; -import { appendJsonLine, appendJsonLinesChecked, jsonlRevision, readJson, stripBom, writeJson } from "../src/fsutil.js"; +import { appendJsonLine, appendJsonLinesChecked, assertWritePathInsideWorkspace, jsonlRevision, readJson, readJsonStrict, stripBom, writeJson } from "../src/fsutil.js"; const casWriter = fileURLToPath(new URL("../test-support/cas-writer.mjs", import.meta.url)); @@ -24,6 +24,18 @@ test("stripBom leaves normal JSON unchanged", () => { assert.equal(stripBom("{\"ok\":true}"), "{\"ok\":true}"); }); +test("readJsonStrict distinguishes missing state from malformed state", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-json-strict-")); + const file = path.join(dir, "state.json"); + assert.equal(await readJsonStrict(file, null), null); + await fs.writeFile(file, "{private-value", "utf8"); + await assert.rejects(readJsonStrict(file), (error) => { + assert.equal(error.code, "AIENVMAP_INVALID_JSON"); + assert.doesNotMatch(error.message, /private-value/); + return true; + }); +}); + test("writeJson replaces artifacts without leaving temporary files", async () => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-atomic-json-")); const file = path.join(dir, "state.json"); @@ -33,6 +45,34 @@ test("writeJson replaces artifacts without leaving temporary files", async () => assert.deepEqual(await fs.readdir(dir), ["state.json"]); }); +test("workspace writes reject state and instruction directories redirected by symbolic links", async (t) => { + const workspace = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-boundary-workspace-")); + const outside = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-boundary-outside-")); + const state = path.join(workspace, ".aienvmap"); + try { + await fs.symlink(outside, state, process.platform === "win32" ? "junction" : "dir"); + } catch (error) { + if (["EPERM", "EACCES", "ENOSYS"].includes(error?.code)) { + t.skip(`symbolic links unavailable: ${error.code}`); + return; + } + throw error; + } + + await assert.rejects( + writeJson(path.join(state, "status.json"), { unsafe: true }), + (error) => error.code === "AIENVMAP_WRITE_OUTSIDE_WORKSPACE" + ); + await assert.rejects(fs.access(path.join(outside, "status.json"))); + + const redirected = path.join(workspace, ".cursor"); + await fs.symlink(outside, redirected, process.platform === "win32" ? "junction" : "dir"); + await assert.rejects( + assertWritePathInsideWorkspace(workspace, path.join(redirected, "rules", "environment.md")), + (error) => error.code === "AIENVMAP_WRITE_OUTSIDE_WORKSPACE" + ); +}); + test("appendJsonLine serializes concurrent AI event writes", async () => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-locked-jsonl-")); const file = path.join(dir, "timeline.jsonl"); From 26a993bef633a0a56e36e0d2657d8b5c86ac1ca0 Mon Sep 17 00:00:00 2001 From: soovwv Date: Wed, 15 Jul 2026 23:22:34 +0900 Subject: [PATCH 2/7] fix: fail closed on corrupt coordination logs --- src/timeline.js | 28 ++++++++++++++++++++++++---- test/timeline.test.js | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 test/timeline.test.js diff --git a/src/timeline.js b/src/timeline.js index 2c49a65..7d7ed2a 100644 --- a/src/timeline.js +++ b/src/timeline.js @@ -1,16 +1,36 @@ import fs from "node:fs/promises"; +import path from "node:path"; export async function readTimeline(file) { return readJsonl(file); } export async function readJsonl(file) { + let raw; try { - const raw = await fs.readFile(file, "utf8"); - return raw.split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line)); - } catch { - return []; + raw = await fs.readFile(file, "utf8"); + } catch (error) { + if (error?.code === "ENOENT") return []; + throw error; } + const events = []; + for (const [index, source] of raw.split(/\r?\n/).entries()) { + const line = index === 0 ? source.replace(/^\uFEFF/, "").trim() : source.trim(); + if (!line) continue; + try { + const event = JSON.parse(line); + if (!event || typeof event !== "object" || Array.isArray(event)) throw new TypeError("coordination event must be an object"); + events.push(event); + } catch (cause) { + const error = new Error(`${path.basename(file)} contains invalid JSON on line ${index + 1}; repair or restore the coordination artifact before continuing`); + error.code = "AIENVMAP_INVALID_JSONL"; + error.file = file; + error.line = index + 1; + error.cause = cause; + throw error; + } + } + return events; } export function openIntents(events = [], now = new Date()) { diff --git a/test/timeline.test.js b/test/timeline.test.js new file mode 100644 index 0000000..e11832c --- /dev/null +++ b/test/timeline.test.js @@ -0,0 +1,39 @@ +import "./temp-cleanup.js"; +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { readJsonl } from "../src/timeline.js"; + +test("readJsonl treats only a missing coordination artifact as empty", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-jsonl-missing-")); + assert.deepEqual(await readJsonl(path.join(dir, "intents.jsonl")), []); +}); + +test("readJsonl accepts a BOM and blank lines without dropping valid events", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-jsonl-valid-")); + const file = path.join(dir, "timeline.jsonl"); + await fs.writeFile(file, `\uFEFF{"id":1}\n \n{"id":2}\n`, "utf8"); + assert.deepEqual(await readJsonl(file), [{ id: 1 }, { id: 2 }]); +}); + +test("readJsonl fails closed on a malformed coordination event without exposing its content", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-jsonl-invalid-")); + const file = path.join(dir, "intents.jsonl"); + await fs.writeFile(file, `{"id":"valid"}\n{"secret":"private-value"\n`, "utf8"); + await assert.rejects(readJsonl(file), (error) => { + assert.equal(error.code, "AIENVMAP_INVALID_JSONL"); + assert.equal(error.line, 2); + assert.match(error.message, /intents\.jsonl contains invalid JSON on line 2/); + assert.doesNotMatch(error.message, /private-value/); + return true; + }); +}); + +test("readJsonl rejects valid JSON that is not a coordination object", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-jsonl-shape-")); + const file = path.join(dir, "intents.jsonl"); + await fs.writeFile(file, `{"id":"valid"}\nnull\n`, "utf8"); + await assert.rejects(readJsonl(file), (error) => error.code === "AIENVMAP_INVALID_JSONL" && error.line === 2); +}); From a20203067966273f3d6a25127b56c53522a14d7a Mon Sep 17 00:00:00 2001 From: soovwv Date: Wed, 15 Jul 2026 23:22:34 +0900 Subject: [PATCH 3/7] fix: reject ambiguous CLI arguments --- bin/aienvmap.js | 2 +- src/cli.js | 34 +++++++++++++++++++++++++++++++++- test/cli.test.js | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/bin/aienvmap.js b/bin/aienvmap.js index 37a2926..c8691d4 100644 --- a/bin/aienvmap.js +++ b/bin/aienvmap.js @@ -3,5 +3,5 @@ import { main } from "../src/cli.js"; main(process.argv.slice(2)).catch((error) => { console.error(`aienvmap: ${error.message}`); - process.exit(1); + process.exitCode = 1; }); diff --git a/src/cli.js b/src/cli.js index 5fd78f7..dbb14a4 100644 --- a/src/cli.js +++ b/src/cli.js @@ -57,6 +57,19 @@ const commands = new Map([ const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version; const globalValueOptions = new Set(["--dir"]); +const booleanOptions = new Set([ + "all", "check", "ci", "clear_import", "deep", "dry_run", "full_packages", "inspect_project_wrappers", + "json", "markdown", "no_sync", "open", "owner_verification", "portable", "quick", "quiet", "record", + "security", "show_paths", "uninstall", "verbose" +]); +const requiredValueOptions = new Set([ + "action", "actor", "after", "against", "agent", "agents", "alias", "baseline", "before", "case_summary", + "change", "comparison", "dir", "evidence", "format", "home_evidence", "id", "if_revision", "import", + "inspect_home", "inspect_homes", "lease_minutes", "portable_compare", "portable_from", "reason", "ref", + "review", "scenario", "session", "status", "strict", "summary", "target", "type" +]); +const knownOptions = new Set([...booleanOptions, ...requiredValueOptions, "write"]); +const positionalCommands = new Set(["demo", "onboard", "snippet"]); export async function main(argv) { const { command, rest, globalArgs } = splitCommand(argv); @@ -73,10 +86,24 @@ export async function main(argv) { printUsage(); throw new Error(`unknown command "${command}"`); } - await run({ ...globalArgs, ...parseArgs(rest) }); + if (rest.includes("--help") || rest.includes("-h")) { + printUsage(); + return; + } + const args = { ...globalArgs, ...parseArgs(rest) }; + if (!positionalCommands.has(command) && args._.length) { + throw new Error(`${command}: unexpected argument "${args._[0]}"`); + } + if (["demo", "snippet"].includes(command) && args._.length > 1) { + throw new Error(`${command}: unexpected argument "${args._[1]}"`); + } + await run(args); } function splitCommand(argv) { + if (["-h", "--help", "-v", "--version", "version"].includes(argv[0])) { + return { command: argv[0], rest: argv.slice(1), globalArgs: { _: [] } }; + } const leading = []; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; @@ -109,10 +136,15 @@ export function parseArgs(argv) { } const [rawKey, inline] = arg.slice(2).split("=", 2); const key = rawKey.replaceAll("-", "_"); + if (!knownOptions.has(key)) throw new Error(`unknown option "--${rawKey}"`); if (inline !== undefined) { out[key] = inline; + } else if (booleanOptions.has(key)) { + out[key] = true; } else if (argv[i + 1] && !argv[i + 1].startsWith("--")) { out[key] = argv[++i]; + } else if (requiredValueOptions.has(key)) { + throw new Error(`--${rawKey} requires a value`); } else { out[key] = true; } diff --git a/test/cli.test.js b/test/cli.test.js index 81d77dc..45ef4dd 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -6,9 +6,49 @@ import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; +import { parseArgs } from "../src/cli.js"; const execFileAsync = promisify(execFile); +test("CLI parser keeps positional values after boolean flags", () => { + assert.deepEqual(parseArgs(["--dry-run", "codex", "--json"]), { _: ["codex"], dry_run: true, json: true }); +}); + +test("CLI parser rejects missing required option values", () => { + assert.throws(() => parseArgs(["--dir"]), /--dir requires a value/); + assert.throws(() => parseArgs(["--import", "--write"]), /--import requires a value/); +}); + +test("CLI rejects hallucinated options and unused positional arguments", async () => { + assert.throws(() => parseArgs(["--jsoon"]), /unknown option "--jsoon"/); + await assert.rejects( + execFileAsync(process.execPath, [path.resolve("bin/aienvmap.js"), "schema", "unexpected"], { cwd: path.resolve(".") }), + /schema: unexpected argument "unexpected"/ + ); +}); + +test("CLI command help does not execute the command", async () => { + const { stdout } = await execFileAsync(process.execPath, [path.resolve("bin/aienvmap.js"), "status", "--help"], { cwd: path.resolve(".") }); + assert.match(stdout, /Usage:/); + assert.match(stdout, /aienvmap status/); +}); + +test("CLI onboard accepts a target after a boolean option", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-cli-boolean-order-")); + const { stdout } = await execFileAsync(process.execPath, [ + path.resolve("bin/aienvmap.js"), + "onboard", + "--dry-run", + "codex", + "--json", + "--dir", + dir + ], { cwd: path.resolve(".") }); + const json = JSON.parse(stdout); + assert.deepEqual(json.verification.requested, ["codex"]); + assert.equal(json.mode, "dry-run"); +}); + test("CLI context reads a workspace passed with --dir", async () => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-cli-dir-")); await fs.mkdir(path.join(dir, ".aienvmap"), { recursive: true }); From da826528e456e26a1e8b4b71eb1c20efe3facc50 Mon Sep 17 00:00:00 2001 From: soovwv Date: Wed, 15 Jul 2026 23:23:22 +0900 Subject: [PATCH 4/7] fix: harden Windows command execution --- src/commands/dash.js | 41 +++++++++++++++++++++++++---------------- src/package-managers.js | 10 ++-------- src/shell.js | 20 +++++++++++++++++++- test/dashboard.test.js | 13 ++++++++++++- test/shell.test.js | 25 ++++++++++++++++++++++++- 5 files changed, 82 insertions(+), 27 deletions(-) diff --git a/src/commands/dash.js b/src/commands/dash.js index f6ffa52..9da36d2 100644 --- a/src/commands/dash.js +++ b/src/commands/dash.js @@ -1,8 +1,7 @@ -import fs from "node:fs/promises"; import { execFile } from "node:child_process"; -import path from "node:path"; +import { promisify } from "node:util"; import { diagnose } from "../doctor.js"; -import { exists, readJson } from "../fsutil.js"; +import { exists, readJsonStrict, writeTextAtomic } from "../fsutil.js"; import { openIntents, readJsonl, readTimeline } from "../timeline.js"; import { dashboardPath, intentsPath, manifestPath, planJsonPath, planMdPath, timelinePath, workspaceDir } from "../paths.js"; import { renderDashboard } from "../render.js"; @@ -11,9 +10,11 @@ import { recommendedActions } from "../actions.js"; import { strictResult } from "../enforcement.js"; import { buildPreflight } from "../preflight.js"; +const execFileAsync = promisify(execFile); + export async function dashWorkspace(args) { const dir = workspaceDir(args); - const manifest = await readJson(manifestPath(dir)); + const manifest = await readJsonStrict(manifestPath(dir)); if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first"); const timeline = await readTimeline(timelinePath(dir)); const intents = openIntents(await readJsonl(intentsPath(dir))); @@ -32,10 +33,9 @@ export async function dashWorkspace(args) { ciReadiness: ciReadiness(warnings) }, timeline, warnings, intents, policy); const out = dashboardPath(dir); - await fs.mkdir(path.dirname(out), { recursive: true }); - await fs.writeFile(out, html, "utf8"); + await writeTextAtomic(out, html); if (!args.quiet) console.log(`dashboard: ${out}`); - if (args.open) openFile(out); + if (args.open) await openDashboardFile(out); return { dashboard: out }; } @@ -60,7 +60,7 @@ async function detectedPlanArtifacts(dir) { } async function detectedPlanRemediation(dir) { - const plan = await readJson(planJsonPath(dir), {}); + const plan = await readJsonStrict(planJsonPath(dir), {}); return (plan.remediationSteps || []).slice(0, 5).map((item) => ({ package: item.package || "unknown", severity: item.severity || "unknown", @@ -71,7 +71,7 @@ async function detectedPlanRemediation(dir) { } async function detectedPlanEnvironment(dir) { - const plan = await readJson(planJsonPath(dir), {}); + const plan = await readJsonStrict(planJsonPath(dir), {}); return (plan.environmentSteps || []).slice(0, 5).map((item) => ({ code: item.code || "unknown", category: item.category || "environment", @@ -79,12 +79,21 @@ async function detectedPlanEnvironment(dir) { })); } -function openFile(file) { - if (process.platform === "win32") { - execFile("cmd", ["/c", "start", "", file], { windowsHide: true }); - } else if (process.platform === "darwin") { - execFile("open", [file]); - } else { - execFile("xdg-open", [file]); +export function dashboardOpenCommand(file, platform = process.platform) { + if (platform === "win32") return { command: "explorer.exe", args: [file] }; + if (platform === "darwin") return { command: "open", args: [file] }; + return { command: "xdg-open", args: [file] }; +} + +export async function openDashboardFile(file, options = {}) { + const launch = dashboardOpenCommand(file, options.platform || process.platform); + const run = options.run || execFileAsync; + try { + await run(launch.command, launch.args, { windowsHide: true, timeout: 10000 }); + } catch (cause) { + const error = new Error(`dashboard was written but could not be opened with ${launch.command}`); + error.code = "AIENVMAP_DASHBOARD_OPEN_FAILED"; + error.cause = cause; + throw error; } } diff --git a/src/package-managers.js b/src/package-managers.js index 385367b..36ec8ac 100644 --- a/src/package-managers.js +++ b/src/package-managers.js @@ -1359,14 +1359,8 @@ async function npmCandidateOutput(file, args) { if (await exists(siblingNode) && await exists(npmCli)) { return commandOutput(siblingNode, [npmCli, ...args], { timeout: 5000 }); } - const comspec = process.env.ComSpec || "cmd.exe"; - const commandLine = `""${file.replaceAll('"', '""')}" ${args.map(quoteCmdArg).join(" ")}"`; - return commandOutput(comspec, ["/d", "/s", "/c", commandLine], { timeout: 5000 }); -} - -function quoteCmdArg(value) { - const text = String(value); - return /^[A-Za-z0-9._@:/=-]+$/.test(text) ? text : `"${text.replaceAll('"', '""')}"`; + const result = await portableCommandResult(file, args, { timeout: 5000, platform: "win32" }); + return result.ok ? result.stdout : ""; } function knownNodeRoots(env, home) { diff --git a/src/shell.js b/src/shell.js index 513078a..cf18869 100644 --- a/src/shell.js +++ b/src/shell.js @@ -25,6 +25,7 @@ export async function commandOutput(command, args = [], options = {}) { maxBuffer: options.maxBuffer || 1024 * 1024, cwd: options.cwd, env: options.env, + windowsVerbatimArguments: options.windowsVerbatimArguments === true, windowsHide: true }); return stdout.trim(); @@ -40,6 +41,7 @@ export async function commandResult(command, args = [], options = {}) { maxBuffer: options.maxBuffer || 2 * 1024 * 1024, cwd: options.cwd, env: options.env, + windowsVerbatimArguments: options.windowsVerbatimArguments === true, windowsHide: true }); return { ok: true, code: 0, stdout: stdout.trim(), stderr: stderr.trim() }; @@ -66,7 +68,23 @@ export async function portableCommandResult(command, args = [], options = {}) { const platform = options.platform || process.platform; if (platform !== "win32" || !/\.(?:cmd|bat)$/i.test(command)) return commandResult(command, args, options); const comspec = options.comspec || process.env.ComSpec || "cmd.exe"; - return commandResult(comspec, ["/d", "/c", command, ...args], options); + const commandLine = windowsCmdCommandLine(command, args); + if (!commandLine) return { + ok: false, + code: 1, + failure: "unsafe-command-input", + stdout: "", + stderr: "refused unsafe Windows command path or argument" + }; + return commandResult(comspec, ["/d", "/v:off", "/s", "/c", commandLine], { ...options, windowsVerbatimArguments: true }); +} + +export function windowsCmdCommandLine(command, args = []) { + const file = String(command || ""); + const values = args.map((item) => String(item)); + if (!file || /[\r\n"%!]/.test(file)) return ""; + if (values.some((item) => !/^[A-Za-z0-9._@:/=+,-]+$/.test(item))) return ""; + return `""${file}"${values.length ? ` ${values.join(" ")}` : ""}"`; } export function firstVersion(text) { diff --git a/test/dashboard.test.js b/test/dashboard.test.js index 6d7e6cb..e20005b 100644 --- a/test/dashboard.test.js +++ b/test/dashboard.test.js @@ -4,7 +4,7 @@ import assert from "node:assert/strict"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; -import { dashWorkspace } from "../src/commands/dash.js"; +import { dashWorkspace, dashboardOpenCommand, openDashboardFile } from "../src/commands/dash.js"; import { writeJson } from "../src/fsutil.js"; import { dashboardAgentClientScript, dashboardAiUseClientScript, dashboardAiUseHtmlClientScript, dashboardCardClientScript, dashboardCardPriority, dashboardDependencyCoordinationClientScript, dashboardDependencyHintsClientScript, dashboardDependencyProtocolClientScript, dashboardDependencyReadSetClientScript, dashboardDependencyReviewClientScript, dashboardDiscoveryFallback, dashboardDiscoveryFallbackClientScript, dashboardDocument, dashboardEnvironmentProtocolClientScript, dashboardEssentialCards, dashboardEssentialSurfaceClientScript, dashboardEssentialSurfaces, dashboardLayoutClientScripts, dashboardMainCardsClientScript, dashboardOperationalCardsClientScript, dashboardPayload, dashboardQualityDefaults, dashboardReleaseClientScripts, dashboardReleaseDefaults, dashboardStyle, dashboardSurfaceBudget, dashboardPackageManagerPolicyClientScript, dashboardPriorityClientScript, dashboardQualitySignalsClientScript, dashboardReleaseReadinessClientScript, dashboardReviewPlanClientScript, dashboardReviewPlanHtmlClientScript, dashboardRiskSummaryClientScript, dashboardSbomClientScripts, dashboardScannerGuidanceClientScript, dashboardScannerGuidanceHtmlClientScript, dashboardStateCardsClientScript, dashboardSupportCardsClientScript, renderDashboard } from "../src/render.js"; @@ -900,3 +900,14 @@ test("dashWorkspace links written plan artifacts", async () => { assert.match(html, /uv\.lock/); assert.match(html, /django/); }); + +test("dashboard opener avoids a command shell and reports launch failure", async () => { + const file = "C:\\workspace & shared\\.aienvmap\\dashboard.html"; + assert.deepEqual(dashboardOpenCommand(file, "win32"), { command: "explorer.exe", args: [file] }); + assert.deepEqual(dashboardOpenCommand("/tmp/dashboard.html", "darwin"), { command: "open", args: ["/tmp/dashboard.html"] }); + assert.deepEqual(dashboardOpenCommand("/tmp/dashboard.html", "linux"), { command: "xdg-open", args: ["/tmp/dashboard.html"] }); + await assert.rejects( + openDashboardFile("/tmp/dashboard.html", { platform: "linux", run: async () => { throw new Error("missing opener"); } }), + (error) => error.code === "AIENVMAP_DASHBOARD_OPEN_FAILED" && /could not be opened with xdg-open/.test(error.message) + ); +}); diff --git a/test/shell.test.js b/test/shell.test.js index 7746024..b4e52ad 100644 --- a/test/shell.test.js +++ b/test/shell.test.js @@ -1,6 +1,10 @@ +import "./temp-cleanup.js"; import test from "node:test"; import assert from "node:assert/strict"; -import { commandOutput, commandResult, commandVersionResult } from "../src/shell.js"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { commandOutput, commandResult, commandVersionResult, portableCommandResult, windowsCmdCommandLine } from "../src/shell.js"; test("commandOutput forwards an explicit UTF-8 subprocess environment", async () => { const output = await commandOutput(process.execPath, ["-e", "process.stdout.write(process.env.AIENVMAP_TEST_UNICODE || '')"], { @@ -41,3 +45,22 @@ test("commandResult distinguishes missing commands, nonzero exits, and timeouts" assert.equal(timeout.ok, false); assert.equal(timeout.failure, "timeout-or-terminated"); }); + +test("Windows batch invocation quotes paths and rejects expandable command input", async () => { + assert.equal(windowsCmdCommandLine("C:\\Program Files (x86)\\tool & sdk\\tool.cmd", ["--version"]), `""C:\\Program Files (x86)\\tool & sdk\\tool.cmd" --version"`); + assert.equal(windowsCmdCommandLine("C:\\%TEMP%\\tool.cmd", ["--version"]), ""); + assert.equal(windowsCmdCommandLine("C:\\safe\\tool.cmd", ["&", "whoami"]), ""); + + const refused = await portableCommandResult("C:\\%TEMP%\\tool.cmd", ["--version"], { platform: "win32" }); + assert.equal(refused.ok, false); + assert.equal(refused.failure, "unsafe-command-input"); + + if (process.platform === "win32") { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-cmd & quoted-")); + const file = path.join(dir, "version.cmd"); + await fs.writeFile(file, "@echo 1.2.3\r\n", "utf8"); + const result = await portableCommandResult(file, ["--version"], { platform: "win32" }); + assert.equal(result.ok, true); + assert.equal(result.stdout, "1.2.3"); + } +}); From 8dad13f19a33b1d0c450414ce5389f95f982a0a4 Mon Sep 17 00:00:00 2001 From: soovwv Date: Wed, 15 Jul 2026 23:23:23 +0900 Subject: [PATCH 5/7] fix: validate owned state before use --- src/commands/compile.js | 8 ++++---- src/commands/context.js | 4 ++-- src/commands/diff.js | 6 +++--- src/commands/discover.js | 4 ++-- src/commands/doctor.js | 4 ++-- src/commands/handoff.js | 4 ++-- src/commands/init.js | 11 +++++++++-- src/commands/plan.js | 7 +++---- src/commands/reconcile.js | 8 ++++---- src/commands/sbom.js | 6 +++--- src/commands/scan.js | 5 +++-- src/commands/snippet.js | 3 ++- src/commands/start.js | 4 ++-- src/commands/status.js | 6 +++--- src/commands/summary.js | 11 ++++------- src/commands/sync.js | 6 +++--- src/portable-reconcile.js | 4 ++-- 17 files changed, 53 insertions(+), 48 deletions(-) diff --git a/src/commands/compile.js b/src/commands/compile.js index 58719f0..2d6e372 100644 --- a/src/commands/compile.js +++ b/src/commands/compile.js @@ -1,6 +1,5 @@ -import fs from "node:fs/promises"; import { diagnose } from "../doctor.js"; -import { readJson } from "../fsutil.js"; +import { assertWritePathInsideWorkspace, readJsonStrict, writeTextAtomic } from "../fsutil.js"; import { openIntents, readJsonl, readTimeline } from "../timeline.js"; import { aiEnvPath, intentsPath, manifestPath, timelinePath, workspaceDir } from "../paths.js"; import { renderAIEnv } from "../render.js"; @@ -9,7 +8,7 @@ import { buildPreflight } from "../preflight.js"; export async function compileWorkspace(args) { const dir = workspaceDir(args); - const manifest = await readJson(manifestPath(dir)); + const manifest = await readJsonStrict(manifestPath(dir)); if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first"); const timeline = await readTimeline(timelinePath(dir)); const intents = openIntents(await readJsonl(intentsPath(dir))); @@ -19,7 +18,8 @@ export async function compileWorkspace(args) { ...manifest, preflight: buildPreflight(manifest, warnings, intents) }, timeline, warnings, intents, policy); - await fs.writeFile(aiEnvPath(dir), rendered, "utf8"); + await assertWritePathInsideWorkspace(dir, aiEnvPath(dir)); + await writeTextAtomic(aiEnvPath(dir), rendered); if (!args.quiet) { console.log(`compiled ${aiEnvPath(dir)}`); } diff --git a/src/commands/context.js b/src/commands/context.js index 5b0bbbe..db56ea5 100644 --- a/src/commands/context.js +++ b/src/commands/context.js @@ -1,5 +1,5 @@ import { diagnose } from "../doctor.js"; -import { readJson } from "../fsutil.js"; +import { readJsonStrict } from "../fsutil.js"; import { openIntents, readJsonl, readTimeline } from "../timeline.js"; import { intentsPath, manifestPath, timelinePath, workspaceDir } from "../paths.js"; import { renderContext } from "../render.js"; @@ -13,7 +13,7 @@ import { externalSbomWarnings, loadExternalSbomStartupSignal } from "../external export async function contextWorkspace(args) { const dir = workspaceDir(args); - const manifest = await readJson(manifestPath(dir)); + const manifest = await readJsonStrict(manifestPath(dir)); if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first"); const timeline = await readTimeline(timelinePath(dir)); const intents = openIntents(await readJsonl(intentsPath(dir))); diff --git a/src/commands/diff.js b/src/commands/diff.js index 4a2a9b8..7b87e90 100644 --- a/src/commands/diff.js +++ b/src/commands/diff.js @@ -1,11 +1,11 @@ import { diffManifests } from "../diff.js"; -import { readJson } from "../fsutil.js"; +import { readJsonStrict } from "../fsutil.js"; import { manifestPath, previousManifestPath, workspaceDir } from "../paths.js"; export async function diffWorkspace(args) { const dir = workspaceDir(args); - const previous = await readJson(previousManifestPath(dir)); - const current = await readJson(manifestPath(dir)); + const previous = await readJsonStrict(previousManifestPath(dir)); + const current = await readJsonStrict(manifestPath(dir)); if (!current) throw new Error("missing manifest; run `aienvmap sync` first"); const changes = diffManifests(previous, current); if (!changes.length) { diff --git a/src/commands/discover.js b/src/commands/discover.js index 8f29fed..d4ca829 100644 --- a/src/commands/discover.js +++ b/src/commands/discover.js @@ -3,7 +3,7 @@ import path from "node:path"; import { aiDefaultReadOrder, aiDiscoveryEntry, aiEntryContract, aiEnvMap, aiSessionUseContract, aiStartHere, aiStatus, aiSummary, npxAiFallbackPrompt, npxAiMissingFallbackPrompt, npxAiStartupChecklist } from "../ai-contract.js"; import { hasAgentPointer } from "../agent-pointer.js"; import { agentSkillLocations, hasAienvmapAgentSkill } from "../agent-skill.js"; -import { readJson } from "../fsutil.js"; +import { readJsonStrict } from "../fsutil.js"; import { aiEnvPath, dashboardPath, discoveryJsonPath, manifestPath, sbomJsonPath, stateDir, stateReadmePath, statusJsonPath, summaryMdPath, workspaceDir } from "../paths.js"; const pointerFiles = [ @@ -25,7 +25,7 @@ const sessionStart = [ export async function discoverWorkspace(args = {}) { const dir = workspaceDir(args); - const status = await readJson(statusJsonPath(dir), null); + const status = await readJsonStrict(statusJsonPath(dir), null); const artifacts = await discoverArtifacts(dir); const pointers = await discoverPointers(dir); const skills = await discoverAgentSkills(dir); diff --git a/src/commands/doctor.js b/src/commands/doctor.js index f8d8422..158cb4e 100644 --- a/src/commands/doctor.js +++ b/src/commands/doctor.js @@ -1,5 +1,5 @@ import { diagnose } from "../doctor.js"; -import { readJson } from "../fsutil.js"; +import { readJsonStrict } from "../fsutil.js"; import { openIntents, readJsonl, readTimeline } from "../timeline.js"; import { intentsPath, manifestPath, timelinePath, workspaceDir } from "../paths.js"; import { loadPolicy, policyWarnings } from "../policy.js"; @@ -11,7 +11,7 @@ export { strictResult } from "../enforcement.js"; export async function doctorWorkspace(args) { const dir = workspaceDir(args); - const manifest = await readJson(manifestPath(dir)); + const manifest = await readJsonStrict(manifestPath(dir)); if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first"); const policy = await loadPolicy(dir); const timeline = await readTimeline(timelinePath(dir)); diff --git a/src/commands/handoff.js b/src/commands/handoff.js index 25d180a..3898238 100644 --- a/src/commands/handoff.js +++ b/src/commands/handoff.js @@ -1,5 +1,5 @@ import { diagnose } from "../doctor.js"; -import { appendJsonLine, readJson } from "../fsutil.js"; +import { appendJsonLine, readJsonStrict } from "../fsutil.js"; import { loadPolicy, policyWarnings } from "../policy.js"; import { intentsPath, manifestPath, timelinePath, workspaceDir } from "../paths.js"; import { renderHandoff } from "../render.js"; @@ -11,7 +11,7 @@ import { buildPreflight } from "../preflight.js"; export async function handoffWorkspace(args) { const dir = workspaceDir(args); - const manifest = await readJson(manifestPath(dir)); + const manifest = await readJsonStrict(manifestPath(dir)); if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first"); const timeline = await readTimeline(timelinePath(dir)); const intents = openIntents(await readJsonl(intentsPath(dir))); diff --git a/src/commands/init.js b/src/commands/init.js index d0475c2..5a7c93a 100644 --- a/src/commands/init.js +++ b/src/commands/init.js @@ -1,10 +1,15 @@ import fs from "node:fs/promises"; +import path from "node:path"; +import { assertWritePathInsideWorkspace } from "../fsutil.js"; import { stateDir, workspaceDir } from "../paths.js"; export async function initWorkspace(args) { const dir = workspaceDir(args); + await fs.mkdir(dir, { recursive: true }); await fs.mkdir(stateDir(dir), { recursive: true }); - await fs.writeFile(`${stateDir(dir)}/policy.yml`, [ + const policy = path.join(stateDir(dir), "policy.yml"); + await assertWritePathInsideWorkspace(dir, policy); + await fs.writeFile(policy, [ "# aienvmap policy", "# Keep this small and explicit so AI agents can avoid version drift.", "# Default behavior is non-blocking: warn, ask, and record instead of locking.", @@ -17,7 +22,9 @@ export async function initWorkspace(args) { "globalInstalls: ask-first", "runtimeChanges: ask-first", "" - ].join("\n"), { flag: "wx" }).catch(() => {}); + ].join("\n"), { flag: "wx" }).catch((error) => { + if (error?.code !== "EEXIST") throw error; + }); if (!args.quiet) console.log(`initialized ${stateDir(dir)}`); return { stateDir: stateDir(dir) }; } diff --git a/src/commands/plan.js b/src/commands/plan.js index 5a1eb1a..0b39165 100644 --- a/src/commands/plan.js +++ b/src/commands/plan.js @@ -1,6 +1,5 @@ -import fs from "node:fs/promises"; import { diagnose } from "../doctor.js"; -import { readJson, writeJson } from "../fsutil.js"; +import { readJsonStrict, writeJson, writeTextAtomic } from "../fsutil.js"; import { loadPolicy, policyWarnings } from "../policy.js"; import { intentsPath, manifestPath, planJsonPath, planMdPath, timelinePath, workspaceDir } from "../paths.js"; import { renderPlan } from "../render.js"; @@ -12,7 +11,7 @@ import { buildPreflight } from "../preflight.js"; export async function planWorkspace(args) { const dir = workspaceDir(args); - const manifest = await readJson(manifestPath(dir)); + const manifest = await readJsonStrict(manifestPath(dir)); if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first"); const timeline = await readTimeline(timelinePath(dir)); const intents = openIntents(await readJsonl(intentsPath(dir))); @@ -22,7 +21,7 @@ export async function planWorkspace(args) { if (args.write) { await writeJson(planJsonPath(dir), plan); - await fs.writeFile(planMdPath(dir), renderPlan(plan), "utf8"); + await writeTextAtomic(planMdPath(dir), renderPlan(plan)); } if (args.json) { diff --git a/src/commands/reconcile.js b/src/commands/reconcile.js index 7fff20d..a6825c8 100644 --- a/src/commands/reconcile.js +++ b/src/commands/reconcile.js @@ -1,7 +1,7 @@ import { inspectPackageManagers } from "../package-managers.js"; import { reconcileJsonPath, workspaceDir } from "../paths.js"; import { writeJson } from "../fsutil.js"; -import { readJson } from "../fsutil.js"; +import { readJsonStrict } from "../fsutil.js"; import { compareReconciliation } from "../reconcile-drift.js"; import path from "node:path"; import { buildPortableCaseSummary, buildPortableReconciliation, comparePortableReconciliations, readPortableEvidence, renderPortableCaseMarkdown } from "../portable-reconcile.js"; @@ -42,7 +42,7 @@ export async function reconcileWorkspace(args = {}) { if (args.case_summary === true) throw new Error("--case-summary requires a portable reconciliation JSON file"); if (args.portable || args.portable_from || args.portable_compare || args.home_evidence || args.inspect_homes || args.write || args.check || args.quick || args.full_packages || args.show_paths || args.inspect_home || args.baseline) throw new Error("--case-summary cannot be combined with scanning, writing, checking, baseline, or path options"); const report = await readPortableEvidence(path.resolve(dir, String(args.case_summary))); - const comparison = args.comparison ? await readJson(path.resolve(dir, String(args.comparison)), null) : null; + const comparison = args.comparison ? await readJsonStrict(path.resolve(dir, String(args.comparison)), null) : null; const summary = buildPortableCaseSummary(report, comparison); if (args.markdown && args.json) throw new Error("use either --markdown or --json, not both"); if (args.markdown) console.log(renderPortableCaseMarkdown(summary)); @@ -65,7 +65,7 @@ export async function reconcileWorkspace(args = {}) { if (args.portable_from) { if (args.portable || args.write || args.check || args.quick || args.full_packages || args.show_paths || args.inspect_home || args.baseline) throw new Error("--portable-from cannot be combined with scanning, writing, checking, baseline, or path options"); if (args.portable_from === true) throw new Error("--portable-from requires a reconciliation JSON file"); - const source = await readJson(path.resolve(dir, String(args.portable_from)), null); + const source = await readJsonStrict(path.resolve(dir, String(args.portable_from)), null); if (source?.schemaName !== "aienvmap.reconcile" || source?.schemaVersion !== 1) throw new Error("--portable-from requires an aienvmap.reconcile v1 JSON artifact"); const portable = buildPortableReconciliation(source, { sourceMode: "artifact" }); if (args.json) console.log(JSON.stringify(portable, null, 2)); @@ -73,7 +73,7 @@ export async function reconcileWorkspace(args = {}) { return portable; } const baselinePath = args.baseline ? path.resolve(dir, String(args.baseline)) : reconcileJsonPath(dir); - const baseline = args.check ? await readJson(baselinePath, null) : null; + const baseline = args.check ? await readJsonStrict(baselinePath, null) : null; if (args.check && !baseline) throw new Error(`missing reconciliation baseline at ${baselinePath}; run \`aienvmap reconcile --write\` first`); if (args.check && baseline?.baselineUse?.checkEligible !== true) { throw new Error(`reconciliation snapshot at ${baselinePath} was created automatically and is not an accepted drift baseline; review the environment, then run \`aienvmap reconcile --write\``); diff --git a/src/commands/sbom.js b/src/commands/sbom.js index acf297f..f0a1634 100644 --- a/src/commands/sbom.js +++ b/src/commands/sbom.js @@ -1,5 +1,5 @@ import { sbomReadOrder } from "../ai-contract.js"; -import { readJson, writeJson } from "../fsutil.js"; +import { readJsonStrict, writeJson } from "../fsutil.js"; import fs from "node:fs/promises"; import { cyclonedxSbomPath, externalSbomEvidencePath, manifestPath, sbomJsonPath, workspaceDir } from "../paths.js"; import { compareSbomEvidence, importSbomEvidence, verifySbomEvidence } from "../sbom-evidence.js"; @@ -7,13 +7,13 @@ import { buildAiDecisionEnvelope } from "../ai-decision-envelope.js"; export async function sbomWorkspace(args = {}) { const dir = workspaceDir(args); - const manifest = await readJson(manifestPath(dir)); + const manifest = await readJsonStrict(manifestPath(dir)); if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first"); if (args.import && args.clear_import) throw new Error("use either --import or --clear-import, not both"); if (args.clear_import && !args.write) throw new Error("--clear-import requires --write"); const evidenceFile = externalSbomEvidencePath(dir); if (args.clear_import) await fs.rm(evidenceFile, { force: true }); - const previousEvidence = !args.clear_import ? await readJson(evidenceFile, null) : null; + const previousEvidence = !args.clear_import ? await readJsonStrict(evidenceFile, null) : null; const imported = args.import ? await importSbomEvidence(dir, args.import) : null; const importedEvidence = imported ? { ...imported, diff --git a/src/commands/scan.js b/src/commands/scan.js index cabc6cf..6ccada4 100644 --- a/src/commands/scan.js +++ b/src/commands/scan.js @@ -1,13 +1,14 @@ import fs from "node:fs/promises"; import { buildManifest } from "../manifest.js"; import { diffManifests } from "../diff.js"; -import { appendJsonLine, exists, readJson, writeJson } from "../fsutil.js"; +import { appendJsonLine, assertWritePathInsideWorkspace, exists, readJsonStrict, writeJson } from "../fsutil.js"; import { manifestPath, previousManifestPath, timelinePath, workspaceDir } from "../paths.js"; export async function scanWorkspace(args) { const dir = workspaceDir(args); const currentPath = manifestPath(dir); - const previous = await readJson(currentPath, null); + await assertWritePathInsideWorkspace(dir, currentPath); + const previous = await readJsonStrict(currentPath, null); if (previous && await exists(currentPath)) { await fs.copyFile(currentPath, previousManifestPath(dir)); } diff --git a/src/commands/snippet.js b/src/commands/snippet.js index ae0dd96..68ae284 100644 --- a/src/commands/snippet.js +++ b/src/commands/snippet.js @@ -1,6 +1,6 @@ import path from "node:path"; import { markerBegin, markerEnd, renderAgentPointer } from "../render.js"; -import { previewMarkerBlock, removeMarkerBlock, replaceMarkerBlock } from "../fsutil.js"; +import { assertWritePathInsideWorkspace, previewMarkerBlock, removeMarkerBlock, replaceMarkerBlock } from "../fsutil.js"; import { workspaceDir } from "../paths.js"; const defaultTargets = { @@ -28,6 +28,7 @@ export async function snippetWorkspace(args) { if (relative.startsWith("..") || path.isAbsolute(relative)) { throw new Error("instruction pointer target must stay inside the workspace"); } + await assertWritePathInsideWorkspace(dir, file); if (args.dry_run) { const preview = await previewMarkerBlock(file, markerBegin, markerEnd, block); if (!args.quiet) console.log(`snippet preview: ${relative} ${preview.action} ${preview.beforeBytes}->${preview.afterBytes} bytes`); diff --git a/src/commands/start.js b/src/commands/start.js index 4cb54f7..326087c 100644 --- a/src/commands/start.js +++ b/src/commands/start.js @@ -2,7 +2,7 @@ import { discoverWorkspace } from "./discover.js"; import { statusWorkspace, renderStatusText } from "./status.js"; import { syncWorkspace } from "./sync.js"; import { reconcileWorkspace, summarizeReconciliation } from "./reconcile.js"; -import { readJson } from "../fsutil.js"; +import { readJsonStrict } from "../fsutil.js"; import { reconcileJsonPath, workspaceDir } from "../paths.js"; export async function startWorkspace(args = {}) { @@ -14,7 +14,7 @@ export async function startWorkspace(args = {}) { await syncWorkspace({ ...args, quiet: true, json: false }); } - let reconciliation = await readJson(reconcileJsonPath(dir), null); + let reconciliation = await readJsonStrict(reconcileJsonPath(dir), null); if (needsSync || !reconciliationFresh(reconciliation)) { reconciliation = await reconcileWorkspace({ ...args, dir, quiet: true, json: false, write: true, quick: true, automatic_snapshot: true }); } diff --git a/src/commands/status.js b/src/commands/status.js index 3552fe4..844320b 100644 --- a/src/commands/status.js +++ b/src/commands/status.js @@ -1,5 +1,5 @@ import { diagnose } from "../doctor.js"; -import { jsonlRevision, readJson, writeJson } from "../fsutil.js"; +import { jsonlRevision, readJsonStrict, writeJson } from "../fsutil.js"; import { loadPolicy, policyWarnings } from "../policy.js"; import { intentsPath, manifestPath, reconcileJsonPath, statusJsonPath, timelinePath, workspaceDir } from "../paths.js"; import { openIntents, readJsonl, readTimeline } from "../timeline.js"; @@ -9,7 +9,7 @@ import { externalSbomWarnings, loadExternalSbomStartupSignal } from "../external export async function statusWorkspace(args) { const dir = workspaceDir(args); - const manifest = await readJson(manifestPath(dir)); + const manifest = await readJsonStrict(manifestPath(dir)); if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first"); const policy = await loadPolicy(dir); const timeline = await readTimeline(timelinePath(dir)); @@ -27,7 +27,7 @@ export async function statusWorkspace(args) { compareAndSwap: "Pass --if-revision to intent or resolve when acting on a previously read state." } }; - const reconciliation = await readJson(reconcileJsonPath(dir), null); + const reconciliation = await readJsonStrict(reconcileJsonPath(dir), null); const status = reconciliation ? { ...baseStatus, reconciliation: summarizeReconciliation(reconciliation) } : { ...baseStatus, reconciliation: { decision: "missing", artifact: ".aienvmap/reconcile.json", nextCommand: "aienvmap reconcile --write", rule: "Generate read-only reconciliation evidence before runtime or package-manager changes." } diff --git a/src/commands/summary.js b/src/commands/summary.js index 7bbabc6..75f3b3d 100644 --- a/src/commands/summary.js +++ b/src/commands/summary.js @@ -1,17 +1,15 @@ -import fs from "node:fs/promises"; -import path from "node:path"; import { schemaContract } from "../contract.js"; -import { readJson } from "../fsutil.js"; +import { readJsonStrict, writeTextAtomic } from "../fsutil.js"; import { manifestPath, statusJsonPath, summaryMdPath, workspaceDir } from "../paths.js"; import { statusWorkspace } from "./status.js"; export async function summaryWorkspace(args) { const dir = workspaceDir(args); - let status = await readJson(statusJsonPath(dir)); + let status = await readJsonStrict(statusJsonPath(dir)); if (!status) { status = await statusWorkspace({ ...args, dir, json: false, write: true, quiet: true }); } - const manifest = await readJson(manifestPath(dir), {}); + const manifest = await readJsonStrict(manifestPath(dir), {}); const markdown = renderSummary(status, manifest); const artifact = args.write ? await writeSummaryArtifact(dir, markdown) : ""; const output = { artifact, summary: markdown, state: status.state || "unknown", sbomRisk: status.sbomRisk || {}, nextCommand: status.nextCommand || "" }; @@ -28,8 +26,7 @@ export async function summaryWorkspace(args) { export async function writeSummaryArtifact(dir, markdown) { const out = summaryMdPath(dir); - await fs.mkdir(path.dirname(out), { recursive: true }); - await fs.writeFile(out, `${markdown.trimEnd()}\n`, "utf8"); + await writeTextAtomic(out, `${markdown.trimEnd()}\n`); return out; } diff --git a/src/commands/sync.js b/src/commands/sync.js index 9db7d19..0dcb47a 100644 --- a/src/commands/sync.js +++ b/src/commands/sync.js @@ -1,4 +1,4 @@ -import fs from "node:fs/promises"; +import { writeTextAtomic } from "../fsutil.js"; import { aiDefaultReadOrder, aiDiscoveryEntry, aiEntryContract, aiFallbackPrompt, aiSessionUseContract, aiStartupChecklist, npxAiContextCommand } from "../ai-contract.js"; import { initWorkspace } from "./init.js"; import { scanWorkspace } from "./scan.js"; @@ -129,7 +129,7 @@ async function writeDiscoveryArtifact(dir, status = {}) { humanInstruction: "Paste copyPastePrompt into an AI session when automatic instruction-file discovery did not happen.", rule: "Do not assume automatic pickup worked. Read discovery/status first, keep local operation advisory, and record intent before shared environment changes." }; - await fs.writeFile(out, JSON.stringify(artifact, null, 2), "utf8"); + await writeTextAtomic(out, `${JSON.stringify(artifact, null, 2)}\n`); return out; } @@ -178,6 +178,6 @@ async function writeStateReadme(dir, status = {}) { "Privacy: treat raw manifests, reconciliation reports, SBOM files, dashboards, and `trial/portable.json` as local-only by default. Coordination files can contain operator text. Review before committing or sharing; use `aienvmap reconcile --portable --json` for redacted evidence. aienvmap never edits `.gitignore`.", "" ]; - await fs.writeFile(out, lines.join("\n"), "utf8"); + await writeTextAtomic(out, lines.join("\n")); return out; } diff --git a/src/portable-reconcile.js b/src/portable-reconcile.js index e299789..65eee3a 100644 --- a/src/portable-reconcile.js +++ b/src/portable-reconcile.js @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import { readJson } from "./fsutil.js"; +import { readJsonStrict } from "./fsutil.js"; export function buildPortableReconciliation(value = {}, runtime = {}) { const administratorNoExec = String(runtime.sourceMode || "").startsWith("administrator-") || (value.findings || []).some((item) => item.code === "unverified-no-exec-evidence"); @@ -163,7 +163,7 @@ function verificationCounts(inventory = {}) { } export async function readPortableEvidence(file) { - const value = await readJson(file, null); + const value = await readJsonStrict(file, null); if (value?.schemaName === "aienvmap.reconcile-portable" && value?.schemaVersion === 1) { validatePortableReconciliation(value); return value; From 813da501f53906a76838d5306ac8b74b6b4b77d4 Mon Sep 17 00:00:00 2001 From: soovwv Date: Wed, 15 Jul 2026 23:23:25 +0900 Subject: [PATCH 6/7] fix: reject invalid policy and SBOM evidence --- src/external-sbom-status.js | 4 ++-- src/policy.js | 26 +++++++++++++++++++++----- test/external-sbom-status.test.js | 11 +++++++++++ test/policy.test.js | 20 +++++++++++++++++++- 4 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/external-sbom-status.js b/src/external-sbom-status.js index 5e80a3e..58081a3 100644 --- a/src/external-sbom-status.js +++ b/src/external-sbom-status.js @@ -1,9 +1,9 @@ -import { readJson } from "./fsutil.js"; +import { readJsonStrict } from "./fsutil.js"; import { externalSbomEvidencePath } from "./paths.js"; import { verifySbomEvidence } from "./sbom-evidence.js"; export async function loadExternalSbomStartupSignal(workspace) { - const persisted = await readJson(externalSbomEvidencePath(workspace), null); + const persisted = await readJsonStrict(externalSbomEvidencePath(workspace), null); if (!persisted) return noExternalSbomSignal(); const evidence = await verifySbomEvidence(workspace, persisted); const stale = evidence?.status === "stale"; diff --git a/src/policy.js b/src/policy.js index 568661f..648343a 100644 --- a/src/policy.js +++ b/src/policy.js @@ -1,23 +1,32 @@ import fs from "node:fs/promises"; import path from "node:path"; +const supportedPolicyKeys = new Set([ + "globalInstalls", "intentionalJavaVersions", "intentionalNodeVersions", "intentionalPythonVersions", + "node", "packageManager", "python", "runtimeChanges" +]); + export async function loadPolicy(dir) { try { const raw = await fs.readFile(path.join(dir, ".aienvmap", "policy.yml"), "utf8"); return parseSimplePolicy(raw); - } catch { - return {}; + } catch (error) { + if (error?.code === "ENOENT") return {}; + throw error; } } export function parseSimplePolicy(raw) { const policy = {}; - for (const line of String(raw).split(/\r?\n/)) { + for (const [index, line] of String(raw).split(/\r?\n/).entries()) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith("#")) continue; const match = trimmed.match(/^([A-Za-z][\w-]*)\s*:\s*(.+)$/); - if (!match) continue; - policy[normalizeKey(match[1])] = unquote(match[2].trim()); + if (!match) throw policyError(`policy.yml contains invalid syntax on line ${index + 1}`, index + 1); + const key = normalizeKey(match[1]); + if (!supportedPolicyKeys.has(key)) throw policyError(`policy.yml contains unsupported key on line ${index + 1}`, index + 1); + if (Object.hasOwn(policy, key)) throw policyError(`policy.yml contains duplicate key on line ${index + 1}`, index + 1); + policy[key] = unquote(match[2].trim()); } return policy; } @@ -83,3 +92,10 @@ function normalizeKey(key) { function unquote(value) { return value.replace(/^["']|["']$/g, ""); } + +function policyError(message, line) { + const error = new Error(message); + error.code = "AIENVMAP_INVALID_POLICY"; + error.line = line; + return error; +} diff --git a/test/external-sbom-status.test.js b/test/external-sbom-status.test.js index 6567aff..bc0d0ae 100644 --- a/test/external-sbom-status.test.js +++ b/test/external-sbom-status.test.js @@ -54,3 +54,14 @@ test("external SBOM startup signal detects source digest drift", async () => { assert.equal(externalSbomWarnings(signal)[0].code, "external-sbom-stale"); } finally { await fs.rm(dir, { recursive: true, force: true }); } }); + +test("external SBOM startup signal fails closed on malformed persisted evidence", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-external-status-invalid-")); + await fs.mkdir(path.join(dir, ".aienvmap"), { recursive: true }); + await fs.writeFile(path.join(dir, ".aienvmap", "external-sbom-evidence.json"), "{invalid-private-data", "utf8"); + await assert.rejects(loadExternalSbomStartupSignal(dir), (error) => { + assert.equal(error.code, "AIENVMAP_INVALID_JSON"); + assert.doesNotMatch(error.message, /invalid-private-data/); + return true; + }); +}); diff --git a/test/policy.test.js b/test/policy.test.js index a1f080d..99347c8 100644 --- a/test/policy.test.js +++ b/test/policy.test.js @@ -1,6 +1,10 @@ +import "./temp-cleanup.js"; import test from "node:test"; import assert from "node:assert/strict"; -import { intentionalRuntimeVersions, parseSimplePolicy, policyWarnings, runtimeVersionsMatchIntentionalPolicy } from "../src/policy.js"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { intentionalRuntimeVersions, loadPolicy, parseSimplePolicy, policyWarnings, runtimeVersionsMatchIntentionalPolicy } from "../src/policy.js"; test("parseSimplePolicy reads simple version policy", () => { assert.deepEqual(parseSimplePolicy(` @@ -24,6 +28,20 @@ test("intentional runtime policy requires an explicit bounded version set", () = assert.equal(runtimeVersionsMatchIntentionalPolicy([{ runtimeVersion: "17.0.12" }, { runtimeVersion: "21.0.4" }], policy, "java"), true); }); +test("policy parsing fails closed on malformed, unknown, and duplicate rules", () => { + assert.throws(() => parseSimplePolicy("runtimeChanges ask-first\n"), (error) => error.code === "AIENVMAP_INVALID_POLICY" && error.line === 1); + assert.throws(() => parseSimplePolicy("runtimeChange: ask-first\n"), /unsupported key on line 1/); + assert.throws(() => parseSimplePolicy("node: 20\nnode: 22\n"), /duplicate key on line 2/); +}); + +test("loadPolicy treats only a missing policy as empty", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aienvmap-policy-")); + assert.deepEqual(await loadPolicy(dir), {}); + await fs.mkdir(path.join(dir, ".aienvmap"), { recursive: true }); + await fs.writeFile(path.join(dir, ".aienvmap", "policy.yml"), "not valid\n", "utf8"); + await assert.rejects(loadPolicy(dir), (error) => error.code === "AIENVMAP_INVALID_POLICY"); +}); + test("policyWarnings reports runtime and lockfile drift", () => { const warnings = policyWarnings({ runtimes: { node: "22.0.0", python: "3.10.0" }, From 011ab0c7e62b251837c9d2dc5a741d5aa3e5de58 Mon Sep 17 00:00:00 2001 From: soovwv Date: Wed, 15 Jul 2026 23:26:40 +0900 Subject: [PATCH 7/7] fix: resolve Windows batch shims safely --- src/shell.js | 14 +++++++++++--- test/shell.test.js | 17 ++++++++++++++++- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/shell.js b/src/shell.js index cf18869..71d10c1 100644 --- a/src/shell.js +++ b/src/shell.js @@ -68,7 +68,14 @@ export async function portableCommandResult(command, args = [], options = {}) { const platform = options.platform || process.platform; if (platform !== "win32" || !/\.(?:cmd|bat)$/i.test(command)) return commandResult(command, args, options); const comspec = options.comspec || process.env.ComSpec || "cmd.exe"; - const commandLine = windowsCmdCommandLine(command, args); + let batchCommand = command; + if (!/[\\/]/.test(batchCommand)) { + const systemRoot = process.env.SystemRoot || process.env.WINDIR || "C:\\Windows"; + const where = `${systemRoot.replace(/[\\/]+$/, "")}\\System32\\where.exe`; + const located = await commandResult(where, [batchCommand], options); + batchCommand = located.ok ? located.stdout.split(/\r?\n/).find(Boolean) || "" : ""; + } + const commandLine = windowsCmdCommandLine(batchCommand, args); if (!commandLine) return { ok: false, code: 1, @@ -83,8 +90,9 @@ export function windowsCmdCommandLine(command, args = []) { const file = String(command || ""); const values = args.map((item) => String(item)); if (!file || /[\r\n"%!]/.test(file)) return ""; - if (values.some((item) => !/^[A-Za-z0-9._@:/=+,-]+$/.test(item))) return ""; - return `""${file}"${values.length ? ` ${values.join(" ")}` : ""}"`; + if (values.some((item) => /[\r\n"%!&|<>^()]/.test(item))) return ""; + const renderedValues = values.map((item) => /^[A-Za-z0-9._@:/=+,-]+$/.test(item) ? item : `"${item}"`); + return `""${file}"${renderedValues.length ? ` ${renderedValues.join(" ")}` : ""}"`; } export function firstVersion(text) { diff --git a/test/shell.test.js b/test/shell.test.js index b4e52ad..7759dc1 100644 --- a/test/shell.test.js +++ b/test/shell.test.js @@ -47,8 +47,9 @@ test("commandResult distinguishes missing commands, nonzero exits, and timeouts" }); test("Windows batch invocation quotes paths and rejects expandable command input", async () => { - assert.equal(windowsCmdCommandLine("C:\\Program Files (x86)\\tool & sdk\\tool.cmd", ["--version"]), `""C:\\Program Files (x86)\\tool & sdk\\tool.cmd" --version"`); + assert.equal(windowsCmdCommandLine("C:\\Program Files (x86)\\tool & sdk\\tool.cmd", ["--output", "C:\\pack destination\\result"]), `""C:\\Program Files (x86)\\tool & sdk\\tool.cmd" --output "C:\\pack destination\\result""`); assert.equal(windowsCmdCommandLine("C:\\%TEMP%\\tool.cmd", ["--version"]), ""); + assert.equal(windowsCmdCommandLine("C:\\safe\\tool.cmd", ["%TEMP%"]), ""); assert.equal(windowsCmdCommandLine("C:\\safe\\tool.cmd", ["&", "whoami"]), ""); const refused = await portableCommandResult("C:\\%TEMP%\\tool.cmd", ["--version"], { platform: "win32" }); @@ -62,5 +63,19 @@ test("Windows batch invocation quotes paths and rejects expandable command input const result = await portableCommandResult(file, ["--version"], { platform: "win32" }); assert.equal(result.ok, true); assert.equal(result.stdout, "1.2.3"); + + const argumentsFile = path.join(dir, "arguments.cmd"); + await fs.writeFile(argumentsFile, "@echo [%~1] [%~2]\r\n", "utf8"); + const destination = path.join(os.tmpdir(), "aienvmap pack destination"); + const argumentsResult = await portableCommandResult(argumentsFile, ["--output", destination], { platform: "win32" }); + assert.equal(argumentsResult.ok, true); + assert.equal(argumentsResult.stdout, `[--output] [${destination}]`); + + const pathResolved = await portableCommandResult("version.cmd", ["--version"], { + platform: "win32", + env: { ...process.env, PATH: dir } + }); + assert.equal(pathResolved.ok, true); + assert.equal(pathResolved.stdout, "1.2.3"); } });