Simplify and harden investigation workflows

This commit is contained in:
morluto
2026-07-12 21:45:26 +00:00
parent fbe8ec1f13
commit 293cea7723
35 changed files with 531 additions and 1041 deletions
+57 -13
View File
@@ -3,6 +3,7 @@ import { constants as fsConstants } from "node:fs";
import { lstat, open, readdir, readlink } from "node:fs/promises";
import { dirname, join, relative, resolve } from "node:path";
import type { FileState, ProcessScenario } from "../domain/processCapture.js";
import type { Stats } from "node:fs";
export interface SnapshotResult {
readonly files: readonly FileState[];
@@ -13,9 +14,29 @@ const isWithin = (candidate: string, root: string): boolean =>
candidate === root ||
candidate.startsWith(`${root.endsWith("/") ? root.slice(0, -1) : root}/`);
const hasSameIdentity = (
before: Stats,
after: Stats,
expected: "directory" | "symlink",
): boolean =>
before.dev === after.dev &&
before.ino === after.ino &&
(expected === "directory" ? after.isDirectory() : after.isSymbolicLink());
const lstatIfPresent = async (path: string): Promise<Stats | undefined> => {
try {
return await lstat(path);
} catch (cause: unknown) {
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
return undefined;
throw cause;
}
};
const hashFile = async (
path: string,
maxBytes: number,
signal?: AbortSignal,
): Promise<string | null> => {
const handle = await open(
path,
@@ -24,9 +45,25 @@ const hashFile = async (
try {
const stats = await handle.stat();
if (!stats.isFile() || stats.size > maxBytes) return null;
return createHash("sha256")
.update(await handle.readFile())
.digest("hex");
const hash = createHash("sha256");
const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes));
let position = 0;
while (position < stats.size) {
signal?.throwIfAborted();
const { bytesRead } = await handle.read(
buffer,
0,
Math.min(buffer.length, stats.size - position),
position,
);
if (bytesRead === 0) return null;
hash.update(buffer.subarray(0, bytesRead));
position += bytesRead;
}
const after = await handle.stat();
if (after.size !== stats.size || after.mtimeMs !== stats.mtimeMs)
return null;
return hash.digest("hex");
} finally {
await handle.close();
}
@@ -35,6 +72,7 @@ const hashFile = async (
/** Capture bounded, root-aliased filesystem state without following symlinks. */
export const snapshotRoots = async (
scenario: ProcessScenario,
signal?: AbortSignal,
): Promise<SnapshotResult> => {
const entries: FileState[] = [];
let remainingBytes = scenario.limits.file_bytes;
@@ -45,6 +83,7 @@ export const snapshotRoots = async (
path: string,
depth: number,
): Promise<void> => {
signal?.throwIfAborted();
if (
entries.length >= scenario.limits.files ||
depth > scenario.limits.filesystem_depth
@@ -52,17 +91,16 @@ export const snapshotRoots = async (
truncated = true;
return;
}
let stats;
try {
stats = await lstat(path);
} catch (error: unknown) {
if (error instanceof Error && "code" in error && error.code === "ENOENT")
return;
throw error;
}
const stats = await lstatIfPresent(path);
if (stats === undefined) return;
const relativePath = relative(root, path) || ".";
if (stats.isSymbolicLink()) {
const target = resolve(dirname(path), await readlink(path));
const afterRead = await lstat(path);
if (!hasSameIdentity(stats, afterRead, "symlink")) {
truncated = true;
return;
}
const safeTarget = isWithin(target, root)
? relative(root, target) || "."
: "<outside-declared-root>";
@@ -80,7 +118,7 @@ export const snapshotRoots = async (
if (stats.isFile()) {
const sha256 =
remainingBytes >= stats.size
? await hashFile(path, remainingBytes)
? await hashFile(path, remainingBytes, signal)
: null;
remainingBytes -= sha256 === null ? 0 : stats.size;
if (sha256 === null) truncated = true;
@@ -104,7 +142,13 @@ export const snapshotRoots = async (
symlink_target: null,
});
if (type !== "directory") return;
for (const child of (await readdir(path)).sort())
const children = await readdir(path);
const afterRead = await lstat(path);
if (!hasSameIdentity(stats, afterRead, "directory")) {
truncated = true;
return;
}
for (const child of children.sort())
await visit(root, rootAlias, join(path, child), depth + 1);
};
for (const [index, root] of scenario.filesystem_roots.entries())