refactor(files): use caller paths for local evidence files

This commit is contained in:
morluto
2026-09-29 14:53:20 +08:00
parent 3f547eafa4
commit c34efca4cd
51 changed files with 289 additions and 936 deletions
+5 -8
View File
@@ -3,19 +3,17 @@ import {
serializeAnalysisSnapshot,
type AnalysisSnapshot,
} from "../domain/analysisSnapshot.js";
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
import { EvidenceFileError, EvidenceIntegrityError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import { readBoundedJson, writeBoundedText } from "./BoundedJsonFiles.js";
import { readJsonFile, writeTextFile } from "./JsonFiles.js";
type SnapshotFailure = EvidenceFileError | EvidenceIntegrityError;
/** Read and validate a bounded analysis snapshot inside an approved root. */
/** Read and validate an analysis snapshot from the caller's path. */
export const readAnalysisSnapshot = async (
path: string,
policy: EvidenceFilePolicy,
): Promise<Result<AnalysisSnapshot, SnapshotFailure>> => {
const loaded = await readBoundedJson(path, policy);
const loaded = await readJsonFile(path);
if (!loaded.ok) return loaded;
try {
return ok(parseAnalysisSnapshot(loaded.value));
@@ -26,12 +24,11 @@ export const readAnalysisSnapshot = async (
}
};
/** Atomically write a deterministic analysis snapshot inside an approved root. */
/** Atomically write a deterministic analysis snapshot to the caller's path. */
export const writeAnalysisSnapshot = async (
snapshot: AnalysisSnapshot,
path: string,
overwrite: boolean,
policy: EvidenceFilePolicy,
): Promise<
Result<{ readonly path: string; readonly bytes: number }, SnapshotFailure>
> => {
@@ -43,7 +40,7 @@ export const writeAnalysisSnapshot = async (
new EvidenceIntegrityError(snapshotValidationMessage(cause), { cause }),
);
}
return writeBoundedText(encoded, path, overwrite, policy);
return writeTextFile(encoded, path, overwrite);
};
const snapshotValidationMessage = (cause: unknown): string =>
+4 -46
View File
@@ -31,10 +31,6 @@ import { err, ok, type Result } from "../domain/result.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import { loadConfiguredPermissionAuthority } from "./PermissionConfiguration.js";
import type { PermissionAuthority } from "./PermissionAuthority.js";
import {
authorizeFileReadWithDeferredWrite,
type DeferredFileWriteAuthorization,
} from "./DeferredFileAuthorization.js";
import {
REA_WORKFLOW_PROVIDER,
workflowAnalysisProfile,
@@ -155,31 +151,6 @@ const permissionAuthorityFor = (
? loadConfiguredPermissionAuthority(config)
: Promise.resolve(ok(supplied));
const authorizeSnapshotAccess = async (
authority: PermissionAuthority,
tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool,
snapshotPath: string | undefined,
): Promise<
Result<DeferredFileWriteAuthorization | undefined, AnalysisError>
> =>
snapshotPath === undefined
? ok(undefined)
: authorizeFileReadWithDeferredWrite(authority, {
path: snapshotPath,
readCapability: "snapshot_read",
writeCapability: "snapshot_write",
operation: tool,
});
const authorizeDeferredWrite = (
authorization: DeferredFileWriteAuthorization | undefined,
): Promise<Result<null, AnalysisError>> =>
authorization?.authorizeWrite() ?? Promise.resolve(ok(null));
const authorizeAnalysisRun = async (input: {
readonly config: AppConfig;
readonly suppliedAuthority: PermissionAuthority | undefined;
@@ -189,10 +160,7 @@ const authorizeAnalysisRun = async (input: {
| ManagedToolName
| DirectAnalysisTool;
readonly arguments: Readonly<Record<string, JsonValue>>;
readonly snapshotPath: string | undefined;
}): Promise<
Result<DeferredFileWriteAuthorization | undefined, AnalysisError>
> => {
}): Promise<Result<null, AnalysisError>> => {
const authority = await permissionAuthorityFor(
input.config,
input.suppliedAuthority,
@@ -204,11 +172,7 @@ const authorizeAnalysisRun = async (input: {
input.arguments,
);
if (!operation.ok) return operation;
return authorizeSnapshotAccess(
authority.value,
input.tool,
input.snapshotPath,
);
return ok(null);
};
const runAnalysis = async (
@@ -235,7 +199,6 @@ const runAnalysis = async (
suppliedAuthority: options.permissionAuthority,
tool,
arguments: arguments_,
snapshotPath,
});
if (!authorization.ok) return cliError(authorization.error);
const session = createBinarySession(config.value, logger);
@@ -243,7 +206,6 @@ const runAnalysis = async (
const prepared = await prepareSnapshot({
path,
snapshotPath,
policy: config.value.analysisSnapshotFilePolicy,
});
if (!prepared.ok) return cliError(prepared.error);
const { snapshot } = prepared.value;
@@ -272,8 +234,6 @@ const runAnalysis = async (
});
if (cached !== undefined) return cached;
}
const writable = await authorizeDeferredWrite(authorization.value);
if (!writable.ok) return cliError(writable.error);
const { output, evidence } = await executeAnalysisTool({
session,
openedTarget: opened.value,
@@ -290,7 +250,6 @@ const runAnalysis = async (
snapshot.value,
snapshotPath,
true,
config.value.analysisSnapshotFilePolicy,
);
if (!written.ok) return cliError(written.error);
}
@@ -386,14 +345,13 @@ const withProcessCancellation = async <Value>(
const prepareSnapshot = async (options: {
readonly path: string;
readonly snapshotPath: string | undefined;
readonly policy: Parameters<typeof readAnalysisSnapshot>[1];
}): Promise<
Result<{ readonly snapshot?: AnalysisSnapshot }, AnalysisError>
> => {
const { path, snapshotPath, policy } = options;
const { path, snapshotPath } = options;
if (snapshotPath === undefined || !(await fileExists(snapshotPath)))
return ok({});
const loaded = await readAnalysisSnapshot(snapshotPath, policy);
const loaded = await readAnalysisSnapshot(snapshotPath);
if (!loaded.ok) return loaded;
const target = await parseBinaryTarget(path);
if (!target.ok) return target;
+6 -12
View File
@@ -2,10 +2,7 @@ import {
EvidenceIntegrityError,
type AnalysisError,
} from "../domain/errors.js";
import type {
EvidenceFilePolicy,
EvidenceBundle,
} from "../domain/evidenceBundle.js";
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -19,9 +16,8 @@ import {
/** Validate and merge one bundle using the session Evidence ledger. */
export const importEvidenceBundleCommand = async (
path: string,
policy: EvidenceFilePolicy,
): Promise<Result<JsonValue, AnalysisError>> => {
const loaded = await readEvidenceBundle(path, policy);
const loaded = await readEvidenceBundle(path);
if (!loaded.ok) return loaded;
const ledger = createLedger();
const imported = ledger.import(loaded.value);
@@ -39,13 +35,12 @@ export const exportEvidenceBundleCommand = async (
sourcePath: string,
outputPath: string,
overwrite: boolean,
policy: EvidenceFilePolicy,
): Promise<Result<JsonValue, AnalysisError>> => {
const loaded = await readEvidenceBundle(sourcePath, policy);
const loaded = await readEvidenceBundle(sourcePath);
if (!loaded.ok) return loaded;
return projectWrite(
loaded.value,
await writeEvidenceBundle(loaded.value, outputPath, overwrite, policy),
await writeEvidenceBundle(loaded.value, outputPath, overwrite),
);
};
@@ -53,11 +48,10 @@ export const exportEvidenceBundleCommand = async (
export const compareEvidenceBundlesCommand = async (input: {
readonly leftPath: string;
readonly rightPath: string;
readonly policy: EvidenceFilePolicy;
}): Promise<Result<JsonValue, AnalysisError>> => {
const [left, right] = await Promise.all([
readEvidenceBundle(input.leftPath, input.policy),
readEvidenceBundle(input.rightPath, input.policy),
readEvidenceBundle(input.leftPath),
readEvidenceBundle(input.rightPath),
]);
if (!left.ok) return left;
if (!right.ok) return right;
+5 -12
View File
@@ -2,24 +2,20 @@ import {
parseEvidenceBundle,
serializeEvidenceBundle,
type EvidenceBundle,
type EvidenceFilePolicy,
} from "../domain/evidenceBundle.js";
import { EvidenceFileError, EvidenceIntegrityError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import { parseProcessCapture } from "../domain/processCapture.js";
import { readBoundedJson, writeBoundedText } from "./BoundedJsonFiles.js";
import { readJsonFile, writeTextFile } from "./JsonFiles.js";
type EvidenceReadFailure = EvidenceFileError | EvidenceIntegrityError;
type EvidenceWriteFailure = EvidenceFileError | EvidenceIntegrityError;
/** Read and validate a bounded evidence bundle inside an approved root. */
/** Read and validate an evidence bundle at the caller-supplied path. */
export const readEvidenceBundle = async (
path: string,
policy: EvidenceFilePolicy,
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> => {
if (policy.roots.length === 0)
return err(new EvidenceFileError("read", "disabled"));
const loaded = await readBoundedJson(path, policy);
const loaded = await readJsonFile(path);
if (!loaded.ok) return loaded;
try {
const bundle = parseEvidenceBundle(loaded.value);
@@ -37,20 +33,17 @@ export const readEvidenceBundle = async (
}
};
/** Atomically write deterministic evidence JSON inside an approved root. */
/** Atomically write deterministic evidence JSON at the caller-supplied path. */
export const writeEvidenceBundle = async (
bundle: EvidenceBundle,
path: string,
overwrite: boolean,
policy: EvidenceFilePolicy,
): Promise<
Result<
{ readonly path: string; readonly bytes: number },
EvidenceWriteFailure
>
> => {
if (policy.roots.length === 0)
return err(new EvidenceFileError("write", "disabled"));
let encoded: string;
try {
encoded = serializeEvidenceBundle(bundle);
@@ -61,5 +54,5 @@ export const writeEvidenceBundle = async (
}),
);
}
return writeBoundedText(encoded, path, overwrite, policy);
return writeTextFile(encoded, path, overwrite);
};
@@ -1,74 +1,45 @@
import { link, lstat, mkdtemp, open, realpath, rm } from "node:fs/promises";
import { link, lstat, mkdtemp, readFile, realpath, rm } from "node:fs/promises";
import { basename, dirname, resolve } from "node:path";
import writeFileAtomic from "write-file-atomic";
import { isPathWithinRoot } from "../domain/localPath.js";
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
import { EvidenceFileError } from "../domain/errors.js";
import { isJsonWithinLimits } from "../domain/jsonLimits.js";
import { err, ok, type Result } from "../domain/result.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
/** Read bounded JSON data from a regular file beneath an approved root. */
export const readBoundedJson = async (
/** Read JSON data from a regular file at the caller-supplied path. */
export const readJsonFile = async (
path: string,
policy: EvidenceFilePolicy,
): Promise<Result<unknown, EvidenceFileError>> => {
if (policy.roots.length === 0)
return err(new EvidenceFileError("read", "disabled"));
try {
const canonicalPath = await realpath(resolve(path));
if (!(await isApproved(canonicalPath, policy.roots)))
return err(new EvidenceFileError("read", "outside-root"));
const stats = await lstat(canonicalPath);
if (!stats.isFile()) return err(new EvidenceFileError("read", "not-file"));
if (stats.size > policy.maxBytes)
return err(new EvidenceFileError("read", "too-large"));
const handle = await open(canonicalPath, "r");
let encoded: Buffer | undefined;
try {
encoded = await readBoundedFileBytes(handle, policy.maxBytes);
} finally {
await handle.close();
}
if (encoded === undefined)
return err(new EvidenceFileError("read", "too-large"));
const encoded = await readFile(canonicalPath);
let decoded: unknown;
try {
decoded = JSON.parse(encoded.toString("utf8"));
} catch (cause: unknown) {
return err(new EvidenceFileError("read", "invalid-json", { cause }));
}
return isJsonWithinLimits(decoded, policy)
? ok(decoded)
: err(new EvidenceFileError("read", "too-large"));
return ok(decoded);
} catch (cause: unknown) {
return err(new EvidenceFileError("read", "io", { cause }));
}
};
/** Atomically write bounded text to a regular file beneath an approved root. */
export const writeBoundedText = async (
/** Atomically write text to the caller-supplied path. */
export const writeTextFile = async (
encoded: string,
path: string,
overwrite: boolean,
policy: EvidenceFilePolicy,
): Promise<
Result<{ readonly path: string; readonly bytes: number }, EvidenceFileError>
> => {
if (policy.roots.length === 0)
return err(new EvidenceFileError("write", "disabled"));
const bytes = Buffer.byteLength(encoded, "utf8");
if (bytes > policy.maxBytes)
return err(new EvidenceFileError("write", "too-large"));
try {
const requestedPath = resolve(path);
const canonicalParent = await realpath(dirname(requestedPath));
const destination = resolve(canonicalParent, basename(requestedPath));
if (!(await isApproved(destination, policy.roots)))
return err(new EvidenceFileError("write", "outside-root"));
const existing = await lstat(destination).catch((cause: unknown) => {
if (fileErrorCode(cause) === "ENOENT") return undefined;
throw cause;
@@ -114,18 +85,6 @@ const publishNewFile = async (
}
};
const isApproved = async (
candidate: string,
roots: readonly string[],
): Promise<boolean> => {
for (const root of await canonicalizeConfiguredRoots(
roots.map((configuredRoot) => resolve(configuredRoot)),
)) {
if (isPathWithinRoot(root, candidate)) return true;
}
return false;
};
const fileErrorCode = (cause: unknown): unknown =>
typeof cause === "object" && cause !== null && "code" in cause
? cause.code
+7 -16
View File
@@ -137,18 +137,14 @@ const deriveInventoryState = (
return "complete";
};
const sortAndLimit = (
const sortExclusions = (
exclusions: HistoricalSourceGraphInput["exclusions"],
maxExclusions: number,
): HistoricalSourceGraphInput["exclusions"] => {
const sorted = [...exclusions].sort((left, right) => {
): HistoricalSourceGraphInput["exclusions"] =>
[...exclusions].sort((left, right) => {
const byPath = compareUnicodeCodePoints(left.path, right.path);
if (byPath !== 0) return byPath;
return compareUnicodeCodePoints(left.reason, right.reason);
});
if (sorted.length <= maxExclusions) return sorted;
return sorted.slice(0, maxExclusions);
};
/**
* Import a reference source directory into a committed historical source graph.
@@ -163,7 +159,7 @@ export const importReferenceSource = async (
if (isAborted(options.signal)) return err(cancelled());
const prepared = await prepareReferenceSourceImport(options);
if (!prepared.ok) return prepared;
const { ignored, limits, root, secrets } = prepared.value;
const { ignored, root, secrets } = prepared.value;
if (isAborted(options.signal)) return err(cancelled());
const exclusions: HistoricalSourceGraphInput["exclusions"] = [];
@@ -180,7 +176,7 @@ export const importReferenceSource = async (
};
const [readResult, vcs] = await Promise.all([
readReferenceSource(root, limits, {
readReferenceSource(root, {
...(options.signal === undefined ? {} : { signal: options.signal }),
shouldExclude,
}),
@@ -190,12 +186,7 @@ export const importReferenceSource = async (
if (!readResult.ok) {
const error = readResult.error;
if (error.code === "cancelled") return err(cancelled());
return err(
failure(
error.code === "invalid-limits" ? "invalid-limits" : "io",
error.message,
),
);
return err(failure("io", error.message));
}
if (isAborted(options.signal)) return err(cancelled());
@@ -218,7 +209,7 @@ export const importReferenceSource = async (
const sortedEntries = [...entries].sort((left, right) =>
compareUnicodeCodePoints(left.path, right.path),
);
const sortedExclusions = sortAndLimit(exclusions, limits.maxEntries);
const sortedExclusions = sortExclusions(exclusions);
const sortedLimitations = [...limitations].sort(compareUnicodeCodePoints);
const input: HistoricalSourceGraphInput = {
@@ -26,8 +26,6 @@ export const projectReferenceSourceEntryFailure = (
): string => {
if (entry.code === "cancelled")
return "This entry was not read because the import was cancelled. Start the import again when ready.";
if (entry.code === "limit")
return "This entry was not read because an import limit was reached. Import a smaller directory or raise the configured limits.";
if (entry.code === "unsupported")
return "This entry cannot be read safely on this system. Exclude it or import the directory on a supported system.";
if (entry.kind === "directory")
@@ -50,7 +48,7 @@ const failedEntry = (
path: entry.path,
kind: "directory",
classifications,
tree_state: entry.code === "limit" ? "partial" : "unreadable",
tree_state: "unreadable",
limitations: [limitation],
};
if (entry.kind === "symlink")
@@ -69,7 +67,7 @@ const failedEntry = (
size: entry.size ?? null,
language: null,
classifications: entry.kind === "file" ? classifications : ["unknown"],
content_state: entry.code === "limit" ? "too-large" : "unreadable",
content_state: "unreadable",
limitations: [limitation],
};
};
+5 -53
View File
@@ -4,20 +4,15 @@ import { join, resolve } from "node:path";
import ignore from "ignore";
import { err, ok, type Result } from "../domain/result.js";
import type { ReferenceSourceLimits } from "../reference/ReferenceSourceReader.js";
import { isPathWithinRoot } from "../domain/localPath.js";
import {
DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS,
DEFAULT_REFERENCE_SOURCE_LIMITS,
type ReferenceSourceImportError,
type ReferenceSourceImportOptions,
} from "./ReferenceSourceImportTypes.js";
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
/** Validated, authorized inputs ready for filesystem traversal. */
/** Validated inputs ready for filesystem traversal. */
export interface PreparedReferenceSourceImport {
readonly root: string;
readonly limits: ReferenceSourceLimits;
readonly ignored: ReturnType<typeof ignore>;
readonly secrets: ReturnType<typeof ignore>;
}
@@ -31,52 +26,16 @@ const failure = (
message,
});
const validLimits = (limits: ReferenceSourceLimits): boolean =>
Object.values(limits).every(
(value) => Number.isSafeInteger(value) && value > 0,
);
const maximumLimits = (
options: ReferenceSourceImportOptions,
): ReferenceSourceLimits => ({
maxBytes: options.policy.maxBytes,
maxEntries: options.policy.maxEntries,
maxDepth: options.policy.maxDepth,
maxPathBytes: options.policy.maxPathBytes,
});
const clampLimits = (
requested: ReferenceSourceLimits,
maximum: ReferenceSourceLimits,
): ReferenceSourceLimits => ({
maxBytes: Math.min(requested.maxBytes, maximum.maxBytes),
maxEntries: Math.min(requested.maxEntries, maximum.maxEntries),
maxDepth: Math.min(requested.maxDepth, maximum.maxDepth),
maxPathBytes: Math.min(requested.maxPathBytes, maximum.maxPathBytes),
});
const authorizeRoot = async (
const resolveRoot = async (
requestedRoot: string,
approvedRoots: readonly string[],
): Promise<Result<string, ReferenceSourceImportError>> => {
if (approvedRoots.length === 0)
return err(failure("policy", "No approved reference source roots"));
try {
if (!(await stat(requestedRoot)).isDirectory())
return err(
failure("invalid-root", "Reference source root is not a directory"),
);
const canonicalRoot = await realpath(resolve(requestedRoot));
const canonicalApprovedRoots = await canonicalizeConfiguredRoots(
approvedRoots.map((approvedRoot) => resolve(approvedRoot)),
);
for (const canonicalApproved of canonicalApprovedRoots) {
if (isPathWithinRoot(canonicalApproved, canonicalRoot))
return ok(canonicalRoot);
}
return err(
failure("policy", "Reference source root is outside approved roots"),
);
return ok(canonicalRoot);
} catch {
return err(
failure("invalid-root", "Reference source root could not be resolved"),
@@ -102,23 +61,16 @@ const buildIgnored = async (
return ignored;
};
/** Validate limits, authorize root, and build non-executing path filters. */
/** Resolve the caller-selected directory and build path filters. */
export const prepareReferenceSourceImport = async (
options: ReferenceSourceImportOptions,
): Promise<
Result<PreparedReferenceSourceImport, ReferenceSourceImportError>
> => {
const requested = options.limits ?? DEFAULT_REFERENCE_SOURCE_LIMITS;
const maximum = maximumLimits(options);
if (!validLimits(requested) || !validLimits(maximum))
return err(
failure("invalid-limits", "Import limits must be positive integers"),
);
const root = await authorizeRoot(options.root, options.policy.roots);
const root = await resolveRoot(options.root);
if (!root.ok) return root;
return ok({
root: root.value,
limits: clampLimits(requested, maximum),
ignored: await buildIgnored(root.value, options.excludePaths ?? []),
secrets: ignore().add([...options.policy.secretPatterns]),
});
+2 -29
View File
@@ -1,16 +1,9 @@
import type { ReferenceSourcePolicy } from "../domain/referenceSourcePolicy.js";
import type { ReferenceSourceLimits } from "../reference/ReferenceSourceReader.js";
/** Typed expected failure returned by historical-source imports. */
export interface ReferenceSourceImportError {
readonly tag: "reference-source-import";
readonly code:
| "cancelled"
| "invalid-limits"
| "invalid-root"
| "io"
| "parse"
| "policy";
readonly code: "cancelled" | "invalid-root" | "io" | "parse";
readonly message: string;
}
@@ -24,24 +17,12 @@ export const projectReferenceSourceImportError = (
message:
"Reference source import was cancelled. Start it again when ready.",
};
if (error.code === "invalid-limits")
return {
category: "invalid_input",
message:
"Reference source limits are invalid. Use positive integer limits, then try again.",
};
if (error.code === "invalid-root")
return {
category: "invalid_input",
message:
"Reference source directory could not be opened. Check that the path exists, is readable, and points to a directory.",
};
if (error.code === "policy")
return {
category: "permission_required",
message:
"Reference source directory is not approved. Add its directory to `REA_REFERENCE_ROOTS_JSON`, restart REA, then try again.",
};
if (error.code === "io")
return {
category: "execution_failure",
@@ -55,10 +36,9 @@ export const projectReferenceSourceImportError = (
};
};
/** Bounded import request paired with mandatory operator policy. */
/** Import a caller-selected local source tree as historical reference. */
export interface ReferenceSourceImportOptions {
readonly root: string;
readonly limits?: ReferenceSourceLimits;
readonly signal?: AbortSignal;
readonly caller: string;
readonly policy: ReferenceSourcePolicy;
@@ -79,12 +59,5 @@ export const DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS = [
"*.log",
] as const;
export const DEFAULT_REFERENCE_SOURCE_LIMITS: ReferenceSourceLimits = {
maxBytes: 16 * 1024 * 1024,
maxEntries: 10_000,
maxDepth: 32,
maxPathBytes: 4_096,
};
export const PARSEABLE_REFERENCE_SOURCE_LANGUAGES: ReadonlySet<string> =
new Set(["JavaScript", "TypeScript", "JSX", "TSX"]);
+3 -38
View File
@@ -7,13 +7,8 @@ import {
} from "../application/DirectAnalysis.js";
import { importReferenceSource } from "../application/ReferenceSourceImport.js";
import { projectReferenceSourceImportError } from "../application/ReferenceSourceImportTypes.js";
import { loadConfiguredPermissionAuthority } from "../application/PermissionConfiguration.js";
import { parseConfig } from "../config.js";
import {
AnalysisProtocolError,
PermissionRequiredError,
projectAnalysisError,
} from "../domain/errors.js";
import { projectAnalysisError } from "../domain/errors.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import { logCliCommand } from "../cliLogging.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
@@ -110,11 +105,11 @@ const registerReferenceSourceCommand = (
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.importReferenceSource, {
description: "Import a bounded source tree as historical reference only",
description: "Import a source tree as historical reference only",
args: z.object({
root: z
.string()
.describe("Source root allowed by REA_REFERENCE_ROOTS_JSON"),
.describe("Local source directory to import as historical reference"),
}),
run: ({ args }) =>
logCliCommand(logger, "import-reference-source", async () => {
@@ -124,36 +119,6 @@ const registerReferenceSourceCommand = (
error: "Import failed",
...projectAnalysisError(config.error),
};
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok)
return {
error: "Import failed",
...projectAnalysisError(authority.error),
};
const authorized = await authority.value.authorize(
{
capability: "reference_read",
roots: [args.root],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: `import_reference_source:${args.root}`,
},
"read",
);
if (!authorized.ok) {
const error =
authorized.error instanceof PermissionRequiredError
? authorized.error
: new AnalysisProtocolError(authorized.error.message, {
cause: authorized.error,
});
return {
error: "Import failed",
...projectAnalysisError(error),
};
}
const imported = await importReferenceSource({
root: args.root,
caller: "rea-cli",
+2 -16
View File
@@ -29,7 +29,6 @@ import {
buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest,
} from "./application/ReconstructionObligationLedgerService.js";
import { authorizeRootPermission } from "./application/DeferredFileAuthorization.js";
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
import { CLI_COMMANDS } from "./cliCommandNames.js";
import { parseCliJsonInput } from "./cliJsonInput.js";
@@ -297,7 +296,7 @@ const registerJsonCommand = <Input>({
logCliCommand(logger, name, async () => {
const input = await parseCliJsonInput(args.inputJson, name);
if (!input.ok) return input.error;
const lookup = await loadEvidenceLookup(options.evidenceBundle, name);
const lookup = await loadEvidenceLookup(options.evidenceBundle);
if (!lookup.ok)
return {
error: "Application workflow failed",
@@ -322,25 +321,12 @@ const registerJsonCommand = <Input>({
const loadEvidenceLookup = async (
bundlePath: string | undefined,
operation: string,
): Promise<
| { readonly ok: true; readonly value: EvidenceLookup | undefined }
| { readonly ok: false; readonly error: AnalysisError }
> => {
if (bundlePath === undefined) return { ok: true, value: undefined };
const configured = await loadConfiguredAuthority();
if (!configured.ok) return configured;
const authorized = await authorizeRootPermission(configured.authority, {
capability: "evidence_read",
roots: [bundlePath],
access: "read",
operation,
});
if (!authorized.ok) return authorized;
const loaded = await readEvidenceBundle(
bundlePath,
configured.config.evidenceFilePolicy,
);
const loaded = await readEvidenceBundle(bundlePath);
if (!loaded.ok) return loaded;
const records = new Map(
loaded.value.records.map((record) => [record.evidence_id, record]),
+3 -69
View File
@@ -5,21 +5,13 @@ import {
exportEvidenceBundleCommand,
importEvidenceBundleCommand,
} from "./application/EvidenceBundleCommands.js";
import { parseConfig } from "./config.js";
import { logCliCommand } from "./cliLogging.js";
import type { Logger } from "./logger.js";
import { CLI_COMMANDS } from "./cliCommandNames.js";
import type { JsonValue } from "./domain/jsonValue.js";
import {
AnalysisProtocolError,
PermissionRequiredError,
projectAnalysisError,
type AnalysisError,
} from "./domain/errors.js";
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
import type { AppConfig } from "./config.js";
import { projectAnalysisError, type AnalysisError } from "./domain/errors.js";
/** Register filesystem-gated Evidence commands. */
/** Register caller-path Evidence commands. */
export const registerEvidenceCommands = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
@@ -31,16 +23,7 @@ export const registerEvidenceCommands = (
}),
run: ({ args }) =>
logCliCommand(logger, "evidence-import", async () => {
const config = parseConfig(process.env);
if (!config.ok) return cliError(config.error);
const denied = await authorizeEvidence(config.value, [
{ capability: "evidence_read", path: args.path, access: "read" },
]);
if (denied !== undefined) return cliError(denied);
const imported = await importEvidenceBundleCommand(
args.path,
config.value.evidenceFilePolicy,
);
const imported = await importEvidenceBundleCommand(args.path);
return imported.ok ? imported.value : cliError(imported.error);
}),
});
@@ -55,18 +38,10 @@ export const registerEvidenceCommands = (
}),
run: ({ args, options }) =>
logCliCommand(logger, "evidence-export", async () => {
const config = parseConfig(process.env);
if (!config.ok) return cliError(config.error);
const denied = await authorizeEvidence(config.value, [
{ capability: "evidence_read", path: args.source, access: "read" },
{ capability: "evidence_write", path: args.output, access: "write" },
]);
if (denied !== undefined) return cliError(denied);
const exported = await exportEvidenceBundleCommand(
args.source,
args.output,
options.overwrite,
config.value.evidenceFilePolicy,
);
return exported.ok ? exported.value : cliError(exported.error);
}),
@@ -80,56 +55,15 @@ export const registerEvidenceCommands = (
}),
run: ({ args }) =>
logCliCommand(logger, "compare", async () => {
const config = parseConfig(process.env);
if (!config.ok) return cliError(config.error);
const denied = await authorizeEvidence(config.value, [
{ capability: "evidence_read", path: args.left, access: "read" },
{ capability: "evidence_read", path: args.right, access: "read" },
]);
if (denied !== undefined) return cliError(denied);
const compared = await compareEvidenceBundlesCommand({
leftPath: args.left,
rightPath: args.right,
policy: config.value.evidenceFilePolicy,
});
return compared.ok ? compared.value : cliError(compared.error);
}),
});
};
const authorizeEvidence = async (
config: AppConfig,
requests: readonly {
readonly capability: "evidence_read" | "evidence_write";
readonly path: string;
readonly access: "read" | "write";
}[],
): Promise<AnalysisError | undefined> => {
const authority = await loadConfiguredPermissionAuthority(config);
if (!authority.ok) return authority.error;
for (const request of requests) {
const result = await authority.value.authorize(
{
capability: request.capability,
roots: [request.path],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: `cli:${request.capability}:${request.path}`,
},
request.access,
);
if (!result.ok)
return result.error instanceof PermissionRequiredError
? result.error
: new AnalysisProtocolError(result.error.message, {
cause: result.error,
});
}
return undefined;
};
const cliError = (error: AnalysisError): JsonValue => ({
error: "Analysis failed",
...projectAnalysisError(error),
-3
View File
@@ -46,9 +46,6 @@ const environmentSchema = z
REA_PROCESS_EXECUTABLE_ROOTS_JSON: z.string().default("[]"),
REA_PROCESS_WORKING_ROOTS_JSON: z.string().default("[]"),
REA_PROCESS_ALLOWED_ENV_JSON: z.string().default("[]"),
REA_EVIDENCE_ROOTS_JSON: z.string().default("[]"),
REA_ANALYSIS_SNAPSHOT_ROOTS_JSON: z.string().default("[]"),
REA_REFERENCE_ROOTS_JSON: z.string().default("[]"),
REA_REFERENCE_SECRET_PATTERNS_JSON: z.string().default("[]"),
REA_BROWSER_OBSERVE_ENABLED: z.enum(["true", "false"]).default("false"),
REA_BROWSER_CDP_ENDPOINTS_JSON: z.string().default("[]"),
+1 -38
View File
@@ -6,11 +6,7 @@ import {
parseAbsoluteRoots,
parseLoaderArgs,
} from "./parsers.js";
import {
filePolicy,
permissionScope,
administratorGrants,
} from "./permissions.js";
import { permissionScope, administratorGrants } from "./permissions.js";
import type { AppConfig } from "./types.js";
import type { PermissionCeiling } from "../domain/permissionPolicy.js";
import {
@@ -53,9 +49,6 @@ const defaultHopperLauncherPath = (): string =>
interface ParsedArrays {
readonly loaderArgs: readonly string[];
readonly evidenceRoots: readonly string[];
readonly analysisSnapshotRoots: readonly string[];
readonly referenceRoots: readonly string[];
readonly secretPatterns: readonly string[];
readonly managedRuntimeRoots: readonly string[];
}
@@ -74,21 +67,6 @@ const parseAllArrays = (
): Result<ParsedArrays, ConfigurationError> => {
const loaderArgs = parseLoaderArgs(env.HOPPER_LOADER_ARGS_JSON);
if (!loaderArgs.ok) return loaderArgs;
const evidenceRoots = parseStringArray(
env.REA_EVIDENCE_ROOTS_JSON,
"REA_EVIDENCE_ROOTS_JSON",
);
if (!evidenceRoots.ok) return evidenceRoots;
const analysisSnapshotRoots = parseStringArray(
env.REA_ANALYSIS_SNAPSHOT_ROOTS_JSON,
"REA_ANALYSIS_SNAPSHOT_ROOTS_JSON",
);
if (!analysisSnapshotRoots.ok) return analysisSnapshotRoots;
const referenceRoots = parseStringArray(
env.REA_REFERENCE_ROOTS_JSON,
"REA_REFERENCE_ROOTS_JSON",
);
if (!referenceRoots.ok) return referenceRoots;
const secretPatterns = parseStringArray(
env.REA_REFERENCE_SECRET_PATTERNS_JSON,
"REA_REFERENCE_SECRET_PATTERNS_JSON",
@@ -101,9 +79,6 @@ const parseAllArrays = (
if (!managedRuntimeRoots.ok) return managedRuntimeRoots;
return ok({
loaderArgs: loaderArgs.value,
evidenceRoots: evidenceRoots.value,
analysisSnapshotRoots: analysisSnapshotRoots.value,
referenceRoots: referenceRoots.value,
secretPatterns: secretPatterns.value,
managedRuntimeRoots: managedRuntimeRoots.value,
});
@@ -123,12 +98,7 @@ const buildPermissionCeilings = (
policies: ParsedPolicies,
): readonly PermissionCeiling[] => {
const ceilings: PermissionCeiling[] = [
permissionScope("evidence_read", arrays.evidenceRoots),
permissionScope("evidence_write", arrays.evidenceRoots),
permissionScope("snapshot_read", arrays.analysisSnapshotRoots),
permissionScope("snapshot_write", arrays.analysisSnapshotRoots),
permissionScope("artifact_extract", ["/"]),
permissionScope("reference_read", arrays.referenceRoots),
];
appendProcessCaptureCeiling(ceilings, policies.processCapture);
appendPassiveObservationCeilings(ceilings, policies.passiveObservation);
@@ -159,15 +129,8 @@ const buildAppConfig = (
artifactNativeMountEnabled: env.REA_ARTIFACT_NATIVE_MOUNT_ENABLED === "true",
artifactIntegrityContinueEnabled:
env.REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED === "true",
evidenceFilePolicy: filePolicy(arrays.evidenceRoots),
analysisSnapshotFilePolicy: filePolicy(arrays.analysisSnapshotRoots),
referenceSourcePolicy: {
roots: arrays.referenceRoots,
secretPatterns: arrays.secretPatterns,
maxBytes: 16 * 1024 * 1024,
maxEntries: 10_000,
maxDepth: 32,
maxPathBytes: 4_096,
},
browserObservationPolicy: policies.passiveObservation.browser,
browserScenarioPolicy: policies.browserScenario,
-9
View File
@@ -1,18 +1,9 @@
import { isLiteralLoopbackHostname } from "../domain/browserObservation.js";
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
import type {
PermissionCeiling,
PermissionGrant,
} from "../domain/permissionPolicy.js";
export const filePolicy = (roots: readonly string[]): EvidenceFilePolicy => ({
roots,
maxBytes: 64 * 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024 * 1024,
maxNodes: 1_000_000,
});
export const permissionScope = (
capability: PermissionCeiling["capability"],
roots: readonly string[],
-3
View File
@@ -1,6 +1,5 @@
import type { LogLevel } from "../logger.js";
import type { ProcessExecutionPolicy } from "../domain/processCapture.js";
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
import type { ReferenceSourcePolicy } from "../domain/referenceSourcePolicy.js";
import type {
PermissionCeiling,
@@ -30,8 +29,6 @@ export interface AppConfig {
readonly processExecutionPolicy: ProcessExecutionPolicy;
readonly artifactNativeMountEnabled: boolean;
readonly artifactIntegrityContinueEnabled: boolean;
readonly evidenceFilePolicy: EvidenceFilePolicy;
readonly analysisSnapshotFilePolicy: EvidenceFilePolicy;
readonly referenceSourcePolicy: ReferenceSourcePolicy;
readonly browserObservationPolicy: BrowserObservationPolicy;
readonly browserScenarioPolicy: BrowserScenarioPolicy;
+27
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
type AnalysisSnapshot,
analysisSnapshotSchema,
snapshotBinding,
snapshotEvidenceForQuery,
snapshotTarget,
@@ -15,6 +16,32 @@ import { createEvidence } from "./evidence.js";
import { createEvidenceBundle } from "./evidenceBundle.js";
describe("analysis snapshot contract", () => {
it("accepts snapshots with more than ten thousand analysis entries", () => {
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
const entry = {
query_id: `query_${"0".repeat(64)}`,
operation: "analyze_function",
parameters: {},
execution: {
result: null,
raw_result: null,
provider: binding.provider,
limitations: [],
locations: [],
subject: null,
},
};
const parsed = analysisSnapshotSchema.parse({
target: snapshotTarget(ANALYSIS_SNAPSHOT_TARGET),
binding,
entries: Array.from({ length: 10_001 }, () => entry),
evidence_bundle: createEvidenceBundle([]),
});
expect(parsed.entries).toHaveLength(10_001);
});
it("finds only Evidence committed to the exact binding and profile", () => {
const evidence = createEvidence(
ANALYSIS_SNAPSHOT_TARGET,
+1 -1
View File
@@ -103,7 +103,7 @@ const entrySchema = z.object({
export const analysisSnapshotSchema = z.object({
target: targetSchema,
binding: bindingSchema,
entries: z.array(entrySchema).max(10_000),
entries: z.array(entrySchema),
evidence_bundle: evidenceBundleSchema,
});
-8
View File
@@ -45,14 +45,6 @@ export const evidenceBundleSchema = z.object({
export type EvidenceBundle = z.infer<typeof evidenceBundleSchema>;
export interface EvidenceFilePolicy {
readonly roots: readonly string[];
readonly maxBytes: number;
readonly maxDepth: number;
readonly maxStringLength: number;
readonly maxNodes: number;
}
/** Project records into a deterministic bundle whose order has no semantics. */
export const createEvidenceBundle = (
records: readonly Evidence[],
+2 -2
View File
@@ -131,7 +131,7 @@ describe("permission policy", () => {
describe("permission policy lifecycle", () => {
it("consumes once grants and applies revocation and ceiling reload immediately", () => {
const ceiling = {
capability: "evidence_write" as const,
capability: "process_capture" as const,
roots: ["/workspace/evidence"],
executables: [],
environment_names: [],
@@ -180,7 +180,7 @@ describe("permission policy lifecycle", () => {
it("reports a missing scope when revoked grants cover a different root", () => {
const ceiling = {
capability: "evidence_write" as const,
capability: "process_capture" as const,
roots: ["/workspace"],
executables: [],
environment_names: [],
-5
View File
@@ -10,13 +10,8 @@ export const PERMISSION_CAPABILITIES = [
"electron_observe",
"electron_automate",
"v8_inspector_observe",
"evidence_read",
"evidence_write",
"snapshot_read",
"snapshot_write",
"artifact_extract",
"native_mount",
"reference_read",
"javascript_replay",
"managed_runtime",
] as const;
+17 -22
View File
@@ -5,13 +5,11 @@ import canonicalize from "canonicalize";
import { z } from "zod";
import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js";
const MAX_PATH = 4_096;
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const boundedTextSchema = z.string().min(1).max(1_024);
const boundedTextSchema = z.string().min(1);
const relativePathSchema = z
.string()
.min(1)
.max(MAX_PATH)
.refine(
(path) =>
!path.startsWith("/") &&
@@ -35,14 +33,14 @@ const classificationSchema = z.enum([
const entryBaseShape = {
path: relativePathSchema,
classifications: z.array(classificationSchema).min(1).max(8),
limitations: z.array(boundedTextSchema).max(100),
classifications: z.array(classificationSchema).min(1),
limitations: z.array(boundedTextSchema),
};
const sourceFileBaseShape = {
...entryBaseShape,
kind: z.literal("file"),
language: z.string().min(1).max(100).nullable(),
language: z.string().min(1).nullable(),
};
const sourceFileSchema = z.union([
@@ -60,7 +58,6 @@ const sourceFileSchema = z.union([
"redacted-secret",
"excluded",
"unreadable",
"too-large",
"unknown",
]),
}),
@@ -81,7 +78,6 @@ const sourceDirectorySchema = z.strictObject({
const symlinkTargetSchema = z
.string()
.min(1)
.max(MAX_PATH)
.refine(
(target) =>
target === "<outside-root>" ||
@@ -112,7 +108,7 @@ const sourceEntrySchema = z.union([
const sourceRelationshipSchema = z.strictObject({
from_path: relativePathSchema,
to: z.string().min(1).max(MAX_PATH),
to: z.string().min(1),
kind: z.enum(["imports", "requires", "references", "declares-module"]),
resolution: z.enum(["internal", "external", "unresolved", "unknown"]),
parse_state: z.enum(["parsed", "partial", "unknown"]),
@@ -120,7 +116,7 @@ const sourceRelationshipSchema = z.strictObject({
const parseFailureSchema = z.strictObject({
path: relativePathSchema,
parser: z.string().min(1).max(100),
parser: z.string().min(1),
reason: boundedTextSchema,
});
@@ -162,23 +158,22 @@ const graphShape = {
root_alias: z.literal("$REFERENCE_ROOT"),
root_sha256: digestSchema,
inventory_state: z.enum(["complete", "partial", "unknown"]),
entries: z.array(sourceEntrySchema).max(100_000),
relationships: z.array(sourceRelationshipSchema).max(200_000),
parse_failures: z.array(parseFailureSchema).max(10_000),
exclusions: z.array(exclusionSchema).max(100_000),
languages: z.array(z.string().min(1).max(100)).max(1_000),
manifests: z.array(relativePathSchema).max(10_000),
entries: z.array(sourceEntrySchema),
relationships: z.array(sourceRelationshipSchema),
parse_failures: z.array(parseFailureSchema),
exclusions: z.array(exclusionSchema),
languages: z.array(z.string().min(1)),
manifests: z.array(relativePathSchema),
vcs: vcsSchema,
provenance: z.strictObject({
importer: z.string().min(1).max(100),
importer_version: z.string().min(1).max(100).nullable(),
importer: z.string().min(1),
importer_version: z.string().min(1).nullable(),
caller: z
.string()
.min(1)
.max(200)
.regex(/^[\w .:@/+-]+$/u),
}),
limitations: z.array(boundedTextSchema).max(1_000),
limitations: z.array(boundedTextSchema),
};
const historicalSourceGraphStructureSchema = z
@@ -209,8 +204,8 @@ const historicalSourceManifestBaseSchema = z.strictObject({
graph_sha256: digestSchema,
root_sha256: digestSchema,
inventory_state: z.enum(["complete", "partial", "unknown"]),
entry_count: z.number().int().min(0).max(100_000),
relationship_count: z.number().int().min(0).max(200_000),
entry_count: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
relationship_count: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
});
export type HistoricalSourceGraph = z.infer<typeof historicalSourceGraphSchema>;
+1 -6
View File
@@ -1,9 +1,4 @@
/** Operator-approved roots, exclusions, and hard caps for source imports. */
/** Exclusions and maximum traversal sizes for historical source imports. */
export interface ReferenceSourcePolicy {
readonly roots: readonly string[];
readonly secretPatterns: readonly string[];
readonly maxBytes: number;
readonly maxEntries: number;
readonly maxDepth: number;
readonly maxPathBytes: number;
}
-8
View File
@@ -55,14 +55,6 @@ export const registerConfigReload = (input: {
return;
}
runtimeState.currentConfig = refreshed.value;
Object.assign(
runtimeState.evidencePolicy,
refreshed.value.evidenceFilePolicy,
);
Object.assign(
runtimeState.snapshotPolicy,
refreshed.value.analysisSnapshotFilePolicy,
);
})
.catch(() => {
serverLogger.error(MCP_PERMISSION_RELOAD_FAILED);
-11
View File
@@ -1,20 +1,9 @@
import type { AppConfig } from "../config.js";
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
export interface RuntimeState {
currentConfig: AppConfig;
evidencePolicy: EvidenceFilePolicy & { roots: string[] };
snapshotPolicy: EvidenceFilePolicy & { roots: string[] };
}
export const createRuntimeState = (config: AppConfig): RuntimeState => ({
currentConfig: config,
evidencePolicy: {
...config.evidenceFilePolicy,
roots: [...config.evidenceFilePolicy.roots],
},
snapshotPolicy: {
...config.analysisSnapshotFilePolicy,
roots: [...config.analysisSnapshotFilePolicy.roots],
},
});
-3
View File
@@ -60,8 +60,6 @@ export const startMcpTransport = async (
logger: serverContext.logger,
processPolicy: () =>
serverContext.runtimeState.currentConfig.processExecutionPolicy,
evidenceFilePolicy: serverContext.runtimeState.evidencePolicy,
analysisSnapshotFilePolicy: serverContext.runtimeState.snapshotPolicy,
permissionAuthority: serverContext.permissionAuthority,
...optionalProviders,
artifactIntegrityContinueEnabled: () =>
@@ -93,7 +91,6 @@ export const startMcpTransport = async (
const runtimeAvailability = (state: RuntimeState) => ({
processCaptureEnabled:
state.currentConfig.processExecutionPolicy.status === "enabled",
evidenceFileRoots: state.currentConfig.evidenceFilePolicy.roots.length,
browserObservationEnabled:
state.currentConfig.browserObservationPolicy.status === "enabled",
browserScenarioEnabled:
+5 -24
View File
@@ -2,7 +2,6 @@ import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { err, ok } from "../domain/result.js";
import { traverseDirectory } from "./ReferenceSourceReaderEntries.js";
import {
type ReferenceSourceLimits,
type ReferenceSourceReaderOptions,
type ReferenceSourceRead,
type ReferenceSourceResult,
@@ -16,24 +15,16 @@ import {
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. */
/** Read a source tree without intentionally following symbolic links. */
export const readReferenceSource = async (
root: string,
limits: ReferenceSourceLimits = DEFAULT_LIMITS,
options: ReferenceSourceReaderOptions = {},
): Promise<ReferenceSourceResult<ReferenceSourceRead>> => {
if (!noFollowOpenSupported())
@@ -42,23 +33,19 @@ export const readReferenceSource = async (
code: "unsupported",
message: "Safe no-follow file opens are unavailable",
});
const prepared = await prepareRoot(root, limits, options.signal);
const prepared = await prepareRoot(root, 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 }],
pending: [{ path: canonicalRoot }],
bytesRead: 0,
filesSeen: 0,
truncated: false,
stopReason: undefined,
};
const traversal = await traverse(state);
if (!traversal.ok) return traversal;
@@ -69,20 +56,14 @@ export const readReferenceSource = async (
root: canonicalRoot,
entries: state.entries,
bytesRead: state.bytesRead,
truncated: state.truncated,
limitations: [
PATH_RACE_LIMITATION,
...(state.stopReason === "entry-limit"
? ["Traversal stopped because the entry limit was reached."]
: []),
],
limitations: [PATH_RACE_LIMITATION],
});
};
const traverse = async (
state: TraversalState,
): Promise<ReferenceSourceResult<undefined>> => {
while (state.pending.length > 0 && state.stopReason === undefined) {
while (state.pending.length > 0) {
if (isAborted(state.signal))
return err({
tag: "reference-source-reader",
+2 -45
View File
@@ -81,7 +81,6 @@ export const traverseDirectory = async (
for (const name of names.value) {
const result = await processEntry(state, current, name, directories);
if (!result.ok) return result;
if (state.stopReason !== undefined) break;
}
directories.reverse();
state.pending.push(...directories);
@@ -145,14 +144,6 @@ const processEntry = async (
},
};
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));
@@ -170,15 +161,8 @@ const processEntry = async (
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;
}
state.entries.push({ status: "read", kind: "directory", path });
directories.push({ path: absolute });
} else if (!metadata.value.isFile())
state.entries.push(
entryFailure(
@@ -199,33 +183,16 @@ const processFileEntry = async (
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);
};
@@ -291,13 +258,3 @@ const applyExclusion = (
return { ok: false };
}
};
const reserveEntry = (state: TraversalState): boolean => {
if (state.filesSeen < state.limits.maxEntries) {
state.filesSeen += 1;
return true;
}
state.truncated = true;
state.stopReason = "entry-limit";
return false;
};
+4 -30
View File
@@ -75,10 +75,9 @@ const prepareFileRead = async (
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 { handle, path, signal } = request;
const chunks: Buffer[] = [];
let total = 0;
for (;;) {
@@ -93,20 +92,8 @@ const readFileContents = async (request: {
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);
const chunk = Buffer.allocUnsafe(READ_CHUNK_BYTES);
const read = await handle.read(chunk, 0, chunk.byteLength, null);
if (isAborted(signal))
return {
status: "failed",
@@ -120,17 +107,6 @@ const readFileContents = async (request: {
};
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 };
@@ -184,8 +160,7 @@ const finalizeFileRead = async (
export const readStableFile = async (
request: StableFileRequest,
): Promise<ReferenceSourceEntry> => {
const { root, rootIdentity, absolute, path, expected, remaining, signal } =
request;
const { root, rootIdentity, absolute, path, expected, signal } = request;
let handle: FileHandle | undefined;
try {
const parentBefore = await validateDirectory(
@@ -207,7 +182,6 @@ export const readStableFile = async (
const contents = await readFileContents({
handle,
path,
remaining,
...(signal === undefined ? {} : { signal }),
});
if (contents.status === "failed") return contents.entry;
+1 -21
View File
@@ -2,13 +2,6 @@ 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;
@@ -18,7 +11,6 @@ export type ReferenceSourceFailureCode =
| "cancelled"
| "changed"
| "io"
| "limit"
| "symlink"
| "unsupported";
@@ -55,19 +47,13 @@ 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 code: "cancelled" | "invalid-root" | "io" | "unsupported";
readonly message: string;
}
@@ -75,21 +61,16 @@ 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;
stopReason: "entry-limit" | undefined;
};
export type StableFileRequest = {
@@ -98,7 +79,6 @@ export type StableFileRequest = {
readonly absolute: string;
readonly path: string;
readonly expected: BigStats;
readonly remaining: number;
readonly signal?: AbortSignal;
};
@@ -7,7 +7,6 @@ import { isPathWithinRoot } from "../domain/localPath.js";
import {
type BigStats,
type ReferenceSourceFailureCode,
type ReferenceSourceLimits,
type ReferenceSourceResult,
} from "./ReferenceSourceReaderTypes.js";
@@ -24,11 +23,6 @@ export const sameFile = (left: BigStats, right: BigStats): boolean =>
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;
@@ -80,7 +74,6 @@ export const validateDirectory = async (
export const prepareRoot = async (
root: string,
limits: ReferenceSourceLimits,
signal?: AbortSignal,
): Promise<
ReferenceSourceResult<{
@@ -88,10 +81,6 @@ export const prepareRoot = async (
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);