Add evidence-backed investigation workflows
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { traverseDirectory } from "./ReferenceSourceReaderEntries.js";
|
||||
import { compareNames } from "./ReferenceSourceReaderPaths.js";
|
||||
import {
|
||||
type ReferenceSourceLimits,
|
||||
type ReferenceSourceReaderOptions,
|
||||
type ReferenceSourceRead,
|
||||
type ReferenceSourceResult,
|
||||
type TraversalState,
|
||||
} from "./ReferenceSourceReaderTypes.js";
|
||||
import {
|
||||
isAborted,
|
||||
noFollowOpenSupported,
|
||||
prepareRoot,
|
||||
} from "./ReferenceSourceReaderValidate.js";
|
||||
|
||||
export type {
|
||||
ReferenceSourceEntry,
|
||||
ReferenceSourceLimits,
|
||||
ReferenceSourceRead,
|
||||
ReferenceSourceReaderOptions,
|
||||
} from "./ReferenceSourceReaderTypes.js";
|
||||
|
||||
const DEFAULT_LIMITS: ReferenceSourceLimits = {
|
||||
maxBytes: 16 * 1024 * 1024,
|
||||
maxEntries: 10_000,
|
||||
maxDepth: 32,
|
||||
maxPathBytes: 4_096,
|
||||
};
|
||||
const PATH_RACE_LIMITATION =
|
||||
"Path identity is revalidated around operations; Node lacks portable descriptor-relative openat traversal, so a syscall-boundary pathname race remains.";
|
||||
|
||||
/** Read a bounded source tree without intentionally following symbolic links. */
|
||||
export const readReferenceSource = async (
|
||||
root: string,
|
||||
limits: ReferenceSourceLimits = DEFAULT_LIMITS,
|
||||
options: ReferenceSourceReaderOptions = {},
|
||||
): Promise<ReferenceSourceResult<ReferenceSourceRead>> => {
|
||||
if (!noFollowOpenSupported())
|
||||
return err({
|
||||
tag: "reference-source-reader",
|
||||
code: "unsupported",
|
||||
message: "Safe no-follow file opens are unavailable",
|
||||
});
|
||||
const prepared = await prepareRoot(root, limits, options.signal);
|
||||
if (!prepared.ok) return prepared;
|
||||
const { canonicalRoot, rootIdentity } = prepared.value;
|
||||
const state: TraversalState = {
|
||||
root: canonicalRoot,
|
||||
rootIdentity,
|
||||
limits,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.shouldExclude === undefined
|
||||
? {}
|
||||
: { shouldExclude: options.shouldExclude }),
|
||||
entries: [],
|
||||
pending: [{ path: canonicalRoot, depth: 0 }],
|
||||
bytesRead: 0,
|
||||
filesSeen: 0,
|
||||
truncated: false,
|
||||
stopped: false,
|
||||
};
|
||||
const traversal = await traverse(state);
|
||||
if (!traversal.ok) return traversal;
|
||||
state.entries.sort((left, right) => compareNames(left.path, right.path));
|
||||
return ok({
|
||||
root: canonicalRoot,
|
||||
entries: state.entries,
|
||||
bytesRead: state.bytesRead,
|
||||
truncated: state.truncated,
|
||||
limitations: [
|
||||
PATH_RACE_LIMITATION,
|
||||
...(state.stopped
|
||||
? ["Traversal stopped because the entry limit was reached."]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const traverse = async (
|
||||
state: TraversalState,
|
||||
): Promise<ReferenceSourceResult<undefined>> => {
|
||||
while (state.pending.length > 0 && !state.stopped) {
|
||||
if (isAborted(state.signal))
|
||||
return err({
|
||||
tag: "reference-source-reader",
|
||||
code: "cancelled",
|
||||
message: "Reference source traversal cancelled",
|
||||
});
|
||||
const current = state.pending.pop();
|
||||
if (current === undefined) break;
|
||||
const result = await traverseDirectory(state, current);
|
||||
if (!result.ok) return result;
|
||||
}
|
||||
return ok(undefined);
|
||||
};
|
||||
@@ -0,0 +1,302 @@
|
||||
import { readdir, readlink, realpath } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
|
||||
import { entryFailure, safeSize } from "./ReferenceSourceReaderErrors.js";
|
||||
import {
|
||||
compareNames,
|
||||
pathFromRoot,
|
||||
withinRoot,
|
||||
} from "./ReferenceSourceReaderPaths.js";
|
||||
import { readStableFile } from "./ReferenceSourceReaderFile.js";
|
||||
import {
|
||||
isAborted,
|
||||
sameFile,
|
||||
validateDirectory,
|
||||
bigLstat,
|
||||
} from "./ReferenceSourceReaderValidate.js";
|
||||
import {
|
||||
type BigStats,
|
||||
type PendingDirectory,
|
||||
type ReferenceSourceEntry,
|
||||
type ReferenceSourceResult,
|
||||
type TraversalState,
|
||||
} from "./ReferenceSourceReaderTypes.js";
|
||||
|
||||
export const traverseDirectory = async (
|
||||
state: TraversalState,
|
||||
current: PendingDirectory,
|
||||
): Promise<ReferenceSourceResult<undefined>> => {
|
||||
const before = await validateDirectory(
|
||||
state.root,
|
||||
state.rootIdentity,
|
||||
current.path,
|
||||
);
|
||||
if (!before.ok) {
|
||||
state.entries.push(
|
||||
entryFailure(
|
||||
pathFromRoot(state.root, current.path),
|
||||
"directory",
|
||||
before.code,
|
||||
before.message,
|
||||
),
|
||||
);
|
||||
return { ok: true, value: undefined };
|
||||
}
|
||||
const names = await readDirectoryNames(current.path);
|
||||
if (!names.ok) {
|
||||
state.entries.push(
|
||||
entryFailure(
|
||||
pathFromRoot(state.root, current.path),
|
||||
"directory",
|
||||
"io",
|
||||
names.message,
|
||||
),
|
||||
);
|
||||
return { ok: true, value: undefined };
|
||||
}
|
||||
if (isAborted(state.signal))
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
tag: "reference-source-reader",
|
||||
code: "cancelled",
|
||||
message: "Reference source traversal cancelled",
|
||||
},
|
||||
};
|
||||
const after = await validateDirectory(
|
||||
state.root,
|
||||
state.rootIdentity,
|
||||
current.path,
|
||||
);
|
||||
if (!after.ok || !sameFile(before.stats, after.stats)) {
|
||||
state.entries.push(
|
||||
entryFailure(
|
||||
pathFromRoot(state.root, current.path),
|
||||
"directory",
|
||||
"changed",
|
||||
"Directory changed while it was read",
|
||||
),
|
||||
);
|
||||
return { ok: true, value: undefined };
|
||||
}
|
||||
const directories: PendingDirectory[] = [];
|
||||
for (const name of names.value) {
|
||||
const result = await processEntry(state, current, name, directories);
|
||||
if (!result.ok) return result;
|
||||
if (state.stopped) break;
|
||||
}
|
||||
directories.reverse();
|
||||
state.pending.push(...directories);
|
||||
return { ok: true, value: undefined };
|
||||
};
|
||||
|
||||
const readDirectoryNames = async (
|
||||
path: string,
|
||||
): Promise<
|
||||
| { readonly ok: true; readonly value: string[] }
|
||||
| { readonly ok: false; readonly message: string }
|
||||
> => {
|
||||
try {
|
||||
return { ok: true, value: (await readdir(path)).sort(compareNames) };
|
||||
} catch {
|
||||
return { ok: false, message: "Directory could not be read" };
|
||||
}
|
||||
};
|
||||
|
||||
const readMetadata = async (
|
||||
path: string,
|
||||
): Promise<
|
||||
| { readonly ok: true; readonly value: BigStats }
|
||||
| { readonly ok: false; readonly message: string }
|
||||
> => {
|
||||
try {
|
||||
return { ok: true, value: await bigLstat(path) };
|
||||
} catch {
|
||||
return { ok: false, message: "Entry metadata could not be read" };
|
||||
}
|
||||
};
|
||||
|
||||
const processEntry = async (
|
||||
state: TraversalState,
|
||||
current: PendingDirectory,
|
||||
name: string,
|
||||
directories: PendingDirectory[],
|
||||
): Promise<ReferenceSourceResult<undefined>> => {
|
||||
if (isAborted(state.signal))
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
tag: "reference-source-reader",
|
||||
code: "cancelled",
|
||||
message: "Reference source traversal cancelled",
|
||||
},
|
||||
};
|
||||
const absolute = join(current.path, name);
|
||||
const path = pathFromRoot(state.root, absolute);
|
||||
const excluded = applyExclusion(state.shouldExclude, path);
|
||||
if (!excluded.ok)
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
tag: "reference-source-reader",
|
||||
code: "io",
|
||||
message: "Reference source exclusion check failed",
|
||||
},
|
||||
};
|
||||
if (excluded.value) return { ok: true, value: undefined };
|
||||
if (!reserveEntry(state)) return { ok: true, value: undefined };
|
||||
if (Buffer.byteLength(path) > state.limits.maxPathBytes) {
|
||||
state.entries.push(
|
||||
entryFailure(path, "unknown", "limit", "Path exceeds maxPathBytes"),
|
||||
);
|
||||
state.truncated = true;
|
||||
return { ok: true, value: undefined };
|
||||
}
|
||||
const metadata = await readMetadata(absolute);
|
||||
if (!metadata.ok) {
|
||||
state.entries.push(entryFailure(path, "unknown", "io", metadata.message));
|
||||
return { ok: true, value: undefined };
|
||||
}
|
||||
if (isAborted(state.signal))
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
tag: "reference-source-reader",
|
||||
code: "cancelled",
|
||||
message: "Reference source traversal cancelled",
|
||||
},
|
||||
};
|
||||
if (metadata.value.isSymbolicLink())
|
||||
state.entries.push(await describeSymlink(state.root, absolute, path));
|
||||
else if (metadata.value.isDirectory()) {
|
||||
if (current.depth < state.limits.maxDepth) {
|
||||
state.entries.push({ status: "read", kind: "directory", path });
|
||||
directories.push({ path: absolute, depth: current.depth + 1 });
|
||||
} else {
|
||||
state.entries.push(
|
||||
entryFailure(path, "directory", "limit", "Directory exceeds maxDepth"),
|
||||
);
|
||||
state.truncated = true;
|
||||
}
|
||||
} else if (!metadata.value.isFile())
|
||||
state.entries.push(
|
||||
entryFailure(
|
||||
path,
|
||||
"other",
|
||||
"unsupported",
|
||||
"Entry is not a regular file",
|
||||
safeSize(metadata.value.size),
|
||||
),
|
||||
);
|
||||
else await processFileEntry(state, absolute, path, metadata.value);
|
||||
return { ok: true, value: undefined };
|
||||
};
|
||||
|
||||
const processFileEntry = async (
|
||||
state: TraversalState,
|
||||
absolute: string,
|
||||
path: string,
|
||||
metadata: BigStats,
|
||||
): Promise<void> => {
|
||||
const remaining = state.limits.maxBytes - state.bytesRead;
|
||||
if (metadata.size > BigInt(remaining)) {
|
||||
state.entries.push(
|
||||
entryFailure(
|
||||
path,
|
||||
"file",
|
||||
"limit",
|
||||
"File exceeds remaining maxBytes",
|
||||
safeSize(metadata.size),
|
||||
),
|
||||
);
|
||||
state.truncated = true;
|
||||
return;
|
||||
}
|
||||
const result = await readStableFile({
|
||||
root: state.root,
|
||||
rootIdentity: state.rootIdentity,
|
||||
absolute,
|
||||
path,
|
||||
expected: metadata,
|
||||
remaining,
|
||||
...(state.signal === undefined ? {} : { signal: state.signal }),
|
||||
});
|
||||
if (result.status === "read" && result.kind === "file")
|
||||
state.bytesRead += result.bytes.byteLength;
|
||||
else if (result.status === "failed" && result.code === "limit")
|
||||
state.truncated = true;
|
||||
state.entries.push(result);
|
||||
};
|
||||
|
||||
const describeSymlink = async (
|
||||
root: string,
|
||||
absolute: string,
|
||||
path: string,
|
||||
): Promise<ReferenceSourceEntry> => {
|
||||
try {
|
||||
const rawTarget = await readlink(absolute);
|
||||
const lexicalTarget = resolve(dirname(absolute), rawTarget);
|
||||
if (!withinRoot(root, lexicalTarget))
|
||||
return {
|
||||
status: "read",
|
||||
kind: "symlink",
|
||||
path,
|
||||
target: "<outside-root>",
|
||||
targetState: "external",
|
||||
};
|
||||
try {
|
||||
const canonicalTarget = await realpath(lexicalTarget);
|
||||
return withinRoot(root, canonicalTarget)
|
||||
? {
|
||||
status: "read",
|
||||
kind: "symlink",
|
||||
path,
|
||||
target: pathFromRoot(root, canonicalTarget),
|
||||
targetState: "internal",
|
||||
}
|
||||
: {
|
||||
status: "read",
|
||||
kind: "symlink",
|
||||
path,
|
||||
target: "<outside-root>",
|
||||
targetState: "external",
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
status: "read",
|
||||
kind: "symlink",
|
||||
path,
|
||||
target: pathFromRoot(root, lexicalTarget),
|
||||
targetState: "missing",
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
return entryFailure(
|
||||
path,
|
||||
"symlink",
|
||||
"io",
|
||||
"Symbolic link target could not be read",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const applyExclusion = (
|
||||
shouldExclude: ((path: string) => boolean) | undefined,
|
||||
path: string,
|
||||
): { readonly ok: true; readonly value: boolean } | { readonly ok: false } => {
|
||||
try {
|
||||
return { ok: true, value: shouldExclude?.(path) === true };
|
||||
} catch {
|
||||
return { ok: false };
|
||||
}
|
||||
};
|
||||
|
||||
const reserveEntry = (state: TraversalState): boolean => {
|
||||
if (state.filesSeen < state.limits.maxEntries) {
|
||||
state.filesSeen += 1;
|
||||
return true;
|
||||
}
|
||||
state.truncated = true;
|
||||
state.stopped = true;
|
||||
return false;
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
type ReferenceSourceEntry,
|
||||
type ReferenceSourceFailureCode,
|
||||
type ReferenceSourceReaderError,
|
||||
} from "./ReferenceSourceReaderTypes.js";
|
||||
|
||||
export const failure = (
|
||||
code: ReferenceSourceReaderError["code"],
|
||||
message: string,
|
||||
): ReferenceSourceReaderError => ({
|
||||
tag: "reference-source-reader",
|
||||
code,
|
||||
message,
|
||||
});
|
||||
|
||||
export const cancelled = (): ReferenceSourceReaderError =>
|
||||
failure("cancelled", "Reference source traversal cancelled");
|
||||
|
||||
export const safeSize = (size: bigint): number | undefined => {
|
||||
const value = Number(size);
|
||||
return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
||||
};
|
||||
|
||||
export const entryFailure = (
|
||||
...[path, kind, code, message, size]: readonly [
|
||||
string,
|
||||
Extract<ReferenceSourceEntry, { status: "failed" }>["kind"],
|
||||
ReferenceSourceFailureCode,
|
||||
string,
|
||||
size?: number,
|
||||
]
|
||||
): ReferenceSourceEntry => ({
|
||||
status: "failed",
|
||||
kind,
|
||||
path,
|
||||
code,
|
||||
message,
|
||||
...(size === undefined ? {} : { size }),
|
||||
});
|
||||
@@ -0,0 +1,246 @@
|
||||
import { constants } from "node:fs";
|
||||
import { open, type FileHandle } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import { entryFailure, safeSize } from "./ReferenceSourceReaderErrors.js";
|
||||
import {
|
||||
isAborted,
|
||||
sameFile,
|
||||
validateDirectory,
|
||||
} from "./ReferenceSourceReaderValidate.js";
|
||||
import {
|
||||
type BigStats,
|
||||
type ReferenceSourceEntry,
|
||||
type StableFileRequest,
|
||||
} from "./ReferenceSourceReaderTypes.js";
|
||||
|
||||
const READ_CHUNK_BYTES = 64 * 1024;
|
||||
|
||||
type PreparedFileRead =
|
||||
| {
|
||||
readonly status: "ready";
|
||||
readonly handle: FileHandle;
|
||||
readonly before: BigStats;
|
||||
readonly parentBefore: { readonly ok: true; readonly stats: BigStats };
|
||||
}
|
||||
| { readonly status: "failed"; readonly entry: ReferenceSourceEntry };
|
||||
|
||||
type FileContentsRead =
|
||||
| { readonly status: "ok"; readonly chunks: Buffer[]; readonly total: number }
|
||||
| { readonly status: "failed"; readonly entry: ReferenceSourceEntry };
|
||||
|
||||
type FinalizeFileReadRequest = {
|
||||
readonly root: string;
|
||||
readonly rootIdentity: BigStats;
|
||||
readonly absolute: string;
|
||||
readonly path: string;
|
||||
readonly handle: FileHandle;
|
||||
readonly before: BigStats;
|
||||
readonly parentBefore: { readonly ok: true; readonly stats: BigStats };
|
||||
readonly chunks: Buffer[];
|
||||
readonly total: number;
|
||||
};
|
||||
|
||||
const prepareFileRead = async (
|
||||
request: StableFileRequest,
|
||||
): Promise<PreparedFileRead> => {
|
||||
const { root, rootIdentity, absolute, path, expected, signal } = request;
|
||||
const parentBefore = await validateDirectory(
|
||||
root,
|
||||
rootIdentity,
|
||||
dirname(absolute),
|
||||
);
|
||||
if (!parentBefore.ok)
|
||||
return {
|
||||
status: "failed",
|
||||
entry: entryFailure(
|
||||
path,
|
||||
"file",
|
||||
parentBefore.code,
|
||||
parentBefore.message,
|
||||
safeSize(expected.size),
|
||||
),
|
||||
};
|
||||
const handle = await open(
|
||||
absolute,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW,
|
||||
);
|
||||
if (isAborted(signal)) {
|
||||
await handle.close().catch(() => undefined);
|
||||
return {
|
||||
status: "failed",
|
||||
entry: entryFailure(
|
||||
path,
|
||||
"file",
|
||||
"cancelled",
|
||||
"File read cancelled",
|
||||
safeSize(expected.size),
|
||||
),
|
||||
};
|
||||
}
|
||||
const before = await handle.stat({ bigint: true });
|
||||
if (!sameFile(expected, before)) {
|
||||
await handle.close().catch(() => undefined);
|
||||
return {
|
||||
status: "failed",
|
||||
entry: entryFailure(
|
||||
path,
|
||||
"file",
|
||||
"changed",
|
||||
"File changed before it was read",
|
||||
safeSize(before.size),
|
||||
),
|
||||
};
|
||||
}
|
||||
return { status: "ready", handle, before, parentBefore };
|
||||
};
|
||||
|
||||
const readFileContents = async (request: {
|
||||
readonly handle: FileHandle;
|
||||
readonly path: string;
|
||||
readonly remaining: number;
|
||||
readonly signal?: AbortSignal;
|
||||
}): Promise<FileContentsRead> => {
|
||||
const { handle, path, remaining, signal } = request;
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
if (isAborted(signal))
|
||||
return {
|
||||
status: "failed",
|
||||
entry: entryFailure(
|
||||
path,
|
||||
"file",
|
||||
"cancelled",
|
||||
"File read cancelled",
|
||||
total,
|
||||
),
|
||||
};
|
||||
const capacity = Math.min(READ_CHUNK_BYTES, remaining + 1 - total);
|
||||
if (capacity <= 0)
|
||||
return {
|
||||
status: "failed",
|
||||
entry: entryFailure(
|
||||
path,
|
||||
"file",
|
||||
"limit",
|
||||
"File exceeds remaining maxBytes",
|
||||
total,
|
||||
),
|
||||
};
|
||||
const chunk = Buffer.allocUnsafe(capacity);
|
||||
const read = await handle.read(chunk, 0, capacity, null);
|
||||
if (isAborted(signal))
|
||||
return {
|
||||
status: "failed",
|
||||
entry: entryFailure(
|
||||
path,
|
||||
"file",
|
||||
"cancelled",
|
||||
"File read cancelled",
|
||||
total,
|
||||
),
|
||||
};
|
||||
if (read.bytesRead === 0) break;
|
||||
total += read.bytesRead;
|
||||
if (total > remaining)
|
||||
return {
|
||||
status: "failed",
|
||||
entry: entryFailure(
|
||||
path,
|
||||
"file",
|
||||
"limit",
|
||||
"File exceeds remaining maxBytes",
|
||||
total,
|
||||
),
|
||||
};
|
||||
chunks.push(chunk.subarray(0, read.bytesRead));
|
||||
}
|
||||
return { status: "ok", chunks, total };
|
||||
};
|
||||
|
||||
const finalizeFileRead = async (
|
||||
request: FinalizeFileReadRequest,
|
||||
): Promise<ReferenceSourceEntry> => {
|
||||
const {
|
||||
root,
|
||||
rootIdentity,
|
||||
absolute,
|
||||
path,
|
||||
handle,
|
||||
before,
|
||||
parentBefore,
|
||||
chunks,
|
||||
total,
|
||||
} = request;
|
||||
const after = await handle.stat({ bigint: true });
|
||||
const parentAfter = await validateDirectory(
|
||||
root,
|
||||
rootIdentity,
|
||||
dirname(absolute),
|
||||
);
|
||||
if (!parentAfter.ok || !sameFile(parentBefore.stats, parentAfter.stats))
|
||||
return entryFailure(
|
||||
path,
|
||||
"file",
|
||||
"changed",
|
||||
"Parent directory changed while file was read",
|
||||
total,
|
||||
);
|
||||
if (!sameFile(before, after) || BigInt(total) !== after.size)
|
||||
return entryFailure(
|
||||
path,
|
||||
"file",
|
||||
"changed",
|
||||
"File changed while it was read",
|
||||
total,
|
||||
);
|
||||
return {
|
||||
status: "read",
|
||||
kind: "file",
|
||||
path,
|
||||
bytes: Buffer.concat(chunks, total),
|
||||
size: total,
|
||||
};
|
||||
};
|
||||
|
||||
export const readStableFile = async (
|
||||
request: StableFileRequest,
|
||||
): Promise<ReferenceSourceEntry> => {
|
||||
const { root, rootIdentity, absolute, path, expected, remaining, signal } =
|
||||
request;
|
||||
let handle: FileHandle | undefined;
|
||||
try {
|
||||
const prepared = await prepareFileRead(request);
|
||||
if (prepared.status === "failed") return prepared.entry;
|
||||
handle = prepared.handle;
|
||||
const contents = await readFileContents({
|
||||
handle,
|
||||
path,
|
||||
remaining,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
if (contents.status === "failed") return contents.entry;
|
||||
return await finalizeFileRead({
|
||||
root,
|
||||
rootIdentity,
|
||||
absolute,
|
||||
path,
|
||||
handle,
|
||||
before: prepared.before,
|
||||
parentBefore: prepared.parentBefore,
|
||||
chunks: contents.chunks,
|
||||
total: contents.total,
|
||||
});
|
||||
} catch {
|
||||
return entryFailure(
|
||||
path,
|
||||
"file",
|
||||
isAborted(signal) ? "cancelled" : "io",
|
||||
"File could not be read safely",
|
||||
safeSize(expected.size),
|
||||
);
|
||||
} finally {
|
||||
await handle?.close().catch(() => undefined);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { isAbsolute, relative, sep } from "node:path";
|
||||
|
||||
export const withinRoot = (root: string, path: string): boolean => {
|
||||
const value = relative(root, path);
|
||||
return (
|
||||
value === "" ||
|
||||
(value !== ".." && !value.startsWith(`..${sep}`) && !isAbsolute(value))
|
||||
);
|
||||
};
|
||||
|
||||
export const pathFromRoot = (root: string, path: string): string => {
|
||||
const value = relative(root, path);
|
||||
return withinRoot(root, path)
|
||||
? value.split(sep).join("/") || "."
|
||||
: "<outside-root>";
|
||||
};
|
||||
|
||||
export const compareNames = (left: string, right: string): number => {
|
||||
const leftPoints = [...left].map((value) => value.codePointAt(0) ?? 0);
|
||||
const rightPoints = [...right].map((value) => value.codePointAt(0) ?? 0);
|
||||
const length = Math.min(leftPoints.length, rightPoints.length);
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);
|
||||
if (difference !== 0) return difference;
|
||||
}
|
||||
return leftPoints.length - rightPoints.length;
|
||||
};
|
||||
@@ -0,0 +1,105 @@
|
||||
import { type BigIntStats } from "node:fs";
|
||||
|
||||
import { type Result } from "../domain/result.js";
|
||||
|
||||
export interface ReferenceSourceLimits {
|
||||
readonly maxBytes: number;
|
||||
readonly maxEntries: number;
|
||||
readonly maxDepth: number;
|
||||
readonly maxPathBytes: number;
|
||||
}
|
||||
|
||||
export interface ReferenceSourceReaderOptions {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly shouldExclude?: (path: string) => boolean;
|
||||
}
|
||||
|
||||
export type ReferenceSourceFailureCode =
|
||||
| "cancelled"
|
||||
| "changed"
|
||||
| "io"
|
||||
| "limit"
|
||||
| "symlink"
|
||||
| "unsupported";
|
||||
|
||||
export type ReferenceSourceEntry =
|
||||
| {
|
||||
readonly status: "read";
|
||||
readonly kind: "file";
|
||||
readonly path: string;
|
||||
readonly bytes: Uint8Array;
|
||||
readonly size: number;
|
||||
}
|
||||
| {
|
||||
readonly status: "read";
|
||||
readonly kind: "directory";
|
||||
readonly path: string;
|
||||
}
|
||||
| {
|
||||
readonly status: "read";
|
||||
readonly kind: "symlink";
|
||||
readonly path: string;
|
||||
readonly target: string;
|
||||
readonly targetState: "internal" | "external" | "missing";
|
||||
}
|
||||
| {
|
||||
readonly status: "failed";
|
||||
readonly kind: "file" | "directory" | "symlink" | "other" | "unknown";
|
||||
readonly path: string;
|
||||
readonly code: ReferenceSourceFailureCode;
|
||||
readonly message: string;
|
||||
readonly size?: number;
|
||||
};
|
||||
|
||||
export interface ReferenceSourceRead {
|
||||
readonly root: string;
|
||||
readonly entries: readonly ReferenceSourceEntry[];
|
||||
readonly bytesRead: number;
|
||||
readonly truncated: boolean;
|
||||
/** Node exposes no portable openat traversal; pathname identity is checked around each operation. */
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
export interface ReferenceSourceReaderError {
|
||||
readonly tag: "reference-source-reader";
|
||||
readonly code:
|
||||
| "cancelled"
|
||||
| "invalid-limits"
|
||||
| "invalid-root"
|
||||
| "io"
|
||||
| "unsupported";
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
export type BigStats = BigIntStats;
|
||||
|
||||
export type PendingDirectory = {
|
||||
readonly path: string;
|
||||
readonly depth: number;
|
||||
};
|
||||
|
||||
export type TraversalState = {
|
||||
readonly root: string;
|
||||
readonly rootIdentity: BigStats;
|
||||
readonly limits: ReferenceSourceLimits;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly shouldExclude?: (path: string) => boolean;
|
||||
readonly entries: ReferenceSourceEntry[];
|
||||
readonly pending: PendingDirectory[];
|
||||
bytesRead: number;
|
||||
filesSeen: number;
|
||||
truncated: boolean;
|
||||
stopped: boolean;
|
||||
};
|
||||
|
||||
export type StableFileRequest = {
|
||||
readonly root: string;
|
||||
readonly rootIdentity: BigStats;
|
||||
readonly absolute: string;
|
||||
readonly path: string;
|
||||
readonly expected: BigStats;
|
||||
readonly remaining: number;
|
||||
readonly signal?: AbortSignal;
|
||||
};
|
||||
|
||||
export type ReferenceSourceResult<T> = Result<T, ReferenceSourceReaderError>;
|
||||
@@ -0,0 +1,118 @@
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, realpath } from "node:fs/promises";
|
||||
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { cancelled, failure } from "./ReferenceSourceReaderErrors.js";
|
||||
import { withinRoot } from "./ReferenceSourceReaderPaths.js";
|
||||
import {
|
||||
type BigStats,
|
||||
type ReferenceSourceFailureCode,
|
||||
type ReferenceSourceLimits,
|
||||
type ReferenceSourceResult,
|
||||
} from "./ReferenceSourceReaderTypes.js";
|
||||
|
||||
export const bigLstat = (path: string): Promise<BigStats> =>
|
||||
lstat(path, { bigint: true });
|
||||
|
||||
export const sameFile = (left: BigStats, right: BigStats): boolean =>
|
||||
left.dev === right.dev &&
|
||||
left.ino === right.ino &&
|
||||
left.size === right.size &&
|
||||
left.mtimeNs === right.mtimeNs &&
|
||||
left.ctimeNs === right.ctimeNs;
|
||||
|
||||
export const isAborted = (signal?: AbortSignal): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
const validLimits = (limits: ReferenceSourceLimits): boolean =>
|
||||
Object.values(limits).every(
|
||||
(value) => Number.isSafeInteger(value) && value > 0,
|
||||
);
|
||||
|
||||
export const noFollowOpenSupported = (): boolean =>
|
||||
Number.isSafeInteger(constants.O_NOFOLLOW) && constants.O_NOFOLLOW !== 0;
|
||||
|
||||
export const validateDirectory = async (
|
||||
root: string,
|
||||
rootIdentity: BigStats,
|
||||
path: string,
|
||||
): Promise<
|
||||
| { readonly ok: true; readonly stats: BigStats }
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly code: ReferenceSourceFailureCode;
|
||||
readonly message: string;
|
||||
}
|
||||
> => {
|
||||
try {
|
||||
const rootNow = await bigLstat(root);
|
||||
if (!sameFile(rootIdentity, rootNow))
|
||||
return { ok: false, code: "changed", message: "Reference root changed" };
|
||||
const stats = await bigLstat(path);
|
||||
if (stats.isSymbolicLink())
|
||||
return {
|
||||
ok: false,
|
||||
code: "symlink",
|
||||
message: "Symbolic links are not followed",
|
||||
};
|
||||
if (!stats.isDirectory())
|
||||
return {
|
||||
ok: false,
|
||||
code: "changed",
|
||||
message: "Directory identity changed",
|
||||
};
|
||||
const canonical = await realpath(path);
|
||||
if (canonical !== path || !withinRoot(root, canonical))
|
||||
return {
|
||||
ok: false,
|
||||
code: "changed",
|
||||
message: "Directory escaped the reference root",
|
||||
};
|
||||
return { ok: true, stats };
|
||||
} catch {
|
||||
return {
|
||||
ok: false,
|
||||
code: "io",
|
||||
message: "Directory identity could not be verified",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export const prepareRoot = async (
|
||||
root: string,
|
||||
limits: ReferenceSourceLimits,
|
||||
signal?: AbortSignal,
|
||||
): Promise<
|
||||
ReferenceSourceResult<{
|
||||
readonly canonicalRoot: string;
|
||||
readonly rootIdentity: BigStats;
|
||||
}>
|
||||
> => {
|
||||
if (!validLimits(limits))
|
||||
return err(
|
||||
failure("invalid-limits", "Reader limits must be positive integers"),
|
||||
);
|
||||
if (isAborted(signal)) return err(cancelled());
|
||||
try {
|
||||
const metadata = await bigLstat(root);
|
||||
if (metadata.isSymbolicLink() || !metadata.isDirectory())
|
||||
return err(
|
||||
failure("invalid-root", "Reference source root must be a directory"),
|
||||
);
|
||||
const canonicalRoot = await realpath(root);
|
||||
if (isAborted(signal)) return err(cancelled());
|
||||
const canonicalMetadata = await bigLstat(canonicalRoot);
|
||||
if (!sameFile(metadata, canonicalMetadata))
|
||||
return err(
|
||||
failure(
|
||||
"invalid-root",
|
||||
"Reference source root changed during resolution",
|
||||
),
|
||||
);
|
||||
return ok({ canonicalRoot, rootIdentity: canonicalMetadata });
|
||||
} catch {
|
||||
return err(
|
||||
failure("invalid-root", "Reference source root could not be resolved"),
|
||||
);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user