Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
fix(ingest): bound the manifest reads a scanned repo controls (#465)
KageBinaryf799c2d6e525
diff --git a/ix-cli/src/cli/__tests__/bounded-read.test.ts b/ix-cli/src/cli/__tests__/bounded-read.test.tsnew file mode 100644index 00000000..9d4223b5--- /dev/null+++ b/ix-cli/src/cli/__tests__/bounded-read.test.ts@@ -0,0 +1,248 @@+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import * as fs from "node:fs";+import * as os from "node:os";+import * as nodePath from "node:path";++import { readBoundedFile, readCapped } from "../bounded-read.js";++/**+ * `readBoundedFile` stands between ingestion and a file whose path AND contents+ * the scanned repository chose. Every case below is a way a repo can name+ * something that is not the small text file the caller expects.+ */+describe("readBoundedFile", () => {+ let root: string;++ beforeAll(() => {+ root = fs.mkdtempSync(nodePath.join(os.tmpdir(), "ix-bounded-"));+ });++ afterAll(() => {+ fs.rmSync(root, { recursive: true, force: true });+ });++ it("reads an ordinary file", () => {+ const p = nodePath.join(root, "plain.json");+ fs.writeFileSync(p, '{ "name": "reads-fine" }');+ expect(readBoundedFile(p)).toBe('{ "name": "reads-fine" }');+ });++ it("refuses a file whose reported size is over the cap", () => {+ const p = nodePath.join(root, "big.json");+ fs.writeFileSync(p, "x".repeat(4096));+ expect(readBoundedFile(p, { maxBytes: 1024 })).toBeNull();+ // ...and the same file is fine under a cap that admits it, so it is the cap+ // doing the work rather than anything else about the file.+ expect(readBoundedFile(p, { maxBytes: 8192 })).not.toBeNull();+ });++ it("refuses a directory", () => {+ const p = nodePath.join(root, "adir");+ fs.mkdirSync(p, { recursive: true });+ expect(readBoundedFile(p)).toBeNull();+ });++ it("refuses a file that does not exist", () => {+ expect(readBoundedFile(nodePath.join(root, "absent.json"))).toBeNull();+ });++ it("refuses when the caller's accept check says no, and reads when it says yes", () => {+ const p = nodePath.join(root, "gated.json");+ fs.writeFileSync(p, "gated");+ expect(readBoundedFile(p, { accept: () => false })).toBeNull();+ expect(readBoundedFile(p, { accept: () => true })).toBe("gated");+ });++ it("hands accept the stats of the file it actually opened", () => {+ const p = nodePath.join(root, "stats.json");+ fs.writeFileSync(p, "12345");+ const real = fs.statSync(p);+ let seen: fs.Stats | null = null;+ readBoundedFile(p, {+ accept: (stats) => {+ seen = stats;+ return true;+ },+ });+ // Same inode as the path names, so a caller can tie a resolved path back to+ // the handle rather than to a name that may have been swapped underneath.+ expect(seen!.ino).toBe(real.ino);+ expect(seen!.dev).toBe(real.dev);+ expect(seen!.size).toBe(5);+ });+});++/**+ * The cap lives in the READ, not in the fstat, because `fs.readFileSync(handle)`+ * re-stats and reads that size instead. Pinning `readCapped` directly is the+ * only way to assert that on every platform: the wiring can only be caught+ * where a size-0 regular file exists, which is Linux alone.+ */+describe("readCapped", () => {+ let root: string;++ beforeAll(() => {+ root = fs.mkdtempSync(nodePath.join(os.tmpdir(), "ix-capped-"));+ });++ afterAll(() => {+ fs.rmSync(root, { recursive: true, force: true });+ });++ // The same flags readBoundedFile opens with, so these exercise the handle+ // production actually hands to readCapped.+ const withHandle = <T>(p: string, fn: (fd: number) => T): T => {+ const fd = fs.openSync(p, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);+ try {+ return fn(fd);+ } finally {+ fs.closeSync(fd);+ }+ };++ it("refuses a handle holding more than the cap", () => {+ const p = nodePath.join(root, "over.txt");+ fs.writeFileSync(p, "x".repeat(4096));+ expect(withHandle(p, (fd) => readCapped(fd, 1024))).toBeNull();+ expect(withHandle(p, (fd) => readCapped(fd, 8192))).toHaveLength(4096);+ });++ it("admits a file exactly at the cap and refuses a cap one byte tighter", () => {+ const at = nodePath.join(root, "at.txt");+ fs.writeFileSync(at, "y".repeat(100));+ expect(withHandle(at, (fd) => readCapped(fd, 100))).toHaveLength(100);+ expect(withHandle(at, (fd) => readCapped(fd, 99))).toBeNull();+ });++ it("reads a file that spans several chunks, without corrupting a split character", () => {+ // Every character is 3 bytes and the chunk is 65536, which is not a+ // multiple of 3 — so whichever byte a read happens to stop on, some+ // character straddles a boundary. Placing one 2-byte character at offset+ // 65535 instead would only split it if the first read returned exactly+ // 65536 bytes, which POSIX does not promise and FUSE/network mounts do not+ // deliver; that test would pass vacuously there. Decoding per chunk rather+ // than after the concat turns the split character into replacement chars.+ const p = nodePath.join(root, "multibyte.txt");+ const text = "€".repeat(30000); // 90000 bytes, > 64 KiB+ fs.writeFileSync(p, text, "utf8");+ expect(fs.statSync(p).size).toBe(90000);+ expect(withHandle(p, (fd) => readCapped(fd, 1024 * 1024))).toBe(text);+ });++ it("returns empty string for an empty file", () => {+ const p = nodePath.join(root, "empty.txt");+ fs.writeFileSync(p, "");+ expect(withHandle(p, (fd) => readCapped(fd, 1024))).toBe("");+ });+});++/**+ * The case the fstat size check cannot catch, and the reason the read is capped+ * separately. A `/proc` entry is a REGULAR file — `isFile()` true — that reports+ * size 0 while holding kilobytes, so a guard built only from `fstat().size`+ * admits the whole file.+ */+describe.skipIf(process.platform !== "linux")("size-0 regular files", () => {+ it("refuses one whose contents exceed the cap", (ctx) => {+ // Not every /proc is the kernel's: lxcfs and gVisor overlays report a real+ // size, and there the premise of this test simply does not hold. Skip+ // explicitly rather than assert, and never pass silently.+ let stats: fs.Stats;+ try {+ stats = fs.statSync("/proc/meminfo");+ } catch {+ return ctx.skip("no /proc/meminfo on this runner");+ }+ if (!stats.isFile() || stats.size !== 0) {+ return ctx.skip("/proc/meminfo is not a size-0 regular file here");+ }+ expect(readBoundedFile("/proc/meminfo", { maxBytes: 100 })).toBeNull();+ // A cap it does fit under still reads, so the refusal above is the cap.+ expect(readBoundedFile("/proc/meminfo")).toContain("MemTotal");+ });+});++// POSIX only: creating a symlink on Windows needs privileges the runner does+// not have, and /dev/zero has no Windows equivalent.+describe.skipIf(process.platform === "win32")("character devices", () => {+ it("refuses one reached through a symlink, rather than reading it forever", () => {+ let dir: string | undefined;+ try {+ dir = fs.mkdtempSync(nodePath.join(os.tmpdir(), "ix-dev-"));+ const dev = nodePath.join(dir, "zero.json");+ fs.symlinkSync("/dev/zero", dev);+ // The assertion that matters is that this returns at all: an unguarded+ // read of /dev/zero does not throw and does not finish, it consumes+ // memory until the process dies.+ const started = Date.now();+ expect(readBoundedFile(dev)).toBeNull();+ expect(Date.now() - started).toBeLessThan(2000);+ } finally {+ if (dir) fs.rmSync(dir, { recursive: true, force: true });+ }+ });++ it("refuses a character device that reads as empty", () => {+ // /dev/null returns EOF immediately, so the cap never fires on it: without+ // the isFile() check it reads as "" rather than being refused. Every other+ // non-regular case in this suite is now caught by the cap instead, so this+ // is the one that pins the type check itself.+ expect(readBoundedFile("/dev/null")).toBeNull();+ });+});++/**+ * The defect this module exists for, reproduced through the public API and+ * therefore pinned on every platform.+ *+ * `accept` runs between the fstat and the read, so a test can grow the file at+ * exactly the moment the real bug needs it to grow. That single assertion kills+ * both ways of getting this wrong: reverting to `fs.readFileSync(handle)` (which+ * re-stats and reads the NEW size), and reordering so the content is read before+ * `accept` decides (which would return the pre-growth content instead of null).+ * The /proc case covers the other half of the same defect — a size that was+ * never right to begin with — but exists on one of the four platforms this+ * suite runs on, and skips itself on an lxcfs or gVisor overlay.+ */+describe("the cap binds against a file that changes under it", () => {+ let root: string;++ beforeAll(() => {+ root = fs.mkdtempSync(nodePath.join(os.tmpdir(), "ix-grow-"));+ });++ afterAll(() => {+ fs.rmSync(root, { recursive: true, force: true });+ });++ it("refuses a file that grows past the cap after its size was checked", () => {+ const p = nodePath.join(root, "grows.json");+ fs.writeFileSync(p, "x".repeat(10));+ let grew = false;+ const out = readBoundedFile(p, {+ maxBytes: 1024,+ accept: () => {+ fs.appendFileSync(p, "y".repeat(4096));+ grew = true;+ return true;+ },+ });+ expect(grew).toBe(true);+ expect(out).toBeNull();+ });++ it("still returns the content when the growth stays under the cap", () => {+ // The control: the refusal above is the cap reacting to the new size, not+ // the write itself upsetting the read.+ const p = nodePath.join(root, "grows-a-little.json");+ fs.writeFileSync(p, "x".repeat(10));+ const out = readBoundedFile(p, {+ maxBytes: 1024,+ accept: () => {+ fs.appendFileSync(p, "y".repeat(100));+ return true;+ },+ });+ expect(out).toBe("x".repeat(10) + "y".repeat(100));+ });+});diff --git a/ix-cli/src/cli/__tests__/system.test.ts b/ix-cli/src/cli/__tests__/system.test.tsindex b3e4f159..b891f7ff 100644--- a/ix-cli/src/cli/__tests__/system.test.ts+++ b/ix-cli/src/cli/__tests__/system.test.ts@@ -2,6 +2,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";import * as fs from "node:fs";import * as os from "node:os";import * as nodePath from "node:path";+import { execFileSync } from "node:child_process";import { buildPackageRegistry, detectSystem, readPackageNames, readPackageDeps, repoWorkspaceIdFor, workspaceIdForPath } from "../system.js";@@ -181,3 +182,87 @@ describe("workspace_id convergence (solo vs co-ingest)", () => {expect(workspaceIdForPath(root)).toMatch(/^[0-9a-f]{8}$/); // 8-hex, not a random UUID slice});});++// ── Manifest reads are bounded ───────────────────────────────────────────────+//+// Every path this module reads is named by the *scanned repository*, so a+// hostile or merely broken one decides what `ix map` opens. `readFileSync` on+// `/dev/zero` does not throw — it consumes memory until the process dies — and+// a 2 GB `Cargo.toml` needs no symlink to do the same.+describe("manifest reads are bounded and typed", () => {+ let dir: string;++ beforeAll(() => {+ dir = fs.mkdtempSync(nodePath.join(os.tmpdir(), "ix-manifest-"));+ });++ afterAll(() => {+ fs.rmSync(dir, { recursive: true, force: true });+ });++ it("still reads an ordinary manifest", () => {+ const ok = nodePath.join(dir, "ok");+ fs.mkdirSync(ok, { recursive: true });+ fs.writeFileSync(nodePath.join(ok, "package.json"), '{ "name": "reads-fine" }');+ expect(readPackageNames(ok)).toContain("reads-fine");+ });++ it("refuses a manifest larger than the cap instead of loading it", () => {+ const big = nodePath.join(dir, "big");+ fs.mkdirSync(big, { recursive: true });+ // Just over 1 MB, and valid JSON, so only the size can be what rejects it.+ const padding = "x".repeat(1024 * 1024);+ fs.writeFileSync(+ nodePath.join(big, "package.json"),+ JSON.stringify({ name: "too-big", description: padding }),+ );+ expect(readPackageNames(big)).toEqual([]);+ });++ it("refuses a manifest that is a directory", () => {+ const weird = nodePath.join(dir, "weird");+ fs.mkdirSync(nodePath.join(weird, "package.json"), { recursive: true });+ // A throw would fail the test on its own, so one call proves both that it+ // does not throw and that it yields nothing.+ expect(readPackageNames(weird)).toEqual([]);+ });++ // POSIX only: /dev/zero has no Windows equivalent, and creating a symlink+ // there needs privileges the runner does not have.+ it.skipIf(process.platform === "win32")(+ "refuses a manifest symlinked to a character device, rather than reading it forever",+ () => {+ const dev = nodePath.join(dir, "dev");+ fs.mkdirSync(dev, { recursive: true });+ fs.symlinkSync("/dev/zero", nodePath.join(dev, "package.json"));++ // The assertion that matters is that this returns at all: unguarded,+ // the read never does.+ const started = Date.now();+ expect(readPackageNames(dev)).toEqual([]);+ expect(readPackageDeps(dev)).toEqual([]);+ expect(Date.now() - started).toBeLessThan(2000);+ },+ );++ it.skipIf(process.platform === "win32")("refuses a manifest that is a FIFO, without blocking on it", () => {+ const fifoDir = nodePath.join(dir, "fifo");+ fs.mkdirSync(fifoDir, { recursive: true });+ const fifo = nodePath.join(fifoDir, "package.json");+ try {+ execFileSync("mkfifo", [fifo]);+ } catch {+ // Returning here would report a pass having asserted nothing, which is+ // indistinguishable from a working guard. Fail loudly instead: every+ // POSIX runner this suite targets has mkfifo.+ throw new Error("mkfifo is required to exercise the FIFO guard on this platform");+ }+ // Opening a FIFO for reading blocks until a writer appears, so the guard+ // cannot stat-then-open: it opens with O_NONBLOCK and fstats the handle.+ // Drop that flag and this test does not go red, it HANGS — the open blocks+ // the same event loop vitest would fire its timeout on.+ const started = Date.now();+ expect(readPackageNames(fifoDir)).toEqual([]);+ expect(Date.now() - started).toBeLessThan(2000);+ });+});diff --git a/ix-cli/src/cli/bounded-read.ts b/ix-cli/src/cli/bounded-read.tsnew file mode 100644index 00000000..e12f0bf9--- /dev/null+++ b/ix-cli/src/cli/bounded-read.ts@@ -0,0 +1,106 @@+// Bounded reads of repository-controlled files (Ix#465).+//+// Ingestion opens files whose paths AND contents the scanned repository+// chooses: build manifests (`package.json`, `Cargo.toml`, `go.mod`, ...) and+// TypeScript configs. Both are read while the system map and the module+// resolver are built, which happens before ingestion's own size gate, so they+// need their own — and the guard has to survive a repo that is hostile rather+// than merely large.+//+// This module is only the READ. Containment is the caller's, via `accept`:+// what counts as "inside" differs per caller, and getting it wrong silently+// deletes input rather than failing, so it does not belong behind a default.++import * as fs from "node:fs";++/**+ * How much of a repository-controlled file is worth reading, in bytes.+ *+ * Mirrors `MAX_FILE_BYTES` in `ingest.ts`. A `package.json` or a+ * `tsconfig.json` past this is not one anybody wrote, and parsing one is how a+ * 64 MB file takes the process out with an uncatchable OOM.+ */+const MAX_REPO_FILE_BYTES = 1024 * 1024;++/**+ * Read at most `maxBytes` from an open handle; null when the file holds more.+ *+ * `fs.readFileSync(handle)` cannot be used here, even behind an fstat size+ * check, because it re-stats the handle and reads *that* size instead:+ *+ * - a file that grows between the check and the read is read at its new size.+ * Measured: an fstat that saw 50 bytes, followed by a `readFileSync` on the+ * same handle that returned 550;+ * - a regular file reporting size 0 makes it fall back to reading 8 KB chunks+ * until EOF with no limit at all. `isFile()` is true and `size` is 0 for+ * every `/proc` and `/sys` entry, and for size-0 regular files on some FUSE+ * and network mounts.+ *+ * So the fstat size check bounds nothing on its own. Reading the handle here is+ * what makes the cap bind.+ *+ * Refuses rather than truncates: half a manifest is neither valid JSON nor a+ * trustworthy `name = "..."`, and a silent truncation is a worse answer than+ * none. The per-chunk copy is required — the scratch buffer is reused — and the+ * decode happens after the concat, so a multi-byte character straddling a chunk+ * boundary round-trips intact.+ *+ * @internal Exported only so the cap can be pinned directly on every platform.+ * Not a reader: it does no open, no type check and no containment, so nothing+ * outside this module should call it. {@link readBoundedFile} is the entry+ * point.+ */+export function readCapped(handle: number, maxBytes: number): string | null {+ const chunks: Buffer[] = [];+ const chunk = Buffer.allocUnsafe(64 * 1024);+ let total = 0;+ for (;;) {+ const bytes = fs.readSync(handle, chunk, 0, chunk.length, null);+ if (bytes === 0) break;+ total += bytes;+ if (total > maxBytes) return null;+ chunks.push(Buffer.from(chunk.subarray(0, bytes)));+ }+ return Buffer.concat(chunks, total).toString("utf8");+}++/**+ * Read a repository-controlled file, bounded and type-checked, or null.+ *+ * Open once and ask the handle:+ *+ * - `O_NONBLOCK` so opening a FIFO returns instead of waiting for a writer. It+ * is the one case a guard placed after the open cannot cover, because without+ * it the open never returns. Undefined on Windows, where `|` with undefined+ * degrades to a plain read — and Windows has no FIFO to open this way.+ * - `fstat` on the handle rather than `stat` on the path, so the checks and the+ * read observe the same inode (CodeQL js/file-system-race).+ * - `openSync` follows symlinks, so fstat describes the *target*. `isFile()`+ * refuses a device, a FIFO and a directory — none of which a size check+ * catches, since `/dev/zero` and a FIFO both report size 0.+ * - `accept`, if given, is the caller's own check on that same open file. It+ * runs before any content is read, and is where a containment rule belongs:+ * it needs the `fs.Stats` of the handle to tie a resolved path back to the+ * file actually held.+ * - the read itself is capped; see {@link readCapped} for why the size check+ * does not do that on its own.+ */+export function readBoundedFile(+ filePath: string,+ opts: { maxBytes?: number; accept?: (opened: fs.Stats) => boolean } = {},+): string | null {+ const { maxBytes = MAX_REPO_FILE_BYTES, accept } = opts;+ try {+ const handle = fs.openSync(filePath, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);+ try {+ const stats = fs.fstatSync(handle);+ if (!stats.isFile() || stats.size > maxBytes) return null;+ if (accept && !accept(stats)) return null;+ return readCapped(handle, maxBytes);+ } finally {+ fs.closeSync(handle);+ }+ } catch {+ return null;+ }+}diff --git a/ix-cli/src/cli/system.ts b/ix-cli/src/cli/system.tsindex 81bc88bd..d4fbc487 100644--- a/ix-cli/src/cli/system.ts+++ b/ix-cli/src/cli/system.ts@@ -1,6 +1,7 @@import * as fs from "node:fs";import * as nodePath from "node:path";import { createHash } from "node:crypto";+import { readBoundedFile } from "./bounded-read.js";/*** Multi-repo system auto-detection (Ix#225 Path 1).@@ -38,6 +39,40 @@ function isRepoRoot(dir: string): boolean {}}+/**+ * Read a build manifest out of a scanned directory, or null.+ *+ * Every path this module reads is *named by the repository being scanned*, so a+ * hostile or merely broken one decides what `ix map` opens. These three readers+ * were the last ones in the ingest path with no guard on what came back: a bare+ * `readFileSync` follows `package.json -> /dev/zero` and never returns — it does+ * not throw, it consumes memory until the process dies — and a plain 2 GB+ * `Cargo.toml` does the same without needing a symlink.+ *+ * The guard is shared with the module resolver, which reads tsconfigs under+ * exactly these conditions; `readBoundedFile` documents what each part of it is+ * for, and why a size check alone bounds nothing.+ *+ * No containment check, deliberately. Both roots that could be used here break+ * a layout that works today, and break it silently:+ *+ * - the scanned directory itself refuses a manifest a repo legitimately+ * symlinks within itself, and does not refuse the case worth refusing — a+ * symlinked member directory resolves root and file to the same outside tree;+ * - the mapped root refuses every symlinked member repo, which `detectSystem`+ * has admitted on purpose since Ix#225 (see the `isSymbolicLink()` filter+ * below): a folder collecting independently-cloned repos is exactly what it+ * is for, and collecting them by symlink is the ordinary way to do it.+ *+ * A refusal here is indistinguishable from "no manifest", so either choice+ * deletes a package from the registry with nothing said. Confining what a+ * scanned repo may name is worth doing, but it needs a diagnostic and a way+ * out, not a silent default bolted onto a read.+ */+function readManifest(dir: string, file: string): string | null {+ return readBoundedFile(nodePath.join(dir, file));+}+/** A directory is its own git repository iff it contains a `.git` entry (a dir* for a normal clone, or a file for a submodule/worktree). This is the* ground-truth signal that a child is a DISTINCT repository — a monorepo's@@ -54,7 +89,7 @@ function hasOwnGit(dir: string): boolean {*/function hasWorkspaceMarker(dir: string): boolean {const has = (f: string) => { try { return fs.existsSync(nodePath.join(dir, f)); } catch { return false; } };- const reads = (f: string): string | null => { try { return fs.readFileSync(nodePath.join(dir, f), "utf8"); } catch { return null; } };+ const reads = (f: string): string | null => readManifest(dir, f);// Dedicated workspace/monorepo config files.if (has("pnpm-workspace.yaml") || has("lerna.json") || has("nx.json") ||has("turbo.json") || has("rush.json") || has("go.work") ||@@ -97,9 +132,7 @@ function isInsideSingleRepo(dir: string): boolean {*/export function readPackageNames(dir: string): string[] {const names = new Set<string>();- const read = (f: string): string | null => {- try { return fs.readFileSync(nodePath.join(dir, f), "utf8"); } catch { return null; }- };+ const read = (f: string): string | null => readManifest(dir, f);const add = (n: unknown) => { if (typeof n === "string" && n.trim()) names.add(n.trim()); };const pkg = read("package.json"); // JS / TS@@ -192,9 +225,7 @@ export function lookupPackage(registry: Record<string, string>, mod: string): st*/export function readPackageDeps(dir: string): string[] {const deps = new Set<string>();- const read = (f: string): string | null => {- try { return fs.readFileSync(nodePath.join(dir, f), "utf8"); } catch { return null; }- };+ const read = (f: string): string | null => readManifest(dir, f);const add = (n: unknown) => { if (typeof n === "string" && n.trim()) deps.add(n.trim()); };// PRODUCTION deps only. The declared-dependency graph gates cross-repo edges,diff --git a/ix-cli/src/cli/ts-module-resolution.ts b/ix-cli/src/cli/ts-module-resolution.tsindex 7c827c2d..50ae325a 100644--- a/ix-cli/src/cli/ts-module-resolution.ts+++ b/ix-cli/src/cli/ts-module-resolution.ts@@ -1,5 +1,6 @@import * as fs from "node:fs";import * as nodePath from "node:path";+import { readBoundedFile } from "./bounded-read.js";interface PathRule {pattern: string;@@ -132,14 +133,6 @@ function parseJsonc(text: string): unknown {return JSON.parse(normalized);}-/**- * Config files are read while the resolver is built, which happens *before*- * ingestion's own size gate, so they need their own. Mirrors `MAX_FILE_BYTES`- * in `ingest.ts`: anything larger is not a tsconfig, and parsing one is how a- * 64 MB JSONC file takes the process out with an uncatchable OOM.- */-const MAX_CONFIG_BYTES = 1024 * 1024;-/*** True when the file we are *holding open* lives inside the workspace.*@@ -184,31 +177,16 @@ function openedWithinWorkspace(}function readObject(workspaceRoot: string, filePath: string): Record<string, unknown> | undefined {+ // The FIFO-safe open, the regular-file check and the bound are shared with+ // the manifest readers — see bounded-read.ts, which also explains why the+ // size check alone does not bound the read. Containment stays here: the root+ // it is measured against is this caller's, and it runs on the same open+ // handle, before any content is read.+ const text = readBoundedFile(filePath, {+ accept: (stats) => openedWithinWorkspace(workspaceRoot, filePath, stats),+ });+ if (text === null) return undefined;try {- // Open once and fstat the same handle so the checks and the read observe the- // same inode — no stat-then-read window (CodeQL js/file-system-race). This is- // the pattern ingest.ts already uses.- //- // O_NONBLOCK is load-bearing, not tidiness: opening a FIFO for reading- // *blocks until a writer appears*, so without it the open never returns and- // no later check can help. It is the one case a guard placed after the open- // cannot cover. Undefined on Windows, where `|` with undefined degrades to- // a plain read — and Windows has no FIFO to open this way.- const handle = fs.openSync(filePath, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);- let text: string;- try {- const stats = fs.fstatSync(handle);- // `openSync` follows symlinks, so fstat describes the *target*. Refusing- // anything that is not a regular file is what stops a link to /dev/zero- // (an unbounded read) and a FIFO (which would otherwise deliver no data- // and no EOF) — neither of which a size check catches, since both- // report size 0.- if (!stats.isFile() || stats.size > MAX_CONFIG_BYTES) return undefined;- if (!openedWithinWorkspace(workspaceRoot, filePath, stats)) return undefined;- text = fs.readFileSync(handle, "utf8");- } finally {- fs.closeSync(handle);- }const parsed = parseJsonc(text);return parsed && typeof parsed === "object" && !Array.isArray(parsed)? (parsed as Record<string, unknown>)