fix: consolidate boundary ownership and cleanup failure paths (#477)
This commit is contained in:
@@ -28,7 +28,7 @@ intentionally not included. -->
|
||||
- Provider, bridge, target-format, or platform compatibility:
|
||||
- Evidence, artifact, provenance, or reconstruction contract:
|
||||
- Process execution, authorization, cleanup, or containment impact:
|
||||
- Generated metadata, package, or installation impact:
|
||||
- Generated metadata (`docs/product-catalog.json`), package, or installation impact:
|
||||
|
||||
## Evidence and regression coverage
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ graph TD
|
||||
end
|
||||
|
||||
subgraph "Provider Process Foundation"
|
||||
PROCESS["src/process/<br/>owned process groups, private roots<br/>deadlines, bounded diagnostics, cleanup"]
|
||||
PROCESS["src/process/<br/>owned process groups, private roots<br/>deadlines, bounded file reads and diagnostics, cleanup"]
|
||||
end
|
||||
|
||||
subgraph "Contracts Layer"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { basename, dirname, isAbsolute, resolve } from "node:path";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { parseBinaryTarget } from "../../dist/domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "../../dist/application/BinaryTargetResolver.js";
|
||||
import { inspectManagedArtifactBytes } from "../../dist/dotnet/ManagedArtifactInspector.js";
|
||||
import { inspectManagedMembersBytes } from "../../dist/dotnet/ManagedMemberInspector.js";
|
||||
import { projectManagedApplicationGraphEvidence } from "../../dist/application/ManagedApplicationGraphService.js";
|
||||
|
||||
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { parseBinaryTarget } from "../../dist/domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "../../dist/application/BinaryTargetResolver.js";
|
||||
import { buildManagedPeFixture } from "./managed-pe-fixture.mjs";
|
||||
import { createManagedConformanceOracleSupport } from "./managed-conformance-oracles.mjs";
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/** Validate the expected fail-closed Linux fixture outcome. */
|
||||
export function assertLinuxPackageProviderFailure(execution: {
|
||||
readonly status: number | null;
|
||||
readonly stdout: string;
|
||||
}): void;
|
||||
|
||||
/** Run platform-specific packaged analysis checks. */
|
||||
export function verifyPackagePlatform(input: {
|
||||
readonly cli: string;
|
||||
readonly environment: Readonly<Record<string, string | undefined>>;
|
||||
}): Promise<void>;
|
||||
@@ -8,14 +8,7 @@ export async function verifyPackagePlatform({ cli, environment }) {
|
||||
["analyze", process.execPath, "--json"],
|
||||
environment,
|
||||
);
|
||||
const unsupported = json(unsupportedExecution.stdout);
|
||||
if (
|
||||
unsupportedExecution.status !== 1 ||
|
||||
unsupported.details?.failure_code !== "unsupported_hopper_build"
|
||||
)
|
||||
throw new Error(
|
||||
`packaged Linux Hopper verification did not fail closed: ${JSON.stringify(unsupported)}`,
|
||||
);
|
||||
assertLinuxPackageProviderFailure(unsupportedExecution);
|
||||
} else {
|
||||
const overview = json(
|
||||
await run(cli, ["analyze", process.execPath, "--json"], environment),
|
||||
@@ -85,3 +78,30 @@ export async function verifyPackagePlatform({ cli, environment }) {
|
||||
throw new Error(`packaged trace CLI failed: ${JSON.stringify(trace)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Require the declared unsupported build or an exact missing-Xvfb diagnostic, never arbitrary provider failure. */
|
||||
export const assertLinuxPackageProviderFailure = (execution) => {
|
||||
const failure = json(execution.stdout);
|
||||
const details = failure?.details;
|
||||
const diagnostic = details?.diagnostics;
|
||||
const unsupportedBuild =
|
||||
details?.failure_code === "unsupported_hopper_build" &&
|
||||
details.exit_code === 72;
|
||||
const missingDisplayDependency =
|
||||
details?.failure_code === "runtime_dependency_unavailable" &&
|
||||
details.exit_code === 79 &&
|
||||
diagnostic?.component === "hopper_private_display" &&
|
||||
diagnostic.operation === "probe" &&
|
||||
diagnostic.reason === "missing_xvfb" &&
|
||||
diagnostic.status === "error" &&
|
||||
diagnostic.failure_code === "runtime_dependency_unavailable" &&
|
||||
diagnostic.strategy === "unavailable";
|
||||
if (
|
||||
execution.status !== 1 ||
|
||||
failure?.code !== "provider_unavailable" ||
|
||||
(!unsupportedBuild && !missingDisplayDependency)
|
||||
)
|
||||
throw new Error(
|
||||
`packaged Linux Hopper verification did not fail closed: ${JSON.stringify(failure)}`,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -118,7 +118,7 @@ const verifySetupApply = async ({ cli, environment, supportedSetupHost }) => {
|
||||
const first = json(firstExecution.stdout);
|
||||
const alignedExecution = await runWithStatus(
|
||||
cli,
|
||||
["setup", "--json"],
|
||||
["setup", "--all-detected", "--json"],
|
||||
environment,
|
||||
);
|
||||
const aligned = json(alignedExecution.stdout);
|
||||
@@ -142,7 +142,7 @@ const verifySetupApply = async ({ cli, environment, supportedSetupHost }) => {
|
||||
second.appliedActions.length !== 0
|
||||
)
|
||||
throw new Error(
|
||||
`packaged setup did not preserve idempotent defaults and explicit Hopper reinstall behavior: ${JSON.stringify({ first, aligned, second })}`,
|
||||
`packaged setup did not preserve idempotent agent configuration and explicit Hopper reinstall behavior: ${JSON.stringify({ first, aligned, second })}`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { access } from "node:fs/promises";
|
||||
|
||||
import { parseBinaryTarget } from "../dist/domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "../dist/application/BinaryTargetResolver.js";
|
||||
import { SUPPORTED_GHIDRA_VERSION } from "../dist/ghidra/GhidraInstallation.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "../dist/ghidra/GhidraSessionValues.js";
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
import { GhidraHeadlessLauncher } from "../dist/ghidra/GhidraLauncher.js";
|
||||
import { GHIDRA_PROVIDER_IDENTITY } from "../dist/ghidra/GhidraProvider.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES as SESSION_CAPABILITIES } from "../dist/ghidra/GhidraSessionValues.js";
|
||||
import { parseBinaryTarget } from "../dist/domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "../dist/application/BinaryTargetResolver.js";
|
||||
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
|
||||
|
||||
const verifierRun = createVerifierRun();
|
||||
|
||||
@@ -7,7 +7,7 @@ import { isAbsolute, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { parseBinaryTarget } from "../dist/domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "../dist/application/BinaryTargetResolver.js";
|
||||
import { resolveGhidraAnalysisProfile } from "../dist/ghidra/GhidraAnalysisProfile.js";
|
||||
import { GhidraClient } from "../dist/ghidra/GhidraClient.js";
|
||||
import { GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS } from "../dist/ghidra/GhidraDefaults.js";
|
||||
|
||||
@@ -11,14 +11,18 @@ export const waitForAbortable = async <Value>(
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<Value | typeof ABORTED> => {
|
||||
if (signal === undefined) return pending;
|
||||
if (signal.aborted) return ABORTED;
|
||||
let onAbort: (() => void) | undefined;
|
||||
const cancelled = new Promise<typeof ABORTED>((resolve) => {
|
||||
if (signal.aborted) {
|
||||
resolve(ABORTED);
|
||||
return;
|
||||
}
|
||||
onAbort = () => resolve(ABORTED);
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
try {
|
||||
return await Promise.race([pending, cancelled]);
|
||||
// Even an already-cancelled wait must own the producer's eventual rejection.
|
||||
return await Promise.race([cancelled, pending]);
|
||||
} finally {
|
||||
if (onAbort !== undefined) signal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@ import { open } from "node:fs/promises";
|
||||
|
||||
import { classifyArtifactPath } from "../ArtifactGraphConstruction.js";
|
||||
import type { ArtifactNode } from "../../domain/artifactGraph.js";
|
||||
import { zipPackageFormatForPath } from "../../domain/zipPackageFormat.js";
|
||||
import {
|
||||
hasZipSignature,
|
||||
zipPackageFormatForPath,
|
||||
} from "../../domain/zipPackageFormat.js";
|
||||
|
||||
const classifyContainerExtension = (
|
||||
path: string,
|
||||
@@ -26,14 +29,7 @@ export const classifyRoot = async (
|
||||
try {
|
||||
const magic = Buffer.alloc(4);
|
||||
const observed = await handle.read(magic, 0, magic.length, 0);
|
||||
if (
|
||||
observed.bytesRead === 4 &&
|
||||
magic[0] === 0x50 &&
|
||||
magic[1] === 0x4b &&
|
||||
[0x03, 0x05, 0x07].includes(magic[2] ?? -1) &&
|
||||
[0x04, 0x06, 0x08].includes(magic[3] ?? -1)
|
||||
)
|
||||
return "zip";
|
||||
if (hasZipSignature(magic.subarray(0, observed.bytesRead))) return "zip";
|
||||
if (observed.bytesRead === 4) {
|
||||
const header = magic.readUInt32BE(0);
|
||||
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(header))
|
||||
|
||||
@@ -2,7 +2,7 @@ import { realpath } from "node:fs/promises";
|
||||
|
||||
import type { ArtifactLimits } from "../artifacts/ArtifactReader.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import { withinRoot } from "../reference/ReferenceSourceReaderPaths.js";
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
import {
|
||||
scanCanonicalArtifactInventory,
|
||||
type ArtifactInventoryOptions,
|
||||
@@ -26,7 +26,7 @@ export const scanAuthorizedArtifactInventory = async (
|
||||
realpath(inputPath),
|
||||
canonicalizeConfiguredRoots(roots),
|
||||
]);
|
||||
if (!approved.some((root) => withinRoot(root, path)))
|
||||
if (!approved.some((root) => isPathWithinRoot(root, path)))
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Artifact path is outside approved input roots",
|
||||
|
||||
@@ -6,10 +6,8 @@ import {
|
||||
snapshotTarget,
|
||||
} from "../domain/analysisSnapshot.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import {
|
||||
parseBinaryTarget,
|
||||
type BinaryTarget,
|
||||
} from "../domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
|
||||
import { type BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
EvidenceIntegrityError,
|
||||
type AnalysisError,
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import { constants } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
access,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
stat,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { execFile } from "node:child_process";
|
||||
import { extname, isAbsolute, join, resolve } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
import { BinaryTargetError } from "../domain/errors.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
hasZipSignature,
|
||||
zipPackageFormatForPath,
|
||||
} from "../domain/zipPackageFormat.js";
|
||||
|
||||
import {
|
||||
parseExecutableHeader,
|
||||
parsePeRecord,
|
||||
type ExecutableMetadata,
|
||||
} from "../domain/binaryTarget.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/**
|
||||
* Resolve and classify a readable local target before a provider is selected.
|
||||
* FAT Mach-O inputs select only a host-compatible architecture so setup remains
|
||||
* non-interactive; unsupported or ambiguous inputs are returned as typed errors.
|
||||
*/
|
||||
export const parseBinaryTarget = async (
|
||||
input: string,
|
||||
cwd = process.cwd(),
|
||||
hostArchitecture: NodeJS.Architecture = process.arch,
|
||||
targetKind?: BinaryTarget["kind"],
|
||||
): Promise<Result<BinaryTarget, BinaryTargetError>> => {
|
||||
const candidate = isAbsolute(input) ? input : resolve(cwd, input);
|
||||
try {
|
||||
await access(candidate, constants.R_OK);
|
||||
const canonical = await realpath(candidate);
|
||||
const resolved = await resolveAppBundle(canonical);
|
||||
if (!resolved.ok) return err(resolved.error);
|
||||
const path = resolved.value;
|
||||
const handle = await open(path, "r");
|
||||
try {
|
||||
if (!(await handle.stat()).isFile())
|
||||
return err(new BinaryTargetError(path, "target is not a regular file"));
|
||||
if (
|
||||
targetKind === "database" ||
|
||||
(targetKind === undefined && path.toLowerCase().endsWith(".hop"))
|
||||
)
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
kind: "database",
|
||||
format: "analysis-database",
|
||||
});
|
||||
const artifactFormat = await detectArtifactFormat(path, handle);
|
||||
if (artifactFormat !== undefined) {
|
||||
const identity = {
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
};
|
||||
return isArchiveFormat(artifactFormat)
|
||||
? ok({ ...identity, kind: "archive", format: artifactFormat })
|
||||
: ok({ ...identity, kind: "artifact", format: artifactFormat });
|
||||
}
|
||||
const detected = await readExecutableMetadata(handle, hostArchitecture);
|
||||
if (!detected.ok) return err(new BinaryTargetError(path, detected.error));
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
kind: "executable",
|
||||
...detected.value,
|
||||
});
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(candidate, "path is not readable", { cause }),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const detectArtifactFormat = async (
|
||||
path: string,
|
||||
handle: FileHandle,
|
||||
): Promise<
|
||||
| Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe"
|
||||
>
|
||||
| undefined
|
||||
> => {
|
||||
const lower = path.toLowerCase();
|
||||
const magic = Buffer.alloc(8);
|
||||
const observed = await handle.read(magic, 0, magic.length, 0);
|
||||
if (hasZipSignature(magic.subarray(0, observed.bytesRead))) {
|
||||
return zipPackageFormatForPath(lower) ?? "zip";
|
||||
}
|
||||
const named = namedArtifactFormat(lower);
|
||||
if (named !== undefined) return named;
|
||||
if (
|
||||
lower.endsWith(".pkg") &&
|
||||
observed.bytesRead >= 4 &&
|
||||
magic.subarray(0, 4).toString("ascii") === "xar!"
|
||||
)
|
||||
return "pkg";
|
||||
if (lower.endsWith(".dmg")) {
|
||||
const size = (await handle.stat()).size;
|
||||
if (size >= 512) {
|
||||
const trailer = Buffer.alloc(4);
|
||||
const read = await handle.read(trailer, 0, trailer.length, size - 512);
|
||||
if (read.bytesRead === 4 && trailer.toString("ascii") === "koly")
|
||||
return "dmg";
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const namedArtifactFormat = (
|
||||
lowerPath: string,
|
||||
): "asar" | "plist" | "source-map" | "javascript" | undefined => {
|
||||
if (lowerPath.endsWith(".asar")) return "asar";
|
||||
if (lowerPath.endsWith(".plist")) return "plist";
|
||||
if (lowerPath.endsWith(".map")) return "source-map";
|
||||
return /\.(?:m?js|cjs)$/u.test(lowerPath) ? "javascript" : undefined;
|
||||
};
|
||||
|
||||
const isArchiveFormat = (
|
||||
format: Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe"
|
||||
>,
|
||||
): format is Extract<BinaryTarget, { kind: "archive" }>["format"] =>
|
||||
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(format);
|
||||
|
||||
const sha256Handle = async (handle: FileHandle): Promise<string> => {
|
||||
const hash = createHash("sha256");
|
||||
const chunk = Buffer.allocUnsafe(64 * 1024);
|
||||
let position = 0;
|
||||
while (true) {
|
||||
const observed = await handle.read(chunk, 0, chunk.length, position);
|
||||
if (observed.bytesRead === 0) break;
|
||||
hash.update(chunk.subarray(0, observed.bytesRead));
|
||||
position += observed.bytesRead;
|
||||
}
|
||||
return hash.digest("hex");
|
||||
};
|
||||
|
||||
const resolveAppBundle = async (
|
||||
path: string,
|
||||
): Promise<Result<string, BinaryTargetError>> => {
|
||||
const metadata = await stat(path);
|
||||
if (!metadata.isDirectory()) return ok(path);
|
||||
if (extname(path).toLowerCase() !== ".app")
|
||||
return err(new BinaryTargetError(path, "target is not an app or file"));
|
||||
const plistPath = join(path, "Contents", "Info.plist");
|
||||
let name: string;
|
||||
try {
|
||||
const plist = await readFile(plistPath);
|
||||
name =
|
||||
plist.subarray(0, 6).toString("ascii") === "bplist"
|
||||
? await readBinaryPlistExecutable(plistPath)
|
||||
: parseXmlPlistExecutable(plist.toString("utf8"));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(path, "app has no readable CFBundleExecutable", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (!isSafeExecutableName(name))
|
||||
return err(
|
||||
new BinaryTargetError(path, "app has an unsafe CFBundleExecutable"),
|
||||
);
|
||||
const programs = join(path, "Contents", "MacOS");
|
||||
const executable = join(programs, name);
|
||||
try {
|
||||
const [canonicalPrograms, canonicalExecutable] = await Promise.all([
|
||||
realpath(programs),
|
||||
realpath(executable),
|
||||
]);
|
||||
if (!isPathWithinRoot(canonicalPrograms, canonicalExecutable))
|
||||
return err(
|
||||
new BinaryTargetError(path, "app program file leaves Contents/MacOS"),
|
||||
);
|
||||
return ok(canonicalExecutable);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(path, "app program file is missing", { cause }),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const parseXmlPlistExecutable = (plist: string): string => {
|
||||
const match =
|
||||
/<key>\s*CFBundleExecutable\s*<\/key>\s*<string>([^<]+)<\/string>/u.exec(
|
||||
plist,
|
||||
);
|
||||
if (match?.[1] === undefined)
|
||||
throw new Error("CFBundleExecutable is missing");
|
||||
return decodeXml(match[1].trim());
|
||||
};
|
||||
|
||||
const readBinaryPlistExecutable = async (plistPath: string): Promise<string> =>
|
||||
(
|
||||
await execFileAsync("/usr/bin/plutil", [
|
||||
"-extract",
|
||||
"CFBundleExecutable",
|
||||
"raw",
|
||||
"-o",
|
||||
"-",
|
||||
plistPath,
|
||||
])
|
||||
).stdout.trim();
|
||||
|
||||
const isSafeExecutableName = (name: string): boolean =>
|
||||
name.length > 0 &&
|
||||
name !== "." &&
|
||||
name !== ".." &&
|
||||
!name.includes("\0") &&
|
||||
!/[/\\]/u.test(name);
|
||||
|
||||
const decodeXml = (value: string): string =>
|
||||
value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll(""", '"')
|
||||
.replaceAll("'", "'");
|
||||
|
||||
const readExecutableMetadata = async (
|
||||
handle: FileHandle,
|
||||
hostArchitecture: NodeJS.Architecture,
|
||||
): Promise<Result<ExecutableMetadata, string>> => {
|
||||
const prefix = Buffer.alloc(4096);
|
||||
const prefixRead = await handle.read(prefix, 0, prefix.length, 0);
|
||||
const bytes = prefix.subarray(0, prefixRead.bytesRead);
|
||||
if (bytes.length >= 64 && bytes[0] === 0x4d && bytes[1] === 0x5a) {
|
||||
const offset = bytes.readUInt32LE(0x3c);
|
||||
return readPeMetadata(handle, offset);
|
||||
}
|
||||
if (bytes.length >= 8) {
|
||||
const magic = bytes.readUInt32BE(0);
|
||||
if ([0xcafebabf, 0xbfbafeca].includes(magic)) {
|
||||
const little = magic === 0xbfbafeca;
|
||||
const count = little ? bytes.readUInt32LE(4) : bytes.readUInt32BE(4);
|
||||
const required = 8 + count * 32;
|
||||
if (count <= 128 && required > bytes.length) {
|
||||
const header = Buffer.alloc(required);
|
||||
const headerRead = await handle.read(header, 0, header.length, 0);
|
||||
return parseExecutableHeader(
|
||||
header.subarray(0, headerRead.bytesRead),
|
||||
hostArchitecture,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return parseExecutableHeader(bytes, hostArchitecture);
|
||||
};
|
||||
|
||||
const readPeMetadata = async (
|
||||
handle: FileHandle,
|
||||
offset: number,
|
||||
): Promise<Result<ExecutableMetadata, string>> => {
|
||||
const fileHeader = Buffer.alloc(24);
|
||||
const fileHeaderRead = await handle.read(
|
||||
fileHeader,
|
||||
0,
|
||||
fileHeader.length,
|
||||
offset,
|
||||
);
|
||||
if (fileHeaderRead.bytesRead !== fileHeader.length)
|
||||
return err("invalid or truncated PE header");
|
||||
const optionalHeaderSize = fileHeader.readUInt16LE(20);
|
||||
if (optionalHeaderSize > 4096) return err("invalid PE optional header size");
|
||||
const record = Buffer.alloc(24 + optionalHeaderSize);
|
||||
const recordRead = await handle.read(record, 0, record.length, offset);
|
||||
return recordRead.bytesRead === record.length
|
||||
? parsePeRecord(record)
|
||||
: err("invalid or truncated PE header");
|
||||
};
|
||||
@@ -1,12 +1,14 @@
|
||||
import { lstat, readFile, realpath } from "node:fs/promises";
|
||||
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
||||
import { link, lstat, mkdtemp, open, 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. */
|
||||
@@ -24,8 +26,14 @@ export const readBoundedJson = async (
|
||||
if (!stats.isFile()) return err(new EvidenceFileError("read", "not-file"));
|
||||
if (stats.size > policy.maxBytes)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
const encoded = await readFile(canonicalPath);
|
||||
if (encoded.byteLength > policy.maxBytes)
|
||||
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"));
|
||||
let decoded: unknown;
|
||||
try {
|
||||
@@ -62,7 +70,7 @@ export const writeBoundedText = async (
|
||||
if (!(await isApproved(destination, policy.roots)))
|
||||
return err(new EvidenceFileError("write", "outside-root"));
|
||||
const existing = await lstat(destination).catch((cause: unknown) => {
|
||||
if (isFileNotFound(cause)) return undefined;
|
||||
if (fileErrorCode(cause) === "ENOENT") return undefined;
|
||||
throw cause;
|
||||
});
|
||||
if (existing !== undefined) {
|
||||
@@ -70,14 +78,39 @@ export const writeBoundedText = async (
|
||||
if (!existing.isFile() || existing.isSymbolicLink())
|
||||
return err(new EvidenceFileError("write", "not-file"));
|
||||
}
|
||||
await writeFileAtomic(destination, encoded, {
|
||||
if (overwrite)
|
||||
await writeFileAtomic(destination, encoded, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
fsync: true,
|
||||
});
|
||||
else await publishNewFile(destination, encoded);
|
||||
return ok({ path: requestedPath, bytes });
|
||||
} catch (cause: unknown) {
|
||||
if (!overwrite && fileErrorCode(cause) === "EEXIST")
|
||||
return err(new EvidenceFileError("write", "exists", { cause }));
|
||||
return err(new EvidenceFileError("write", "io", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
const publishNewFile = async (
|
||||
destination: string,
|
||||
encoded: string,
|
||||
): Promise<void> => {
|
||||
const stagingDirectory = await mkdtemp(
|
||||
resolve(dirname(destination), ".rea-write-"),
|
||||
);
|
||||
try {
|
||||
const staged = resolve(stagingDirectory, "content");
|
||||
await writeFileAtomic(staged, encoded, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
fsync: true,
|
||||
});
|
||||
return ok({ path: requestedPath, bytes });
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("write", "io", { cause }));
|
||||
// A hard link publishes complete bytes atomically and cannot replace an existing name.
|
||||
await link(staged, destination);
|
||||
} finally {
|
||||
await rm(stagingDirectory, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -88,18 +121,12 @@ const isApproved = async (
|
||||
for (const root of await canonicalizeConfiguredRoots(
|
||||
roots.map((configuredRoot) => resolve(configuredRoot)),
|
||||
)) {
|
||||
const relation = relative(root, candidate);
|
||||
if (
|
||||
relation === "" ||
|
||||
(!relation.startsWith("..") && !isAbsolute(relation))
|
||||
)
|
||||
return true;
|
||||
if (isPathWithinRoot(root, candidate)) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const isFileNotFound = (cause: unknown): boolean =>
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
cause.code === "ENOENT";
|
||||
const fileErrorCode = (cause: unknown): unknown =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
isLiteralLoopbackHostname,
|
||||
@@ -14,8 +15,6 @@ import type {
|
||||
} from "../domain/webScreenshot.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
@@ -248,14 +247,7 @@ const prepare = async (
|
||||
},
|
||||
"read",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return browser === undefined
|
||||
? err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { BrowserScenarioCapturePort } from "./BrowserScenarioCapturePort.js";
|
||||
import { createBrowserScenarioEvidence } from "./BrowserScenarioEvidence.js";
|
||||
@@ -5,8 +6,6 @@ import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import { digestJson } from "./JavaScriptReplayPlanning.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
@@ -57,14 +56,7 @@ const authorizeScenario = async (
|
||||
},
|
||||
"write",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return { ok: true, value: true };
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
|
||||
/** Validated client document and its server table, preserving unrelated settings. */
|
||||
export interface ClientConfigurationDocument {
|
||||
readonly document: Record<string, unknown>;
|
||||
readonly servers: Record<string, unknown>;
|
||||
readonly serversKey: "mcp_servers" | "mcpServers";
|
||||
}
|
||||
|
||||
const objectSchema = z.record(z.string(), z.unknown());
|
||||
|
||||
/** Parse the client format and reject malformed root or server-table values. */
|
||||
export const parseClientConfiguration = (
|
||||
text: string,
|
||||
format: SetupClient["format"],
|
||||
): ClientConfigurationDocument => {
|
||||
const document = objectSchema.parse(
|
||||
format === "toml" ? parseToml(text) : JSON.parse(text),
|
||||
);
|
||||
const serversKey = format === "toml" ? "mcp_servers" : "mcpServers";
|
||||
const value = document[serversKey];
|
||||
const servers = value === undefined ? {} : objectSchema.parse(value);
|
||||
return { document, servers, serversKey };
|
||||
};
|
||||
|
||||
/** Serialize a validated client document using the selected format. */
|
||||
export const serializeClientConfiguration = (
|
||||
document: Record<string, unknown>,
|
||||
format: SetupClient["format"],
|
||||
): string =>
|
||||
format === "toml"
|
||||
? stringifyToml(document)
|
||||
: `${JSON.stringify(document, null, 2)}\n`;
|
||||
@@ -1,7 +1,7 @@
|
||||
import { parseClientConfiguration } from "./ClientConfigurationDocument.js";
|
||||
import { access, readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { parse as parseToml } from "smol-toml";
|
||||
import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
@@ -39,7 +39,6 @@ export type UnhealthyClientRegistrationStatus = Exclude<
|
||||
{ readonly state: "aligned" }
|
||||
>;
|
||||
|
||||
const objectSchema = z.record(z.string(), z.unknown());
|
||||
const registrationSchema = z
|
||||
.object({
|
||||
command: z.string().min(1),
|
||||
@@ -59,12 +58,7 @@ export const readClientRegistrationStatuses = async (
|
||||
continue;
|
||||
try {
|
||||
const content = await readFile(client.configPath, "utf8");
|
||||
const document = objectSchema.parse(
|
||||
client.format === "toml" ? parseToml(content) : JSON.parse(content),
|
||||
);
|
||||
const servers = objectSchema.parse(
|
||||
document[client.format === "toml" ? "mcp_servers" : "mcpServers"] ?? {},
|
||||
);
|
||||
const { servers } = parseClientConfiguration(content, client.format);
|
||||
const raw = servers[PRODUCT_IDENTITY.mcpServerKey];
|
||||
if (raw === undefined) {
|
||||
statuses.push(
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import { type AnalysisError } from "../domain/errors.js";
|
||||
import type { PermissionCapability } from "../domain/permissionPolicy.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
@@ -36,13 +33,7 @@ export const authorizeRootPermission = async (
|
||||
);
|
||||
return authorized.ok
|
||||
? ok(null)
|
||||
: err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
: err(projectPermissionFailure(authorized.error));
|
||||
};
|
||||
|
||||
export interface DeferredFileWriteAuthorization {
|
||||
@@ -77,13 +68,7 @@ export const authorizeFileReadWithDeferredWrite = async (
|
||||
!(read.error instanceof PermissionPathError) ||
|
||||
read.error.reason !== "not_found"
|
||||
)
|
||||
return err(
|
||||
read.error instanceof PermissionRequiredError
|
||||
? read.error
|
||||
: new AnalysisProtocolError(read.error.message, {
|
||||
cause: read.error,
|
||||
}),
|
||||
);
|
||||
return err(projectPermissionFailure(read.error));
|
||||
writeAuthorization = authorizeRootPermission(authority, {
|
||||
capability: input.writeCapability,
|
||||
roots: [input.path],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import { parseConfig, type AppConfig } from "../config.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { EnhancedTools } from "./EnhancedTools.js";
|
||||
@@ -10,8 +11,6 @@ import type { ArtifactToolName } from "../contracts/artifactToolContracts.js";
|
||||
import type { ManagedToolName } from "../contracts/managedToolContracts.js";
|
||||
import {
|
||||
EvidenceIntegrityError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
projectAnalysisError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
@@ -20,7 +19,7 @@ import {
|
||||
readAnalysisSnapshot,
|
||||
writeAnalysisSnapshot,
|
||||
} from "./AnalysisSnapshotFiles.js";
|
||||
import { parseBinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
snapshotEvidenceForQuery,
|
||||
@@ -136,14 +135,7 @@ const authorizeAnalysis = async (
|
||||
},
|
||||
request.access,
|
||||
);
|
||||
if (!result.ok)
|
||||
return err(
|
||||
result.error instanceof PermissionRequiredError
|
||||
? result.error
|
||||
: new AnalysisProtocolError(result.error.message, {
|
||||
cause: result.error,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) return err(projectPermissionFailure(result.error));
|
||||
}
|
||||
if (
|
||||
["inventory_artifact", "inspect_artifact"].includes(tool) &&
|
||||
@@ -161,14 +153,7 @@ const authorizeAnalysis = async (
|
||||
},
|
||||
"read",
|
||||
);
|
||||
if (!result.ok)
|
||||
return err(
|
||||
result.error instanceof PermissionRequiredError
|
||||
? result.error
|
||||
: new AnalysisProtocolError(result.error.message, {
|
||||
cause: result.error,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) return err(projectPermissionFailure(result.error));
|
||||
}
|
||||
return ok(null);
|
||||
};
|
||||
|
||||
@@ -5,7 +5,7 @@ import { delimiter, join } from "node:path";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { parseBinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { probeHomebrew } from "./homebrew.js";
|
||||
import {
|
||||
@@ -90,7 +90,6 @@ export interface DoctorHost {
|
||||
manualHopperPaths(): Promise<readonly string[]>;
|
||||
providerInspections?(): Promise<readonly DoctorProviderInspection[]>;
|
||||
installationPaths?(): Promise<readonly string[]>;
|
||||
installedSkillVersion?(): Promise<string | undefined>;
|
||||
installedSkillIdentity?(): Promise<InstalledSkillIdentity | undefined>;
|
||||
clientRegistrations?(): Promise<readonly ClientRegistrationStatus[]>;
|
||||
javascriptReplayCheck?(): Promise<DoctorCheck>;
|
||||
@@ -208,7 +207,7 @@ const collectDoctorIdentity = async (
|
||||
readonly value: DoctorIdentity;
|
||||
}> => {
|
||||
const installationPaths = (await host.installationPaths?.()) ?? [];
|
||||
const installedSkillIdentity = await readInstalledSkillIdentity(host);
|
||||
const installedSkillIdentity = await host.installedSkillIdentity?.();
|
||||
const skillAligned = skillIdentityAligned(installedSkillIdentity);
|
||||
const registrations = (await host.clientRegistrations?.()) ?? [];
|
||||
return {
|
||||
@@ -255,17 +254,6 @@ const collectDoctorIdentity = async (
|
||||
};
|
||||
};
|
||||
|
||||
const readInstalledSkillIdentity = async (
|
||||
host: DoctorHost,
|
||||
): Promise<InstalledSkillIdentity | undefined> => {
|
||||
const observed = await host.installedSkillIdentity?.();
|
||||
if (observed !== undefined) return observed;
|
||||
const legacyVersion = await host.installedSkillVersion?.();
|
||||
return legacyVersion === undefined
|
||||
? undefined
|
||||
: { version: legacyVersion, toolCount: null, catalogDigest: null };
|
||||
};
|
||||
|
||||
const skillIdentityAligned = (
|
||||
identity: InstalledSkillIdentity | undefined,
|
||||
): boolean =>
|
||||
@@ -383,7 +371,6 @@ export const systemDoctorHost = (
|
||||
return [];
|
||||
}
|
||||
},
|
||||
installedSkillVersion,
|
||||
installedSkillIdentity,
|
||||
clientRegistrations: () => readClientRegistrationStatuses(homedir()),
|
||||
});
|
||||
@@ -437,16 +424,6 @@ const readInstalledSkill = (): Promise<string> =>
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const installedSkillVersion = async (): Promise<string | undefined> => {
|
||||
try {
|
||||
return /^\s{2}version:\s*"([^"]+)"\s*$/mu.exec(
|
||||
await readInstalledSkill(),
|
||||
)?.[1];
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const installedSkillIdentity = async (): Promise<
|
||||
InstalledSkillIdentity | undefined
|
||||
> => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import { realpath } from "node:fs/promises";
|
||||
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
@@ -7,8 +8,6 @@ import { digestJson } from "./JavaScriptReplayPlanning.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
@@ -90,14 +89,7 @@ const authorize = async (
|
||||
},
|
||||
"write",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return canonical;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { ElectronObservationPort } from "./ElectronObservationPort.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
@@ -8,8 +9,6 @@ import type {
|
||||
} from "../domain/electronObservation.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
@@ -96,14 +95,7 @@ const prepare = async (
|
||||
},
|
||||
"read",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return provider === undefined
|
||||
? err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { lstat, open, readdir, readlink } from "node:fs/promises";
|
||||
@@ -10,10 +11,6 @@ export interface SnapshotResult {
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
const isWithin = (candidate: string, root: string): boolean =>
|
||||
candidate === root ||
|
||||
candidate.startsWith(`${root.endsWith("/") ? root.slice(0, -1) : root}/`);
|
||||
|
||||
const hasSameIdentity = (
|
||||
before: Stats,
|
||||
after: Stats,
|
||||
@@ -101,7 +98,7 @@ export const snapshotRoots = async (
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
const safeTarget = isWithin(target, root)
|
||||
const safeTarget = isPathWithinRoot(root, target)
|
||||
? relative(root, target) || "."
|
||||
: "<outside-declared-root>";
|
||||
if (safeTarget === "<outside-declared-root>") truncated = true;
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import {
|
||||
lstat,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
unlink,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
||||
createStoreFileLock,
|
||||
removeStaleStoreFileLock,
|
||||
type StoreFileLock,
|
||||
} from "./StoreFileLock.js";
|
||||
import { lstat, readFile, realpath } from "node:fs/promises";
|
||||
import { basename, dirname, resolve } from "node:path";
|
||||
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
@@ -19,6 +18,7 @@ import {
|
||||
type InvestigationWorkspace,
|
||||
} from "../domain/investigationWorkspace.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
|
||||
|
||||
type WorkspaceResult<Value> = Result<Value, InvestigationWorkspaceError>;
|
||||
|
||||
@@ -108,7 +108,7 @@ export const writeRevisionedWorkspace = async <Document>(
|
||||
const bytes = Buffer.byteLength(encoded, "utf8");
|
||||
if (bytes > policy.maxBytes)
|
||||
return err(new InvestigationWorkspaceError("update", "too-large"));
|
||||
let lock: { readonly path: string; readonly handle: FileHandle } | undefined;
|
||||
let lock: StoreFileLock | undefined;
|
||||
try {
|
||||
const destination = await resolveDestination(path, policy.roots);
|
||||
if (destination === null)
|
||||
@@ -133,7 +133,7 @@ export const writeRevisionedWorkspace = async <Document>(
|
||||
} catch (cause: unknown) {
|
||||
return err(new InvestigationWorkspaceError("update", "io", { cause }));
|
||||
} finally {
|
||||
if (lock !== undefined) await releaseLock(lock);
|
||||
if (lock !== undefined) await lock.release();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -144,14 +144,10 @@ const resolveDestination = async (
|
||||
const requested = resolve(path);
|
||||
const canonicalParent = await realpath(dirname(requested));
|
||||
const destination = resolve(canonicalParent, basename(requested));
|
||||
for (const configuredRoot of roots) {
|
||||
const root = await realpath(resolve(configuredRoot));
|
||||
const relation = relative(root, destination);
|
||||
if (
|
||||
relation === "" ||
|
||||
(!relation.startsWith("..") && !isAbsolute(relation))
|
||||
)
|
||||
return destination;
|
||||
for (const root of await canonicalizeConfiguredRoots(
|
||||
roots.map((configuredRoot) => resolve(configuredRoot)),
|
||||
)) {
|
||||
if (isPathWithinRoot(root, destination)) return destination;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
@@ -192,16 +188,14 @@ const readWorkspaceFile = async <Document>(
|
||||
|
||||
const acquireLock = async (
|
||||
destination: string,
|
||||
): Promise<
|
||||
WorkspaceResult<{ readonly path: string; readonly handle: FileHandle }>
|
||||
> => {
|
||||
): Promise<WorkspaceResult<StoreFileLock>> => {
|
||||
const path = `${destination}.lock`;
|
||||
try {
|
||||
return ok(await createLock(path));
|
||||
return ok(await createStoreFileLock(path));
|
||||
} catch (cause: unknown) {
|
||||
if (isAlreadyExists(cause) && (await removeStaleLock(path))) {
|
||||
if (isAlreadyExists(cause) && (await removeStaleStoreFileLock(path))) {
|
||||
try {
|
||||
return ok(await createLock(path));
|
||||
return ok(await createStoreFileLock(path));
|
||||
} catch (retryCause: unknown) {
|
||||
return err(
|
||||
new InvestigationWorkspaceError(
|
||||
@@ -222,54 +216,6 @@ const acquireLock = async (
|
||||
}
|
||||
};
|
||||
|
||||
const createLock = async (
|
||||
path: string,
|
||||
): Promise<{ readonly path: string; readonly handle: FileHandle }> => {
|
||||
const handle = await open(path, "wx", 0o600);
|
||||
try {
|
||||
await handle.writeFile(`${String(process.pid)}\n`, "utf8");
|
||||
await handle.sync();
|
||||
return { path, handle };
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
await unlink(path).catch(() => undefined);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const removeStaleLock = async (path: string): Promise<boolean> => {
|
||||
try {
|
||||
const stats = await lstat(path);
|
||||
if (!stats.isFile() || stats.isSymbolicLink() || stats.size > 32)
|
||||
return false;
|
||||
const encoded = (await readFile(path, "utf8")).trim();
|
||||
if (!/^[1-9][0-9]{0,9}$/u.test(encoded)) return false;
|
||||
const pid = Number(encoded);
|
||||
if (processIsAlive(pid)) return false;
|
||||
await unlink(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const processIsAlive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
return errorCode(cause) !== "ESRCH";
|
||||
}
|
||||
};
|
||||
|
||||
const releaseLock = async (lock: {
|
||||
readonly path: string;
|
||||
readonly handle: FileHandle;
|
||||
}): Promise<void> => {
|
||||
await lock.handle.close().catch(() => undefined);
|
||||
await unlink(lock.path).catch(() => undefined);
|
||||
};
|
||||
|
||||
function validateNextRevision(
|
||||
current: InvestigationWorkspace | null,
|
||||
next: InvestigationWorkspace,
|
||||
|
||||
@@ -207,6 +207,8 @@ const prepareSide = async (
|
||||
if (remaining <= 0)
|
||||
throw new RangeError("Replay module bytes exceed the aggregate limit");
|
||||
const source = await host.readSource(module.path, remaining);
|
||||
if (source.bytes.byteLength > remaining)
|
||||
throw new RangeError("Replay module bytes exceed the aggregate limit");
|
||||
totalBytes += source.bytes.byteLength;
|
||||
loaded.push({ module, source });
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import { z } from "zod";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
@@ -14,7 +15,6 @@ import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
ReplayPlanStaleError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
@@ -170,14 +170,7 @@ const authorizeReplay = async (
|
||||
input.mode === "plan"
|
||||
? await dependencies.authority.explain(request, "read")
|
||||
: await dependencies.authority.authorize(request, "read");
|
||||
if (!authorized.ok)
|
||||
return err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return ok(policy);
|
||||
};
|
||||
|
||||
@@ -235,13 +228,7 @@ const authorizeReproducerExport = async (
|
||||
"write",
|
||||
);
|
||||
if (!exportAuthorized.ok)
|
||||
return err(
|
||||
exportAuthorized.error instanceof PermissionRequiredError
|
||||
? exportAuthorized.error
|
||||
: new AnalysisProtocolError(exportAuthorized.error.message, {
|
||||
cause: exportAuthorized.error,
|
||||
}),
|
||||
);
|
||||
return err(projectPermissionFailure(exportAuthorized.error));
|
||||
const canonicalExportPath = exportAuthorized.value.request.roots[0];
|
||||
if (canonicalExportPath !== input.reproducer_export.path)
|
||||
return err(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { JavaScriptRuntimeObservationPort } from "./JavaScriptRuntimeObservationPort.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
@@ -5,8 +6,6 @@ import { createJavaScriptRuntimeObservationEvidence } from "./JavaScriptRuntimeO
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type {
|
||||
@@ -96,14 +95,7 @@ const prepare = async (
|
||||
},
|
||||
"read",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return provider === undefined
|
||||
? err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
|
||||
@@ -15,11 +15,16 @@ import {
|
||||
} from "../domain/errors.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { parseBinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { inspectManagedMembersBytes } from "../dotnet/ManagedMemberInspector.js";
|
||||
import { MANAGED_STATIC_PROVIDER } from "./InvestigationProviders.js";
|
||||
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
|
||||
import {
|
||||
type ManagedMemberInspectionLimits,
|
||||
inspectManagedMembersBytes,
|
||||
} from "../dotnet/ManagedMemberInspector.js";
|
||||
import {
|
||||
MANAGED_STATIC_PROVIDER,
|
||||
MANAGED_WORKFLOW_PROVIDER,
|
||||
} from "./InvestigationProviders.js";
|
||||
|
||||
/** Compare managed members from input parsed by a trusted adapter. */
|
||||
export const compareManagedMembersEvidenceValidated = (
|
||||
@@ -140,24 +145,10 @@ export const compareManagedMemberPaths = async (input: {
|
||||
}
|
||||
};
|
||||
|
||||
export interface ManagedMemberPathInspectionLimits {
|
||||
/** Byte-inspection limits plus the file admission bound for path comparisons. */
|
||||
export interface ManagedMemberPathInspectionLimits
|
||||
extends ManagedMemberInspectionLimits {
|
||||
readonly maxFileBytes: number;
|
||||
readonly typeOffset: number;
|
||||
readonly typeLimit: number;
|
||||
readonly methodOffset: number;
|
||||
readonly methodLimit: number;
|
||||
readonly fieldOffset: number;
|
||||
readonly fieldLimit: number;
|
||||
readonly memberRefOffset: number;
|
||||
readonly memberRefLimit: number;
|
||||
readonly edgeOffset: number;
|
||||
readonly edgeLimit: number;
|
||||
readonly instructionAnchorLimit: number;
|
||||
readonly maxMetadataBytes: number;
|
||||
readonly maxTableRows: number;
|
||||
readonly maxHeapItemBytes: number;
|
||||
readonly maxMethodBodyBytes: number;
|
||||
readonly maxMethodInstructions: number;
|
||||
}
|
||||
|
||||
const createManagedMemberComparisonEvidence = (
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import {
|
||||
@@ -99,14 +99,7 @@ export const planManagedRuntimeCorrelationEvidenceValidated = async (
|
||||
"read",
|
||||
{ remediation: "restart" },
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
try {
|
||||
const result = planManagedRuntimeCorrelation(
|
||||
input,
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
} from "../domain/errors.js";
|
||||
import type { PermissionPathError } from "./PermissionAuthority.js";
|
||||
|
||||
/** Preserve permission denials and project failed path resolution for callers. */
|
||||
export const projectPermissionFailure = (
|
||||
error: PermissionRequiredError | PermissionPathError,
|
||||
): PermissionRequiredError | AnalysisProtocolError =>
|
||||
error instanceof PermissionRequiredError
|
||||
? error
|
||||
: new AnalysisProtocolError(error.message, { cause: error });
|
||||
@@ -1,4 +1,5 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
|
||||
import type {
|
||||
EnabledProcessExecutionPolicy,
|
||||
@@ -10,10 +11,6 @@ import {
|
||||
} from "./ProcessCaptureError.js";
|
||||
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
|
||||
|
||||
const isWithin = (candidate: string, root: string): boolean =>
|
||||
candidate === root ||
|
||||
candidate.startsWith(`${root.endsWith("/") ? root.slice(0, -1) : root}/`);
|
||||
|
||||
export const assertRealPathAuthority = async (
|
||||
scenario: ProcessScenario,
|
||||
policy: EnabledProcessExecutionPolicy,
|
||||
@@ -22,28 +19,28 @@ export const assertRealPathAuthority = async (
|
||||
const executableRoots = await canonicalizeConfiguredRoots(
|
||||
policy.executableRoots,
|
||||
);
|
||||
if (!executableRoots.some((root) => isWithin(executable, root)))
|
||||
if (!executableRoots.some((root) => isPathWithinRoot(root, executable)))
|
||||
throw new ProcessCaptureError(
|
||||
"resolved executable is outside approved roots",
|
||||
);
|
||||
const workingDirectory = await realpath(scenario.working_directory);
|
||||
const workingRoots = await canonicalizeConfiguredRoots(policy.workingRoots);
|
||||
if (!workingRoots.some((root) => isWithin(workingDirectory, root)))
|
||||
if (!workingRoots.some((root) => isPathWithinRoot(root, workingDirectory)))
|
||||
throw new ProcessCaptureError(
|
||||
"resolved working directory is outside approved roots",
|
||||
);
|
||||
for (const root of scenario.filesystem_roots) {
|
||||
const resolvedRoot = await realpath(root);
|
||||
if (!workingRoots.some((approved) => isWithin(resolvedRoot, approved)))
|
||||
if (
|
||||
!workingRoots.some((approved) => isPathWithinRoot(approved, resolvedRoot))
|
||||
)
|
||||
throw new ProcessCaptureError(
|
||||
"resolved filesystem root is outside approved roots",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** Expected refusal or runtime failure from the process capture adapter. */
|
||||
/** Reject cancellation before a process capture operation begins. */
|
||||
export const assertNotCancelled = (signal: AbortSignal | undefined): void => {
|
||||
if (signal?.aborted === true) throw processCaptureCancelled();
|
||||
};
|
||||
|
||||
/** Runtime availability of the native PTY adapter on this host. */
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { parseConfig } from "../config.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
projectAnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { createEvidence, parseEvidence } from "../domain/evidence.js";
|
||||
@@ -57,13 +56,7 @@ export const captureProcessScenarioFile = async (path: string) => {
|
||||
"read",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return cliAnalysisError(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
return cliAnalysisError(projectPermissionFailure(authorized.error));
|
||||
const captured = await captureProcessScenario(
|
||||
scenario,
|
||||
config.value.processExecutionPolicy,
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import {
|
||||
createStoreFileLock,
|
||||
removeStaleStoreFileLock,
|
||||
type StoreFileLock,
|
||||
} from "./StoreFileLock.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import {
|
||||
lstat,
|
||||
mkdir,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
unlink,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
@@ -15,30 +18,15 @@ import { setTimeout as delay } from "node:timers/promises";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { PermissionGrant } from "../domain/permissionPolicy.js";
|
||||
import {
|
||||
PERMISSION_CAPABILITIES,
|
||||
type PermissionGrant,
|
||||
} from "../domain/permissionPolicy.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
const grantSchema = z.object({
|
||||
grant_id: z.string().min(1),
|
||||
capability: z.enum([
|
||||
"process_capture",
|
||||
"browser_observe",
|
||||
"browser_automate",
|
||||
"electron_observe",
|
||||
"electron_automate",
|
||||
"evidence_read",
|
||||
"evidence_write",
|
||||
"investigation_input",
|
||||
"investigation_workspace_read",
|
||||
"investigation_workspace_write",
|
||||
"snapshot_read",
|
||||
"snapshot_write",
|
||||
"artifact_extract",
|
||||
"native_mount",
|
||||
"reference_read",
|
||||
"javascript_replay",
|
||||
"managed_runtime",
|
||||
]),
|
||||
capability: z.enum(PERMISSION_CAPABILITIES),
|
||||
roots: z.array(z.string()),
|
||||
executables: z.array(z.string()),
|
||||
environment_names: z.array(z.string()),
|
||||
@@ -156,27 +144,28 @@ export const writeProjectPermissionStore = async (
|
||||
);
|
||||
if (process.getuid === undefined)
|
||||
return err(new ProjectPermissionStoreError("not_owner_only"));
|
||||
try {
|
||||
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
||||
await writeFileAtomic(
|
||||
path,
|
||||
`${JSON.stringify(candidate.data, null, 2)}\n`,
|
||||
{
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
},
|
||||
);
|
||||
const verified = await readProjectPermissionStore(path, projectRoot);
|
||||
if (!verified.ok) return verified;
|
||||
if (
|
||||
verified.value === null ||
|
||||
JSON.stringify(verified.value) !== JSON.stringify(candidate.data)
|
||||
)
|
||||
return err(new ProjectPermissionStoreError("invalid"));
|
||||
return ok(candidate.data);
|
||||
} catch (cause: unknown) {
|
||||
return err(new ProjectPermissionStoreError("io", { cause }));
|
||||
}
|
||||
return withPermissionStoreLock(path, () =>
|
||||
writePreparedPermissionStore(path, projectRoot, candidate.data),
|
||||
);
|
||||
};
|
||||
|
||||
const writePreparedPermissionStore = async (
|
||||
path: string,
|
||||
projectRoot: string,
|
||||
candidate: ProjectPermissionStore,
|
||||
): Promise<Result<ProjectPermissionStore, ProjectPermissionStoreError>> => {
|
||||
await writeFileAtomic(path, `${JSON.stringify(candidate, null, 2)}\n`, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
});
|
||||
const verified = await readProjectPermissionStore(path, projectRoot);
|
||||
if (!verified.ok) return verified;
|
||||
if (
|
||||
verified.value === null ||
|
||||
JSON.stringify(verified.value) !== JSON.stringify(candidate)
|
||||
)
|
||||
return err(new ProjectPermissionStoreError("invalid"));
|
||||
return ok(candidate);
|
||||
};
|
||||
|
||||
/** Revoke one grant while serializing the complete read-modify-write cycle. */
|
||||
@@ -184,47 +173,51 @@ export const revokeProjectPermissionGrant = async (
|
||||
path: string,
|
||||
projectRoot: string,
|
||||
grantId: string,
|
||||
): Promise<Result<boolean, ProjectPermissionStoreError>> => {
|
||||
let lock: PermissionStoreLock | undefined;
|
||||
): Promise<Result<boolean, ProjectPermissionStoreError>> =>
|
||||
withPermissionStoreLock(path, async () => {
|
||||
const current = await readProjectPermissionStore(path, projectRoot);
|
||||
if (!current.ok) return current;
|
||||
if (current.value === null) return ok(false);
|
||||
const retained = current.value.grants.filter(
|
||||
({ grant_id }) => grant_id !== grantId,
|
||||
);
|
||||
if (retained.length === current.value.grants.length) return ok(false);
|
||||
const written = await writePreparedPermissionStore(path, projectRoot, {
|
||||
...current.value,
|
||||
grants: retained,
|
||||
});
|
||||
return written.ok ? ok(true) : written;
|
||||
});
|
||||
|
||||
const withPermissionStoreLock = async <Value>(
|
||||
path: string,
|
||||
action: () => Promise<Result<Value, ProjectPermissionStoreError>>,
|
||||
): Promise<Result<Value, ProjectPermissionStoreError>> => {
|
||||
let lock: StoreFileLock | undefined;
|
||||
try {
|
||||
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
||||
const acquired = await acquirePermissionStoreLock(path);
|
||||
if (!acquired.ok) return acquired;
|
||||
lock = acquired.value;
|
||||
const current = await readProjectPermissionStore(path, projectRoot);
|
||||
if (!current.ok) return current;
|
||||
const grants = current.value?.grants ?? [];
|
||||
const retained = grants.filter(({ grant_id }) => grant_id !== grantId);
|
||||
if (retained.length === grants.length) return ok(false);
|
||||
const written = await writeProjectPermissionStore(
|
||||
path,
|
||||
projectRoot,
|
||||
retained,
|
||||
);
|
||||
return written.ok ? ok(true) : written;
|
||||
return await action();
|
||||
} catch (cause: unknown) {
|
||||
return err(new ProjectPermissionStoreError("io", { cause }));
|
||||
} finally {
|
||||
if (lock !== undefined) await releasePermissionStoreLock(lock);
|
||||
if (lock !== undefined) await lock.release();
|
||||
}
|
||||
};
|
||||
|
||||
interface PermissionStoreLock {
|
||||
readonly path: string;
|
||||
readonly handle: FileHandle;
|
||||
}
|
||||
|
||||
const acquirePermissionStoreLock = async (
|
||||
destination: string,
|
||||
): Promise<Result<PermissionStoreLock, ProjectPermissionStoreError>> => {
|
||||
): Promise<Result<StoreFileLock, ProjectPermissionStoreError>> => {
|
||||
const path = `${destination}.lock`;
|
||||
for (let attempt = 0; attempt < 100; attempt += 1) {
|
||||
try {
|
||||
return ok(await createPermissionStoreLock(path));
|
||||
return ok(await createStoreFileLock(path));
|
||||
} catch (cause: unknown) {
|
||||
if (!isAlreadyExists(cause))
|
||||
return err(new ProjectPermissionStoreError("io", { cause }));
|
||||
if (await removeStalePermissionStoreLock(path)) continue;
|
||||
if (await removeStaleStoreFileLock(path)) continue;
|
||||
if (attempt === 99)
|
||||
return err(new ProjectPermissionStoreError("locked", { cause }));
|
||||
await delay(10);
|
||||
@@ -233,54 +226,6 @@ const acquirePermissionStoreLock = async (
|
||||
return err(new ProjectPermissionStoreError("locked"));
|
||||
};
|
||||
|
||||
const createPermissionStoreLock = async (
|
||||
path: string,
|
||||
): Promise<PermissionStoreLock> => {
|
||||
const handle = await open(path, "wx", 0o600);
|
||||
try {
|
||||
await handle.writeFile(`${String(process.pid)}\n`, "utf8");
|
||||
await handle.sync();
|
||||
return { path, handle };
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
await unlink(path).catch(() => undefined);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const removeStalePermissionStoreLock = async (
|
||||
path: string,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
const metadata = await lstat(path);
|
||||
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 32)
|
||||
return false;
|
||||
const encoded = (await readFile(path, "utf8")).trim();
|
||||
if (!/^[1-9][0-9]{0,9}$/u.test(encoded)) return false;
|
||||
if (processIsAlive(Number(encoded))) return false;
|
||||
await unlink(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const processIsAlive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
return errorCode(cause) !== "ESRCH";
|
||||
}
|
||||
};
|
||||
|
||||
const releasePermissionStoreLock = async (
|
||||
lock: PermissionStoreLock,
|
||||
): Promise<void> => {
|
||||
await lock.handle.close().catch(() => undefined);
|
||||
await unlink(lock.path).catch(() => undefined);
|
||||
};
|
||||
|
||||
const isNotFound = (cause: unknown): boolean => errorCode(cause) === "ENOENT";
|
||||
|
||||
const openPrivateStore = async (
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
import { isSecretLikePath } from "../domain/referenceSourceClassification.js";
|
||||
import {
|
||||
createHistoricalSourceGraph,
|
||||
@@ -20,20 +21,6 @@ export type {
|
||||
ReferenceSourceImportOptions,
|
||||
} from "./ReferenceSourceImportTypes.js";
|
||||
|
||||
const compareCodePoints = (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;
|
||||
};
|
||||
|
||||
const byCodePoint = (left: string, right: string): number =>
|
||||
compareCodePoints(left, right);
|
||||
|
||||
const failure = (
|
||||
code: ReferenceSourceImportError["code"],
|
||||
message: string,
|
||||
@@ -73,7 +60,7 @@ export const normalizeHistoricalSourceParseFailures = (
|
||||
): HistoricalSourceGraphInput["parse_failures"] =>
|
||||
[...failures]
|
||||
.sort((left, right) =>
|
||||
byCodePoint(
|
||||
compareUnicodeCodePoints(
|
||||
historicalSourceParseFailureKey(left),
|
||||
historicalSourceParseFailureKey(right),
|
||||
),
|
||||
@@ -107,7 +94,7 @@ const deriveLanguages = (
|
||||
: [],
|
||||
),
|
||||
),
|
||||
].sort(byCodePoint);
|
||||
].sort(compareUnicodeCodePoints);
|
||||
|
||||
const deriveManifests = (
|
||||
entries: HistoricalSourceGraphInput["entries"],
|
||||
@@ -118,7 +105,7 @@ const deriveManifests = (
|
||||
? [entry.path]
|
||||
: [],
|
||||
)
|
||||
.sort(byCodePoint);
|
||||
.sort(compareUnicodeCodePoints);
|
||||
|
||||
const deriveInventoryState = (
|
||||
input: Pick<
|
||||
@@ -155,9 +142,9 @@ const sortAndLimit = (
|
||||
maxExclusions: number,
|
||||
): HistoricalSourceGraphInput["exclusions"] => {
|
||||
const sorted = [...exclusions].sort((left, right) => {
|
||||
const byPath = byCodePoint(left.path, right.path);
|
||||
const byPath = compareUnicodeCodePoints(left.path, right.path);
|
||||
if (byPath !== 0) return byPath;
|
||||
return byCodePoint(left.reason, right.reason);
|
||||
return compareUnicodeCodePoints(left.reason, right.reason);
|
||||
});
|
||||
if (sorted.length <= maxExclusions) return sorted;
|
||||
return sorted.slice(0, maxExclusions);
|
||||
@@ -229,10 +216,10 @@ export const importReferenceSource = async (
|
||||
const uniqueFailures = normalizeHistoricalSourceParseFailures(parseFailures);
|
||||
|
||||
const sortedEntries = [...entries].sort((left, right) =>
|
||||
byCodePoint(left.path, right.path),
|
||||
compareUnicodeCodePoints(left.path, right.path),
|
||||
);
|
||||
const sortedExclusions = sortAndLimit(exclusions, limits.maxEntries);
|
||||
const sortedLimitations = [...limitations].sort(byCodePoint);
|
||||
const sortedLimitations = [...limitations].sort(compareUnicodeCodePoints);
|
||||
|
||||
const input: HistoricalSourceGraphInput = {
|
||||
schema: "HistoricalSourceGraph/v1",
|
||||
@@ -247,7 +234,7 @@ export const importReferenceSource = async (
|
||||
}),
|
||||
entries: sortedEntries,
|
||||
relationships: uniqueRelationships.sort((left, right) =>
|
||||
byCodePoint(relationshipKey(left), relationshipKey(right)),
|
||||
compareUnicodeCodePoints(relationshipKey(left), relationshipKey(right)),
|
||||
),
|
||||
parse_failures: uniqueFailures,
|
||||
exclusions: sortedExclusions,
|
||||
|
||||
@@ -5,7 +5,7 @@ import ignore from "ignore";
|
||||
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { ReferenceSourceLimits } from "../reference/ReferenceSourceReader.js";
|
||||
import { withinRoot } from "../reference/ReferenceSourceReaderPaths.js";
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
import {
|
||||
DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS,
|
||||
DEFAULT_REFERENCE_SOURCE_LIMITS,
|
||||
@@ -71,7 +71,7 @@ const authorizeRoot = async (
|
||||
approvedRoots.map((approvedRoot) => resolve(approvedRoot)),
|
||||
);
|
||||
for (const canonicalApproved of canonicalApprovedRoots) {
|
||||
if (withinRoot(canonicalApproved, canonicalRoot))
|
||||
if (isPathWithinRoot(canonicalApproved, canonicalRoot))
|
||||
return ok(canonicalRoot);
|
||||
}
|
||||
return err(
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import {
|
||||
parseClientConfiguration,
|
||||
serializeClientConfiguration,
|
||||
type ClientConfigurationDocument,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
|
||||
@@ -24,44 +27,59 @@ const defaultCommand = (): readonly string[] => [
|
||||
];
|
||||
|
||||
/** Back up, atomically update, and semantically read back one JSON MCP configuration. */
|
||||
export const configureJsonClient = async (
|
||||
export const configureJsonClient = (
|
||||
client: SetupClient,
|
||||
environment: SetupProviderEnvironment | string = {},
|
||||
environment: SetupProviderEnvironment = {},
|
||||
command: readonly string[] = defaultCommand(),
|
||||
): Promise<ClientConfigurationResult> =>
|
||||
configureClientDocument(client, environment, command, "json");
|
||||
|
||||
/** Back up, atomically update, and semantically read back one TOML MCP configuration. */
|
||||
export const configureTomlClient = (
|
||||
client: SetupClient,
|
||||
environment: SetupProviderEnvironment = {},
|
||||
command: readonly string[] = defaultCommand(),
|
||||
): Promise<ClientConfigurationResult> =>
|
||||
configureClientDocument(client, environment, command, "toml");
|
||||
|
||||
const configureClientDocument = async (
|
||||
client: SetupClient,
|
||||
environment: SetupProviderEnvironment,
|
||||
command: readonly string[],
|
||||
format: "json" | "toml",
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
const transactionPath = await resolveClientConfigTransactionPath(
|
||||
client.configPath,
|
||||
);
|
||||
if (transactionPath === undefined)
|
||||
return { status: "failed", reason: "path" };
|
||||
let document: Record<string, unknown> = {};
|
||||
let original: string | undefined;
|
||||
try {
|
||||
original = await readFile(transactionPath, "utf8");
|
||||
document = parseObject(original);
|
||||
} catch (cause: unknown) {
|
||||
if (!isMissing(cause)) return { status: "failed", reason: "readback" };
|
||||
}
|
||||
let servers: Record<string, unknown>;
|
||||
let parsed: ClientConfigurationDocument;
|
||||
try {
|
||||
servers = parseOptionalObject(document.mcpServers);
|
||||
parsed = parseClientConfiguration(
|
||||
original ?? (format === "toml" ? "" : "{}"),
|
||||
format,
|
||||
);
|
||||
} catch {
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
const desired = clientConfigurationDesired(
|
||||
client,
|
||||
normalizeProviderEnvironment(environment),
|
||||
command,
|
||||
);
|
||||
if (sameConfiguration(servers[PRODUCT_IDENTITY.mcpServerKey], desired))
|
||||
const { document, servers, serversKey } = parsed;
|
||||
const desired = clientConfigurationDesired(client, environment, command);
|
||||
if (isDeepStrictEqual(servers[PRODUCT_IDENTITY.mcpServerKey], desired))
|
||||
return { status: "unchanged" };
|
||||
let backupPath: string | undefined;
|
||||
if (original !== undefined) {
|
||||
backupPath = `${client.configPath}.rea.backup`;
|
||||
if (!(await preserveConfigBackup(transactionPath, backupPath)))
|
||||
return { status: "failed", reason: "backup" };
|
||||
}
|
||||
document.mcpServers = {
|
||||
const backupPath =
|
||||
original === undefined ? undefined : `${client.configPath}.rea.backup`;
|
||||
if (
|
||||
backupPath !== undefined &&
|
||||
!(await preserveConfigBackup(transactionPath, backupPath))
|
||||
)
|
||||
return { status: "failed", reason: "backup" };
|
||||
document[serversKey] = {
|
||||
...servers,
|
||||
[PRODUCT_IDENTITY.mcpServerKey]: desired,
|
||||
};
|
||||
@@ -69,7 +87,7 @@ export const configureJsonClient = async (
|
||||
await mkdir(dirname(client.configPath), { recursive: true });
|
||||
await writeFileAtomic(
|
||||
transactionPath,
|
||||
`${JSON.stringify(document, null, 2)}\n`,
|
||||
serializeClientConfiguration(document, format),
|
||||
{
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
@@ -79,10 +97,13 @@ export const configureJsonClient = async (
|
||||
return { status: "failed", reason: "write" };
|
||||
}
|
||||
try {
|
||||
const readback = parseObject(await readFile(transactionPath, "utf8"));
|
||||
const readback = parseClientConfiguration(
|
||||
await readFile(transactionPath, "utf8"),
|
||||
format,
|
||||
);
|
||||
if (
|
||||
!sameConfiguration(
|
||||
parseOptionalObject(readback.mcpServers)[PRODUCT_IDENTITY.mcpServerKey],
|
||||
!isDeepStrictEqual(
|
||||
readback.servers[PRODUCT_IDENTITY.mcpServerKey],
|
||||
desired,
|
||||
)
|
||||
) {
|
||||
@@ -99,77 +120,6 @@ export const configureJsonClient = async (
|
||||
};
|
||||
};
|
||||
|
||||
/** Back up, atomically update, and semantically read back Codex TOML configuration. */
|
||||
export const configureTomlClient = async (
|
||||
client: SetupClient,
|
||||
environment: SetupProviderEnvironment | string = {},
|
||||
command: readonly string[] = defaultCommand(),
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
const transactionPath = await resolveClientConfigTransactionPath(
|
||||
client.configPath,
|
||||
);
|
||||
if (transactionPath === undefined)
|
||||
return { status: "failed", reason: "path" };
|
||||
let document: Record<string, unknown> = {};
|
||||
let original: string | undefined;
|
||||
try {
|
||||
original = await readFile(transactionPath, "utf8");
|
||||
document = objectSchema.parse(parseToml(original));
|
||||
} catch (cause: unknown) {
|
||||
if (!isMissing(cause)) return { status: "failed", reason: "readback" };
|
||||
}
|
||||
let servers: Record<string, unknown>;
|
||||
try {
|
||||
servers = parseOptionalObject(document.mcp_servers);
|
||||
} catch {
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
const desired = clientConfigurationDesired(
|
||||
client,
|
||||
normalizeProviderEnvironment(environment),
|
||||
command,
|
||||
);
|
||||
if (sameConfiguration(servers[PRODUCT_IDENTITY.mcpServerKey], desired))
|
||||
return { status: "unchanged" };
|
||||
const backupPath =
|
||||
original === undefined ? undefined : `${client.configPath}.rea.backup`;
|
||||
if (
|
||||
backupPath !== undefined &&
|
||||
!(await preserveConfigBackup(transactionPath, backupPath))
|
||||
)
|
||||
return { status: "failed", reason: "backup" };
|
||||
document.mcp_servers = {
|
||||
...servers,
|
||||
[PRODUCT_IDENTITY.mcpServerKey]: desired,
|
||||
};
|
||||
try {
|
||||
await mkdir(dirname(client.configPath), { recursive: true });
|
||||
await writeFileAtomic(transactionPath, stringifyToml(document), {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
});
|
||||
const readback = objectSchema.parse(
|
||||
parseToml(await readFile(transactionPath, "utf8")),
|
||||
);
|
||||
if (
|
||||
!sameConfiguration(
|
||||
parseOptionalObject(readback.mcp_servers)[
|
||||
PRODUCT_IDENTITY.mcpServerKey
|
||||
],
|
||||
desired,
|
||||
)
|
||||
)
|
||||
throw new Error("TOML readback mismatch");
|
||||
} catch {
|
||||
await restoreConfig(transactionPath, original);
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
return {
|
||||
status: "configured",
|
||||
...(backupPath === undefined ? {} : { backupPath }),
|
||||
};
|
||||
};
|
||||
|
||||
/** Determine whether an existing client configuration matches the desired registration. */
|
||||
export const clientConfigurationAligned = async (
|
||||
client: SetupClient,
|
||||
@@ -183,14 +133,8 @@ export const clientConfigurationAligned = async (
|
||||
);
|
||||
try {
|
||||
const original = await readFile(client.configPath, "utf8");
|
||||
const document =
|
||||
client.format === "toml"
|
||||
? objectSchema.parse(parseToml(original))
|
||||
: parseObject(original);
|
||||
const servers = parseOptionalObject(
|
||||
client.format === "toml" ? document.mcp_servers : document.mcpServers,
|
||||
);
|
||||
return sameConfiguration(servers[PRODUCT_IDENTITY.mcpServerKey], desired);
|
||||
const { servers } = parseClientConfiguration(original, client.format);
|
||||
return isDeepStrictEqual(servers[PRODUCT_IDENTITY.mcpServerKey], desired);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@@ -229,14 +173,8 @@ export const inspectClientConfiguration = async (
|
||||
command,
|
||||
);
|
||||
try {
|
||||
const document =
|
||||
client.format === "toml"
|
||||
? objectSchema.parse(parseToml(original))
|
||||
: parseObject(original);
|
||||
const servers = parseOptionalObject(
|
||||
client.format === "toml" ? document.mcp_servers : document.mcpServers,
|
||||
);
|
||||
if (sameConfiguration(servers[PRODUCT_IDENTITY.mcpServerKey], desired))
|
||||
const { servers } = parseClientConfiguration(original, client.format);
|
||||
if (isDeepStrictEqual(servers[PRODUCT_IDENTITY.mcpServerKey], desired))
|
||||
return { status: "already_current" };
|
||||
} catch {
|
||||
return {
|
||||
@@ -251,19 +189,8 @@ export const inspectClientConfiguration = async (
|
||||
};
|
||||
};
|
||||
|
||||
const objectSchema = z.record(z.string(), z.unknown());
|
||||
const parseOptionalObject = (value: unknown): Record<string, unknown> =>
|
||||
value === undefined ? {} : objectSchema.parse(value);
|
||||
const parseObject = (text: string): Record<string, unknown> =>
|
||||
objectSchema.parse(JSON.parse(text));
|
||||
const isMissing = (cause: unknown): boolean =>
|
||||
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|
||||
const sameConfiguration = (left: unknown, right: unknown): boolean => {
|
||||
const encodedLeft = canonicalize(left);
|
||||
const encodedRight = canonicalize(right);
|
||||
return encodedLeft !== undefined && encodedLeft === encodedRight;
|
||||
};
|
||||
|
||||
const preserveConfigBackup = async (
|
||||
source: string,
|
||||
destination: string,
|
||||
@@ -309,10 +236,3 @@ const clientConfigurationDesired = (
|
||||
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
|
||||
};
|
||||
};
|
||||
|
||||
const normalizeProviderEnvironment = (
|
||||
environment: SetupProviderEnvironment | string,
|
||||
): SetupProviderEnvironment =>
|
||||
typeof environment === "string"
|
||||
? { HOPPER_LAUNCHER_PATH: environment }
|
||||
: environment;
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
lstat,
|
||||
mkdtemp,
|
||||
open,
|
||||
readdir,
|
||||
rename,
|
||||
rm,
|
||||
rmdir,
|
||||
unlink,
|
||||
} from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
|
||||
|
||||
/** One acquired store transaction lock with cleanup bound to its unique owner. */
|
||||
export interface StoreFileLock {
|
||||
readonly release: () => Promise<void>;
|
||||
}
|
||||
|
||||
class StoreFileLockOccupied extends Error {
|
||||
readonly code = "EEXIST";
|
||||
|
||||
constructor(cause?: unknown) {
|
||||
super("Store transaction lock is occupied", { cause });
|
||||
}
|
||||
}
|
||||
|
||||
/** Atomically publish a populated directory so another owner cannot replace a live lock. */
|
||||
export const createStoreFileLock = async (
|
||||
path: string,
|
||||
): Promise<StoreFileLock> => {
|
||||
if (await exists(path)) throw new StoreFileLockOccupied();
|
||||
const staged = await mkdtemp(join(dirname(path), ".rea-store-lock-"));
|
||||
const owner = `owner-${randomUUID()}`;
|
||||
try {
|
||||
const handle = await open(join(staged, owner), "wx", 0o600);
|
||||
try {
|
||||
await handle.writeFile(`${String(process.pid)}\n`, "utf8");
|
||||
await handle.sync();
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
try {
|
||||
// Rename cannot replace a nonempty directory: the owner entry is present before publication.
|
||||
await rename(staged, path);
|
||||
} catch (cause: unknown) {
|
||||
if (await exists(path)) throw new StoreFileLockOccupied(cause);
|
||||
throw cause;
|
||||
}
|
||||
return {
|
||||
release: async () => {
|
||||
await removeOwner(path, owner).catch(() => undefined);
|
||||
},
|
||||
};
|
||||
} finally {
|
||||
await rm(staged, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
/** Recover a dead owner's directory lock or a legacy PID file; leave live and unknown owners intact. */
|
||||
export const removeStaleStoreFileLock = async (
|
||||
path: string,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
const stats = await lstat(path);
|
||||
if (stats.isFile()) {
|
||||
if (!(await ownerIsDead(path))) return false;
|
||||
await unlink(path);
|
||||
return true;
|
||||
}
|
||||
if (!stats.isDirectory()) return false;
|
||||
const entries = await readdir(path);
|
||||
if (entries.length === 0) {
|
||||
await rmdir(path);
|
||||
return true;
|
||||
}
|
||||
const owner = entries[0];
|
||||
if (
|
||||
entries.length !== 1 ||
|
||||
owner === undefined ||
|
||||
!/^owner-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u.test(owner) ||
|
||||
!(await ownerIsDead(join(path, owner)))
|
||||
)
|
||||
return false;
|
||||
await removeOwner(path, owner);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const removeOwner = async (path: string, owner: string): Promise<void> => {
|
||||
// A successor has a different entry, so stale cleanup cannot make its directory empty.
|
||||
await unlink(join(path, owner));
|
||||
await rmdir(path);
|
||||
};
|
||||
|
||||
const ownerIsDead = async (path: string): Promise<boolean> => {
|
||||
const stats = await lstat(path);
|
||||
if (!stats.isFile() || stats.size > 32) return false;
|
||||
const handle = await open(path, "r");
|
||||
let bytes: Buffer | undefined;
|
||||
try {
|
||||
bytes = await readBoundedFileBytes(handle, 32);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
const encoded = bytes?.toString("utf8").trim();
|
||||
return (
|
||||
encoded !== undefined &&
|
||||
/^[1-9][0-9]{0,9}$/u.test(encoded) &&
|
||||
!processIsAlive(Number(encoded))
|
||||
);
|
||||
};
|
||||
|
||||
const exists = async (path: string): Promise<boolean> => {
|
||||
try {
|
||||
await lstat(path);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
if (errorCode(cause) === "ENOENT") return false;
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const processIsAlive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
return errorCode(cause) !== "ESRCH";
|
||||
}
|
||||
};
|
||||
|
||||
const errorCode = (cause: unknown): unknown =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
@@ -1,8 +1,11 @@
|
||||
import {
|
||||
parseClientConfiguration,
|
||||
serializeClientConfiguration,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { copyFile, lstat, readFile, realpath, rm } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { basename, isAbsolute, join } from "node:path";
|
||||
|
||||
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -123,11 +126,11 @@ const removeClient = async (
|
||||
let key: "mcp_servers" | "mcpServers";
|
||||
let servers: Record<string, unknown>;
|
||||
try {
|
||||
document = objectSchema.parse(
|
||||
client.format === "toml" ? parseToml(original) : JSON.parse(original),
|
||||
);
|
||||
key = client.format === "toml" ? "mcp_servers" : "mcpServers";
|
||||
servers = optionalObject(document[key]);
|
||||
({
|
||||
document,
|
||||
servers,
|
||||
serversKey: key,
|
||||
} = parseClientConfiguration(original, client.format));
|
||||
} catch {
|
||||
return item(
|
||||
client.name,
|
||||
@@ -158,17 +161,15 @@ const removeClient = async (
|
||||
);
|
||||
}
|
||||
try {
|
||||
const encoded =
|
||||
client.format === "toml"
|
||||
? stringifyToml(document)
|
||||
: `${JSON.stringify(document, null, 2)}\n`;
|
||||
await fileSystem.writeText(transactionPath, encoded);
|
||||
const readback = objectSchema.parse(
|
||||
client.format === "toml"
|
||||
? parseToml(await fileSystem.readText(transactionPath))
|
||||
: JSON.parse(await fileSystem.readText(transactionPath)),
|
||||
await fileSystem.writeText(
|
||||
transactionPath,
|
||||
serializeClientConfiguration(document, client.format),
|
||||
);
|
||||
if (PRODUCT_IDENTITY.mcpServerKey in optionalObject(readback[key]))
|
||||
const readback = parseClientConfiguration(
|
||||
await fileSystem.readText(transactionPath),
|
||||
client.format,
|
||||
);
|
||||
if (PRODUCT_IDENTITY.mcpServerKey in readback.servers)
|
||||
throw new Error("registration readback mismatch");
|
||||
return item(
|
||||
client.name,
|
||||
@@ -278,9 +279,6 @@ const item = (
|
||||
status: UninstallItem["status"],
|
||||
detail: string,
|
||||
): UninstallItem => ({ name, status, detail });
|
||||
const objectSchema = z.record(z.string(), z.unknown());
|
||||
const optionalObject = (value: unknown): Record<string, unknown> =>
|
||||
value === undefined ? {} : objectSchema.parse(value);
|
||||
const registrationSchema = z
|
||||
.object({ command: z.string(), args: z.array(z.string()) })
|
||||
.passthrough();
|
||||
|
||||
@@ -86,20 +86,24 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
entry.adapterKey,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW,
|
||||
);
|
||||
const observed = await handle.stat();
|
||||
if (
|
||||
!observed.isFile() ||
|
||||
entry.sourceIdentity === undefined ||
|
||||
observed.dev !== entry.sourceIdentity.device ||
|
||||
observed.ino !== entry.sourceIdentity.inode
|
||||
) {
|
||||
await handle.close();
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Directory entry changed before open: ${entry.path}`,
|
||||
);
|
||||
try {
|
||||
const observed = await handle.stat();
|
||||
if (
|
||||
!observed.isFile() ||
|
||||
entry.sourceIdentity === undefined ||
|
||||
observed.dev !== entry.sourceIdentity.device ||
|
||||
observed.ino !== entry.sourceIdentity.inode
|
||||
) {
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Directory entry changed before open: ${entry.path}`,
|
||||
);
|
||||
}
|
||||
return handle.createReadStream({ autoClose: true });
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
throw cause;
|
||||
}
|
||||
return handle.createReadStream({ autoClose: true });
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, mkdir, open, realpath, rm } from "node:fs/promises";
|
||||
import {
|
||||
lstat,
|
||||
mkdir,
|
||||
open,
|
||||
realpath,
|
||||
rm,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
||||
import type { Readable } from "node:stream";
|
||||
import { streamChunkToBuffer } from "./StreamBytes.js";
|
||||
@@ -35,20 +42,14 @@ export class SafeOutputTree {
|
||||
readonly #registry = new ArtifactPathRegistry();
|
||||
readonly #limits: ArtifactLimits;
|
||||
readonly #outputRoot: string;
|
||||
readonly #stagingRoot: string;
|
||||
#totalBytes = 0;
|
||||
#published = false;
|
||||
#cleanup: SafeOutputCleanup = {
|
||||
status: "not-required",
|
||||
};
|
||||
|
||||
private constructor(
|
||||
outputRoot: string,
|
||||
stagingRoot: string,
|
||||
limits: ArtifactLimits,
|
||||
) {
|
||||
private constructor(outputRoot: string, limits: ArtifactLimits) {
|
||||
this.#outputRoot = outputRoot;
|
||||
this.#stagingRoot = stagingRoot;
|
||||
this.#limits = limits;
|
||||
}
|
||||
|
||||
@@ -95,7 +96,7 @@ export class SafeOutputTree {
|
||||
} finally {
|
||||
await stagingHandle.close();
|
||||
}
|
||||
return new SafeOutputTree(canonicalOutput, canonicalOutput, limits);
|
||||
return new SafeOutputTree(canonicalOutput, limits);
|
||||
} catch (cause: unknown) {
|
||||
await rm(canonicalOutput, { recursive: true, force: true });
|
||||
throw cause;
|
||||
@@ -184,12 +185,13 @@ export class SafeOutputTree {
|
||||
dirname(this.#outputRoot),
|
||||
constants.O_RDONLY | constants.O_DIRECTORY,
|
||||
);
|
||||
const staging = await open(
|
||||
this.#stagingRoot,
|
||||
constants.O_RDONLY | constants.O_DIRECTORY,
|
||||
);
|
||||
let output: FileHandle | undefined;
|
||||
try {
|
||||
await staging.sync();
|
||||
output = await open(
|
||||
this.#outputRoot,
|
||||
constants.O_RDONLY | constants.O_DIRECTORY,
|
||||
);
|
||||
await output.sync();
|
||||
await parent.sync();
|
||||
this.#published = true;
|
||||
} catch (cause: unknown) {
|
||||
@@ -199,20 +201,20 @@ export class SafeOutputTree {
|
||||
{ cause },
|
||||
);
|
||||
} finally {
|
||||
await Promise.allSettled([parent.close(), staging.close()]);
|
||||
await Promise.allSettled([parent.close(), output?.close()]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove only this operation's unsealed tree and verify absence. */
|
||||
async rollback(): Promise<SafeOutputCleanup> {
|
||||
if (this.#published) return structuredClone(this.#cleanup);
|
||||
await rm(this.#stagingRoot, { recursive: true, force: true });
|
||||
const absent = await isAbsent(this.#stagingRoot);
|
||||
await rm(this.#outputRoot, { recursive: true, force: true });
|
||||
const absent = await isAbsent(this.#outputRoot);
|
||||
this.#cleanup = absent
|
||||
? { status: "complete", residualPaths: [] }
|
||||
: {
|
||||
status: "incomplete",
|
||||
residualPaths: [basename(this.#stagingRoot)],
|
||||
residualPaths: [basename(this.#outputRoot)],
|
||||
};
|
||||
if (!absent)
|
||||
throw new ArtifactReaderFailure(
|
||||
@@ -227,7 +229,7 @@ export class SafeOutputTree {
|
||||
const fileName = parts.pop();
|
||||
if (fileName === undefined)
|
||||
throw new ArtifactReaderFailure("path", "Invalid extraction path");
|
||||
let current = this.#stagingRoot;
|
||||
let current = this.#outputRoot;
|
||||
for (const part of parts) {
|
||||
current = join(current, part);
|
||||
await mkdir(current, { mode: 0o700 }).catch((cause: unknown) => {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { isAbsolute, relative } from "node:path";
|
||||
import { isAbsolute } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
/** Canonicalize operator roots before evaluating any Electron file target. */
|
||||
export const canonicalElectronRoots = async (
|
||||
roots: readonly string[],
|
||||
@@ -43,14 +44,7 @@ export const authorizedElectronFile = async (
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
return roots.some((root) => withinRoot(root, canonical))
|
||||
return roots.some((root) => isPathWithinRoot(root, canonical))
|
||||
? canonical
|
||||
: undefined;
|
||||
};
|
||||
|
||||
const withinRoot = (root: string, path: string): boolean => {
|
||||
const remainder = relative(root, path);
|
||||
return (
|
||||
remainder === "" || (!remainder.startsWith("..") && !isAbsolute(remainder))
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
import { Cli, z } from "incur";
|
||||
|
||||
import { browserContext, browserCliError } from "./cliBrowserContext.js";
|
||||
import { browserScopeOptions } from "./cliObservationOptions.js";
|
||||
import {
|
||||
captureWebScreenshot,
|
||||
compareWebCaptureEvidence,
|
||||
compareWebScreenshotEvidence,
|
||||
discoverWebMcpTools,
|
||||
} from "./application/BrowserObservationService.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import { CdpBrowserProvider } from "./browser/CdpBrowserProvider.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
projectAnalysisError,
|
||||
} from "./domain/errors.js";
|
||||
import { AnalysisInputError } from "./domain/errors.js";
|
||||
import { browserCaptureComparisonInputSchema } from "./domain/browserCaptureComparison.js";
|
||||
import { discoverWebMcpToolsInputSchema } from "./domain/webMcpDiscovery.js";
|
||||
import {
|
||||
@@ -25,16 +21,6 @@ import type { JsonValue } from "./domain/jsonValue.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
|
||||
const scopeOptions = {
|
||||
allowedOrigins: z
|
||||
.array(z.string().min(1))
|
||||
.optional()
|
||||
.describe(
|
||||
"Exact origins to observe; defaults to REA_BROWSER_ALLOWED_ORIGINS_JSON",
|
||||
),
|
||||
approved: z.boolean().default(false).describe("Approve passive observation"),
|
||||
};
|
||||
|
||||
/** Register WebMCP, capture-diff, and screenshot CLI equivalents. */
|
||||
export const registerAdvancedBrowserCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
@@ -57,7 +43,7 @@ const registerWebMcp = (
|
||||
targetId: z.string().describe("Target ID from list-browser-targets"),
|
||||
}),
|
||||
options: z.object({
|
||||
...scopeOptions,
|
||||
...browserScopeOptions,
|
||||
observationMs: z
|
||||
.number()
|
||||
.int()
|
||||
@@ -116,7 +102,7 @@ const registerWebMcp = (
|
||||
context.authority,
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -170,7 +156,7 @@ const registerCaptureDiff = (
|
||||
new CdpBrowserProvider(),
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -186,7 +172,7 @@ const registerScreenshot = (
|
||||
targetId: z.string().describe("Target ID from list-browser-targets"),
|
||||
}),
|
||||
options: z.object({
|
||||
...scopeOptions,
|
||||
...browserScopeOptions,
|
||||
screenshotApproved: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
@@ -218,7 +204,7 @@ const registerScreenshot = (
|
||||
context.authority,
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -262,37 +248,11 @@ const registerScreenshotDiff = (
|
||||
new CdpBrowserProvider(),
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const browserContext = async (operation: string) => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok) return { ok: false as const, error: cliError(config.error) };
|
||||
const policy = config.value.browserObservationPolicy;
|
||||
if (policy.status === "disabled")
|
||||
return {
|
||||
ok: false as const,
|
||||
error: cliError(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-cdp-browser",
|
||||
operation,
|
||||
"browser observation is disabled; configure exact endpoints and origins before enabling it",
|
||||
),
|
||||
),
|
||||
};
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok)
|
||||
return { ok: false as const, error: cliError(authority.error) };
|
||||
return {
|
||||
ok: true as const,
|
||||
authority: authority.value,
|
||||
provider: new CdpBrowserProvider(),
|
||||
allowedBrowserOrigins: policy.allowedOrigins,
|
||||
};
|
||||
};
|
||||
|
||||
const parseJson = (value: string): unknown => {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
@@ -302,11 +262,4 @@ const parseJson = (value: string): unknown => {
|
||||
};
|
||||
|
||||
const inputError = (operation: string): JsonValue =>
|
||||
cliError(new AnalysisInputError(operation));
|
||||
|
||||
const cliError = (
|
||||
error: Parameters<typeof projectAnalysisError>[0],
|
||||
): JsonValue => ({
|
||||
error: "Browser observation failed",
|
||||
...projectAnalysisError(error),
|
||||
});
|
||||
browserCliError(new AnalysisInputError(operation));
|
||||
|
||||
+18
-78
@@ -1,57 +1,28 @@
|
||||
import { Cli, z } from "incur";
|
||||
|
||||
import { browserContext, browserCliError } from "./cliBrowserContext.js";
|
||||
import {
|
||||
analyzeWebBundle,
|
||||
inspectWebPage,
|
||||
listBrowserTargets,
|
||||
observeWebSession,
|
||||
} from "./application/BrowserObservationService.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import { CdpBrowserProvider } from "./browser/CdpBrowserProvider.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import {
|
||||
inspectWebPageInputSchema,
|
||||
listBrowserTargetsInputSchema,
|
||||
} from "./domain/browserObservation.js";
|
||||
import { analyzeWebBundleInputSchema } from "./domain/webBundleAnalysis.js";
|
||||
import { observeWebSessionInputSchema } from "./domain/browserSession.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
projectAnalysisError,
|
||||
} from "./domain/errors.js";
|
||||
import type { JsonValue } from "./domain/jsonValue.js";
|
||||
import { AnalysisInputError } from "./domain/errors.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
import { browserPageInspectionOptions } from "./cliObservationOptions.js";
|
||||
|
||||
const browserScopeOptions = {
|
||||
allowedOrigins: z
|
||||
.array(z.string().min(1))
|
||||
.optional()
|
||||
.describe(
|
||||
"Exact origins to observe; defaults to REA_BROWSER_ALLOWED_ORIGINS_JSON",
|
||||
),
|
||||
approved: z.boolean().default(false).describe("Approve passive observation"),
|
||||
};
|
||||
|
||||
const boundedCount = (
|
||||
subject: string,
|
||||
maximum: number,
|
||||
fallback: number,
|
||||
minimum = 1,
|
||||
) =>
|
||||
z
|
||||
.number()
|
||||
.int()
|
||||
.min(minimum)
|
||||
.max(maximum)
|
||||
.default(fallback)
|
||||
.describe(`Maximum ${subject}`);
|
||||
|
||||
const boundedBytes = (subject: string, maximum: number, fallback: number) =>
|
||||
boundedCount(`${subject} in bytes`, maximum, fallback);
|
||||
import {
|
||||
browserPageInspectionOptions,
|
||||
browserScopeOptions,
|
||||
boundedCount,
|
||||
boundedBytes,
|
||||
} from "./cliObservationOptions.js";
|
||||
|
||||
/** Register CLI equivalents of the passive browser MCP tools. */
|
||||
export const registerBrowserCommands = (
|
||||
@@ -96,13 +67,15 @@ const registerTargetList = (
|
||||
limit: options.limit,
|
||||
});
|
||||
if (!parsed.success)
|
||||
return cliError(new AnalysisInputError("list_browser_targets"));
|
||||
return browserCliError(
|
||||
new AnalysisInputError("list_browser_targets"),
|
||||
);
|
||||
const result = await listBrowserTargets(
|
||||
context.provider,
|
||||
context.authority,
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -167,13 +140,13 @@ const registerPageInspection = (
|
||||
},
|
||||
});
|
||||
if (!parsed.success)
|
||||
return cliError(new AnalysisInputError("inspect_web_page"));
|
||||
return browserCliError(new AnalysisInputError("inspect_web_page"));
|
||||
const result = await inspectWebPage(
|
||||
context.provider,
|
||||
context.authority,
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -256,13 +229,13 @@ const registerBundleAnalysis = (
|
||||
},
|
||||
});
|
||||
if (!parsed.success)
|
||||
return cliError(new AnalysisInputError("analyze_web_bundle"));
|
||||
return browserCliError(new AnalysisInputError("analyze_web_bundle"));
|
||||
const result = await analyzeWebBundle(
|
||||
context.provider,
|
||||
context.authority,
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -300,46 +273,13 @@ const registerObservationSession = (
|
||||
max_timeline_events: options.maxTimelineEvents,
|
||||
});
|
||||
if (!parsed.success)
|
||||
return cliError(new AnalysisInputError("observe_web_session"));
|
||||
return browserCliError(new AnalysisInputError("observe_web_session"));
|
||||
const result = await observeWebSession(
|
||||
context.provider,
|
||||
context.authority,
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
return result.ok ? result.value : browserCliError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const browserContext = async (operation: string) => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok) return { ok: false as const, error: cliError(config.error) };
|
||||
const policy = config.value.browserObservationPolicy;
|
||||
if (policy.status === "disabled")
|
||||
return {
|
||||
ok: false as const,
|
||||
error: cliError(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-cdp-browser",
|
||||
operation,
|
||||
"browser observation is disabled; configure exact endpoints and origins before enabling it",
|
||||
),
|
||||
),
|
||||
};
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok)
|
||||
return { ok: false as const, error: cliError(authority.error) };
|
||||
return {
|
||||
ok: true as const,
|
||||
authority: authority.value,
|
||||
provider: new CdpBrowserProvider(),
|
||||
allowedBrowserOrigins: policy.allowedOrigins,
|
||||
};
|
||||
};
|
||||
|
||||
const cliError = (
|
||||
error: Parameters<typeof projectAnalysisError>[0],
|
||||
): JsonValue => ({
|
||||
error: "Browser observation failed",
|
||||
...projectAnalysisError(error),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import { CdpBrowserProvider } from "./browser/CdpBrowserProvider.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
projectAnalysisError,
|
||||
} from "./domain/errors.js";
|
||||
import type { JsonValue } from "./domain/jsonValue.js";
|
||||
|
||||
/** Load the configured passive browser authority and provider for one CLI operation. */
|
||||
export const browserContext = async (operation: string) => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return { ok: false as const, error: browserCliError(config.error) };
|
||||
const policy = config.value.browserObservationPolicy;
|
||||
if (policy.status === "disabled")
|
||||
return {
|
||||
ok: false as const,
|
||||
error: browserCliError(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-cdp-browser",
|
||||
operation,
|
||||
"browser observation is disabled; configure exact endpoints and origins before enabling it",
|
||||
),
|
||||
),
|
||||
};
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok)
|
||||
return { ok: false as const, error: browserCliError(authority.error) };
|
||||
return {
|
||||
ok: true as const,
|
||||
authority: authority.value,
|
||||
provider: new CdpBrowserProvider(),
|
||||
allowedBrowserOrigins: policy.allowedOrigins,
|
||||
};
|
||||
};
|
||||
|
||||
/** Project a browser operation failure consistently across CLI command groups. */
|
||||
export const browserCliError = (
|
||||
error: Parameters<typeof projectAnalysisError>[0],
|
||||
): JsonValue => ({
|
||||
error: "Browser observation failed",
|
||||
...projectAnalysisError(error),
|
||||
});
|
||||
@@ -27,18 +27,11 @@ import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
import { parseCliJsonInput } from "./cliJsonInput.js";
|
||||
import {
|
||||
electronPageInspectionOptions,
|
||||
electronScopeOptions,
|
||||
javascriptApplicationOptions,
|
||||
} from "./cliObservationOptions.js";
|
||||
import { runCliJavaScriptApplicationAnalysis } from "./cli/javascriptApplicationAnalysis.js";
|
||||
|
||||
const scopeOptions = {
|
||||
allowedFileRoots: z
|
||||
.array(z.string().min(1))
|
||||
.optional()
|
||||
.describe("Filesystem roots; defaults to REA_ELECTRON_FILE_ROOTS_JSON"),
|
||||
approved: z.boolean().default(false).describe("Approve passive observation"),
|
||||
};
|
||||
|
||||
/** Register CLI equivalents of the Electron MCP tools. */
|
||||
export const registerElectronCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
@@ -137,7 +130,7 @@ const registerElectronTargetList = (
|
||||
.describe("Configured loopback Electron CDP endpoint"),
|
||||
}),
|
||||
options: z.object({
|
||||
...scopeOptions,
|
||||
...electronScopeOptions,
|
||||
offset: z
|
||||
.number()
|
||||
.int()
|
||||
|
||||
+14
-5
@@ -1,7 +1,8 @@
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { open, stat } from "node:fs/promises";
|
||||
|
||||
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
|
||||
import type { JsonValue } from "./domain/jsonValue.js";
|
||||
import { readBoundedFileBytes } from "./process/BoundedFileBytes.js";
|
||||
|
||||
const MAX_JSON_INPUT_BYTES = 64 * 1_024 * 1_024;
|
||||
|
||||
@@ -13,6 +14,8 @@ export const parseCliJsonInput = async (
|
||||
| { readonly ok: true; readonly value: unknown }
|
||||
| { readonly ok: false; readonly error: JsonValue }
|
||||
> => {
|
||||
if (Buffer.byteLength(value, "utf8") > MAX_JSON_INPUT_BYTES)
|
||||
return jsonFileError(undefined, operation, "too-large");
|
||||
const inline = parseJson(value);
|
||||
if (inline !== undefined) return { ok: true, value: inline };
|
||||
if (["{", "["].includes(value.trimStart()[0] ?? ""))
|
||||
@@ -22,8 +25,14 @@ export const parseCliJsonInput = async (
|
||||
if (!metadata.isFile()) return jsonFileError(value, operation, "not-file");
|
||||
if (metadata.size > MAX_JSON_INPUT_BYTES)
|
||||
return jsonFileError(value, operation, "too-large");
|
||||
const bytes = await readFile(value);
|
||||
if (bytes.byteLength > MAX_JSON_INPUT_BYTES)
|
||||
const handle = await open(value, "r");
|
||||
let bytes: Buffer | undefined;
|
||||
try {
|
||||
bytes = await readBoundedFileBytes(handle, MAX_JSON_INPUT_BYTES);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
if (bytes === undefined)
|
||||
return jsonFileError(value, operation, "too-large");
|
||||
const parsed = parseJson(bytes.toString("utf8"));
|
||||
return parsed === undefined
|
||||
@@ -52,7 +61,7 @@ const inputError = (operation: string): JsonValue => ({
|
||||
});
|
||||
|
||||
const jsonFileError = (
|
||||
path: string,
|
||||
path: string | undefined,
|
||||
operation: string,
|
||||
reason: "not-file" | "too-large" | "invalid-json" | "read-failed",
|
||||
) => ({
|
||||
@@ -68,7 +77,7 @@ const jsonFileError = (
|
||||
: [],
|
||||
),
|
||||
),
|
||||
input_path: path,
|
||||
...(path === undefined ? {} : { input_path: path }),
|
||||
input_reason: reason,
|
||||
maximum_input_bytes: MAX_JSON_INPUT_BYTES,
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from "incur";
|
||||
|
||||
const boundedCount = (
|
||||
/** Bound a CLI observation count while preserving its subject-specific help. */
|
||||
export const boundedCount = (
|
||||
subject: string,
|
||||
maximum: number,
|
||||
fallback: number,
|
||||
@@ -14,13 +15,18 @@ const boundedCount = (
|
||||
.default(fallback)
|
||||
.describe(`Maximum ${subject}`);
|
||||
|
||||
const boundedBytes = (subject: string, maximum: number, fallback: number) =>
|
||||
boundedCount(`${subject} in bytes`, maximum, fallback);
|
||||
/** Bound a CLI observation byte budget. */
|
||||
export const boundedBytes = (
|
||||
subject: string,
|
||||
maximum: number,
|
||||
fallback: number,
|
||||
) => boundedCount(`${subject} in bytes`, maximum, fallback);
|
||||
|
||||
const positiveCount = (subject: string, fallback: number) =>
|
||||
z.number().int().min(1).default(fallback).describe(`Maximum ${subject}`);
|
||||
|
||||
const browserScopeOptions = {
|
||||
/** Shared passive browser origin and approval options. */
|
||||
export const browserScopeOptions = {
|
||||
allowedOrigins: z
|
||||
.array(z.string().min(1))
|
||||
.optional()
|
||||
@@ -146,7 +152,8 @@ export const browserPageInspectionOptions = z.object({
|
||||
),
|
||||
});
|
||||
|
||||
const electronScopeOptions = {
|
||||
/** Shared passive Electron root and approval options. */
|
||||
export const electronScopeOptions = {
|
||||
allowedFileRoots: z
|
||||
.array(z.string().min(1))
|
||||
.optional()
|
||||
|
||||
@@ -12,27 +12,14 @@ import {
|
||||
PermissionRequiredError,
|
||||
projectAnalysisError,
|
||||
} from "./domain/errors.js";
|
||||
import type { PermissionCapability } from "./domain/permissionPolicy.js";
|
||||
import {
|
||||
PERMISSION_CAPABILITIES,
|
||||
type PermissionCapability,
|
||||
} from "./domain/permissionPolicy.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
|
||||
const capabilitySchema = z.enum([
|
||||
"process_capture",
|
||||
"browser_observe",
|
||||
"browser_automate",
|
||||
"electron_observe",
|
||||
"electron_automate",
|
||||
"evidence_read",
|
||||
"evidence_write",
|
||||
"investigation_input",
|
||||
"investigation_workspace_read",
|
||||
"investigation_workspace_write",
|
||||
"snapshot_read",
|
||||
"snapshot_write",
|
||||
"artifact_extract",
|
||||
"native_mount",
|
||||
"reference_read",
|
||||
]);
|
||||
const capabilitySchema = z.enum(PERMISSION_CAPABILITIES);
|
||||
|
||||
type PolicyRevocationApproval =
|
||||
| { readonly approved: true }
|
||||
|
||||
@@ -5,6 +5,28 @@ import { managedOutputSchemas } from "./toolOutputSchemas.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
|
||||
|
||||
const managedReadLimits = {
|
||||
max_file_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(4_096)
|
||||
.max(1_073_741_824)
|
||||
.default(268_435_456),
|
||||
max_metadata_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(256)
|
||||
.max(268_435_456)
|
||||
.default(67_108_864),
|
||||
max_table_rows: z.number().int().min(1).max(1_000_000).default(100_000),
|
||||
max_heap_item_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16_777_216)
|
||||
.default(1_048_576),
|
||||
};
|
||||
|
||||
/** Exact caller boundary for execution-free PE/CLI triage and identity. */
|
||||
export const managedArtifactInputSchema = z.object({
|
||||
path: z
|
||||
@@ -20,25 +42,7 @@ export const managedArtifactInputSchema = z.object({
|
||||
resource_limit: z.number().int().min(1).max(500).default(100),
|
||||
attribute_offset: z.number().int().min(0).default(0),
|
||||
attribute_limit: z.number().int().min(1).max(500).default(100),
|
||||
max_file_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(4_096)
|
||||
.max(1_073_741_824)
|
||||
.default(268_435_456),
|
||||
max_metadata_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(256)
|
||||
.max(268_435_456)
|
||||
.default(67_108_864),
|
||||
max_table_rows: z.number().int().min(1).max(1_000_000).default(100_000),
|
||||
max_heap_item_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16_777_216)
|
||||
.default(1_048_576),
|
||||
...managedReadLimits,
|
||||
});
|
||||
|
||||
/** Exact caller boundary for execution-free metadata/signature/IL inspection. */
|
||||
@@ -54,25 +58,7 @@ export const managedMemberInputSchema = z.object({
|
||||
edge_offset: z.number().int().min(0).default(0),
|
||||
edge_limit: z.number().int().min(1).max(1_000).default(250),
|
||||
instruction_anchor_limit: z.number().int().min(0).max(500).default(100),
|
||||
max_file_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(4_096)
|
||||
.max(1_073_741_824)
|
||||
.default(268_435_456),
|
||||
max_metadata_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(256)
|
||||
.max(268_435_456)
|
||||
.default(67_108_864),
|
||||
max_table_rows: z.number().int().min(1).max(1_000_000).default(100_000),
|
||||
max_heap_item_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16_777_216)
|
||||
.default(1_048_576),
|
||||
...managedReadLimits,
|
||||
max_method_body_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
@@ -90,25 +76,7 @@ export const managedNativeBoundaryInputSchema = z.object({
|
||||
import_limit: z.number().int().min(1).max(500).default(100),
|
||||
implementation_offset: z.number().int().min(0).default(0),
|
||||
implementation_limit: z.number().int().min(1).max(500).default(100),
|
||||
max_file_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(4_096)
|
||||
.max(1_073_741_824)
|
||||
.default(268_435_456),
|
||||
max_metadata_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(256)
|
||||
.max(268_435_456)
|
||||
.default(67_108_864),
|
||||
max_table_rows: z.number().int().min(1).max(1_000_000).default(100_000),
|
||||
max_heap_item_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16_777_216)
|
||||
.default(1_048_576),
|
||||
...managedReadLimits,
|
||||
});
|
||||
|
||||
const outputSchema = requireOutputSchema(
|
||||
|
||||
+7
-295
@@ -1,249 +1,10 @@
|
||||
import { constants } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
access,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
stat,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { execFile } from "node:child_process";
|
||||
import { extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { BinaryTargetError } from "./errors.js";
|
||||
import type { BinaryArchitecture, BinaryTarget } from "./binaryTargetTypes.js";
|
||||
import type { BinaryArchitecture } from "./binaryTargetTypes.js";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
import { zipPackageFormatForPath } from "./zipPackageFormat.js";
|
||||
|
||||
export type { BinaryArchitecture, BinaryTarget } from "./binaryTargetTypes.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/**
|
||||
* Resolve and classify a readable local target before a provider is selected.
|
||||
* FAT Mach-O inputs select only a host-compatible architecture so setup remains
|
||||
* non-interactive; unsupported or ambiguous inputs are returned as typed errors.
|
||||
*/
|
||||
export const parseBinaryTarget = async (
|
||||
input: string,
|
||||
cwd = process.cwd(),
|
||||
hostArchitecture: NodeJS.Architecture = process.arch,
|
||||
targetKind?: BinaryTarget["kind"],
|
||||
): Promise<Result<BinaryTarget, BinaryTargetError>> => {
|
||||
const candidate = isAbsolute(input) ? input : resolve(cwd, input);
|
||||
try {
|
||||
await access(candidate, constants.R_OK);
|
||||
const canonical = await realpath(candidate);
|
||||
const resolved = await resolveAppBundle(canonical);
|
||||
if (!resolved.ok) return err(resolved.error);
|
||||
const path = resolved.value;
|
||||
const handle = await open(path, "r");
|
||||
try {
|
||||
if (!(await handle.stat()).isFile())
|
||||
return err(new BinaryTargetError(path, "target is not a regular file"));
|
||||
if (
|
||||
targetKind === "database" ||
|
||||
(targetKind === undefined && path.toLowerCase().endsWith(".hop"))
|
||||
)
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
kind: "database",
|
||||
format: "analysis-database",
|
||||
});
|
||||
const artifactFormat = await detectArtifactFormat(path, handle);
|
||||
if (artifactFormat !== undefined) {
|
||||
const identity = {
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
};
|
||||
return isArchiveFormat(artifactFormat)
|
||||
? ok({ ...identity, kind: "archive", format: artifactFormat })
|
||||
: ok({ ...identity, kind: "artifact", format: artifactFormat });
|
||||
}
|
||||
const detected = await readExecutableMetadata(handle, hostArchitecture);
|
||||
if (!detected.ok) return err(new BinaryTargetError(path, detected.error));
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
kind: "executable",
|
||||
...detected.value,
|
||||
});
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(candidate, "path is not readable", { cause }),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const detectArtifactFormat = async (
|
||||
path: string,
|
||||
handle: FileHandle,
|
||||
): Promise<
|
||||
| Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe"
|
||||
>
|
||||
| undefined
|
||||
> => {
|
||||
const lower = path.toLowerCase();
|
||||
const magic = Buffer.alloc(8);
|
||||
const observed = await handle.read(magic, 0, magic.length, 0);
|
||||
if (
|
||||
observed.bytesRead >= 4 &&
|
||||
magic[0] === 0x50 &&
|
||||
magic[1] === 0x4b &&
|
||||
[0x03, 0x05, 0x07].includes(magic[2] ?? -1) &&
|
||||
[0x04, 0x06, 0x08].includes(magic[3] ?? -1)
|
||||
) {
|
||||
return zipPackageFormatForPath(lower) ?? "zip";
|
||||
}
|
||||
const named = namedArtifactFormat(lower);
|
||||
if (named !== undefined) return named;
|
||||
if (
|
||||
lower.endsWith(".pkg") &&
|
||||
observed.bytesRead >= 4 &&
|
||||
magic.subarray(0, 4).toString("ascii") === "xar!"
|
||||
)
|
||||
return "pkg";
|
||||
if (lower.endsWith(".dmg")) {
|
||||
const size = (await handle.stat()).size;
|
||||
if (size >= 512) {
|
||||
const trailer = Buffer.alloc(4);
|
||||
const read = await handle.read(trailer, 0, trailer.length, size - 512);
|
||||
if (read.bytesRead === 4 && trailer.toString("ascii") === "koly")
|
||||
return "dmg";
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const namedArtifactFormat = (
|
||||
lowerPath: string,
|
||||
): "asar" | "plist" | "source-map" | "javascript" | undefined => {
|
||||
if (lowerPath.endsWith(".asar")) return "asar";
|
||||
if (lowerPath.endsWith(".plist")) return "plist";
|
||||
if (lowerPath.endsWith(".map")) return "source-map";
|
||||
return /\.(?:m?js|cjs)$/u.test(lowerPath) ? "javascript" : undefined;
|
||||
};
|
||||
|
||||
const isArchiveFormat = (
|
||||
format: Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe"
|
||||
>,
|
||||
): format is Extract<BinaryTarget, { kind: "archive" }>["format"] =>
|
||||
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(format);
|
||||
|
||||
const sha256Handle = async (handle: FileHandle): Promise<string> => {
|
||||
const hash = createHash("sha256");
|
||||
const chunk = Buffer.allocUnsafe(64 * 1024);
|
||||
let position = 0;
|
||||
while (true) {
|
||||
const observed = await handle.read(chunk, 0, chunk.length, position);
|
||||
if (observed.bytesRead === 0) break;
|
||||
hash.update(chunk.subarray(0, observed.bytesRead));
|
||||
position += observed.bytesRead;
|
||||
}
|
||||
return hash.digest("hex");
|
||||
};
|
||||
|
||||
const resolveAppBundle = async (
|
||||
path: string,
|
||||
): Promise<Result<string, BinaryTargetError>> => {
|
||||
const metadata = await stat(path);
|
||||
if (!metadata.isDirectory()) return ok(path);
|
||||
if (extname(path).toLowerCase() !== ".app")
|
||||
return err(new BinaryTargetError(path, "target is not an app or file"));
|
||||
const plistPath = join(path, "Contents", "Info.plist");
|
||||
let name: string;
|
||||
try {
|
||||
const plist = await readFile(plistPath);
|
||||
name =
|
||||
plist.subarray(0, 6).toString("ascii") === "bplist"
|
||||
? await readBinaryPlistExecutable(plistPath)
|
||||
: parseXmlPlistExecutable(plist.toString("utf8"));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(path, "app has no readable CFBundleExecutable", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (!isSafeExecutableName(name))
|
||||
return err(
|
||||
new BinaryTargetError(path, "app has an unsafe CFBundleExecutable"),
|
||||
);
|
||||
const programs = join(path, "Contents", "MacOS");
|
||||
const executable = join(programs, name);
|
||||
try {
|
||||
const [canonicalPrograms, canonicalExecutable] = await Promise.all([
|
||||
realpath(programs),
|
||||
realpath(executable),
|
||||
]);
|
||||
const location = relative(canonicalPrograms, canonicalExecutable);
|
||||
if (
|
||||
location === ".." ||
|
||||
location.startsWith(`..${sep}`) ||
|
||||
isAbsolute(location)
|
||||
)
|
||||
return err(
|
||||
new BinaryTargetError(path, "app program file leaves Contents/MacOS"),
|
||||
);
|
||||
return ok(canonicalExecutable);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(path, "app program file is missing", { cause }),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const parseXmlPlistExecutable = (plist: string): string => {
|
||||
const match =
|
||||
/<key>\s*CFBundleExecutable\s*<\/key>\s*<string>([^<]+)<\/string>/u.exec(
|
||||
plist,
|
||||
);
|
||||
if (match?.[1] === undefined)
|
||||
throw new Error("CFBundleExecutable is missing");
|
||||
return decodeXml(match[1].trim());
|
||||
};
|
||||
|
||||
const readBinaryPlistExecutable = async (plistPath: string): Promise<string> =>
|
||||
(
|
||||
await execFileAsync("/usr/bin/plutil", [
|
||||
"-extract",
|
||||
"CFBundleExecutable",
|
||||
"raw",
|
||||
"-o",
|
||||
"-",
|
||||
plistPath,
|
||||
])
|
||||
).stdout.trim();
|
||||
|
||||
const isSafeExecutableName = (name: string): boolean =>
|
||||
name.length > 0 &&
|
||||
name !== "." &&
|
||||
name !== ".." &&
|
||||
!name.includes("\0") &&
|
||||
!/[/\\]/u.test(name);
|
||||
|
||||
const decodeXml = (value: string): string =>
|
||||
value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll(""", '"')
|
||||
.replaceAll("'", "'");
|
||||
|
||||
type ExecutableMetadata =
|
||||
/** Format and architecture facts recovered from an executable header. */
|
||||
export type ExecutableMetadata =
|
||||
| {
|
||||
readonly format: "mach-o" | "elf";
|
||||
readonly architecture: BinaryArchitecture;
|
||||
@@ -260,58 +21,6 @@ type ExecutableMetadata =
|
||||
readonly managed: boolean;
|
||||
};
|
||||
|
||||
const readExecutableMetadata = async (
|
||||
handle: FileHandle,
|
||||
hostArchitecture: NodeJS.Architecture,
|
||||
): Promise<Result<ExecutableMetadata, string>> => {
|
||||
const prefix = Buffer.alloc(4096);
|
||||
const prefixRead = await handle.read(prefix, 0, prefix.length, 0);
|
||||
const bytes = prefix.subarray(0, prefixRead.bytesRead);
|
||||
if (bytes.length >= 64 && bytes[0] === 0x4d && bytes[1] === 0x5a) {
|
||||
const offset = bytes.readUInt32LE(0x3c);
|
||||
return readPeMetadata(handle, offset);
|
||||
}
|
||||
if (bytes.length >= 8) {
|
||||
const magic = bytes.readUInt32BE(0);
|
||||
if ([0xcafebabf, 0xbfbafeca].includes(magic)) {
|
||||
const little = magic === 0xbfbafeca;
|
||||
const count = little ? bytes.readUInt32LE(4) : bytes.readUInt32BE(4);
|
||||
const required = 8 + count * 32;
|
||||
if (count <= 128 && required > bytes.length) {
|
||||
const header = Buffer.alloc(required);
|
||||
const headerRead = await handle.read(header, 0, header.length, 0);
|
||||
return parseExecutableHeader(
|
||||
header.subarray(0, headerRead.bytesRead),
|
||||
hostArchitecture,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return parseExecutableHeader(bytes, hostArchitecture);
|
||||
};
|
||||
|
||||
const readPeMetadata = async (
|
||||
handle: FileHandle,
|
||||
offset: number,
|
||||
): Promise<Result<ExecutableMetadata, string>> => {
|
||||
const fileHeader = Buffer.alloc(24);
|
||||
const fileHeaderRead = await handle.read(
|
||||
fileHeader,
|
||||
0,
|
||||
fileHeader.length,
|
||||
offset,
|
||||
);
|
||||
if (fileHeaderRead.bytesRead !== fileHeader.length)
|
||||
return err("invalid or truncated PE header");
|
||||
const optionalHeaderSize = fileHeader.readUInt16LE(20);
|
||||
if (optionalHeaderSize > 4096) return err("invalid PE optional header size");
|
||||
const record = Buffer.alloc(24 + optionalHeaderSize);
|
||||
const recordRead = await handle.read(record, 0, record.length, offset);
|
||||
return recordRead.bytesRead === record.length
|
||||
? parsePeRecord(record)
|
||||
: err("invalid or truncated PE header");
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse supported executable headers without I/O. The caller supplies the host
|
||||
* architecture used for deterministic FAT Mach-O slice selection.
|
||||
@@ -414,7 +123,10 @@ const parsePe = (bytes: Buffer): Result<ExecutableMetadata, string> => {
|
||||
return parsePeRecord(bytes.subarray(offset));
|
||||
};
|
||||
|
||||
const parsePeRecord = (record: Buffer): Result<ExecutableMetadata, string> => {
|
||||
/** Parse a bounded PE signature, COFF record, and optional header without I/O. */
|
||||
export const parsePeRecord = (
|
||||
record: Buffer,
|
||||
): Result<ExecutableMetadata, string> => {
|
||||
if (
|
||||
record.length < 24 ||
|
||||
record.toString("binary", 0, 4) !== "PE\u0000\u0000"
|
||||
|
||||
@@ -380,3 +380,17 @@ export const sanitizeBrowserUrl = (value: string): SanitizedBrowserUrl => {
|
||||
redacted: wasTruncated || hadCredentials || hadFragment || names.length > 0,
|
||||
};
|
||||
};
|
||||
|
||||
/** Remove credentials, fragments, and query values from endpoint candidates. */
|
||||
export const sanitizeEndpointCandidate = (value: string): string => {
|
||||
const bounded = value.slice(0, 4_096);
|
||||
try {
|
||||
const parsed = new URL(bounded, "https://rea.invalid");
|
||||
const sanitized = sanitizeBrowserUrl(parsed.href).url;
|
||||
return parsed.origin === "https://rea.invalid"
|
||||
? sanitized.replace("https://rea.invalid", "")
|
||||
: sanitized;
|
||||
} catch {
|
||||
return bounded.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
}
|
||||
};
|
||||
|
||||
+2
-15
@@ -190,22 +190,9 @@ export class ProviderSelectionError extends AnalysisError {
|
||||
readonly rejections: readonly ProviderSelectionRejection[];
|
||||
override readonly userMessage: string;
|
||||
|
||||
constructor(input: string | ProviderSelectionErrorOptions) {
|
||||
const legacy = typeof input === "string";
|
||||
const options: ProviderSelectionErrorOptions = legacy
|
||||
? {
|
||||
operation: input,
|
||||
reason: "provider_unavailable",
|
||||
requestedProviderId: "auto",
|
||||
candidateIds: [],
|
||||
}
|
||||
: input;
|
||||
constructor(options: ProviderSelectionErrorOptions) {
|
||||
const operation = options.operation ?? "open_binary";
|
||||
super(
|
||||
legacy
|
||||
? `No configured provider can execute ${operation}`
|
||||
: providerSelectionDiagnostic(options),
|
||||
);
|
||||
super(providerSelectionDiagnostic(options));
|
||||
this.operation = operation;
|
||||
this.reason = options.reason;
|
||||
this.requestedProviderId = options.requestedProviderId;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { isAbsolute, relative } from "node:path";
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
import { isPathWithinRoot } from "./localPath.js";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -33,7 +34,7 @@ export const parseActiveElectronCapture = (
|
||||
.parse(evidence.parameters);
|
||||
if (
|
||||
result.application.application_path !== parameters.application_path ||
|
||||
!isWithinRoot(
|
||||
!isPathWithinRoot(
|
||||
parameters.application_root,
|
||||
result.application.application_path,
|
||||
)
|
||||
@@ -129,10 +130,3 @@ const digestCanonical = (value: unknown): string => {
|
||||
throw new TypeError("Runtime reconciliation could not canonicalize input");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
|
||||
const isWithinRoot = (root: string, path: string): boolean => {
|
||||
const remainder = relative(root, path);
|
||||
return (
|
||||
remainder === "" || (!remainder.startsWith("..") && !isAbsolute(remainder))
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { isAbsolute, relative } from "node:path";
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
import { isPathWithinRoot } from "./localPath.js";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -310,7 +311,7 @@ const assertV8RuntimeParameters = (
|
||||
if (
|
||||
(location.kind === "file" &&
|
||||
!parameters.allowed_file_roots.some((root) =>
|
||||
isWithinRoot(root, location.file_path),
|
||||
isPathWithinRoot(root, location.file_path),
|
||||
)) ||
|
||||
(location.kind === "url" &&
|
||||
!parameters.allowed_origins.includes(location.origin)) ||
|
||||
@@ -321,13 +322,6 @@ const assertV8RuntimeParameters = (
|
||||
);
|
||||
};
|
||||
|
||||
const isWithinRoot = (root: string, path: string): boolean => {
|
||||
const remainder = relative(root, path);
|
||||
return (
|
||||
remainder === "" || (!remainder.startsWith("..") && !isAbsolute(remainder))
|
||||
);
|
||||
};
|
||||
|
||||
const normalizeV8Inspection = (
|
||||
result: JavaScriptRuntimeObservation,
|
||||
): NormalizedV8Inspection => ({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { isAbsolute, posix, relative } from "node:path";
|
||||
import { posix, relative } from "node:path";
|
||||
|
||||
import { isPathWithinRoot } from "./localPath.js";
|
||||
import {
|
||||
compareCodePoints,
|
||||
type ApplicationNode,
|
||||
@@ -210,8 +211,7 @@ const pathBelowRoot = (root: string, value: string): string | null => {
|
||||
const remainder = relative(root, value);
|
||||
if (
|
||||
remainder === "" ||
|
||||
remainder.startsWith("..") ||
|
||||
isAbsolute(remainder) ||
|
||||
!isPathWithinRoot(root, value) ||
|
||||
remainder.includes("\\")
|
||||
)
|
||||
return null;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import { sanitizeEndpointCandidate } from "./browserObservation.js";
|
||||
import {
|
||||
addBoundedFinding,
|
||||
addLocatedFinding,
|
||||
@@ -14,7 +15,6 @@ import {
|
||||
propertyName,
|
||||
range,
|
||||
rangeForOffsets,
|
||||
sanitizeCandidate,
|
||||
sourceSlice,
|
||||
staticPath,
|
||||
staticPathResolutionContext,
|
||||
@@ -264,7 +264,7 @@ const addEndpoint = (context: FindingContext, input: EndpointInput): void =>
|
||||
node: input.node,
|
||||
value: {
|
||||
kind: input.kind,
|
||||
value: sanitizeCandidate(input.value),
|
||||
value: sanitizeEndpointCandidate(input.value),
|
||||
mechanism: input.mechanism,
|
||||
module_key: null,
|
||||
location: range(input.node),
|
||||
|
||||
@@ -3,7 +3,6 @@ import { posix } from "node:path";
|
||||
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import { sanitizeBrowserUrl } from "./browserObservation.js";
|
||||
import type {
|
||||
JavaScriptBundlerRegistration,
|
||||
JavaScriptSourceRange,
|
||||
@@ -411,20 +410,6 @@ export const detectVendors = (source: string): string[] =>
|
||||
patterns.some((pattern) => source.includes(pattern)) ? [name] : [],
|
||||
);
|
||||
|
||||
/** Remove credentials, fragments, and query values from endpoint candidates. */
|
||||
export const sanitizeCandidate = (value: string): string => {
|
||||
const bounded = value.slice(0, 4_096);
|
||||
try {
|
||||
const parsed = new URL(bounded, "https://rea.invalid");
|
||||
const sanitized = sanitizeBrowserUrl(parsed.href).url;
|
||||
return parsed.origin === "https://rea.invalid"
|
||||
? sanitized.replace("https://rea.invalid", "")
|
||||
: sanitized;
|
||||
} catch {
|
||||
return bounded.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
}
|
||||
};
|
||||
|
||||
/** Commit the static semantic content used to deduplicate registrations. */
|
||||
export const registrationKey = (
|
||||
registration: JavaScriptBundlerRegistration,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { isAbsolute, relative, sep } from "node:path";
|
||||
|
||||
/** Test lexical containment on the host platform; callers must resolve symlinks first. */
|
||||
export const isPathWithinRoot = (root: string, path: string): boolean => {
|
||||
const value = relative(root, path);
|
||||
return (
|
||||
value === "" ||
|
||||
(value !== ".." && !value.startsWith(`..${sep}`) && !isAbsolute(value))
|
||||
);
|
||||
};
|
||||
@@ -2,26 +2,30 @@ import { isAbsolute, relative, resolve, sep } from "node:path";
|
||||
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Local capabilities governed by the shared REA permission policy. */
|
||||
export type PermissionCapability =
|
||||
| "process_capture"
|
||||
| "browser_observe"
|
||||
| "browser_automate"
|
||||
| "electron_observe"
|
||||
| "electron_automate"
|
||||
| "v8_inspector_observe"
|
||||
| "evidence_read"
|
||||
| "evidence_write"
|
||||
| "investigation_input"
|
||||
| "investigation_workspace_read"
|
||||
| "investigation_workspace_write"
|
||||
| "snapshot_read"
|
||||
| "snapshot_write"
|
||||
| "artifact_extract"
|
||||
| "native_mount"
|
||||
| "reference_read"
|
||||
| "javascript_replay"
|
||||
| "managed_runtime";
|
||||
/** Canonical local capabilities governed by the shared REA permission policy. */
|
||||
export const PERMISSION_CAPABILITIES = [
|
||||
"process_capture",
|
||||
"browser_observe",
|
||||
"browser_automate",
|
||||
"electron_observe",
|
||||
"electron_automate",
|
||||
"v8_inspector_observe",
|
||||
"evidence_read",
|
||||
"evidence_write",
|
||||
"investigation_input",
|
||||
"investigation_workspace_read",
|
||||
"investigation_workspace_write",
|
||||
"snapshot_read",
|
||||
"snapshot_write",
|
||||
"artifact_extract",
|
||||
"native_mount",
|
||||
"reference_read",
|
||||
"javascript_replay",
|
||||
"managed_runtime",
|
||||
] as const;
|
||||
|
||||
/** One capability from the canonical local permission inventory. */
|
||||
export type PermissionCapability = (typeof PERMISSION_CAPABILITIES)[number];
|
||||
|
||||
/** Ordered network authority; each mode includes the modes before it. */
|
||||
type PermissionNetwork = "none" | "loopback" | "external";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { resolve } from "node:path";
|
||||
import { isPathWithinRoot } from "./localPath.js";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
@@ -451,12 +451,6 @@ export type ProcessPolicyDecision =
|
||||
| "filesystem root is outside approved roots";
|
||||
};
|
||||
|
||||
const isWithin = (candidate: string, root: string): boolean =>
|
||||
resolve(candidate) === resolve(root) ||
|
||||
resolve(candidate).startsWith(
|
||||
`${resolve(root)}${resolve(root).endsWith("/") ? "" : "/"}`,
|
||||
);
|
||||
|
||||
/** Evaluate scenario authority before any process or filesystem side effect occurs. */
|
||||
export const authorizeProcessScenario = (
|
||||
scenario: ProcessScenario,
|
||||
@@ -470,13 +464,15 @@ export const authorizeProcessScenario = (
|
||||
reason: "host network access is not approved by operator policy",
|
||||
};
|
||||
if (
|
||||
!policy.executableRoots.some((root) => isWithin(scenario.executable, root))
|
||||
!policy.executableRoots.some((root) =>
|
||||
isPathWithinRoot(root, scenario.executable),
|
||||
)
|
||||
) {
|
||||
return { allowed: false, reason: "executable is outside approved roots" };
|
||||
}
|
||||
if (
|
||||
!policy.workingRoots.some((root) =>
|
||||
isWithin(scenario.working_directory, root),
|
||||
isPathWithinRoot(root, scenario.working_directory),
|
||||
)
|
||||
) {
|
||||
return {
|
||||
@@ -498,7 +494,8 @@ export const authorizeProcessScenario = (
|
||||
}
|
||||
if (
|
||||
scenario.filesystem_roots.some(
|
||||
(path) => !policy.workingRoots.some((root) => isWithin(path, root)),
|
||||
(path) =>
|
||||
!policy.workingRoots.some((root) => isPathWithinRoot(root, path)),
|
||||
)
|
||||
) {
|
||||
return {
|
||||
|
||||
@@ -100,6 +100,33 @@ const graphInput = (): HistoricalSourceGraphInput => ({
|
||||
});
|
||||
|
||||
describe("historical source graph", () => {
|
||||
it("validates supplementary paths and derived indexes by code point", () => {
|
||||
const paths = ["a", "aa", "\uE000", "\u{10000}"];
|
||||
const input: HistoricalSourceGraphInput = {
|
||||
...graphInput(),
|
||||
entries: paths.map((path) =>
|
||||
fileEntry({
|
||||
path,
|
||||
language: path,
|
||||
classifications: ["manifest"],
|
||||
}),
|
||||
),
|
||||
relationships: [],
|
||||
languages: paths,
|
||||
manifests: paths,
|
||||
};
|
||||
const graph = createHistoricalSourceGraph(input);
|
||||
expect(parseHistoricalSourceGraph(graph)).toEqual(graph);
|
||||
expect(() =>
|
||||
createHistoricalSourceGraph({
|
||||
...input,
|
||||
entries: [...input.entries].sort((left, right) =>
|
||||
left.path < right.path ? -1 : left.path > right.path ? 1 : 0,
|
||||
),
|
||||
}),
|
||||
).toThrow(/Unicode code point/u);
|
||||
});
|
||||
|
||||
it("builds and verifies internal root and manifest commitments", () => {
|
||||
const graph = createHistoricalSourceGraph(graphInput());
|
||||
const first = createHistoricalSourceManifest(graph);
|
||||
|
||||
@@ -4,6 +4,7 @@ import { posix } from "node:path";
|
||||
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);
|
||||
@@ -240,16 +241,16 @@ const relationshipKey = (
|
||||
): string =>
|
||||
`${relationship.from_path}\u0000${relationship.to}\u0000${relationship.kind}\u0000${relationship.resolution}\u0000${relationship.parse_state}`;
|
||||
|
||||
const compareCodePoints = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
|
||||
const checkSortedUnique = (
|
||||
values: readonly string[],
|
||||
field: string,
|
||||
context: z.RefinementCtx,
|
||||
): void => {
|
||||
for (let index = 1; index < values.length; index += 1)
|
||||
if (compareCodePoints(values[index - 1] ?? "", values[index] ?? "") >= 0) {
|
||||
if (
|
||||
compareUnicodeCodePoints(values[index - 1] ?? "", values[index] ?? "") >=
|
||||
0
|
||||
) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: `${field} must be sorted and unique by Unicode code point`,
|
||||
@@ -270,7 +271,7 @@ const expectedLanguages = (
|
||||
: [],
|
||||
),
|
||||
),
|
||||
].sort(compareCodePoints);
|
||||
].sort(compareUnicodeCodePoints);
|
||||
|
||||
const expectedManifests = (
|
||||
entries: readonly z.infer<typeof sourceEntrySchema>[],
|
||||
@@ -281,7 +282,7 @@ const expectedManifests = (
|
||||
? [entry.path]
|
||||
: [],
|
||||
)
|
||||
.sort(compareCodePoints);
|
||||
.sort(compareUnicodeCodePoints);
|
||||
|
||||
type GraphStructure = z.infer<typeof historicalSourceGraphStructureSchema>;
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/** Compare strings lexicographically by Unicode code point, independent of locale. */
|
||||
export const compareUnicodeCodePoints = (
|
||||
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;
|
||||
};
|
||||
@@ -58,19 +58,6 @@ export const resolveSpecifier = (
|
||||
}
|
||||
};
|
||||
|
||||
export const sanitizeCandidate = (value: string): string => {
|
||||
const bounded = value.slice(0, 4_096);
|
||||
try {
|
||||
const parsed = new URL(bounded, "https://rea.invalid");
|
||||
const sanitized = sanitizeBrowserUrl(parsed.href).url;
|
||||
return parsed.origin === "https://rea.invalid"
|
||||
? sanitized.replace("https://rea.invalid", "")
|
||||
: sanitized;
|
||||
} catch {
|
||||
return bounded.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
}
|
||||
};
|
||||
|
||||
export const location = (scriptKey: string, node: t.Node) => ({
|
||||
script_key: scriptKey,
|
||||
...locationFields(node),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { parse } from "@babel/parser";
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import { sanitizeEndpointCandidate } from "./browserObservation.js";
|
||||
import type { WebPageInspection } from "./browserObservation.js";
|
||||
import type {
|
||||
AnalyzeWebBundleInput,
|
||||
@@ -15,7 +16,6 @@ import {
|
||||
objectValue,
|
||||
propertyName,
|
||||
resolveSpecifier,
|
||||
sanitizeCandidate,
|
||||
stringArgument,
|
||||
} from "./webBundleAnalyzerAst.js";
|
||||
|
||||
@@ -242,7 +242,7 @@ interface AddFindingContext {
|
||||
}
|
||||
|
||||
const addFinding = (context: AddFindingContext): void => {
|
||||
const value = sanitizeCandidate(context.rawValue);
|
||||
const value = sanitizeEndpointCandidate(context.rawValue);
|
||||
const key = `finding\0${context.mechanism}\0${context.script.script_key}\0${value}`;
|
||||
addBounded(context.accumulator, key, context.maximumFindings, () =>
|
||||
context.collection.push({
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
/** ZIP-backed application package families that share the hardened archive reader. */
|
||||
export type ZipPackageFormat = "zip" | "ipa" | "apk" | "msix" | "appx";
|
||||
|
||||
/** Recognize local-header, empty-archive, or split-archive ZIP signatures, not archive validity. */
|
||||
export const hasZipSignature = (bytes: Uint8Array): boolean =>
|
||||
bytes.length >= 4 &&
|
||||
bytes[0] === 0x50 &&
|
||||
bytes[1] === 0x4b &&
|
||||
((bytes[2] === 0x03 && bytes[3] === 0x04) ||
|
||||
(bytes[2] === 0x05 && bytes[3] === 0x06) ||
|
||||
(bytes[2] === 0x07 && bytes[3] === 0x08));
|
||||
|
||||
/**
|
||||
* Classify a ZIP-backed package by its complete lower-cased path suffix.
|
||||
*
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
import type { ManagedMemberInspection } from "../domain/managedArtifact.js";
|
||||
import {
|
||||
metadataRowOffset,
|
||||
type ManagedMetadataLayout,
|
||||
type MetadataTableLayout,
|
||||
} from "./ManagedMetadataLayout.js";
|
||||
import {
|
||||
MetadataRowCursor,
|
||||
metadataRowCursor,
|
||||
metadataCodedToken,
|
||||
metadataToken,
|
||||
readMetadataString,
|
||||
sha256Bytes,
|
||||
} from "./ManagedMetadataHeaps.js";
|
||||
import { managedFailure } from "./ManagedReaderFailure.js";
|
||||
|
||||
export type ManagedPage<Item> = {
|
||||
readonly items: readonly Item[];
|
||||
@@ -117,41 +116,6 @@ export const page = <Item>(
|
||||
};
|
||||
};
|
||||
|
||||
export const rowCursor = (
|
||||
bytes: Buffer,
|
||||
layout: ManagedMetadataLayout,
|
||||
table: number,
|
||||
row: number,
|
||||
): MetadataRowCursor => {
|
||||
const descriptor = layout.table(table);
|
||||
const start = metadataRowOffset(layout, table, row);
|
||||
if (descriptor === undefined)
|
||||
throw managedFailure(
|
||||
"invalid-row",
|
||||
`metadata.${String(table)}`,
|
||||
"Metadata table is absent",
|
||||
start,
|
||||
);
|
||||
return new MetadataRowCursor(
|
||||
bytes,
|
||||
start,
|
||||
start + descriptor.rowSize,
|
||||
`metadata.${descriptor.name}`,
|
||||
);
|
||||
};
|
||||
|
||||
export const codedToken = (
|
||||
raw: number,
|
||||
bits: number,
|
||||
tables: readonly (number | undefined)[],
|
||||
): string | null => {
|
||||
if (raw === 0) return null;
|
||||
const tag = raw & (2 ** bits - 1);
|
||||
const row = Math.floor(raw / 2 ** bits);
|
||||
const table = tables[tag];
|
||||
return table === undefined || row === 0 ? null : metadataToken(table, row);
|
||||
};
|
||||
|
||||
const rowRange = (
|
||||
table: MetadataTableLayout | undefined,
|
||||
start: number,
|
||||
@@ -179,7 +143,7 @@ const readTypeRange = (
|
||||
): TypeRange => {
|
||||
const methods = layout.table(6);
|
||||
const fields = layout.table(4);
|
||||
const cursor = rowCursor(bytes, layout, 2, row);
|
||||
const cursor = metadataRowCursor(bytes, layout, 2, row);
|
||||
cursor.readUInt32();
|
||||
const name = readMetadataString(
|
||||
bytes,
|
||||
@@ -200,7 +164,7 @@ const readTypeRange = (
|
||||
let nextMethod = (methods?.rowCount ?? 0) + 1;
|
||||
const typeTable = layout.table(2);
|
||||
if (typeTable !== undefined && row < typeTable.rowCount) {
|
||||
const next = rowCursor(bytes, layout, 2, row + 1);
|
||||
const next = metadataRowCursor(bytes, layout, 2, row + 1);
|
||||
next.readUInt32();
|
||||
next.readIndex(layout.stringIndexSize);
|
||||
next.readIndex(layout.stringIndexSize);
|
||||
@@ -255,7 +219,7 @@ export const parseTypes = (
|
||||
const methods = layout.table(6);
|
||||
const items: ManagedType[] = [];
|
||||
for (let row = 1; row <= (typeTable?.rowCount ?? 0); row += 1) {
|
||||
const cursor = rowCursor(bytes, layout, 2, row);
|
||||
const cursor = metadataRowCursor(bytes, layout, 2, row);
|
||||
const flags = cursor.readUInt32();
|
||||
const name = readMetadataString(
|
||||
bytes,
|
||||
@@ -286,7 +250,7 @@ export const parseTypes = (
|
||||
name,
|
||||
full_name: fullName(namespace, name),
|
||||
flags,
|
||||
extends_token: codedToken(extendsRaw, 2, [2, 1, 27]),
|
||||
extends_token: metadataCodedToken(extendsRaw, 2, [2, 1, 27]),
|
||||
field_list: {
|
||||
first_row: fieldRange.first,
|
||||
last_row: fieldRange.last,
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type { ManagedPeLayout } from "./ManagedPeReader.js";
|
||||
import type { ManagedMetadataLayout } from "./ManagedMetadataLayout.js";
|
||||
import {
|
||||
codedToken,
|
||||
declaringType,
|
||||
rowCursor,
|
||||
signature,
|
||||
type FieldCore,
|
||||
type ManagedCallEdge,
|
||||
@@ -18,6 +16,8 @@ import {
|
||||
} from "./ManagedMemberInspectorCore.js";
|
||||
import {
|
||||
metadataToken,
|
||||
metadataRowCursor,
|
||||
metadataCodedToken,
|
||||
readMetadataBlob,
|
||||
readMetadataString,
|
||||
} from "./ManagedMetadataHeaps.js";
|
||||
@@ -36,7 +36,7 @@ export const parseFields = (
|
||||
const core = new Map<string, FieldCore>();
|
||||
const table = layout.table(4);
|
||||
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
|
||||
const cursor = rowCursor(bytes, layout, 4, row);
|
||||
const cursor = metadataRowCursor(bytes, layout, 4, row);
|
||||
const flags = cursor.readUInt16();
|
||||
const name = readMetadataString(
|
||||
bytes,
|
||||
@@ -78,7 +78,7 @@ export const parseMemberRefs = (
|
||||
const core = new Map<string, MemberRefCore>();
|
||||
const table = layout.table(10);
|
||||
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
|
||||
const cursor = rowCursor(bytes, layout, 10, row);
|
||||
const cursor = metadataRowCursor(bytes, layout, 10, row);
|
||||
const parentRaw = cursor.readIndex(
|
||||
layout.codedIndexSize("MemberRefParent"),
|
||||
);
|
||||
@@ -98,7 +98,7 @@ export const parseMemberRefs = (
|
||||
refs.push({
|
||||
token,
|
||||
row_offset: cursor.start,
|
||||
parent_token: codedToken(parentRaw, 3, [2, 1, 26, 6, 27]),
|
||||
parent_token: metadataCodedToken(parentRaw, 3, [2, 1, 26, 6, 27]),
|
||||
name,
|
||||
signature: signature(sig),
|
||||
});
|
||||
@@ -131,7 +131,7 @@ export const parseMethods = ({
|
||||
const core = new Map<string, MethodCore>();
|
||||
const table = layout.table(6);
|
||||
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
|
||||
const cursor = rowCursor(bytes, layout, 6, row);
|
||||
const cursor = metadataRowCursor(bytes, layout, 6, row);
|
||||
const rva = cursor.readUInt32();
|
||||
const implFlags = cursor.readUInt16();
|
||||
const flags = cursor.readUInt16();
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import type { ManagedMetadataLayout } from "./ManagedMetadataLayout.js";
|
||||
import {
|
||||
metadataRowOffset,
|
||||
type ManagedMetadataLayout,
|
||||
} from "./ManagedMetadataLayout.js";
|
||||
import { managedFailure } from "./ManagedReaderFailure.js";
|
||||
|
||||
const requireRange = (
|
||||
@@ -219,3 +222,40 @@ export const strongNameToken = (publicKey: Buffer): string =>
|
||||
Buffer.from(createHash("sha1").update(publicKey).digest().subarray(-8))
|
||||
.reverse()
|
||||
.toString("hex");
|
||||
|
||||
/** Create a cursor bounded to one admitted metadata table row. */
|
||||
export const metadataRowCursor = (
|
||||
bytes: Buffer,
|
||||
layout: ManagedMetadataLayout,
|
||||
table: number,
|
||||
row: number,
|
||||
): MetadataRowCursor => {
|
||||
const descriptor = layout.table(table);
|
||||
const start = metadataRowOffset(layout, table, row);
|
||||
if (descriptor === undefined)
|
||||
throw managedFailure(
|
||||
"invalid-row",
|
||||
`metadata.${String(table)}`,
|
||||
"Metadata table is absent",
|
||||
start,
|
||||
);
|
||||
return new MetadataRowCursor(
|
||||
bytes,
|
||||
start,
|
||||
start + descriptor.rowSize,
|
||||
`metadata.${descriptor.name}`,
|
||||
);
|
||||
};
|
||||
|
||||
/** Decode a metadata coded index without signed 32-bit coercion. */
|
||||
export const metadataCodedToken = (
|
||||
raw: number,
|
||||
bits: number,
|
||||
tables: readonly (number | undefined)[],
|
||||
): string | null => {
|
||||
if (raw === 0) return null;
|
||||
const tag = raw & (2 ** bits - 1);
|
||||
const row = Math.floor(raw / 2 ** bits);
|
||||
const table = tables[tag];
|
||||
return table === undefined || row === 0 ? null : metadataToken(table, row);
|
||||
};
|
||||
|
||||
@@ -7,7 +7,8 @@ import {
|
||||
type ManagedMetadataLayout,
|
||||
} from "./ManagedMetadataLayout.js";
|
||||
import {
|
||||
MetadataRowCursor,
|
||||
metadataRowCursor,
|
||||
metadataCodedToken,
|
||||
metadataToken,
|
||||
readMetadataBlob,
|
||||
readMetadataGuid,
|
||||
@@ -25,36 +26,6 @@ type AssemblyReference =
|
||||
type ManagedResource = ManagedArtifactInspection["resources"]["items"][number];
|
||||
type CustomAttribute = ManagedArtifactInspection["attributes"]["items"][number];
|
||||
|
||||
interface RowCursorContext {
|
||||
readonly bytes: Buffer;
|
||||
readonly layout: ManagedMetadataLayout;
|
||||
readonly table: number;
|
||||
readonly row: number;
|
||||
}
|
||||
|
||||
const rowCursor = ({
|
||||
bytes,
|
||||
layout,
|
||||
table,
|
||||
row,
|
||||
}: RowCursorContext): MetadataRowCursor => {
|
||||
const descriptor = layout.table(table);
|
||||
const start = metadataRowOffset(layout, table, row);
|
||||
if (descriptor === undefined)
|
||||
throw managedFailure(
|
||||
"invalid-row",
|
||||
`metadata.${String(table)}`,
|
||||
"Metadata table is absent",
|
||||
start,
|
||||
);
|
||||
return new MetadataRowCursor(
|
||||
bytes,
|
||||
start,
|
||||
start + descriptor.rowSize,
|
||||
`metadata.${descriptor.name}`,
|
||||
);
|
||||
};
|
||||
|
||||
const publicKeyIdentity = (
|
||||
bytes: Buffer,
|
||||
kind: "public-key" | "public-key-token",
|
||||
@@ -79,7 +50,7 @@ export const readModule = (
|
||||
): ModuleIdentity | null => {
|
||||
const table = layout.table(0);
|
||||
if (table === undefined || table.rowCount === 0) return null;
|
||||
const cursor = rowCursor({ bytes, layout, table: 0, row: 1 });
|
||||
const cursor = metadataRowCursor(bytes, layout, 0, 1);
|
||||
const generation = cursor.readUInt16();
|
||||
const name = readMetadataString(
|
||||
bytes,
|
||||
@@ -120,7 +91,7 @@ export const readAssembly = (
|
||||
): AssemblyIdentity | null => {
|
||||
const table = layout.table(32);
|
||||
if (table === undefined || table.rowCount === 0) return null;
|
||||
const cursor = rowCursor({ bytes, layout, table: 32, row: 1 });
|
||||
const cursor = metadataRowCursor(bytes, layout, 32, 1);
|
||||
const hashAlgorithm = cursor.readUInt32();
|
||||
const version = [
|
||||
cursor.readUInt16(),
|
||||
@@ -168,7 +139,7 @@ export const readAssemblyReference = (
|
||||
row: number,
|
||||
maxBytes: number,
|
||||
): AssemblyReference => {
|
||||
const cursor = rowCursor({ bytes, layout, table: 35, row });
|
||||
const cursor = metadataRowCursor(bytes, layout, 35, row);
|
||||
const version = [
|
||||
cursor.readUInt16(),
|
||||
cursor.readUInt16(),
|
||||
@@ -216,18 +187,6 @@ export const readAssemblyReference = (
|
||||
};
|
||||
};
|
||||
|
||||
const codedToken = (
|
||||
raw: number,
|
||||
bits: number,
|
||||
tables: readonly (number | undefined)[],
|
||||
): string | null => {
|
||||
if (raw === 0) return null;
|
||||
const tag = raw & (2 ** bits - 1);
|
||||
const row = Math.floor(raw / 2 ** bits);
|
||||
const table = tables[tag];
|
||||
return table === undefined || row === 0 ? null : metadataToken(table, row);
|
||||
};
|
||||
|
||||
interface ReadTypeNameContext {
|
||||
readonly bytes: Buffer;
|
||||
readonly layout: ManagedMetadataLayout;
|
||||
@@ -246,7 +205,7 @@ const readTypeName = ({
|
||||
const descriptor = layout.table(table);
|
||||
if (descriptor === undefined || row < 1 || row > descriptor.rowCount)
|
||||
return null;
|
||||
const cursor = rowCursor({ bytes, layout, table, row });
|
||||
const cursor = metadataRowCursor(bytes, layout, table, row);
|
||||
if (table === 1) cursor.readIndex(layout.codedIndexSize("ResolutionScope"));
|
||||
else cursor.readUInt32();
|
||||
const name = readMetadataString(
|
||||
@@ -274,7 +233,7 @@ const declaringTypeForMethod = (
|
||||
const methods = layout.table(6);
|
||||
if (types === undefined || methods === undefined) return null;
|
||||
for (let row = 1; row <= types.rowCount; row += 1) {
|
||||
const cursor = rowCursor({ bytes, layout, table: 2, row });
|
||||
const cursor = metadataRowCursor(bytes, layout, 2, row);
|
||||
cursor.readUInt32();
|
||||
const nameIndex = cursor.readIndex(layout.stringIndexSize);
|
||||
const namespaceIndex = cursor.readIndex(layout.stringIndexSize);
|
||||
@@ -303,7 +262,7 @@ const methodListForType = (
|
||||
layout: ManagedMetadataLayout,
|
||||
row: number,
|
||||
): number => {
|
||||
const cursor = rowCursor({ bytes, layout, table: 2, row });
|
||||
const cursor = metadataRowCursor(bytes, layout, 2, row);
|
||||
cursor.readUInt32();
|
||||
cursor.readIndex(layout.stringIndexSize);
|
||||
cursor.readIndex(layout.stringIndexSize);
|
||||
@@ -325,7 +284,7 @@ const attributeTypeName = (
|
||||
if (tag !== 3) return null;
|
||||
const memberRefs = layout.table(10);
|
||||
if (memberRefs === undefined || row > memberRefs.rowCount) return null;
|
||||
const cursor = rowCursor({ bytes, layout, table: 10, row });
|
||||
const cursor = metadataRowCursor(bytes, layout, 10, row);
|
||||
const parent = cursor.readIndex(layout.codedIndexSize("MemberRefParent"));
|
||||
const parentTag = parent & 7;
|
||||
const parentRow = Math.floor(parent / 8);
|
||||
@@ -389,7 +348,7 @@ export const readCustomAttribute = (
|
||||
row: number,
|
||||
maxBytes: number,
|
||||
): CustomAttribute => {
|
||||
const cursor = rowCursor({ bytes, layout, table: 12, row });
|
||||
const cursor = metadataRowCursor(bytes, layout, 12, row);
|
||||
const parentRaw = cursor.readIndex(
|
||||
layout.codedIndexSize("HasCustomAttribute"),
|
||||
);
|
||||
@@ -402,7 +361,7 @@ export const readCustomAttribute = (
|
||||
cursor.readIndex(layout.blobIndexSize),
|
||||
maxBytes,
|
||||
);
|
||||
const parent = codedToken(
|
||||
const parent = metadataCodedToken(
|
||||
parentRaw,
|
||||
5,
|
||||
[
|
||||
@@ -420,7 +379,12 @@ export const readCustomAttribute = (
|
||||
const typeName = attributeTypeName(bytes, layout, typeRaw, maxBytes);
|
||||
return {
|
||||
parent_token: parent,
|
||||
constructor_token: codedToken(typeRaw, 3, [undefined, undefined, 6, 10]),
|
||||
constructor_token: metadataCodedToken(typeRaw, 3, [
|
||||
undefined,
|
||||
undefined,
|
||||
6,
|
||||
10,
|
||||
]),
|
||||
type_name: typeName,
|
||||
value_length: value.length,
|
||||
value_sha256: sha256Bytes(value),
|
||||
@@ -450,7 +414,7 @@ export const readResource = ({
|
||||
directory,
|
||||
issues,
|
||||
}: ReadResourceContext): ManagedResource => {
|
||||
const cursor = rowCursor({ bytes, layout, table: 40, row });
|
||||
const cursor = metadataRowCursor(bytes, layout, 40, row);
|
||||
const declaredOffset = cursor.readUInt32();
|
||||
const flags = cursor.readUInt32();
|
||||
const name = readMetadataString(
|
||||
@@ -462,7 +426,11 @@ export const readResource = ({
|
||||
const implementationRaw = cursor.readIndex(
|
||||
layout.codedIndexSize("Implementation"),
|
||||
);
|
||||
const implementationToken = codedToken(implementationRaw, 2, [38, 35, 39]);
|
||||
const implementationToken = metadataCodedToken(
|
||||
implementationRaw,
|
||||
2,
|
||||
[38, 35, 39],
|
||||
);
|
||||
let dataLength: number | null = null;
|
||||
let dataSha256: string | null = null;
|
||||
if (implementationRaw === 0) {
|
||||
|
||||
@@ -4,18 +4,15 @@ import {
|
||||
type ManagedNativeBoundaryInspection,
|
||||
type ManagedParseIssue,
|
||||
} from "../domain/managedArtifact.js";
|
||||
import { type ManagedMetadataLayout } from "./ManagedMetadataLayout.js";
|
||||
import {
|
||||
metadataRowOffset,
|
||||
type ManagedMetadataLayout,
|
||||
} from "./ManagedMetadataLayout.js";
|
||||
import {
|
||||
MetadataRowCursor,
|
||||
metadataRowCursor,
|
||||
metadataCodedToken,
|
||||
metadataToken,
|
||||
readMetadataString,
|
||||
} from "./ManagedMetadataHeaps.js";
|
||||
import { managedTableRowCounts } from "./ManagedMetadataInventory.js";
|
||||
import type { ManagedMetadataInventory } from "./ManagedMetadataInventory.js";
|
||||
import { managedFailure } from "./ManagedReaderFailure.js";
|
||||
import type { ManagedNativeBoundaryInspectionLimits } from "./ManagedNativeBoundaryInspector.js";
|
||||
import type { ManagedPeLayout } from "./ManagedPeReader.js";
|
||||
|
||||
@@ -46,48 +43,6 @@ interface MemberCore {
|
||||
readonly rva: number | null;
|
||||
}
|
||||
|
||||
interface RowCursorContext {
|
||||
readonly bytes: Buffer;
|
||||
readonly layout: ManagedMetadataLayout;
|
||||
readonly table: number;
|
||||
readonly row: number;
|
||||
}
|
||||
|
||||
const rowCursor = ({
|
||||
bytes,
|
||||
layout,
|
||||
table,
|
||||
row,
|
||||
}: RowCursorContext): MetadataRowCursor => {
|
||||
const descriptor = layout.table(table);
|
||||
const start = metadataRowOffset(layout, table, row);
|
||||
if (descriptor === undefined)
|
||||
throw managedFailure(
|
||||
"invalid-row",
|
||||
`metadata.${String(table)}`,
|
||||
"Metadata table is absent",
|
||||
start,
|
||||
);
|
||||
return new MetadataRowCursor(
|
||||
bytes,
|
||||
start,
|
||||
start + descriptor.rowSize,
|
||||
`metadata.${descriptor.name}`,
|
||||
);
|
||||
};
|
||||
|
||||
const codedToken = (
|
||||
raw: number,
|
||||
tagBits: number,
|
||||
tables: readonly number[],
|
||||
): string | null => {
|
||||
const tagMask = (1 << tagBits) - 1;
|
||||
const table = tables[raw & tagMask];
|
||||
const row = raw >> tagBits;
|
||||
if (table === undefined || row === 0) return null;
|
||||
return metadataToken(table, row);
|
||||
};
|
||||
|
||||
const flagsHex = (value: number): string =>
|
||||
`0x${value.toString(16).padStart(4, "0")}`;
|
||||
|
||||
@@ -117,7 +72,7 @@ export const parseModuleRefs = (
|
||||
const refs: ModuleRef[] = [];
|
||||
const table = layout.table(26);
|
||||
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
|
||||
const cursor = rowCursor({ bytes, layout, table: 26, row });
|
||||
const cursor = metadataRowCursor(bytes, layout, 26, row);
|
||||
refs.push({
|
||||
token: metadataToken(26, row),
|
||||
row_offset: cursor.start,
|
||||
@@ -140,7 +95,7 @@ export const parseFields = (
|
||||
const fields = new Map<string, MemberCore>();
|
||||
const table = layout.table(4);
|
||||
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
|
||||
const cursor = rowCursor({ bytes, layout, table: 4, row });
|
||||
const cursor = metadataRowCursor(bytes, layout, 4, row);
|
||||
const flags = cursor.readUInt16();
|
||||
const name = readMetadataString(
|
||||
bytes,
|
||||
@@ -171,7 +126,7 @@ export const parseMethods = (
|
||||
const methods = new Map<string, MemberCore>();
|
||||
const table = layout.table(6);
|
||||
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
|
||||
const cursor = rowCursor({ bytes, layout, table: 6, row });
|
||||
const cursor = metadataRowCursor(bytes, layout, 6, row);
|
||||
const rva = cursor.readUInt32();
|
||||
const implFlags = cursor.readUInt16();
|
||||
const flags = cursor.readUInt16();
|
||||
@@ -216,9 +171,9 @@ export const parseImplMaps = ({
|
||||
const imports: NativeImport[] = [];
|
||||
const table = layout.table(28);
|
||||
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
|
||||
const cursor = rowCursor({ bytes, layout, table: 28, row });
|
||||
const cursor = metadataRowCursor(bytes, layout, 28, row);
|
||||
const mappingFlags = cursor.readUInt16();
|
||||
const memberToken = codedToken(
|
||||
const memberToken = metadataCodedToken(
|
||||
cursor.readIndex(layout.codedIndexSize("MemberForwarded")),
|
||||
1,
|
||||
[4, 6],
|
||||
|
||||
@@ -234,7 +234,7 @@ const limitationsFor = (operation: ManagedToolName): readonly string[] =>
|
||||
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
|
||||
]
|
||||
: [
|
||||
"This capability decodes bounded PE/CLI metadata members, signatures, and file-backed method bodies; decompiled C# and cross-build matching are separate future contracts.",
|
||||
"This capability decodes bounded PE/CLI metadata members, signatures, and file-backed method bodies; decompiled C# reconstruction and cross-build member comparison are separate operations.",
|
||||
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
|
||||
],
|
||||
);
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,25 @@
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
|
||||
/** Read through EOF, returning undefined on overflow; consume at most maxBytes + 1 bytes without closing the handle. */
|
||||
export const readBoundedFileBytes = async (
|
||||
handle: FileHandle,
|
||||
maxBytes: number,
|
||||
): Promise<Buffer | undefined> => {
|
||||
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0)
|
||||
throw new RangeError("File byte limit must be a nonnegative safe integer");
|
||||
const chunks: Buffer[] = [];
|
||||
const buffer = Buffer.allocUnsafe(Math.min(64 * 1_024, maxBytes + 1));
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const { bytesRead } = await handle.read(
|
||||
buffer,
|
||||
0,
|
||||
Math.min(buffer.length, maxBytes - total + 1),
|
||||
null,
|
||||
);
|
||||
if (bytesRead === 0) return Buffer.concat(chunks, total);
|
||||
total += bytesRead;
|
||||
if (total > maxBytes) return undefined;
|
||||
chunks.push(Buffer.from(buffer.subarray(0, bytesRead)));
|
||||
}
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { traverseDirectory } from "./ReferenceSourceReaderEntries.js";
|
||||
import { compareNames } from "./ReferenceSourceReaderPaths.js";
|
||||
import {
|
||||
type ReferenceSourceLimits,
|
||||
type ReferenceSourceReaderOptions,
|
||||
@@ -62,7 +62,9 @@ export const readReferenceSource = async (
|
||||
};
|
||||
const traversal = await traverse(state);
|
||||
if (!traversal.ok) return traversal;
|
||||
state.entries.sort((left, right) => compareNames(left.path, right.path));
|
||||
state.entries.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.path, right.path),
|
||||
);
|
||||
return ok({
|
||||
root: canonicalRoot,
|
||||
entries: state.entries,
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { readdir, readlink, realpath } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
import { entryFailure, safeSize } from "./ReferenceSourceReaderErrors.js";
|
||||
import {
|
||||
compareNames,
|
||||
pathFromRoot,
|
||||
withinRoot,
|
||||
} from "./ReferenceSourceReaderPaths.js";
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
import { pathFromRoot } from "./ReferenceSourceReaderPaths.js";
|
||||
import { readStableFile } from "./ReferenceSourceReaderFile.js";
|
||||
import {
|
||||
isAborted,
|
||||
@@ -97,7 +95,10 @@ const readDirectoryNames = async (
|
||||
| { readonly ok: false; readonly message: string }
|
||||
> => {
|
||||
try {
|
||||
return { ok: true, value: (await readdir(path)).sort(compareNames) };
|
||||
return {
|
||||
ok: true,
|
||||
value: (await readdir(path)).sort(compareUnicodeCodePoints),
|
||||
};
|
||||
} catch {
|
||||
return { ok: false, message: "Directory could not be read" };
|
||||
}
|
||||
@@ -236,7 +237,7 @@ const describeSymlink = async (
|
||||
try {
|
||||
const rawTarget = await readlink(absolute);
|
||||
const lexicalTarget = resolve(dirname(absolute), rawTarget);
|
||||
if (!withinRoot(root, lexicalTarget))
|
||||
if (!isPathWithinRoot(root, lexicalTarget))
|
||||
return {
|
||||
status: "read",
|
||||
kind: "symlink",
|
||||
@@ -246,7 +247,7 @@ const describeSymlink = async (
|
||||
};
|
||||
try {
|
||||
const canonicalTarget = await realpath(lexicalTarget);
|
||||
return withinRoot(root, canonicalTarget)
|
||||
return isPathWithinRoot(root, canonicalTarget)
|
||||
? {
|
||||
status: "read",
|
||||
kind: "symlink",
|
||||
|
||||
@@ -19,9 +19,7 @@ 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 };
|
||||
|
||||
@@ -43,30 +41,10 @@ type FinalizeFileReadRequest = {
|
||||
|
||||
const prepareFileRead = async (
|
||||
request: StableFileRequest,
|
||||
handle: FileHandle,
|
||||
): 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,
|
||||
);
|
||||
const { path, expected, signal } = request;
|
||||
if (isAborted(signal)) {
|
||||
await handle.close().catch(() => undefined);
|
||||
return {
|
||||
status: "failed",
|
||||
entry: entryFailure(
|
||||
@@ -80,7 +58,6 @@ const prepareFileRead = async (
|
||||
}
|
||||
const before = await handle.stat({ bigint: true });
|
||||
if (!sameFile(expected, before)) {
|
||||
await handle.close().catch(() => undefined);
|
||||
return {
|
||||
status: "failed",
|
||||
entry: entryFailure(
|
||||
@@ -92,7 +69,7 @@ const prepareFileRead = async (
|
||||
),
|
||||
};
|
||||
}
|
||||
return { status: "ready", handle, before, parentBefore };
|
||||
return { status: "ready", before };
|
||||
};
|
||||
|
||||
const readFileContents = async (request: {
|
||||
@@ -211,9 +188,22 @@ export const readStableFile = async (
|
||||
request;
|
||||
let handle: FileHandle | undefined;
|
||||
try {
|
||||
const prepared = await prepareFileRead(request);
|
||||
const parentBefore = await validateDirectory(
|
||||
root,
|
||||
rootIdentity,
|
||||
dirname(absolute),
|
||||
);
|
||||
if (!parentBefore.ok)
|
||||
return entryFailure(
|
||||
path,
|
||||
"file",
|
||||
parentBefore.code,
|
||||
parentBefore.message,
|
||||
safeSize(expected.size),
|
||||
);
|
||||
handle = await open(absolute, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
const prepared = await prepareFileRead(request, handle);
|
||||
if (prepared.status === "failed") return prepared.entry;
|
||||
handle = prepared.handle;
|
||||
const contents = await readFileContents({
|
||||
handle,
|
||||
path,
|
||||
@@ -228,7 +218,7 @@ export const readStableFile = async (
|
||||
path,
|
||||
handle,
|
||||
before: prepared.before,
|
||||
parentBefore: prepared.parentBefore,
|
||||
parentBefore,
|
||||
chunks: contents.chunks,
|
||||
total: contents.total,
|
||||
});
|
||||
|
||||
@@ -1,27 +1,10 @@
|
||||
import { isAbsolute, relative, sep } from "node:path";
|
||||
import { 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))
|
||||
);
|
||||
};
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
|
||||
export const pathFromRoot = (root: string, path: string): string => {
|
||||
const value = relative(root, path);
|
||||
return withinRoot(root, path)
|
||||
return isPathWithinRoot(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;
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@ 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 { isPathWithinRoot } from "../domain/localPath.js";
|
||||
import {
|
||||
type BigStats,
|
||||
type ReferenceSourceFailureCode,
|
||||
@@ -62,7 +62,7 @@ export const validateDirectory = async (
|
||||
message: "Directory identity changed",
|
||||
};
|
||||
const canonical = await realpath(path);
|
||||
if (canonical !== path || !withinRoot(root, canonical))
|
||||
if (canonical !== path || !isPathWithinRoot(root, canonical))
|
||||
return {
|
||||
ok: false,
|
||||
code: "changed",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { temporaryFilterHandle } from "./ReplaySeccompFile.js";
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
@@ -14,7 +15,6 @@ import { resolveLinuxRuntimeClosure } from "./LinuxRuntimeClosure.js";
|
||||
import {
|
||||
assertRuntimeCommitment,
|
||||
systemdArguments,
|
||||
temporaryFilterHandle,
|
||||
type RuntimeFile,
|
||||
} from "./LinuxJavaScriptReplaySandbox.js";
|
||||
import {
|
||||
@@ -56,39 +56,42 @@ export class LinuxJavaScriptReplayRunner implements JavaScriptReplayRunner {
|
||||
const closure = await validateReplayCommitments(prepared, policy);
|
||||
const encoded = buildWorkerPayload(prepared);
|
||||
const filter = await temporaryFilterHandle();
|
||||
const replayProcess = launchReplayProcess({
|
||||
prepared,
|
||||
policy,
|
||||
encoded,
|
||||
closure,
|
||||
filterPath: filter.path,
|
||||
unit,
|
||||
signal,
|
||||
});
|
||||
try {
|
||||
const collected = await replayProcess.completion;
|
||||
if (replayProcess.terminationRequest !== undefined)
|
||||
await replayProcess.terminationRequest;
|
||||
const unitResult = await observeUnitResult(policy.systemctlPath, unit);
|
||||
const cleanup = await observeCleanup(policy.systemctlPath, unit);
|
||||
return resolveReplayResult({
|
||||
const replayProcess = launchReplayProcess({
|
||||
prepared,
|
||||
collected,
|
||||
unitResult,
|
||||
cleanup,
|
||||
termination: replayProcess.termination,
|
||||
policy,
|
||||
encoded,
|
||||
closure,
|
||||
filterPath: filter.path,
|
||||
unit,
|
||||
signal,
|
||||
});
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", replayProcess.terminate);
|
||||
if (replayProcess.timeout !== undefined)
|
||||
clearTimeout(replayProcess.timeout);
|
||||
if (
|
||||
replayProcess.child !== undefined &&
|
||||
replayProcess.child.exitCode === null
|
||||
) {
|
||||
replayProcess.requestTermination();
|
||||
await replayProcess.terminationRequest;
|
||||
try {
|
||||
const collected = await replayProcess.completion;
|
||||
if (replayProcess.terminationRequest !== undefined)
|
||||
await replayProcess.terminationRequest;
|
||||
const unitResult = await observeUnitResult(policy.systemctlPath, unit);
|
||||
const cleanup = await observeCleanup(policy.systemctlPath, unit);
|
||||
return resolveReplayResult({
|
||||
prepared,
|
||||
collected,
|
||||
unitResult,
|
||||
cleanup,
|
||||
termination: replayProcess.termination,
|
||||
});
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", replayProcess.terminate);
|
||||
if (replayProcess.timeout !== undefined)
|
||||
clearTimeout(replayProcess.timeout);
|
||||
if (
|
||||
replayProcess.child !== undefined &&
|
||||
replayProcess.child.exitCode === null
|
||||
) {
|
||||
replayProcess.requestTermination();
|
||||
await replayProcess.terminationRequest;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await filter.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { open } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import {
|
||||
@@ -6,7 +5,6 @@ import {
|
||||
type EnabledJavaScriptReplayPolicy,
|
||||
type PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import { buildLinuxX64ReplaySeccomp } from "./LinuxSeccompPolicy.js";
|
||||
import { resolveLinuxRuntimeClosure } from "./LinuxRuntimeClosure.js";
|
||||
|
||||
export type RuntimeFile = Awaited<
|
||||
@@ -38,24 +36,6 @@ export const assertRuntimeCommitment = (
|
||||
throw new TypeError("Replay runtime closure changed after approval");
|
||||
};
|
||||
|
||||
export const temporaryFilterHandle = async () => {
|
||||
const { mkdtemp, writeFile, rm } = await import("node:fs/promises");
|
||||
const { tmpdir } = await import("node:os");
|
||||
const { join } = await import("node:path");
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-replay-filter-"));
|
||||
const path = join(directory, "seccomp.bpf");
|
||||
await writeFile(path, buildLinuxX64ReplaySeccomp(), { mode: 0o600 });
|
||||
const handle = await open(path, "r");
|
||||
return {
|
||||
path,
|
||||
handle,
|
||||
close: async () => {
|
||||
await handle.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const systemdArguments = (
|
||||
options: SandboxArgumentsOptions,
|
||||
): string[] => {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { mkdtemp, open, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { buildLinuxX64ReplaySeccomp } from "./LinuxSeccompPolicy.js";
|
||||
|
||||
/** Own a private seccomp file and descriptor until probe or execution cleanup. */
|
||||
export const temporaryFilterHandle = async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-replay-filter-"));
|
||||
const path = join(directory, "seccomp.bpf");
|
||||
try {
|
||||
await writeFile(path, buildLinuxX64ReplaySeccomp(), { mode: 0o600 });
|
||||
const handle = await open(path, "r");
|
||||
return {
|
||||
path,
|
||||
handle,
|
||||
close: async () => {
|
||||
try {
|
||||
await handle.close();
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
@@ -1,15 +1,6 @@
|
||||
import { temporaryFilterHandle } from "./ReplaySeccompFile.js";
|
||||
import { constants } from "node:fs";
|
||||
import {
|
||||
mkdtemp,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
rm,
|
||||
stat,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { open, readFile, realpath, stat } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { spawn, type StdioOptions } from "node:child_process";
|
||||
|
||||
@@ -20,12 +11,11 @@ import type {
|
||||
ReplaySourceBytes,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import { digestBytes } from "../application/JavaScriptReplayPlanning.js";
|
||||
import {
|
||||
buildLinuxX64ReplaySeccomp,
|
||||
linuxX64ReplaySeccompDigest,
|
||||
} from "./LinuxSeccompPolicy.js";
|
||||
import { linuxX64ReplaySeccompDigest } from "./LinuxSeccompPolicy.js";
|
||||
import { resolveLinuxRuntimeClosure } from "./LinuxRuntimeClosure.js";
|
||||
|
||||
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
|
||||
|
||||
const VERSION_OUTPUT_LIMIT = 16 * 1024;
|
||||
|
||||
/** Production planning host for descriptor-backed reads and fail-closed probes. */
|
||||
@@ -45,7 +35,11 @@ export class SystemJavaScriptReplayHost implements JavaScriptReplayHost {
|
||||
throw new RangeError(
|
||||
`Replay source exceeds its declared limit: ${canonicalPath}`,
|
||||
);
|
||||
const bytes = await handle.readFile();
|
||||
const bytes = await readBoundedFileBytes(handle, maximumBytes);
|
||||
if (bytes === undefined)
|
||||
throw new RangeError(
|
||||
`Replay source exceeds its declared limit: ${canonicalPath}`,
|
||||
);
|
||||
return { canonicalPath, bytes };
|
||||
} finally {
|
||||
await handle.close();
|
||||
@@ -97,10 +91,7 @@ export class SystemJavaScriptReplayHost implements JavaScriptReplayHost {
|
||||
.length === 0
|
||||
)
|
||||
throw new TypeError("Controlled replay requires delegated cgroup v2");
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-replay-probe-"));
|
||||
const filterPath = join(directory, "seccomp.bpf");
|
||||
await writeFile(filterPath, buildLinuxX64ReplaySeccomp(), { mode: 0o600 });
|
||||
const filter = await open(filterPath, "r");
|
||||
const filter = await temporaryFilterHandle();
|
||||
try {
|
||||
await run(
|
||||
policy.bubblewrapPath,
|
||||
@@ -130,7 +121,7 @@ export class SystemJavaScriptReplayHost implements JavaScriptReplayHost {
|
||||
"--",
|
||||
"/usr/bin/true",
|
||||
],
|
||||
["ignore", "pipe", "pipe", filter.fd],
|
||||
["ignore", "pipe", "pipe", filter.handle.fd],
|
||||
);
|
||||
await runExpectFailure(
|
||||
policy.bubblewrapPath,
|
||||
@@ -162,7 +153,7 @@ export class SystemJavaScriptReplayHost implements JavaScriptReplayHost {
|
||||
"--mount",
|
||||
"/usr/bin/true",
|
||||
],
|
||||
["ignore", "pipe", "pipe", filter.fd],
|
||||
["ignore", "pipe", "pipe", filter.handle.fd],
|
||||
);
|
||||
await run(policy.systemdRunPath, [
|
||||
"--user",
|
||||
@@ -178,7 +169,6 @@ export class SystemJavaScriptReplayHost implements JavaScriptReplayHost {
|
||||
]);
|
||||
} finally {
|
||||
await filter.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
|
||||
/** Preserve a typed permission denial or contain an unexpected authority error. */
|
||||
export const permissionFailure = (
|
||||
failure: Awaited<ReturnType<PermissionAuthority["authorize"]>>,
|
||||
): Result<never, AnalysisError> => {
|
||||
if (failure.ok)
|
||||
return err(new AnalysisProtocolError("Expected a denied permission"));
|
||||
return err(
|
||||
failure.error instanceof PermissionRequiredError
|
||||
? failure.error
|
||||
: new AnalysisProtocolError(failure.error.message, {
|
||||
cause: failure.error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import {
|
||||
@@ -14,7 +15,7 @@ import { mcpProgressReporter } from "../mcpProgress.js";
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
import { recordSources } from "./helpers.js";
|
||||
|
||||
import type { ApplicationToolRegistration } from "./types.js";
|
||||
|
||||
const prepareContract = applicationToolContract(
|
||||
@@ -79,7 +80,10 @@ export const registerCharacterizationTools = (
|
||||
output.replay.evidence,
|
||||
output.evidence,
|
||||
].map((item) => parseEvidence(item));
|
||||
const recorded = recordSources(options.recordEvidence, sources);
|
||||
const recorded = recordSessionEvidenceSources(
|
||||
options.recordEvidence,
|
||||
sources,
|
||||
);
|
||||
if (!recorded.ok) return toCallToolResult(recorded, executeContract);
|
||||
return toCallToolResult(result, executeContract, {
|
||||
evidenceResourcesAvailable: options.recordEvidence !== undefined,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { resolveCompareJavaScriptExportShapesRequestValidated } from "../../application/ApplicationWorkflowEvidenceResolver.js";
|
||||
@@ -7,7 +8,7 @@ import { javaScriptExportShapeComparisonResultSchema } from "../../domain/javasc
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
import { recordResult, recordSources } from "./helpers.js";
|
||||
import { recordResult } from "./helpers.js";
|
||||
import type { ApplicationToolRegistration } from "./types.js";
|
||||
|
||||
const contract = applicationToolContract("compare_javascript_export_shapes");
|
||||
@@ -31,7 +32,7 @@ export const registerCompareJavaScriptExportShapesTool = (
|
||||
Promise.resolve(compareJavaScriptExportShapesEvidenceValidated(parsed)),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, contract);
|
||||
const recorded = recordSources(options.recordEvidence, [
|
||||
const recorded = recordSessionEvidenceSources(options.recordEvidence, [
|
||||
parsed.left,
|
||||
parsed.right,
|
||||
]);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { resolveCompareSourceToBundleRequestValidated } from "../../application/ApplicationWorkflowEvidenceResolver.js";
|
||||
@@ -7,7 +8,7 @@ import { sourceToBundleComparisonResultSchema } from "../../domain/sourceToBundl
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
import { recordResult, recordSources } from "./helpers.js";
|
||||
import { recordResult } from "./helpers.js";
|
||||
import type { ApplicationToolRegistration } from "./types.js";
|
||||
|
||||
const contract = applicationToolContract("compare_source_to_bundle");
|
||||
@@ -30,7 +31,7 @@ export const registerCompareSourceToBundleTool = (
|
||||
Promise.resolve(compareSourceToBundleEvidenceValidated(resolved.value)),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, contract);
|
||||
const recorded = recordSources(options.recordEvidence, [
|
||||
const recorded = recordSessionEvidenceSources(options.recordEvidence, [
|
||||
resolved.value.application,
|
||||
]);
|
||||
if (!recorded.ok) return toCallToolResult(recorded, contract);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { resolveCompareApplicationVersionsRequestValidated } from "../../application/ApplicationWorkflowEvidenceResolver.js";
|
||||
@@ -7,7 +8,7 @@ import { applicationVersionComparisonResultSchema } from "../../domain/javascrip
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
import { recordResult, recordSources } from "./helpers.js";
|
||||
import { recordResult } from "./helpers.js";
|
||||
import type { ApplicationToolRegistration } from "./types.js";
|
||||
|
||||
const compareContract = applicationToolContract("compare_application_versions");
|
||||
@@ -40,7 +41,10 @@ export const registerCompareApplicationVersionsTool = (
|
||||
...parsed.left_native_observations,
|
||||
...parsed.right_native_observations,
|
||||
];
|
||||
const recorded = recordSources(options.recordEvidence, sources);
|
||||
const recorded = recordSessionEvidenceSources(
|
||||
options.recordEvidence,
|
||||
sources,
|
||||
);
|
||||
if (!recorded.ok) return toCallToolResult(recorded, compareContract);
|
||||
const comparison = applicationVersionComparisonResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { runControlledReplayValidated } from "../../application/JavaScriptReplayService.js";
|
||||
@@ -8,7 +9,7 @@ import { mcpProgressReporter } from "../mcpProgress.js";
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
import { recordSources } from "./helpers.js";
|
||||
|
||||
import type { ApplicationToolRegistration } from "./types.js";
|
||||
|
||||
const replayContract = applicationToolContract("run_controlled_replay");
|
||||
@@ -34,7 +35,7 @@ export const registerControlledReplayTool = (
|
||||
if (!result.ok) return toCallToolResult(result, replayContract);
|
||||
const output = controlledReplayOutputSchema.parse(result.value);
|
||||
if (output.phase === "execute") {
|
||||
const sourcesRecorded = recordSources(
|
||||
const sourcesRecorded = recordSessionEvidenceSources(
|
||||
options.recordEvidence,
|
||||
output.source_evidence.map((item) => parseEvidence(item)),
|
||||
);
|
||||
|
||||
@@ -9,17 +9,6 @@ export const coverageWorkspaceUri = (workspace: {
|
||||
}): string =>
|
||||
`rea://reconstruction-coverage/${workspace.workspace_id}/revision/${String(workspace.revision)}`;
|
||||
|
||||
export const recordSources = (
|
||||
recordEvidence: ApplicationToolRegistration["recordEvidence"],
|
||||
sources: readonly Evidence[],
|
||||
) => {
|
||||
for (const source of sources) {
|
||||
const recorded = recordEvidence?.(source);
|
||||
if (recorded !== undefined && !recorded.ok) return recorded;
|
||||
}
|
||||
return { ok: true as const, value: null };
|
||||
};
|
||||
|
||||
export const recordResult = (
|
||||
options: ApplicationToolRegistration,
|
||||
contract: (typeof APPLICATION_TOOL_CONTRACTS)[number],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import {
|
||||
@@ -8,7 +9,7 @@ import { applicationToolContract } from "../../contracts/applicationToolContract
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
import { recordResult, recordSources } from "./helpers.js";
|
||||
import { recordResult } from "./helpers.js";
|
||||
import type { ApplicationToolRegistration } from "./types.js";
|
||||
|
||||
const contract = applicationToolContract(
|
||||
@@ -32,7 +33,7 @@ export const registerReconstructionObligationLedgerTool = (
|
||||
),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, contract);
|
||||
const recorded = recordSources(
|
||||
const recorded = recordSessionEvidenceSources(
|
||||
options.recordEvidence,
|
||||
resolved.value.evidence_bundle.records,
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import {
|
||||
@@ -9,7 +10,7 @@ import { reconstructionReadinessReportSchema } from "../../domain/reconstruction
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
import { recordSources } from "./helpers.js";
|
||||
|
||||
import type { ApplicationToolRegistration } from "./types.js";
|
||||
|
||||
const contract = applicationToolContract("evaluate_reconstruction_readiness");
|
||||
@@ -31,7 +32,7 @@ export const registerReconstructionReadinessTool = (
|
||||
),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, contract);
|
||||
const recorded = recordSources(
|
||||
const recorded = recordSessionEvidenceSources(
|
||||
options.recordEvidence,
|
||||
resolved.value.evidence_bundle.records,
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { resolveTraceApplicationFeatureRequestValidated } from "../../application/ApplicationWorkflowEvidenceResolver.js";
|
||||
@@ -6,7 +7,7 @@ import { applicationToolContract } from "../../contracts/applicationToolContract
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
import { recordResult, recordSources } from "./helpers.js";
|
||||
import { recordResult } from "./helpers.js";
|
||||
import type { ApplicationToolRegistration } from "./types.js";
|
||||
|
||||
const traceContract = applicationToolContract("trace_application_feature");
|
||||
@@ -33,7 +34,10 @@ export const registerTraceFeatureTool = (
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, traceContract);
|
||||
const sources = [parsed.application, ...parsed.native_observations];
|
||||
const recorded = recordSources(options.recordEvidence, sources);
|
||||
const recorded = recordSessionEvidenceSources(
|
||||
options.recordEvidence,
|
||||
sources,
|
||||
);
|
||||
if (!recorded.ok) return toCallToolResult(recorded, traceContract);
|
||||
return recordResult(options, traceContract, result.value);
|
||||
},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { recordSessionEvidenceSources } from "../sessionEvidence.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { resolveTraceJavaScriptSemanticsRequestValidated } from "../../application/ApplicationWorkflowEvidenceResolver.js";
|
||||
@@ -6,7 +7,7 @@ import { applicationToolContract } from "../../contracts/applicationToolContract
|
||||
import { logToolExecution } from "../toolLogging.js";
|
||||
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "../toolResult.js";
|
||||
import { recordResult, recordSources } from "./helpers.js";
|
||||
import { recordResult } from "./helpers.js";
|
||||
import type { ApplicationToolRegistration } from "./types.js";
|
||||
|
||||
const contract = applicationToolContract("trace_javascript_semantics");
|
||||
@@ -31,7 +32,7 @@ export const registerTraceJavaScriptSemanticsTool = (
|
||||
),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, contract);
|
||||
const recorded = recordSources(options.recordEvidence, [
|
||||
const recorded = recordSessionEvidenceSources(options.recordEvidence, [
|
||||
resolved.value.application,
|
||||
]);
|
||||
if (!recorded.ok) return toCallToolResult(recorded, contract);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { writeAnalysisSnapshot } from "../application/AnalysisSnapshotFiles.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import {
|
||||
reportLifecycleEnd,
|
||||
reportLifecycleStart,
|
||||
} from "./lifecycleProgress.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import { permissionFailure } from "./permissionFailure.js";
|
||||
import { projectPermissionFailure } from "../application/PermissionFailure.js";
|
||||
import type { LifecycleToolRegistration } from "./registerSessionTools.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
@@ -47,7 +47,10 @@ export const registerCloseLifecycleTool = ({
|
||||
"write",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return toCallToolResult(permissionFailure(authorized), closeContract);
|
||||
return toCallToolResult(
|
||||
err(projectPermissionFailure(authorized.error)),
|
||||
closeContract,
|
||||
);
|
||||
}
|
||||
const snapshot = session.exportAnalysisSnapshot();
|
||||
if (!snapshot.ok) return toCallToolResult(snapshot, closeContract);
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { registerJavaScriptApplicationGraphResource } from "./registerJavaScriptApplicationGraphResource.js";
|
||||
import { registerReconstructionObligationLedgerResource } from "./registerReconstructionObligationLedgerResource.js";
|
||||
import { registerReconstructionReadinessResource } from "./registerReconstructionReadinessResource.js";
|
||||
import { jsonResource } from "./resourceResult.js";
|
||||
|
||||
/** Expose immutable session-owned Evidence v2 records as MCP resources. */
|
||||
export const registerEvidenceResources = (
|
||||
@@ -118,15 +119,7 @@ const registerSessionEvidenceResource = (
|
||||
throw new ResourceNotFoundError(uri.href);
|
||||
const evidence = session.evidenceById(evidenceId);
|
||||
if (evidence === undefined) throw new ResourceNotFoundError(uri.href);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.href,
|
||||
mimeType: "application/json",
|
||||
text: JSON.stringify(evidence, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
return jsonResource(uri.href, evidence);
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -398,16 +391,6 @@ const pick = (
|
||||
return entries.length === 0 ? undefined : Object.fromEntries(entries);
|
||||
};
|
||||
|
||||
const jsonResource = (uri: string, value: JsonValue) => ({
|
||||
contents: [
|
||||
{
|
||||
uri,
|
||||
mimeType: "application/json" as const,
|
||||
text: JSON.stringify(value, null, 2),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const ARTIFACT_COLLECTIONS = new Set(["nodes", "occurrences", "edges"]);
|
||||
|
||||
const objectValue = (
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { projectPermissionFailure } from "../application/PermissionFailure.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type {
|
||||
@@ -8,10 +9,6 @@ import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
} from "../domain/errors.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import { err } from "../domain/result.js";
|
||||
@@ -61,13 +58,7 @@ export const registerEvidenceTools = (
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return toCallToolResult(
|
||||
err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
),
|
||||
err(projectPermissionFailure(authorized.error)),
|
||||
contract,
|
||||
);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user