fix: consolidate boundary ownership and cleanup failure paths (#477)

This commit is contained in:
morluto
2026-09-08 10:59:13 +08:00
committed by GitHub
parent c490d85045
commit 2160d4fae5
138 changed files with 2220 additions and 1781 deletions
+6 -2
View File
@@ -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",
+2 -4
View File
@@ -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,
+293
View File
@@ -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("&amp;", "&")
.replaceAll("&lt;", "<")
.replaceAll("&gt;", ">")
.replaceAll("&quot;", '"')
.replaceAll("&apos;", "'");
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");
};
+47 -20
View File
@@ -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;
+2 -10
View File
@@ -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`;
+2 -8
View File
@@ -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(
+4 -19
View File
@@ -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],
+4 -19
View File
@@ -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);
};
+2 -25
View File
@@ -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;
};
+2 -10
View File
@@ -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(
+2 -5
View File
@@ -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;
+18 -72
View File
@@ -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 });
}
+3 -16
View File
@@ -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,
+13
View File
@@ -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 });
+7 -10
View File
@@ -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. */
+2 -9
View File
@@ -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,
+58 -113
View File
@@ -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 (
+9 -22
View File
@@ -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(
+51 -131
View File
@@ -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;
+139
View File
@@ -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;
+17 -19
View File
@@ -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();