chore: sync captured review base for PR 2815

This commit is contained in:
morluto
2026-10-13 23:09:50 +08:00
234 changed files with 12183 additions and 1979 deletions
+32 -7
View File
@@ -45,7 +45,7 @@ const methodsOf = (summary: ClassSummary) => {
reported_signature: method.signature,
overload_index: index,
is_constructor: method.is_constructor,
dex_descriptor: null,
dex_descriptor: method.dex_descriptor,
};
});
};
@@ -314,11 +314,25 @@ const traceReferences = async (
): Promise<JsonValue> => {
const methodName = request.input.method_name;
const candidates = matchingMethods(summary, request);
if (candidates.length > 1)
throw new AnalysisCapabilityUnavailableError(
"jadx",
request.operation,
`References require a unique method name; ${summary.full_name}.${methodName} has ${candidates.length} overloads. No unambiguous reference result is available.`,
if (methodName === undefined && request.input.overload_index !== undefined)
inputFailure(
request,
"overload_index",
"Method name is required for an overload index.",
);
if (candidates.length > 1 && request.input.overload_index === undefined)
inputFailure(
request,
"overload_index",
`Select one of ${candidates.length} overloads: ${candidates.map((method) => `${method.overload_index}: ${method.reported_signature}`).join("; ")}`,
);
const index = request.input.overload_index ?? 0;
const selected = methodName === undefined ? undefined : candidates[index];
if (methodName !== undefined && selected === undefined)
inputFailure(
request,
"overload_index",
`Index ${index} is outside the ${candidates.length} matching overloads.`,
);
const expectedTarget =
methodName === undefined
@@ -329,7 +343,9 @@ const traceReferences = async (
methodName === undefined ? "get_xrefs_to_class" : "get_xrefs_to_method",
{
class_name: summary.full_name,
...(methodName === undefined ? {} : { method_name: methodName }),
...(methodName === undefined
? {}
: { method_name: methodName, overload_index: index }),
limit: 2_147_483_647,
resolve_line: false,
},
@@ -337,6 +353,9 @@ const traceReferences = async (
);
if (
xrefs.target !== expectedTarget ||
(selected !== undefined &&
(xrefs.overload_index !== index ||
xrefs.reported_signature !== selected.reported_signature)) ||
xrefs.total !== xrefs.count ||
xrefs.count !== xrefs.items.length
)
@@ -348,6 +367,9 @@ const traceReferences = async (
engine,
class_name: summary.full_name,
method_name: methodName ?? null,
overload_index: selected?.overload_index ?? null,
reported_signature: selected?.reported_signature ?? null,
dex_descriptor: selected?.dex_descriptor ?? null,
total: xrefs.total,
references: xrefs.items.map((reference) => ({
kind: reference.kind,
@@ -357,7 +379,10 @@ const traceReferences = async (
top_class: reference.top_class,
source_line: null,
dex_offset: null,
direct_invokes: reference.direct_invokes ?? null,
direct_invokes_exhaustive: reference.direct_invokes_exhaustive ?? null,
})),
coverage: "complete",
reference_unit: "using_node",
});
};
+16
View File
@@ -2,6 +2,7 @@ import { z } from "zod";
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import type { AndroidOperation } from "../domain/android/androidAnalysis.js";
import { dexDescriptorSchema } from "../domain/android/androidAnalysis.js";
const count = z.number().int().nonnegative();
/** Selector failures authored by REA's bridge, separate from arbitrary engine errors. */
@@ -50,6 +51,7 @@ export const jadxClassSchema = z.object({
z.object({
name: z.string(),
signature: z.string(),
dex_descriptor: dexDescriptorSchema,
is_constructor: z.boolean(),
def_pos: z.number().int(),
}),
@@ -72,6 +74,8 @@ export const jadxMethodSchema = z.object({
});
export const jadxXrefsSchema = z.object({
target: z.string(),
overload_index: count.optional(),
reported_signature: z.string().optional(),
total: count,
count,
resolve_line: z.literal(false),
@@ -83,6 +87,18 @@ export const jadxXrefsSchema = z.object({
containing_class: z.string(),
top_class: z.string(),
def_pos: z.number().int(),
direct_invokes_exhaustive: z.boolean().optional(),
direct_invokes: z
.array(
z.object({
dex_entry: z.string().min(1),
source_raw_method_id: z.string().min(1),
dex_code_unit_offset: count,
dex_method_index: count,
opcode: z.string().regex(/^INVOKE_/u),
}),
)
.optional(),
}),
),
});
+23 -12
View File
@@ -18,7 +18,10 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { AndroidRequest } from "../domain/android/androidAnalysis.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { err, ok, type Result } from "../domain/result.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import {
createJadxWorkspaceRoot,
type JadxWorkspaceRoot,
} from "./JadxWorkspaceRoot.js";
import {
snapshotAndroidEngine,
snapshotAndroidTarget,
@@ -152,7 +155,7 @@ const hashAndroidSource = async (
interface PendingCleanup {
session: JadxSession | undefined;
root: PrivateRuntimeRoot | undefined;
root: JadxWorkspaceRoot | undefined;
readonly previousError: AnalysisError | undefined;
}
@@ -211,7 +214,7 @@ const cleanup = async (
interface RetainedSession {
readonly key: string;
readonly root: PrivateRuntimeRoot;
readonly root: JadxWorkspaceRoot;
readonly session: JadxSession;
readonly snapshot: string;
readonly jarHash: string;
@@ -325,7 +328,7 @@ export class JadxProvider implements AndroidAnalysisPort {
options?.signal === undefined
? timeout
: AbortSignal.any([options.signal, timeout]);
let root: PrivateRuntimeRoot | undefined;
let root: JadxWorkspaceRoot | undefined;
let session: JadxSession | undefined;
try {
if (target.format !== "apk")
@@ -389,20 +392,24 @@ export class JadxProvider implements AndroidAnalysisPort {
request.operation,
signal,
);
root = await PrivateRuntimeRoot.create({ prefix: "rea-android-" });
root = await createJadxWorkspaceRoot();
const workspaceSignal =
root.failureSignal === undefined
? signal
: AbortSignal.any([signal, root.failureSignal]);
const engine = await snapshotAndroidEngine(
configuration.jar,
jarHash,
root.path,
request.operation,
signal,
workspaceSignal,
);
const snapshot = await snapshotAndroidTarget(
target.path,
target.sha256,
root.path,
request.operation,
signal,
workspaceSignal,
);
const bridge = join(root.path, "ReaJadxBridge.java");
await copyFile(BRIDGE_SOURCE, bridge);
@@ -410,7 +417,7 @@ export class JadxProvider implements AndroidAnalysisPort {
const copiedBridgeHash = await hashAndroidSource(
bridge,
request.operation,
signal,
workspaceSignal,
);
if (copiedBridgeHash !== bridgeHash)
throw androidSourceChanged(
@@ -418,7 +425,7 @@ export class JadxProvider implements AndroidAnalysisPort {
BRIDGE_SOURCE,
undefined,
);
signal.throwIfAborted();
workspaceSignal.throwIfAborted();
session = new JadxSession(
{
command: configuration.java,
@@ -430,7 +437,7 @@ export class JadxProvider implements AndroidAnalysisPort {
],
cwd: root.path,
hostEnvironment: this.environment,
signal,
signal: workspaceSignal,
},
this.launcher,
);
@@ -445,6 +452,10 @@ export class JadxProvider implements AndroidAnalysisPort {
}
root = retained.root;
session = retained.session;
const activeSignal =
root.failureSignal === undefined
? signal
: AbortSignal.any([signal, root.failureSignal]);
const { snapshot } = retained;
const outcome = ok(
await session.execute({
@@ -453,10 +464,10 @@ export class JadxProvider implements AndroidAnalysisPort {
snapshot,
jarHash: retained.jarHash,
bridgeHash: retained.bridgeHash,
signal,
signal: activeSignal,
}),
);
signal.throwIfAborted();
activeSignal.throwIfAborted();
this.#retained = retained;
return outcome;
} catch (cause) {
+2 -1
View File
@@ -25,7 +25,8 @@ export const JADX_PROVIDER_IDENTITY = Object.freeze({
/** Audited engine coverage, kept outside portable Android semantics. */
export const JADX_LIMITATIONS = [
"Static decompiler observations do not establish runtime behavior; the APK is never executed.",
"Method signatures use provider display types; exact DEX descriptors and instruction offsets are unavailable. Overload indices are local to this engine and artifact.",
"Method signatures use provider display types; DEX prototypes come from frozen JADX metadata. Display names may be aliases, and overload indices are local to this engine and artifact.",
"Class inventories use parsed metadata before code generation, including synthetic members that may be omitted from decompiled source. Source positions remain unknown.",
"Incoming reference totals count JADX using nodes. Direct invoke entries within a using method report raw DEX code-unit offsets and method indexes, but coverage is limited to those nodes and directly matched invokes; it does not establish every possible dynamic or reflective call site.",
"Manifest summary fields are extracted by the upstream engine; decoded XML is retained for verification. APK signatures, split APKs, native libraries and Android runtime capture are not verified by this provider.",
] as const;
+224
View File
@@ -0,0 +1,224 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { lstat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { win32 } from "node:path";
import { fileURLToPath } from "node:url";
import { z } from "zod";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
/** Match the native owner's ordinary spelling only for extended local drive paths. */
const localDrivePath = (path: string): string =>
path.replace(/^\\\\\?\\(?=[A-Za-z]:\\)/u, "");
const guardianSource = fileURLToPath(
new URL("../../scripts/rea-android-workspace-guardian.mjs", import.meta.url),
);
const readySchema = z.strictObject({
path: z.string(),
volumeSerial: z.string().regex(/^[a-f0-9]{16}$/u),
fileId: z.string().regex(/^[a-f0-9]{32}$/u),
privateDacl: z.literal(true),
});
/** The Android provider needs a path and a cleanup owner, regardless of host. */
export interface JadxWorkspaceRoot {
readonly path: string;
readonly failureSignal?: AbortSignal;
close(): Promise<void>;
}
type GuardianExit = {
readonly code: number | null;
readonly signal: NodeJS.Signals | null;
readonly error?: Error;
};
const boundedWait = async <T>(
promise: Promise<T>,
milliseconds: number,
label: string,
): Promise<T> => {
let timer: NodeJS.Timeout | undefined;
try {
return await Promise.race([
promise,
new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => reject(new Error(label)), milliseconds);
}),
]);
} finally {
clearTimeout(timer);
}
};
/** A detached guardian retains native cleanup ownership without keeping its caller alive. */
const releaseGuardianReferences = (
child: ChildProcessWithoutNullStreams,
): void => {
child.stdin.destroy();
child.stdout.destroy();
child.stderr.destroy();
child.unref();
};
class WindowsJadxWorkspaceRoot implements JadxWorkspaceRoot {
readonly #failure = new AbortController();
readonly failureSignal = this.#failure.signal;
readonly #child: ChildProcessWithoutNullStreams;
readonly #exit: Promise<GuardianExit>;
readonly #diagnostics: () => string;
#closing = false;
#closePromise: Promise<void> | undefined;
private constructor(
readonly path: string,
child: ChildProcessWithoutNullStreams,
exit: Promise<GuardianExit>,
diagnostics: () => string,
) {
this.#child = child;
this.#exit = exit;
this.#diagnostics = diagnostics;
void this.#exit.then((result) => {
if (!this.#closing)
this.#failure.abort(
new Error(
`Android workspace guardian exited before cleanup: ${result.error?.message ?? result.code ?? result.signal ?? "unknown"}`,
),
);
});
}
static async create(): Promise<WindowsJadxWorkspaceRoot> {
const parent = tmpdir();
const child = spawn(process.execPath, [guardianSource, parent], {
detached: true,
windowsHide: true,
stdio: ["pipe", "pipe", "pipe"],
env: {
SystemRoot: process.env.SystemRoot,
WINDIR: process.env.WINDIR,
TEMP: parent,
TMP: parent,
},
});
let diagnostics = "";
child.stderr.on("data", (chunk: Buffer) => {
diagnostics = (diagnostics + chunk.toString()).slice(-8192);
});
const exit = new Promise<GuardianExit>((resolve) => {
child.once("error", (error: Error) =>
resolve({ code: null, signal: null, error }),
);
child.once("close", (code, signal) => resolve({ code, signal }));
});
const ready = new Promise<string>((resolve, reject) => {
let frame = "";
child.stdout.on("data", (chunk: Buffer) => {
frame += chunk.toString();
if (frame.length > 4096) {
reject(
new Error("Android workspace guardian readiness exceeded 4 KiB"),
);
return;
}
const end = frame.indexOf("\n");
if (end !== -1) resolve(frame.slice(0, end));
});
child.stdout.once("error", reject);
});
try {
const line = await boundedWait(
Promise.race([
ready,
exit.then((result) => {
throw new Error(
`Android workspace guardian exited during startup: ${result.error?.message ?? result.code ?? result.signal ?? "unknown"}; ${diagnostics}`,
);
}),
]),
15000,
"Android workspace guardian startup timed out",
);
const observation = readySchema.parse(JSON.parse(line));
if (
win32.dirname(localDrivePath(observation.path)).toLowerCase() !==
localDrivePath(win32.resolve(parent)).toLowerCase() ||
!/^rea-android-[a-f0-9]{32}$/u.test(win32.basename(observation.path))
)
throw new Error(
"Android workspace guardian returned an unexpected root",
);
child.stdout.resume();
return new WindowsJadxWorkspaceRoot(
observation.path,
child,
exit,
() => diagnostics,
);
} catch (cause) {
if (!child.stdin.destroyed) child.stdin.end();
try {
await boundedWait(
exit,
30000,
"Android workspace guardian did not settle after startup failure",
);
} catch (cleanupFailure) {
throw new AggregateError(
[cause, cleanupFailure],
"Android workspace guardian startup and cleanup failed",
);
} finally {
releaseGuardianReferences(child);
}
throw cause;
}
}
close(): Promise<void> {
this.#closing = true;
this.#closePromise ??= this.#finish().catch((cause: unknown) => {
this.#closePromise = undefined;
throw cause;
});
return this.#closePromise;
}
async #finish(): Promise<void> {
if (!this.#child.stdin.destroyed) this.#child.stdin.end();
let result: GuardianExit;
try {
result = await boundedWait(
this.#exit,
120000,
`Android workspace guardian cleanup timed out for ${this.path}`,
);
} catch (cause) {
releaseGuardianReferences(this.#child);
throw cause;
}
if (result.error !== undefined || result.code !== 0)
throw new Error(
`Android workspace guardian cleanup failed for ${this.path}: ${result.error?.message ?? result.code ?? result.signal ?? "unknown"}; ${this.#diagnostics()}`,
);
try {
await lstat(this.path);
} catch (cause) {
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
return;
throw cause;
}
throw new Error(
`Android workspace guardian exited but retained ${this.path}`,
);
}
}
/** POSIX retains its in-process root; Windows keeps a detached native owner. */
export const createJadxWorkspaceRoot = (): Promise<JadxWorkspaceRoot> =>
process.platform === "win32"
? WindowsJadxWorkspaceRoot.create()
: PrivateRuntimeRoot.create({ prefix: "rea-android-" });
+271 -10
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
APKTOOL_COMMAND_ENV,
@@ -10,29 +10,43 @@ import {
resolveApktoolCommand,
} from "./ApktoolConfiguration.js";
const lookup = vi.hoisted(() => ({ stat: vi.fn() }));
vi.mock("node:fs/promises", async (importOriginal) => ({
...(await importOriginal<typeof import("node:fs/promises")>()),
stat: lookup.stat,
}));
beforeEach(() => {
lookup.stat
.mockReset()
.mockRejectedValue(Object.assign(new Error("missing"), { code: "ENOENT" }));
});
describe("resolveApktoolCommand", () => {
it("prefers an absolute REA_APKTOOL_COMMAND", () => {
it("prefers an absolute REA_APKTOOL_COMMAND", async () => {
expect(
resolveApktoolCommand({
[APKTOOL_COMMAND_ENV]: "/usr/local/bin/apktool",
}),
await resolveApktoolCommand(
{
[APKTOOL_COMMAND_ENV]: "/usr/local/bin/apktool",
},
"linux",
),
).toEqual({
command: "/usr/local/bin/apktool",
commandSource: "environment",
});
});
it("falls back to PATH resolution without the environment key", () => {
expect(resolveApktoolCommand({})).toEqual({
it("leaves POSIX PATH lookup to process creation", async () => {
expect(await resolveApktoolCommand({}, "linux")).toEqual({
command: "apktool",
commandSource: "path",
});
});
it("rejects a relative environment path explicitly", () => {
expect(() =>
it("rejects a relative environment path explicitly", async () => {
await expect(
resolveApktoolCommand({ [APKTOOL_COMMAND_ENV]: "bin/apktool" }),
).toThrow(/must be an absolute path/u);
).rejects.toThrow(/must be an absolute path/u);
});
});
@@ -119,3 +133,250 @@ describe("apktoolInvocation", () => {
});
});
});
describe("Windows PATH launcher selection", () => {
const environment = {
Path: '"C:\\Selected Tools";C:\\Other Tools',
PathExt: ".EXE;.CMD;.BAT",
ComSpec: "C:\\Windows\\System32\\cmd.exe",
NoDefaultCurrentDirectoryInExePath: "",
};
const files = (...paths: string[]) => {
const selected = new Set(paths.map((path) => path.toLowerCase()));
lookup.stat.mockImplementation(async (path: string) => {
if (selected.has(path.toLowerCase())) return { isFile: () => true };
throw Object.assign(new Error("missing"), { code: "ENOENT" });
});
};
it.each([".BAT", ".CMD"])(
"resolves a default %s launcher before choosing cmd.exe for version and decode",
async (extension) => {
const command = `C:\\Selected Tools\\apktool${extension}`;
files(command);
const selection = await resolveApktoolCommand(environment, "win32");
expect(selection).toEqual({ command, commandSource: "path" });
for (const arguments_ of [
["--version"],
["d", "-o", "C:\\output folder", "C:\\target.apk"],
]) {
const invocation = apktoolInvocation(
selection,
arguments_,
environment,
"win32",
);
expect(invocation).toEqual({
command: environment.ComSpec,
arguments: [
"/d",
"/e:on",
"/v:off",
"/s",
"/c",
`"${[command, ...arguments_].map((token) => `"${token}"`).join(" ")}"`,
],
windowsVerbatimArguments: true,
});
}
},
);
it("honors PATH directory order before extension order", async () => {
files("C:\\Selected Tools\\apktool.CMD", "C:\\Other Tools\\apktool.EXE");
expect(await resolveApktoolCommand(environment, "win32")).toMatchObject({
command: "C:\\Selected Tools\\apktool.CMD",
});
});
it("honors the selected PATHEXT ordering", async () => {
files("C:\\Selected Tools\\apktool.CMD", "C:\\Selected Tools\\apktool.EXE");
expect(
await resolveApktoolCommand(
{ ...environment, PathExt: ".CMD;.EXE" },
"win32",
),
).toMatchObject({ command: "C:\\Selected Tools\\apktool.CMD" });
});
it("keeps native executable arguments outside cmd.exe interpretation", async () => {
const command = "C:\\Selected Tools\\apktool.EXE";
files(command);
const selection = await resolveApktoolCommand(environment, "win32");
const arguments_ = ["d", "C:\\input & literal.apk"];
expect(
apktoolInvocation(selection, arguments_, environment, "win32"),
).toEqual({
command,
arguments: arguments_,
windowsVerbatimArguments: false,
});
});
it("preserves explicit launcher spelling without searching PATH", async () => {
const command = "C:\\selected alias\\APKTOOL.cmd";
expect(
await resolveApktoolCommand(
{ ...environment, [APKTOOL_COMMAND_ENV]: command },
"win32",
),
).toEqual({ command, commandSource: "environment" });
expect(lookup.stat).not.toHaveBeenCalled();
});
it("does not inspect the current directory when the caller disables it", async () => {
await expect(
resolveApktoolCommand(environment, "win32"),
).rejects.toMatchObject({ code: "command_missing" });
expect(
lookup.stat.mock.calls.every(
([path]) =>
String(path).startsWith("C:\\Selected Tools\\") ||
String(path).startsWith("C:\\Other Tools\\"),
),
).toBe(true);
});
it("does not turn an explicitly empty PATHEXT into default extensions", async () => {
files("C:\\Selected Tools\\apktool.EXE");
await expect(
resolveApktoolCommand({ ...environment, PathExt: "" }, "win32"),
).rejects.toMatchObject({ code: "command_missing" });
expect(lookup.stat).not.toHaveBeenCalled();
});
it("skips directories without treating them as executable launchers", async () => {
files("C:\\Other Tools\\apktool.EXE");
const stat = lookup.stat.getMockImplementation()!;
lookup.stat.mockImplementation(async (path: string) =>
path === "C:\\Selected Tools\\apktool.EXE"
? { isFile: () => false }
: stat(path),
);
expect(await resolveApktoolCommand(environment, "win32")).toMatchObject({
command: "C:\\Other Tools\\apktool.EXE",
});
});
it("preserves inspection failures instead of reporting a missing command or selecting a later file", async () => {
lookup.stat.mockRejectedValue(
Object.assign(new Error("denied"), { code: "EACCES" }),
);
const failure = await resolveApktoolCommand(environment, "win32").catch(
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(ApktoolConfigurationFailure);
if (!(failure instanceof ApktoolConfigurationFailure)) throw failure;
expect(failure).toMatchObject({
code: "command_unresolved",
diagnostics: {
candidate_path: "C:\\Selected Tools\\apktool.EXE",
filesystem_error: "EACCES",
},
});
expect(apktoolConfigurationAvailability(failure)).toMatchObject({
code: "not_configured",
});
expect(lookup.stat).toHaveBeenCalledTimes(1);
});
it("honors cancellation before inspecting launchers", async () => {
const controller = new AbortController();
controller.abort();
await expect(
resolveApktoolCommand(environment, "win32", controller.signal),
).rejects.toMatchObject({ _tag: "AnalysisCancelledError" });
expect(lookup.stat).not.toHaveBeenCalled();
});
});
it("does not select a launcher when cancellation arrives during lookup", async () => {
const controller = new AbortController();
lookup.stat.mockImplementation(async () => {
controller.abort();
return { isFile: () => true };
});
await expect(
resolveApktoolCommand(
{
PATH: "C:\\Tools",
PATHEXT: ".CMD",
NoDefaultCurrentDirectoryInExePath: "1",
},
"win32",
controller.signal,
),
).rejects.toMatchObject({ _tag: "AnalysisCancelledError" });
expect(lookup.stat).toHaveBeenCalledTimes(1);
});
it.each(["EXE", ".CMD\\..\\outside.exe", ".CMD\0"])(
"rejects malformed PATHEXT %j before path lookup",
async (PATHEXT) => {
await expect(
resolveApktoolCommand({ PATH: "C:\\Tools", PATHEXT }, "win32"),
).rejects.toMatchObject({
code: "command_unresolved",
diagnostics: { invalid_extension: PATHEXT },
});
expect(lookup.stat).not.toHaveBeenCalled();
},
);
it("cancels a pending filesystem lookup and owns its eventual rejection", async () => {
const controller = new AbortController();
let started!: () => void;
let rejectLookup!: (cause: Error) => void;
const pendingStat = new Promise((_resolve, reject) => {
rejectLookup = reject;
});
const observed = new Promise<void>((resolve) => {
started = resolve;
});
lookup.stat.mockImplementation(() => {
started();
return pendingStat;
});
const pending = resolveApktoolCommand(
{
PATH: "C:\\Tools",
PATHEXT: ".CMD",
NODEFAULTCURRENTDIRECTORYINEXEPATH: "1",
},
"win32",
controller.signal,
);
await observed;
controller.abort();
await expect(pending).rejects.toMatchObject({
_tag: "AnalysisCancelledError",
});
rejectLookup(new Error("filesystem completed after cancellation"));
await Promise.resolve();
expect(lookup.stat).toHaveBeenCalledTimes(1);
});
it("bounds the entire pending PATH lookup by the selection deadline", async () => {
vi.useFakeTimers();
try {
lookup.stat.mockReturnValue(new Promise(() => {}));
const failure = expect(
resolveApktoolCommand(
{
PATH: "C:\\Tools",
PATHEXT: ".CMD",
NODEFAULTCURRENTDIRECTORYINEXEPATH: "1",
},
"win32",
),
).rejects.toMatchObject({
_tag: "AnalysisTimeoutError",
timeoutMs: 20_000,
});
await vi.advanceTimersByTimeAsync(20_000);
await failure;
expect(lookup.stat).toHaveBeenCalledTimes(1);
} finally {
vi.useRealTimers();
}
});
+118 -20
View File
@@ -1,5 +1,12 @@
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { isAbsolute } from "node:path";
import {
AnalysisCancelledError,
AnalysisTimeoutError,
} from "../domain/analysisErrorCore.js";
import { isAbsolute, win32 } from "node:path";
import { stat } from "node:fs/promises";
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js";
import { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
import {
execFileOutput,
@@ -27,30 +34,119 @@ export interface ApktoolCommandSelection {
}
/**
* Resolve the caller-supplied apktool launcher. `REA_APKTOOL_COMMAND` must
* be absolute so the selection stays explicit; without it, apktool is
* resolved from `PATH` at run time. Both the upstream wrapper script and
* `java -jar` launcher scripts work: REA only runs `<command> --version`
* and `<command> d ...`.
* Preserve an explicit launcher, or resolve the default Windows command before
* choosing native versus batch process creation. POSIX keeps execFile's PATH
* lookup. The resolved selection is reused for the version and decode runs.
*/
export const resolveApktoolCommand = (
export const resolveApktoolCommand = async (
environment: Readonly<Record<string, string | undefined>>,
): ApktoolCommandSelection => {
const configured = environment[APKTOOL_COMMAND_ENV];
if (configured === undefined || configured.trim() === "")
platform: NodeJS.Platform = process.platform,
signal?: AbortSignal,
): Promise<ApktoolCommandSelection> => {
if (signal?.aborted === true)
throw new AnalysisCancelledError("inspect_apktool_client");
const selectedEnvironment = snapshotEnvironment(environment, platform);
const configured = selectedEnvironment[APKTOOL_COMMAND_ENV];
if (configured !== undefined && configured.trim() !== "") {
if (
!(platform === "win32"
? win32.isAbsolute(configured)
: isAbsolute(configured))
)
throw new ApktoolConfigurationFailure(
"not_absolute",
`${APKTOOL_COMMAND_ENV} must be an absolute path to the apktool launcher`,
{ configured_command: configured },
);
return { command: configured, commandSource: "environment" };
}
if (platform !== "win32")
return { command: "apktool", commandSource: "path" };
if (!isAbsolute(configured))
throw new ApktoolConfigurationFailure(
"not_absolute",
`${APKTOOL_COMMAND_ENV} must be an absolute path to the apktool launcher`,
{ configured_command: configured },
);
return { command: configured, commandSource: "environment" };
const extensions = (selectedEnvironment.PATHEXT ?? ".EXE;.COM;.BAT;.CMD")
.split(";")
.filter((extension) => extension !== "");
for (const extension of extensions)
if (!extension.startsWith(".") || /[\\/:\0]/u.test(extension))
throw new ApktoolConfigurationFailure(
"command_unresolved",
"Windows PATHEXT must contain filename extensions, not paths",
{
selected_command: "apktool",
command_source: "path",
invalid_extension: extension,
},
);
const directories = (selectedEnvironment.PATH ?? "")
.split(";")
.filter((directory) => directory !== "");
if (selectedEnvironment.NODEFAULTCURRENTDIRECTORYINEXEPATH === undefined)
directories.unshift(process.cwd());
// A single deadline owns the whole PATH search, including filesystem waits.
const deadline = new ProviderStartupDeadline(VERSION_TIMEOUT_MS, signal);
const lookupInterruption = () =>
deadline.interruption === "cancelled"
? new AnalysisCancelledError("inspect_apktool_client")
: new AnalysisTimeoutError("inspect_apktool_client", VERSION_TIMEOUT_MS, {
diagnostics: { phase: "windows_path_lookup" },
});
try {
for (const entry of directories) {
const directory =
entry.startsWith('"') && entry.endsWith('"')
? entry.slice(1, -1)
: entry;
for (const extension of extensions) {
if (deadline.interruption !== undefined) throw lookupInterruption();
const candidate = win32.resolve(directory, `apktool${extension}`);
try {
const metadata = await waitForAbortable(
stat(candidate),
deadline.signal,
);
if (metadata === ABORTED || deadline.interruption !== undefined)
throw lookupInterruption();
if (metadata.isFile())
return { command: candidate, commandSource: "path" };
} catch (cause: unknown) {
if (deadline.interruption !== undefined) throw lookupInterruption();
const code =
typeof cause === "object" && cause !== null
? Reflect.get(cause, "code")
: undefined;
if (code === "ENOENT" || code === "ENOTDIR") continue;
throw new ApktoolConfigurationFailure(
"command_unresolved",
`The PATH-selected apktool launcher could not be inspected: ${candidate}`,
{
selected_command: "apktool",
command_source: "path",
candidate_path: candidate,
...(typeof code === "string" ? { filesystem_error: code } : {}),
},
{ cause },
);
}
}
}
} finally {
deadline.dispose();
}
throw new ApktoolConfigurationFailure(
"command_missing",
"The apktool launcher was not found on the selected Windows PATH/PATHEXT",
{
selected_command: "apktool",
command_source: "path",
remediation: `Set ${APKTOOL_COMMAND_ENV} to an absolute apktool launcher, or add its directory and extension to PATH and PATHEXT`,
},
);
};
export type ApktoolConfigurationFailureCode =
| "not_absolute"
| "command_missing"
| "command_unresolved"
| "launcher_unsupported"
| "version_unresolved";
@@ -121,7 +217,7 @@ export const inspectApktoolClient = async (
environment: Readonly<Record<string, string | undefined>> = process.env,
platform: NodeJS.Platform = process.platform,
): Promise<ApktoolClientIdentity> => {
const hostEnvironment = { ...process.env, ...environment };
const hostEnvironment = snapshotEnvironment(environment, platform);
let invocation: ApktoolInvocation;
try {
invocation = apktoolInvocation(
@@ -195,7 +291,9 @@ const rejectionCodeOf = (
): ProviderRejectionCode =>
code === "command_missing"
? "executable_missing"
: code === "not_absolute" || code === "launcher_unsupported"
: code === "not_absolute" ||
code === "launcher_unsupported" ||
code === "command_unresolved"
? "not_configured"
: "version_unresolved";
+40 -15
View File
@@ -51,6 +51,7 @@ import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import { WindowsBatchCommandError } from "../process/WindowsBatchCommand.js";
import {
APKTOOL_COMMAND_ENV,
ApktoolConfigurationFailure,
apktoolConfigurationAvailability,
apktoolInvocation,
@@ -155,10 +156,9 @@ const runApktool = async (
): Promise<Result<{ stdout: string; stderr: string }, AnalysisError>> => {
if (signal?.aborted === true)
return err(new AnalysisCancelledError(operation));
const hostEnvironment = { ...process.env, ...environment };
let invocation: ReturnType<typeof apktoolInvocation>;
try {
invocation = apktoolInvocation(selection, arguments_, hostEnvironment);
invocation = apktoolInvocation(selection, arguments_, environment);
} catch (cause) {
if (!(cause instanceof WindowsBatchCommandError)) throw cause;
const reason = `The apktool batch launcher cannot receive REA's decode paths through cmd.exe: ${cause.message}`;
@@ -178,7 +178,7 @@ const runApktool = async (
arguments: invocation.arguments,
windowsVerbatimArguments: invocation.windowsVerbatimArguments,
runId: randomUUID(),
hostEnvironment,
hostEnvironment: environment,
},
{
timeoutMs: limits.timeoutMs,
@@ -317,7 +317,9 @@ export interface ApktoolProviderOptions {
* (`--no-src`) because Java-source recovery belongs to the JADX family.
*/
export class ApktoolProvider {
private readonly environment: Readonly<Record<string, string | undefined>>;
private readonly selectedEnvironment:
| Readonly<Record<string, string | undefined>>
| undefined;
private readonly workspaces = new Set<string>();
private readonly removeWorkspace: (path: string) => Promise<void>;
@@ -328,14 +330,25 @@ export class ApktoolProvider {
#closePromise: Promise<void> | undefined;
constructor(options: ApktoolProviderOptions = {}) {
this.environment = snapshotEnvironment(options.environment ?? process.env);
this.selectedEnvironment =
options.environment === undefined
? undefined
: snapshotEnvironment(options.environment);
this.removeWorkspace =
options.removeWorkspace ??
((path) => rm(path, { recursive: true, force: true }));
}
private selection(): ApktoolCommandSelection {
return resolveApktoolCommand(this.environment);
private operationEnvironment(): Readonly<NodeJS.ProcessEnv> {
const ambient = snapshotEnvironment(process.env);
if (this.selectedEnvironment === undefined) return ambient;
// Child inheritance is sampled per operation. An explicit map keeps its
// launcher choice authoritative, including an omitted command selecting PATH.
return snapshotEnvironment({
...ambient,
...this.selectedEnvironment,
[APKTOOL_COMMAND_ENV]: this.selectedEnvironment[APKTOOL_COMMAND_ENV],
});
}
/** Probe the selected apktool launcher; decodes nothing. */
@@ -354,9 +367,14 @@ export class ApktoolProvider {
async #inspectAvailability(
signal: AbortSignal,
): Promise<ProviderAvailability> {
const environment = this.operationEnvironment();
try {
const selection = this.selection();
await inspectApktoolClient(selection, signal, this.environment);
const selection = await resolveApktoolCommand(
environment,
process.platform,
signal,
);
await inspectApktoolClient(selection, signal, environment);
throwIfCancelled("inspect_apktool_client", signal);
return {
status: "available",
@@ -406,17 +424,22 @@ export class ApktoolProvider {
): Promise<Result<AnalysisExecution, AnalysisError>> {
if (signal?.aborted === true)
return err(new AnalysisCancelledError(request.operation));
const environment = this.operationEnvironment();
let selection: ApktoolCommandSelection;
let identity: ApktoolClientIdentity;
try {
selection = this.selection();
identity = await inspectApktoolClient(
selection,
selection = await resolveApktoolCommand(
environment,
process.platform,
signal,
this.environment,
);
identity = await inspectApktoolClient(selection, signal, environment);
} catch (cause) {
if (cause instanceof AnalysisCancelledError) return err(cause);
if (
cause instanceof AnalysisCancelledError ||
cause instanceof AnalysisTimeoutError
)
return err(cause);
if (cause instanceof ApktoolConfigurationFailure) {
return err(
providerConfigurationRefusal(
@@ -449,6 +472,7 @@ export class ApktoolProvider {
return this.decodeResources(
request.operation,
selection,
environment,
client,
provider,
request.input,
@@ -500,6 +524,7 @@ export class ApktoolProvider {
private async decodeResources(
operation: "decode_android_resources",
selection: ApktoolCommandSelection,
environment: Readonly<NodeJS.ProcessEnv>,
client: {
command: string;
command_source: string;
@@ -628,7 +653,7 @@ export class ApktoolProvider {
maxOutputBytes: DECODE_MAX_OUTPUT_BYTES,
},
signal,
this.environment,
environment,
(owner) => this.#pendingCommandOwners.set(owner, root),
);
if (!decoded.ok) {
@@ -0,0 +1,341 @@
import { basename, dirname, join, sep } from "node:path";
import { describe, expect, it } from "vitest";
import {
CLAUDE_DESKTOP_PACKAGE_FAMILY,
resolveWindowsClaudeDesktopLocation,
type ClaudeDesktopLocationFileSystem,
} from "./ClaudeDesktopConfigLocation.js";
import {
packagePrivateLauncherBlocker,
packagePrivateStorageFamily,
redirectedWriteBlocker,
type MsixPackageView,
} from "./MsixPackageStorage.js";
const home = join("/profile", "a");
const env = {
APPDATA: join(home, "AppData", "Roaming"),
LOCALAPPDATA: join(home, "AppData", "Local"),
};
const packages = join(env.LOCALAPPDATA, "Packages");
const appDataConfig = join(env.APPDATA, "Claude", "claude_desktop_config.json");
const privateConfig = join(
packages,
CLAUDE_DESKTOP_PACKAGE_FAMILY,
"LocalCache",
"Roaming",
"Claude",
"claude_desktop_config.json",
);
const failure = (code: string): Error =>
Object.assign(new Error(`${code}: injected`), { code });
const file = { isFile: () => true };
const privateDirectory = dirname(privateConfig);
const privatePreferences = join(privateDirectory, "Preferences");
const appDataDirectory = dirname(appDataConfig);
/** Package storage holding `privateFiles`; realpath decides the process view. */
const packagedFileSystem = (
realpath: ClaudeDesktopLocationFileSystem["realpath"],
privateFiles: readonly string[] = [privateConfig],
): ClaudeDesktopLocationFileSystem => ({
readdir: (path) => {
if (path === packages) return [CLAUDE_DESKTOP_PACKAGE_FAMILY];
if (path === privateDirectory)
return privateFiles.map((name) => basename(name));
throw failure("ENOENT");
},
lstat: (path) => {
if (!privateFiles.includes(path)) throw failure("ENOENT");
return file;
},
realpath,
});
describe("Claude Desktop MSIX process view", () => {
it("recognizes a process that sees the private copy at the AppData path", () => {
const location = resolveWindowsClaudeDesktopLocation(
home,
env,
packagedFileSystem((path) =>
path === appDataConfig ? privateConfig : path,
),
);
expect(location).toEqual({
ok: true,
value: expect.objectContaining({
configPath: privateConfig,
msixPackage: expect.objectContaining({ processView: "redirected" }),
}),
});
});
it("treats an absent AppData file as an unredirected process", () => {
const location = resolveWindowsClaudeDesktopLocation(
home,
env,
packagedFileSystem((path) => {
if (path === appDataConfig) throw failure("ENOENT");
return path;
}),
);
expect(location.ok && location.value.msixPackage?.processView).toBe(
"direct",
);
});
it("recognizes redirection through another private file before the configuration exists", () => {
const location = resolveWindowsClaudeDesktopLocation(
home,
env,
packagedFileSystem(
(path) =>
path === join(appDataDirectory, "Preferences")
? privatePreferences
: path,
[privatePreferences],
),
);
expect(location.ok && location.value.configPath).toBe(privateConfig);
expect(location.ok && location.value.msixPackage?.processView).toBe(
"redirected",
);
});
it("continues after a listed private file disappears", () => {
const fs = packagedFileSystem(
(path) =>
path === join(appDataDirectory, "Preferences")
? privatePreferences
: path,
[privatePreferences],
);
const location = resolveWindowsClaudeDesktopLocation(home, env, {
...fs,
readdir: (path) =>
path === privateDirectory
? ["vanished", "Preferences"]
: fs.readdir(path),
});
expect(location.ok && location.value.msixPackage?.processView).toBe(
"redirected",
);
});
it("keeps the view unknown when the package has no private files", () => {
const location = resolveWindowsClaudeDesktopLocation(
home,
env,
packagedFileSystem((path) => path, []),
);
expect(location.ok && location.value.msixPackage?.processView).toBe(
"unknown",
);
});
it("keeps the view unknown when the AppData path cannot be resolved", () => {
const location = resolveWindowsClaudeDesktopLocation(
home,
env,
packagedFileSystem((path) => {
if (path === appDataConfig) throw failure("EACCES");
return path;
}),
);
expect(location.ok && location.value.msixPackage?.processView).toBe(
"unknown",
);
});
});
describe("unresolved Claude Desktop package identity", () => {
it("reports unreadable package storage instead of assuming AppData", () => {
const location = resolveWindowsClaudeDesktopLocation(home, env, {
readdir: () => {
throw failure("EACCES");
},
lstat: () => file,
realpath: (path) => path,
});
expect(location).toEqual({
ok: false,
error: {
path: packages,
message: expect.stringContaining("could not be inspected"),
},
});
});
it("reports an uninspectable private copy instead of choosing a file", () => {
const location = resolveWindowsClaudeDesktopLocation(home, env, {
readdir: () => [CLAUDE_DESKTOP_PACKAGE_FAMILY],
lstat: () => {
throw failure("EPERM");
},
realpath: (path) => path,
});
expect(location.ok).toBe(false);
expect(!location.ok && location.error.path).toBe(privateConfig);
});
it("matches the package family case-insensitively, as Windows does", () => {
const location = resolveWindowsClaudeDesktopLocation(home, env, {
readdir: () => [CLAUDE_DESKTOP_PACKAGE_FAMILY.toUpperCase()],
lstat: () => {
throw failure("ENOENT");
},
realpath: (path) => path,
});
expect(location.ok && location.value.msixPackage?.packageFamilyName).toBe(
CLAUDE_DESKTOP_PACKAGE_FAMILY.toUpperCase(),
);
});
});
describe("package-private REA launchers", () => {
const launcher = join(
env.APPDATA,
"npm",
"node_modules",
"rea-agents",
"scripts",
"rea.mjs",
);
const stored = join(
packages,
CLAUDE_DESKTOP_PACKAGE_FAMILY,
"LocalCache",
"Roaming",
"npm",
"node_modules",
"rea-agents",
"scripts",
"rea.mjs",
);
it("names the package that privately stores a path", () => {
expect(packagePrivateStorageFamily(stored, packages)).toBe(
CLAUDE_DESKTOP_PACKAGE_FAMILY,
);
expect(packagePrivateStorageFamily(launcher, packages)).toBeUndefined();
expect(
packagePrivateStorageFamily(
join(packages, CLAUDE_DESKTOP_PACKAGE_FAMILY, "LocalState", "x"),
packages,
),
).toBeUndefined();
});
it("blocks a launcher that only the package's processes can see", () => {
const blocker = packagePrivateLauncherBlocker(
[join("/Program Files", "nodejs", "node.exe"), launcher, "mcp"],
packages,
(path) => (path === launcher ? stored : path),
);
expect(blocker).toContain(stored);
expect(blocker).toContain(CLAUDE_DESKTOP_PACKAGE_FAMILY);
expect(blocker).toContain("npm install -g rea-agents");
});
it("compares the launcher with the canonical package storage path", () => {
const shortProfilePackages = join(
"/profile",
"A~1",
"AppData",
"Local",
"Packages",
);
const blocker = packagePrivateLauncherBlocker(
[launcher, "mcp"],
shortProfilePackages,
(path) =>
path === shortProfilePackages
? packages
: path === launcher
? stored
: path,
);
expect(blocker).toContain(CLAUDE_DESKTOP_PACKAGE_FAMILY);
});
it("allows ordinary and unresolvable launchers", () => {
expect(
packagePrivateLauncherBlocker(
["cmd.exe", "/d", "/c", "npx", "-y", "rea-agents@6.4.0", "mcp"],
packages,
() => {
throw new Error("package runners are not resolved");
},
),
).toBeUndefined();
expect(
packagePrivateLauncherBlocker([launcher, "mcp"], packages, () => {
throw failure("ENOENT");
}),
).toBeUndefined();
});
});
describe("writes from a redirected AppData view", () => {
const view: MsixPackageView = {
packageFamilyName: CLAUDE_DESKTOP_PACKAGE_FAMILY,
privateConfigPath: privateConfig,
appDataConfigPath: appDataConfig,
virtualizedRoots: [env.APPDATA, env.LOCALAPPDATA],
processView: "redirected",
};
const vscode = join(env.APPDATA, "Code", "User", "mcp.json");
const hermes = join(env.LOCALAPPDATA, "hermes", "config.yaml");
const codex = join(home, ".codex", "config.toml");
it("refuses only targets under the package's virtualized roots", () => {
const blocker = redirectedWriteBlocker(
view,
[vscode, codex, hermes],
"setup",
);
expect(blocker).toContain(`${vscode}, ${hermes}`);
expect(blocker).not.toContain(codex);
expect(blocker).toContain("Rerun setup from a terminal");
expect(redirectedWriteBlocker(view, [codex], "setup")).toBeUndefined();
});
it("compares aliases through the existing parent of a new destination", () => {
const alias = join(home, "skill-alias");
const target = join(alias, "skills", "reverse-engineer-anything");
const blocker = redirectedWriteBlocker(
view,
[target],
"uninstall",
(path) => {
if (path === alias) return join(env.APPDATA, "dsh");
if (path.startsWith(`${alias}${sep}`)) throw failure("ENOENT");
return path;
},
);
expect(blocker).toContain(target);
expect(blocker).toContain("Rerun uninstall");
});
it("keeps canonicalization failures visible instead of assuming a target is outside AppData", () => {
expect(
redirectedWriteBlocker(view, [codex], "setup", () => {
throw failure("EACCES");
}),
).toContain("Cannot establish the MSIX write location");
});
it("allows every target without positive evidence of redirection", () => {
for (const processView of ["direct", "unknown"] as const)
expect(
redirectedWriteBlocker({ ...view, processView }, [vscode], "uninstall"),
).toBeUndefined();
expect(
redirectedWriteBlocker(undefined, [vscode], "setup"),
).toBeUndefined();
});
});
@@ -0,0 +1,199 @@
import { lstatSync, readdirSync, realpathSync } from "node:fs";
import { join } from "node:path";
import { err, ok, type Result } from "../domain/result.js";
import {
windowsAppDataRoots,
type MsixPackageView,
} from "./MsixPackageStorage.js";
const CONFIG_FILE = "claude_desktop_config.json";
/** Private files compared at most when looking for a redirected AppData view. */
const PROCESS_VIEW_PROBES = 8;
/**
* Claude Desktop's MSIX package family: package name `Claude` and the
* publisher ID Windows derives from `CN="Anthropic, PBC", O="Anthropic, PBC",
* L=San Francisco, S=California, C=US, …`.
*/
export const CLAUDE_DESKTOP_PACKAGE_FAMILY = "Claude_pzs8sxrjxfjjc";
/** `Claude_` plus a 13-character Crockford base32 MSIX publisher ID. */
const CLAUDE_PACKAGE_FAMILY = /^Claude_[0-9a-hjkmnp-tv-z]{13}$/iu;
/** The configuration Claude Desktop reads and the evidence that it is installed. */
export interface ClaudeDesktopLocation {
readonly configPath: string;
readonly markerPath: string;
readonly msixPackage?: MsixPackageView;
}
/** Unresolved Claude Desktop identity, reported instead of guessing a file. */
export interface ClaudeDesktopLocationFailure {
readonly path: string;
readonly message: string;
}
/** Synchronous probes; each throws for failures other than absence. */
export interface ClaudeDesktopLocationFileSystem {
readonly readdir: (path: string) => readonly string[];
readonly lstat: (path: string) => { isFile(): boolean };
readonly realpath: (path: string) => string;
}
const systemFileSystem: ClaudeDesktopLocationFileSystem = {
readdir: (path) => readdirSync(path),
lstat: (path) => lstatSync(path),
realpath: (path) => realpathSync.native(path),
};
/**
* Resolve the `claude_desktop_config.json` that Windows Claude Desktop reads.
* Without its MSIX package storage, that is the AppData file. With it, the
* package reads its private copy when one exists and the AppData file
* otherwise; a new registration goes to the private copy. A `Claude_*`
* package from another publisher leaves the reader unknown.
*/
export const resolveWindowsClaudeDesktopLocation = (
home: string,
env: Readonly<NodeJS.ProcessEnv>,
fileSystem: ClaudeDesktopLocationFileSystem = systemFileSystem,
): Result<ClaudeDesktopLocation, ClaudeDesktopLocationFailure> => {
const roots = windowsAppDataRoots(home, env);
const appDataDirectory = join(roots.roaming, "Claude");
const appDataConfigPath = join(appDataDirectory, CONFIG_FILE);
const packagesDirectory = join(roots.local, "Packages");
let families: readonly string[];
try {
families = fileSystem
.readdir(packagesDirectory)
.filter((name) => CLAUDE_PACKAGE_FAMILY.test(name));
} catch (cause: unknown) {
if (!isMissing(cause))
return err({
path: packagesDirectory,
message: `MSIX package storage ${packagesDirectory} could not be inspected, so REA cannot establish whether Claude Desktop reads ${appDataConfigPath} or a package-private copy: ${errorMessage(cause)}. Repair access to that directory, then rerun.`,
});
families = [];
}
const foreign = families.filter(
(name) =>
name.toLowerCase() !== CLAUDE_DESKTOP_PACKAGE_FAMILY.toLowerCase(),
);
if (foreign.length > 0)
return err({
path: join(packagesDirectory, foreign[0] ?? ""),
message: `MSIX package storage ${foreign.map((name) => join(packagesDirectory, name)).join(", ")} uses Claude Desktop's package name with an unrecognized publisher (Claude Desktop is ${CLAUDE_DESKTOP_PACKAGE_FAMILY}). REA cannot establish which ${CONFIG_FILE} that package reads and does not fall back to ${appDataConfigPath}. Remove the unrecognized package, or register REA in the configuration it reads.`,
});
const family = families[0];
if (family === undefined)
return ok({ configPath: appDataConfigPath, markerPath: appDataDirectory });
const container = join(packagesDirectory, family);
const privateDirectory = join(container, "LocalCache", "Roaming", "Claude");
const privateConfigPath = join(privateDirectory, CONFIG_FILE);
const privateCopy = present(fileSystem, privateConfigPath);
if (!privateCopy.ok) return privateCopy;
const appDataCopy = privateCopy.value
? ok(false)
: present(fileSystem, appDataConfigPath);
if (!appDataCopy.ok) return appDataCopy;
return ok({
configPath:
privateCopy.value || !appDataCopy.value
? privateConfigPath
: appDataConfigPath,
markerPath: container,
msixPackage: {
packageFamilyName: family,
privateConfigPath,
appDataConfigPath,
virtualizedRoots: [roots.roaming, roots.local],
processView: processView(
fileSystem,
privateDirectory,
appDataDirectory,
privateCopy.value,
),
},
});
};
/**
* A process the package started sees the package's private files at their
* AppData paths; any other process sees the real AppData files or nothing.
* Claude Desktop saves its user data there while it runs, so the
* configuration, or any other private file, can show which view this is.
*/
const processView = (
fileSystem: ClaudeDesktopLocationFileSystem,
privateDirectory: string,
appDataDirectory: string,
privateConfig: boolean,
): MsixPackageView["processView"] => {
let probes: readonly string[];
try {
probes = privateConfig
? [CONFIG_FILE]
: fileSystem
.readdir(privateDirectory)
.filter((name) => {
try {
return fileSystem.lstat(join(privateDirectory, name)).isFile();
} catch (cause: unknown) {
// A candidate may vanish or become unreadable while listed.
void cause;
return false;
}
})
.slice(0, PROCESS_VIEW_PROBES);
} catch (cause: unknown) {
// No private file can be listed, so no view can be compared.
void cause;
return "unknown";
}
let view: MsixPackageView["processView"] = "unknown";
for (const name of probes) {
let privateTarget: string;
try {
privateTarget = fileSystem.realpath(join(privateDirectory, name));
} catch (cause: unknown) {
// A private file that vanished cannot be compared; try another.
void cause;
continue;
}
try {
if (fileSystem.realpath(join(appDataDirectory, name)) === privateTarget)
return "redirected";
view = "direct";
} catch (cause: unknown) {
if (!isMissing(cause)) return "unknown";
view = "direct";
}
}
return view;
};
const present = (
fileSystem: ClaudeDesktopLocationFileSystem,
path: string,
): Result<boolean, ClaudeDesktopLocationFailure> => {
try {
fileSystem.lstat(path);
return ok(true);
} catch (cause: unknown) {
if (isMissing(cause)) return ok(false);
return err({
path,
message: `${path} could not be inspected, so REA cannot establish which ${CONFIG_FILE} Claude Desktop's MSIX package reads: ${errorMessage(cause)}. Repair access to that path, then rerun.`,
});
}
};
const isMissing = (cause: unknown): boolean =>
cause instanceof Error &&
"code" in cause &&
(cause.code === "ENOENT" || cause.code === "ENOTDIR");
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
+27 -23
View File
@@ -155,7 +155,7 @@ export const readClientRegistrationInspections = async (
}
const parsed = effectiveClientConfiguration(files.value);
if (parsed === undefined) {
record(unavailableStatus(client.name, client.configPath, "missing"));
record(unavailableStatus(client, "missing"));
continue;
}
const policy = await readClientPolicyBlock(
@@ -191,7 +191,7 @@ export const readClientRegistrationInspections = async (
});
continue;
}
record(unavailableStatus(client.name, client.configPath, "missing"));
record(unavailableStatus(client, "missing"));
continue;
}
const registration = parseRegistration(raw, client);
@@ -202,8 +202,7 @@ export const readClientRegistrationInspections = async (
const activation = registrationActivation(registration, client, parsed);
record(
configuredStatus(
client.name,
client.configPath,
client,
command,
activation === "enabled" &&
registrationAligned(
@@ -222,11 +221,7 @@ export const readClientRegistrationInspections = async (
);
} catch (cause: unknown) {
record(
unavailableStatus(
client.name,
client.configPath,
isMissing(cause) ? "missing" : "invalid",
),
unavailableStatus(client, isMissing(cause) ? "missing" : "invalid"),
);
}
}
@@ -352,36 +347,45 @@ const parseRegistration = (
return registration;
};
const remediation =
"Run rea setup to refresh this registration, then restart the client.";
/** A client that rewrites its file from memory must be quit before setup. */
const remediation = (client: SetupClient): string => {
if (client.quitBeforeSetup !== true)
return "Run rea setup to refresh this registration, then restart the client.";
const name = client.displayName ?? client.name;
return `Quit ${name} fully, run rea setup to refresh this registration, then start ${name} again. A running ${name} can rewrite its configuration from memory and drop the registration.`;
};
const configuredStatus = (
client: string,
configPath: string,
client: SetupClient,
command: RegistrationCommand,
state: "aligned" | "stale",
policyRemediation?: string,
): ClientRegistrationStatus =>
state === "aligned"
? { client, config_path: configPath, command, state, remediation: null }
: {
client,
config_path: configPath,
? {
client: client.name,
config_path: client.configPath,
command,
state,
remediation: policyRemediation ?? remediation,
remediation: null,
}
: {
client: client.name,
config_path: client.configPath,
command,
state,
remediation: policyRemediation ?? remediation(client),
};
const unavailableStatus = (
client: string,
configPath: string,
client: SetupClient,
state: "missing" | "invalid",
): ClientRegistrationStatus => ({
client,
config_path: configPath,
client: client.name,
config_path: client.configPath,
command: [],
state,
remediation,
remediation: remediation(client),
});
const clientEvidencePresent = async (client: SetupClient): Promise<boolean> => {
+7 -3
View File
@@ -11,6 +11,7 @@ import { compareBundles } from "../domain/bundleComparison.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import {
readEvidenceBundle,
readImmutableEvidenceBundle,
writeEvidenceBundle,
} from "./EvidenceBundleFiles.js";
@@ -33,7 +34,8 @@ export const exportEvidenceBundleCommand = async (
outputPath: string,
overwrite: boolean,
): Promise<Result<JsonValue, AnalysisError>> => {
const loaded = await readEvidenceBundle(sourcePath);
// The sealed snapshot lets the writer reuse this authentication.
const loaded = await readImmutableEvidenceBundle(sourcePath);
if (!loaded.ok) return loaded;
const resources = new ArtifactResourceScope();
const written = await writeEvidenceBundle(
@@ -69,9 +71,11 @@ export const compareEvidenceBundlesCommand = async (input: {
readonly leftPath: string;
readonly rightPath: string;
}): Promise<Result<JsonValue, AnalysisError>> => {
// Sealed snapshots let comparison and its bundle digests reuse this
// authentication instead of re-validating every record twice more.
const [left, right] = await Promise.all([
readEvidenceBundle(input.leftPath),
readEvidenceBundle(input.rightPath),
readImmutableEvidenceBundle(input.leftPath),
readImmutableEvidenceBundle(input.rightPath),
]);
if (!left.ok) return left;
if (!right.ok) return right;
+187
View File
@@ -0,0 +1,187 @@
import { lstat } from "node:fs/promises";
import { realpathSync } from "node:fs";
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
import { err, ok, type Result } from "../domain/result.js";
/**
* How one MSIX-packaged client reads its AppData configuration. A package
* with write virtualization saves AppData files to its private
* `LocalCache\Roaming` copy, then reads that copy whenever it exists and the
* ordinary AppData file otherwise.
*/
export interface MsixPackageView {
readonly packageFamilyName: string;
/** The package-private copy, which shadows the AppData file once it exists. */
readonly privateConfigPath: string;
/** The AppData path that unpackaged processes read and write. */
readonly appDataConfigPath: string;
/** Roots whose writes the package redirects for processes it starts. */
readonly virtualizedRoots: readonly string[];
/**
* `redirected`: this process sees one of the package's private files at its
* AppData path, so the running package started it. `direct`: it does not.
* `unknown`: no private file could be compared.
*/
readonly processView: "redirected" | "direct" | "unknown";
}
/** Windows' roaming and local application data roots; empty means unset. */
export const windowsAppDataRoots = (
home: string,
env: Readonly<NodeJS.ProcessEnv>,
): { readonly roaming: string; readonly local: string } => ({
roaming: env.APPDATA?.trim() || join(home, "AppData", "Roaming"),
local: env.LOCALAPPDATA?.trim() || join(home, "AppData", "Local"),
});
/** The per-user root of MSIX package data containers. */
export const msixPackagesDirectory = (
home: string,
env: Readonly<NodeJS.ProcessEnv>,
): string => join(windowsAppDataRoots(home, env).local, "Packages");
/** Whether `path` is `root` or inside it, using the host's path comparison. */
const pathWithin = (path: string, root: string): boolean => {
const inner = relative(root, path);
return (
inner === "" ||
(inner !== ".." && !inner.startsWith(`..${sep}`) && !isAbsolute(inner))
);
};
/**
* Name the package whose private `LocalCache` holds a canonical path. Its
* processes see those files at virtual AppData locations; other processes do
* not, and Windows removes them with the package.
*/
export const packagePrivateStorageFamily = (
canonicalPath: string,
packagesDirectory: string,
): string | undefined => {
if (!pathWithin(canonicalPath, packagesDirectory)) return undefined;
const [family, storage] = relative(packagesDirectory, canonicalPath).split(
/[\\/]/u,
);
return family !== undefined &&
family !== "" &&
storage?.toLowerCase() === "localcache"
? family
: undefined;
};
/**
* Explain why setup must not register a launcher that exists only in one
* package's private storage. Other clients could not start it, and doctor
* outside that package could not verify it.
*/
export const packagePrivateLauncherBlocker = (
command: readonly string[],
packagesDirectory: string,
canonicalPath: (path: string) => string = realpathSync.native,
): string | undefined => {
// Compare canonical forms: a short-name, junctioned or substituted profile
// spells the same directory differently.
let packages = packagesDirectory;
try {
packages = canonicalPath(packagesDirectory);
} catch (cause: unknown) {
// Without package storage, the spelled path is the only comparison.
void cause;
}
for (const part of command) {
if (!isAbsolute(part)) continue;
let resolved: string;
try {
resolved = canonicalPath(part);
} catch (cause: unknown) {
// A launcher that cannot be resolved is not evidence of package storage.
void cause;
continue;
}
const family = packagePrivateStorageFamily(resolved, packages);
if (family !== undefined)
return `The REA launcher ${part} is stored at ${resolved}, inside the private storage of MSIX package ${family}. Only processes started by that app can see it at ${part}, and Windows removes it with the package, so other clients could not start this registration. Install REA from a terminal that the app did not start (for example with \`npm install -g rea-agents\`), then rerun setup from that terminal.`;
}
return undefined;
};
/**
* Explain why this process must not write `targets`: the running package
* started it, so writes under its virtualized roots land in that package's
* private storage, which the targets' owners never read.
*/
const canonicalDestination = (
path: string,
canonicalPath: (path: string) => string,
): Result<string, { readonly path: string; readonly detail: string }> => {
let ancestor = path;
const missing: string[] = [];
while (true) {
try {
return ok(join(canonicalPath(ancestor), ...missing));
} catch (cause: unknown) {
if (
cause instanceof Error &&
"code" in cause &&
(cause.code === "ENOENT" || cause.code === "ENOTDIR") &&
dirname(ancestor) !== ancestor
) {
missing.unshift(basename(ancestor));
ancestor = dirname(ancestor);
continue;
}
return err({
path,
detail: cause instanceof Error ? cause.message : String(cause),
});
}
}
};
export const redirectedWriteBlocker = (
view: MsixPackageView | undefined,
targets: readonly string[],
operation: "setup" | "uninstall",
canonicalPath: (path: string) => string = realpathSync.native,
): string | undefined => {
if (view?.processView !== "redirected" || targets.length === 0)
return undefined;
const roots: string[] = [];
const redirected: string[] = [];
for (const root of view.virtualizedRoots) {
const resolved = canonicalDestination(root, canonicalPath);
if (!resolved.ok)
return `Cannot establish the MSIX write location for ${resolved.error.path}: ${resolved.error.detail}. Rerun ${operation} from a terminal that this app did not start.`;
roots.push(resolved.value);
}
for (const target of targets) {
const resolved = canonicalDestination(target, canonicalPath);
if (!resolved.ok)
return `Cannot establish the MSIX write location for ${resolved.error.path}: ${resolved.error.detail}. Rerun ${operation} from a terminal that this app did not start.`;
if (roots.some((root) => pathWithin(resolved.value, root)))
redirected.push(target);
}
if (redirected.length === 0) return undefined;
return `This process was started by MSIX package ${view.packageFamilyName}, which redirects its writes under ${view.virtualizedRoots.join(" and ")} into the package's private storage. Changes to ${redirected.join(", ")} would not reach the files other apps read. Rerun ${operation} from a terminal that this app did not start.`;
};
/**
* Whether the package began reading its private copy after the AppData file
* was chosen, for example by saving its settings when it quit.
*/
export const packageReadTargetChanged = async (
view: MsixPackageView,
configPath: string,
): Promise<boolean> => {
if (configPath !== view.appDataConfigPath) return false;
try {
await lstat(view.privateConfigPath);
return true;
} catch (cause: unknown) {
return !(
cause instanceof Error &&
"code" in cause &&
(cause.code === "ENOENT" || cause.code === "ENOTDIR")
);
}
};
+117 -1
View File
@@ -1,9 +1,43 @@
import { describe, expect, it } from "vitest";
import { resolve } from "node:path";
import { join, resolve } from "node:path";
import { FakeSetupHost, options } from "./Setup.fixture.js";
import { runSetup } from "./Setup.js";
import { setupRegistrationCommand } from "./SetupHost.js";
import type { MsixPackageView } from "./MsixPackageStorage.js";
import type { SetupClient } from "./SupportedClients.js";
// Host joins keep containment checks meaningful on POSIX test hosts too.
const PROFILE = String.raw`C:\Users\a`;
const ROAMING = join(PROFILE, "AppData", "Roaming");
const LOCAL = join(PROFILE, "AppData", "Local");
const PRIVATE_CONFIG = join(
LOCAL,
"Packages",
"Claude_pzs8sxrjxfjjc",
"LocalCache",
"Roaming",
"Claude",
"claude_desktop_config.json",
);
const APPDATA_CONFIG = join(ROAMING, "Claude", "claude_desktop_config.json");
/** Claude Desktop as setup resolves it from its MSIX package storage. */
const msixClaudeDesktop = (
processView: MsixPackageView["processView"],
): SetupClient => ({
name: "claude_desktop",
displayName: "Claude Desktop",
configPath: PRIVATE_CONFIG,
quitBeforeSetup: true,
msixPackage: {
packageFamilyName: "Claude_pzs8sxrjxfjjc",
privateConfigPath: PRIVATE_CONFIG,
appDataConfigPath: APPDATA_CONFIG,
virtualizedRoots: [ROAMING, LOCAL],
processView,
},
});
describe("setup workflow", () => {
it("omits an aligned managed skill from an otherwise empty plan", async () => {
@@ -293,3 +327,85 @@ describe("setup workflow action selection", () => {
expect(result.remediation).not.toContain("internal_client_key");
});
});
describe("MSIX Claude Desktop setup", () => {
it("discloses which file MSIX Claude Desktop reads and that it must be quit", async () => {
const host = new FakeSetupHost("win32");
host.hopper = join(PROFILE, "Hopper");
host.skill = "unchanged";
host.clients = [msixClaudeDesktop("direct")];
const result = await runSetup(
{ ...options(false), clientIds: ["claude_desktop"], dryRun: true },
host,
);
expect(result.status).toBe("planned");
const [action] = result.plannedActions;
expect(action?.target).toBe(PRIVATE_CONFIG);
expect(action?.detail).toContain(
`Claude Desktop is installed as MSIX package Claude_pzs8sxrjxfjjc, which reads this package-private file instead of ${APPDATA_CONFIG}.`,
);
expect(action?.detail).toContain(
"Quit Claude Desktop fully before approving; closing its window is not enough.",
);
});
it("refuses AppData writes from a process the MSIX package started", async () => {
const host = new FakeSetupHost("win32");
host.hopper = join(PROFILE, "Hopper");
host.skill = "unchanged";
const vscode = join(ROAMING, "Code", "User", "mcp.json");
host.clients = [
msixClaudeDesktop("redirected"),
{ name: "vscode", displayName: "VS Code", configPath: vscode },
{
name: "codex",
displayName: "Codex",
configPath: join(PROFILE, ".codex", "config.toml"),
},
];
const blocked = await runSetup(
{ ...options(true), clientIds: ["vscode", "codex"] },
host,
);
expect(blocked.status).toBe("needs_human");
expect(blocked.remediation).toContain(
`Changes to ${vscode} would not reach the files other apps read.`,
);
expect(host.configurations).toBe(0);
const homeOnly = await runSetup(
{ ...options(true), clientIds: ["codex"] },
host,
);
expect(homeOnly.status).toBe("ready");
expect(host.configurations).toBe(1);
});
it("refuses registrations whose launcher only one MSIX package can see", async () => {
const host = new FakeSetupHost("win32");
host.hopper = join(PROFILE, "Hopper");
host.registrationCommandBlocker = "Install REA outside the package.";
host.clients = [
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
];
const blocked = await runSetup(
{ ...options(true), clientIds: ["codex"] },
host,
);
expect(blocked.status).toBe("needs_human");
expect(blocked.remediation).toBe("Install REA outside the package.");
expect(host.configurations).toBe(0);
expect(host.skillInstalls).toBe(0);
const skillOnly = await runSetup(
{ ...options(true), clientIds: [], installSkill: true },
host,
);
expect(skillOnly.status).toBe("ready");
expect(host.skillInstalls).toBe(1);
});
});
+1
View File
@@ -25,6 +25,7 @@ export class FakeSetupHost implements SetupHost {
return skillDestinations(this.homeDirectory, clientIds);
}
readonly registrationCommand: readonly string[];
registrationCommandBlocker?: string;
nodeVersion = "24.18.0";
version: string | undefined = "14.5";
distribution: LinuxDistribution | undefined;
+31 -1
View File
@@ -29,6 +29,7 @@ import { PRODUCT_IDENTITY } from "../identity.js";
import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js";
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
import { packageReadTargetChanged } from "./MsixPackageStorage.js";
import {
readRegularFile,
readRegularFileText,
@@ -40,7 +41,10 @@ import type {
ClientConfigurationResult,
SetupProviderEnvironment,
} from "./SetupTypes.js";
import type { SetupClient } from "./SupportedClients.js";
import {
registrationWriteBlocker,
type SetupClient,
} from "./SupportedClients.js";
export class ClientConfigurationCleanupRollbackFailure extends RegularFileCleanupFailure<string> {
constructor(
@@ -187,6 +191,13 @@ const persistClientConfiguration = async ({
desired,
fallbackServers,
}: ClientConfigurationUpdate): Promise<ClientConfigurationResult> => {
// The plan chose this file; an MSIX package may have switched to its
// private copy since, for example when it quit.
if (
client.msixPackage !== undefined &&
(await packageReadTargetChanged(client.msixPackage, client.configPath))
)
return { status: "failed", reason: "target_changed" };
const backupPath =
original === undefined ? undefined : `${client.configPath}.rea.backup`;
let recoveryBackupPath: string | undefined;
@@ -358,6 +369,25 @@ export const inspectClientConfiguration = async (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<ClientConfigurationInspection> => {
const inspection = await inspectClientDocument(
client,
providerEnvironment,
command,
);
if (inspection.status !== "create" && inspection.status !== "update")
return inspection;
// A change the running client would overwrite is not a persisted registration.
const blocker = registrationWriteBlocker(client, "setup");
return blocker === undefined
? inspection
: { status: "invalid", remediation: blocker };
};
const inspectClientDocument = async (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<ClientConfigurationInspection> => {
if (client.configPathError !== undefined)
return { status: "invalid", remediation: client.configPathError };
+2
View File
@@ -9,6 +9,8 @@ import type { SetupClient } from "./SupportedClients.js";
export const failedConfigurationMessage = (
result: Extract<ClientConfigurationResult, { readonly status: "failed" }>,
): string => {
if (result.reason === "target_changed")
return "The client began reading a different configuration file after the plan was shown, so no change was made. Rerun setup to review the new target.";
if (result.reason === "path")
return "Agent configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun setup.";
if (result.reason === "backup")
+30 -4
View File
@@ -44,6 +44,10 @@ import {
retryRegularFileCleanup,
} from "./RegularFileRead.js";
import { providerRegistrationEnvironment } from "./SetupRegistrationEnvironment.js";
import {
msixPackagesDirectory,
packagePrivateLauncherBlocker,
} from "./MsixPackageStorage.js";
import type {
SetupHost,
SetupInitialState,
@@ -66,6 +70,31 @@ export const setupRegistrationCommand = (
]
: [resolve(process.argv[1] ?? PRODUCT_IDENTITY.cliBinary), "mcp"];
/**
* The launcher setup registers, and why it must not be registered when it
* exists only inside one MSIX package's private storage.
*/
const setupRegistration = (
platform: NodeJS.Platform,
homeDirectory: string,
environment: Readonly<NodeJS.ProcessEnv>,
): Pick<SetupHost, "registrationCommand" | "registrationCommandBlocker"> => {
const registrationCommand = setupRegistrationCommand(
platform,
invokingPackageRunner(environment, platform),
);
const registrationCommandBlocker =
platform === "win32"
? packagePrivateLauncherBlocker(
registrationCommand,
msixPackagesDirectory(homeDirectory, environment),
)
: undefined;
return registrationCommandBlocker === undefined
? { registrationCommand }
: { registrationCommand, registrationCommandBlocker };
};
export const filterClientsNeedingConfigure = async (
host: SetupHost,
detectedClients: readonly SetupClient[],
@@ -117,10 +146,7 @@ export const systemSetupHost = (
homeDirectory,
skillDestinations: (clientIds) =>
skillDestinations(homeDirectory, clientIds, environment, platform),
registrationCommand: setupRegistrationCommand(
platform,
invokingPackageRunner(environment, platform),
),
...setupRegistration(platform, homeDirectory, environment),
nodeVersion: process.versions.node,
macosVersion: () => doctorHost.macosVersion(),
linuxDistribution: readLinuxDistribution,
+60 -28
View File
@@ -8,12 +8,18 @@ import {
import type { SkillDestination } from "./SetupSkill.js";
import { macHopperInstallDisclosure } from "./MacHopper.js";
import type {
ClientConfigurationInspection,
SetupAction,
SetupClientState,
SetupHost,
SetupProviderEnvironment,
} from "./SetupTypes.js";
import type { SetupClient } from "./SupportedClients.js";
import {
appDataRedirection,
registrationPersistenceDetail,
type SetupClient,
} from "./SupportedClients.js";
import { redirectedWriteBlocker } from "./MsixPackageStorage.js";
import type { DoctorReport } from "./Doctor.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
@@ -161,12 +167,58 @@ export const planSetupActions = async (input: {
blocker: `${invalid.client.displayName ?? invalid.client.name}: ${invalid.inspection.remediation}`,
};
}
const clientPlans = inspections.flatMap(({ client, inspection }) =>
const clientPlans = plannedClientWrites(
inspections,
input.discovery.installHopper,
);
const plannedActions = setupPlan({
platform: input.host.platform,
homeDirectory: input.host.homeDirectory,
installHopper: input.discovery.installHopper,
installSkill: input.installSkill,
skillClientIds: input.skillClientIds,
skillDestinations: input.host.skillDestinations(input.skillClientIds),
clients: clientPlans,
providerEnvironment: input.providerEnvironment,
...(input.discovery.linuxPackageFamily === undefined
? {}
: { linuxPackageFamily: input.discovery.linuxPackageFamily }),
command: input.command,
});
const blocker =
(clientPlans.length > 0
? input.host.registrationCommandBlocker
: undefined) ??
redirectedWriteBlocker(
appDataRedirection(input.discovery.clients),
plannedActions
.filter(({ kind }) => kind !== "install_hopper")
.map(({ target }) => target),
"setup",
);
return {
plannedActions,
selectedClients,
clientsToConfigure: selectedClients.filter((client) =>
clientPlans.some(({ client: planned }) => planned.name === client.name),
),
...(blocker === undefined ? {} : { blocker }),
};
};
/** Selected clients whose registration setup writes, with the disclosed operation. */
const plannedClientWrites = (
inspections: readonly {
readonly client: SetupClient;
readonly inspection: ClientConfigurationInspection;
}[],
installHopper: boolean,
) =>
inspections.flatMap(({ client, inspection }) =>
client.format !== "unsupported" &&
(inspection.status === "create" ||
inspection.status === "update" ||
(input.discovery.installHopper &&
inspection.status === "already_current"))
(installHopper && inspection.status === "already_current"))
? [
{
client,
@@ -182,27 +234,6 @@ export const planSetupActions = async (input: {
]
: [],
);
return {
plannedActions: setupPlan({
platform: input.host.platform,
homeDirectory: input.host.homeDirectory,
installHopper: input.discovery.installHopper,
installSkill: input.installSkill,
skillClientIds: input.skillClientIds,
skillDestinations: input.host.skillDestinations(input.skillClientIds),
clients: clientPlans,
providerEnvironment: input.providerEnvironment,
...(input.discovery.linuxPackageFamily === undefined
? {}
: { linuxPackageFamily: input.discovery.linuxPackageFamily }),
command: input.command,
}),
selectedClients,
clientsToConfigure: selectedClients.filter((client) =>
clientPlans.some(({ client: planned }) => planned.name === client.name),
),
};
};
/** Describe every selected setup mutation before user approval. */
const setupPlan = (input: {
@@ -259,7 +290,7 @@ const setupPlan = (input: {
label: client.displayName ?? client.name,
target: client.configPath,
detail: clientConfigurationDetail(
client.displayName ?? client.name,
client,
input.command,
input.providerEnvironment,
input.installHopper,
@@ -303,7 +334,7 @@ const majorVersion = (version: string): number =>
Number.parseInt(version.split(".")[0] ?? "0", 10);
const clientConfigurationDetail = (
client: string,
client: SetupClient,
command: readonly string[],
environment: SetupProviderEnvironment,
installHopper: boolean,
@@ -320,5 +351,6 @@ const clientConfigurationDetail = (
? " If this plan installs Hopper, REA will add HOPPER_LAUNCHER_PATH using the launcher path reported by that installation."
: " The HOPPER_LAUNCHER_PATH value shown above is the current fallback; if this plan installs Hopper, REA will replace it with the launcher path reported by that installation."
: "";
return `Add the REA MCP registration for ${client}; preserve unrelated configuration. The backup path reflects the configuration inspected for this plan; if that file changes before execution, setup will select a recovery path for its current contents. Command: ${command.map((part) => JSON.stringify(part)).join(" ")}.${environmentDetail}${hopperDetail}`;
const persistence = registrationPersistenceDetail(client);
return `Add the REA MCP registration for ${client.displayName ?? client.name}; preserve unrelated configuration. The backup path reflects the configuration inspected for this plan; if that file changes before execution, setup will select a recovery path for its current contents. Command: ${command.map((part) => JSON.stringify(part)).join(" ")}.${environmentDetail}${hopperDetail}${persistence === undefined ? "" : ` ${persistence}`}`;
};
+8 -1
View File
@@ -25,7 +25,12 @@ export type ClientConfigurationResult =
}
| {
readonly status: "failed";
readonly reason: "path" | "backup" | "write" | "readback";
readonly reason:
| "path"
| "target_changed"
| "backup"
| "write"
| "readback";
}
| {
readonly status: "failed";
@@ -55,6 +60,8 @@ export interface SetupHost {
readonly homeDirectory: string;
skillDestinations(clientIds: readonly string[]): readonly SkillDestination[];
readonly registrationCommand: readonly string[];
/** Why no client may be registered with `registrationCommand` from this host. */
readonly registrationCommandBlocker?: string;
readonly nodeVersion: string;
macosVersion(): Promise<string | undefined>;
linuxDistribution(): Promise<LinuxDistribution | undefined>;
+120 -33
View File
@@ -7,6 +7,8 @@ import {
resolveHermesClientHome,
} from "./HermesClientHome.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { resolveWindowsClaudeDesktopLocation } from "./ClaudeDesktopConfigLocation.js";
import type { MsixPackageView } from "./MsixPackageStorage.js";
/** One supported client configuration location. */
export interface SetupClient {
@@ -29,6 +31,10 @@ export interface SetupClient {
/** Same-scope fallback ZCode stops loading after its first native server. */
readonly zcodeFallbackPath?: string;
readonly markerPath?: string;
/** MSIX package storage that decides which configuration the client reads. */
readonly msixPackage?: MsixPackageView;
/** A running client can rewrite its configuration from memory. */
readonly quitBeforeSetup?: boolean;
readonly format?:
| "json"
| "toml"
@@ -61,12 +67,35 @@ interface ClientPathContext {
readonly env: Readonly<NodeJS.ProcessEnv>;
}
interface ClientDefinition {
/** One resolved configuration location and its detection evidence. */
interface ClientLocation {
readonly configPath: string;
readonly markerPath: string;
readonly msixPackage?: MsixPackageView;
}
type ClientDefinition = ClientDefinitionBase &
(
| {
readonly configPath: ClientPath;
readonly markerPath: ClientPath;
readonly location?: undefined;
}
| {
/** Resolve configuration and marker together when they share probes. */
readonly location: (
context: ClientPathContext,
) => Result<ClientLocation, ClientPathFailure>;
readonly configPath?: undefined;
readonly markerPath?: undefined;
}
);
interface ClientDefinitionBase {
readonly name: string;
readonly displayName: string;
readonly configPath: ClientPath;
readonly markerPath: ClientPath;
readonly format: NonNullable<SetupClient["format"]>;
readonly quitBeforeSetup?: boolean;
readonly zcodeFallbackPath?: (context: ClientPathContext) => string;
readonly skillPath?: ClientPath;
readonly configPaths?: (context: ClientPathContext) => readonly string[];
@@ -111,16 +140,20 @@ const traeUserDirectory = ({
return join(xdgConfigHome({ home, platform, env }), "Trae", "User");
};
const claudeDesktopDirectory = ({
home,
platform,
env,
}: ClientPathContext): string => {
if (platform === "win32")
return join(env.APPDATA ?? join(home, "AppData", "Roaming"), "Claude");
if (platform === "linux")
return join(xdgConfigHome({ home, platform, env }), "Claude");
return join(home, "Library", "Application Support", "Claude");
/** Windows packaging decides which file Claude Desktop reads; see its resolver. */
const claudeDesktopLocation = (
context: ClientPathContext,
): Result<ClientLocation, ClientPathFailure> => {
if (context.platform === "win32")
return resolveWindowsClaudeDesktopLocation(context.home, context.env);
const directory =
context.platform === "linux"
? join(xdgConfigHome(context), "Claude")
: join(context.home, "Library", "Application Support", "Claude");
return ok({
configPath: join(directory, "claude_desktop_config.json"),
markerPath: directory,
});
};
const claudeCodeConfigDirectory = ({ home, env }: ClientPathContext): string =>
@@ -211,6 +244,55 @@ export const manualRegistrationRemediation = (
? GROK_BOT_MANUAL_REGISTRATION_REMEDIATION
: undefined;
/**
* Facts a setup plan must disclose so an approved registration persists:
* which file an MSIX package reads, and that a running client can overwrite it.
*/
export const registrationPersistenceDetail = (
client: SetupClient,
): string | undefined => {
const name = client.displayName ?? client.name;
const msix = client.msixPackage;
const packageDetail =
msix === undefined
? undefined
: client.configPath === msix.privateConfigPath
? `${name} is installed as MSIX package ${msix.packageFamilyName}, which reads this package-private file instead of ${msix.appDataConfigPath}.`
: `${name} is installed as MSIX package ${msix.packageFamilyName}, which reads this file until it saves its own copy at ${msix.privateConfigPath}.`;
const quitDetail =
client.quitBeforeSetup === true
? `Quit ${name} fully before approving; closing its window is not enough. A running ${name} can rewrite this file from memory and drop the registration. Start it again after setup.`
: undefined;
const details = [packageDetail, quitDetail].filter(
(detail): detail is string => detail !== undefined,
);
return details.length === 0 ? undefined : details.join(" ");
};
/**
* Why this process must not change an MSIX client's configuration. A process
* the running app started sees its redirected AppData, and the app would
* overwrite the change from memory; an unknown view cannot rule that out.
*/
export const registrationWriteBlocker = (
client: SetupClient,
operation: "setup" | "uninstall",
): string | undefined => {
const msix = client.msixPackage;
if (msix === undefined || msix.processView === "direct") return undefined;
const name = client.displayName ?? client.name;
return msix.processView === "redirected"
? `This process was started from ${name}'s MSIX package ${msix.packageFamilyName}: its AppData is redirected into that package, so ${name} is running and would overwrite ${msix.privateConfigPath} from memory. Quit ${name} fully, then rerun ${operation} from a terminal that ${name} did not start.`
: `REA cannot tell whether ${name}'s MSIX package ${msix.packageFamilyName} started this process, because none of its files under ${dirname(msix.privateConfigPath)} could be compared with ${dirname(msix.appDataConfigPath)}. A running ${name} would overwrite the change. Open ${name} once if it has never run, quit it fully, then rerun ${operation} from a terminal that ${name} did not start.`;
};
/** The MSIX package view, if any, that redirects this process's AppData writes. */
export const appDataRedirection = (
clients: readonly SetupClient[],
): MsixPackageView | undefined =>
clients.find(({ msixPackage }) => msixPackage?.processView === "redirected")
?.msixPackage;
const OMP_PROFILE_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
const OMP_RESERVED_PROFILE =
/^(?:CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\..*)?$/iu;
@@ -408,9 +490,8 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
{
name: "claude_desktop",
displayName: "Claude Desktop",
configPath: (context: ClientPathContext) =>
join(claudeDesktopDirectory(context), "claude_desktop_config.json"),
markerPath: claudeDesktopDirectory,
location: claudeDesktopLocation,
quitBeforeSetup: true,
format: "json",
},
{
@@ -627,6 +708,19 @@ const resolvePath = (
return typeof resolved === "string" ? ok(resolved) : resolved;
};
const resolveLocation = (
definition: ClientDefinition,
context: ClientPathContext,
): Result<ClientLocation, ClientPathFailure> => {
if (definition.location !== undefined) return definition.location(context);
const config = resolvePath(definition.configPath, context);
if (!config.ok) return config;
const marker = resolvePath(definition.markerPath, context);
return marker.ok
? ok({ configPath: config.value, markerPath: marker.value })
: marker;
};
/** Describe every client location that setup, doctor, or uninstall may inspect. */
export const supportedClients = (
home: string,
@@ -637,27 +731,16 @@ export const supportedClients = (
const definitions: readonly ClientDefinition[] = SUPPORTED_CLIENT_DEFINITIONS;
return definitions.map((definition) => {
try {
const config = resolvePath(definition.configPath, context);
const marker = config.ok
? resolvePath(definition.markerPath, context)
: config;
if (!config.ok)
const location = resolveLocation(definition, context);
if (!location.ok)
return {
name: definition.name,
displayName: definition.displayName,
format: definition.format,
configPath: config.error.path,
configPathError: config.error.message,
configPath: location.error.path,
configPathError: location.error.message,
};
if (!marker.ok)
return {
name: definition.name,
displayName: definition.displayName,
format: definition.format,
configPath: marker.error.path,
configPathError: marker.error.message,
};
const configPath = config.value;
const { configPath, markerPath, msixPackage } = location.value;
return {
name: definition.name,
displayName: definition.displayName,
@@ -675,7 +758,11 @@ export const supportedClients = (
...(definition.zcodeFallbackPath === undefined
? {}
: { zcodeFallbackPath: definition.zcodeFallbackPath(context) }),
markerPath: marker.value,
markerPath,
...(msixPackage === undefined ? {} : { msixPackage }),
...(definition.quitBeforeSetup === true
? { quitBeforeSetup: true }
: {}),
format: definition.format,
};
} catch (cause: unknown) {
+157 -33
View File
@@ -32,10 +32,16 @@ import {
} from "./RegularFileRead.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import {
appDataRedirection,
manualRegistrationRemediation,
registrationWriteBlocker,
supportedClients,
type SetupClient,
} from "./SupportedClients.js";
import {
redirectedWriteBlocker,
type MsixPackageView,
} from "./MsixPackageStorage.js";
export { isUninstallFailure } from "./UninstallFailure.js";
interface ManagedPathStats {
@@ -93,6 +99,7 @@ export interface UninstallHost {
/** Report a configuration that cannot be read safely, before any removal. */
inspectClient(client: SetupClient): Promise<UninstallItem | undefined>;
removeClient(client: SetupClient): Promise<UninstallItem>;
inspectSkill?(): Promise<UninstallItem | undefined>;
removeSkill(): Promise<UninstallItem>;
purgeData(): Promise<readonly UninstallItem[]>;
close?(): Promise<string | undefined>;
@@ -118,6 +125,8 @@ export const runUninstall = async (
const blocking = await host.inspectClient(client);
if (blocking !== undefined) blocked.push(blocking);
}
const skillBlocker = await host.inspectSkill?.();
if (skillBlocker !== undefined) blocked.push(skillBlocker);
const items: UninstallItem[] =
blocked.length > 0
? [
@@ -209,27 +218,70 @@ export const systemUninstallHost = (
selectedHome ?? homeDirectoryFromEnvironment(environment, platform);
const resources = new ArtifactResourceScope();
const fileSystem = selectedFileSystem ?? systemFileSystem(resources);
// Set with the client list: the package view that redirects this
// process's AppData writes, if any.
let redirection: MsixPackageView | undefined;
const clientWriteBlocker = (client: SetupClient): string | undefined =>
registrationWriteBlocker(client, "uninstall") ??
redirectedWriteBlocker(redirection, [client.configPath], "uninstall");
const skillWriteBlocker = (path: string): string | undefined =>
redirectedWriteBlocker(redirection, [path], "uninstall");
return {
clients: () =>
Promise.resolve(
supportedClients(home, platform, environment).flatMap((client) =>
client.configPaths === undefined
? [client]
: client.configPaths.map((configPath) => ({
...client,
configPath,
})),
clients: () => {
const clients = supportedClients(home, platform, environment);
redirection = appDataRedirection(clients);
return Promise.resolve(
clients.flatMap((client) =>
uninstallConfigPaths(client).map((configPath) => ({
...client,
configPath,
})),
),
),
);
},
inspectClient: async (client) => {
const read = await readClientConfiguration(client, fileSystem);
return read.kind === "item" && read.item.status === "failed"
? read.item
: undefined;
if (read.kind === "item")
return read.item.status === "failed" ? read.item : undefined;
const removal = clientRegistrationRemoval(read.parsed, client);
if (!removal.removeNative && removal.legacyPath === undefined)
return undefined;
// A removal the running package would revert, or redirect into its
// private storage, would leave the registration in place.
const blocker = clientWriteBlocker(client);
return blocker === undefined
? undefined
: item(client.name, "failed", blocker);
},
removeClient: (client) =>
removeClient(client, fileSystem, () => clientWriteBlocker(client)),
inspectSkill: async () => {
for (const destination of skillDestinations(
home,
undefined,
environment,
platform,
)) {
const inspected = await inspectManagedSkill(
destination.path,
destination.client,
fileSystem,
);
if (inspected?.status === "failed") return inspected;
if (inspected !== undefined) continue;
const blocker = skillWriteBlocker(destination.path);
if (blocker !== undefined) return item("skill", "failed", blocker);
}
return undefined;
},
removeClient: (client) => removeClient(client, fileSystem),
removeSkill: () =>
removeManagedSkills(home, fileSystem, environment, platform),
removeManagedSkills(
home,
fileSystem,
environment,
platform,
skillWriteBlocker,
),
purgeData: () => purgeManagedData(join(home, ".rea"), fileSystem),
close: async () => {
try {
@@ -242,6 +294,36 @@ export const systemUninstallHost = (
};
};
/**
* Every user file that can hold REA's registration for one client. An MSIX
* package can read either its private copy or the AppData file, and earlier
* setups wrote the AppData file, so both lose REA's entry.
*/
const uninstallConfigPaths = (client: SetupClient): readonly string[] => [
...new Set([
...(client.configPaths ?? [client.configPath]),
...(client.msixPackage === undefined
? []
: [
client.msixPackage.privateConfigPath,
client.msixPackage.appDataConfigPath,
]),
]),
];
/** Whether removal would change this configuration. */
const registrationPresent = (parsed: ClientConfigurationDocument): boolean => {
const name = PRODUCT_IDENTITY.mcpServerKey;
return (
Object.hasOwn(parsed.servers, name) ||
// Beside a native OpenCode V2 table, OpenCode also loads a V1 `mcp.rea`.
legacyClientServerPath(parsed, name) !== undefined ||
// Harness ownership is the stable entry id. A stale or malformed launcher
// still belongs to that id, and so does a direct patch that projects no row.
(parsed.dialect === "dsh" && dshDocument(parsed.document).carriesEntry)
);
};
type ClientConfigurationRead =
| { readonly kind: "item"; readonly item: UninstallItem }
| {
@@ -308,21 +390,47 @@ const itemRead = (result: UninstallItem): ClientConfigurationRead => ({
item: result,
});
/**
* Share the exact ownership and applicability decision with preflight. A
* removable legacy entry carries its document path, so removal edits exactly
* the entry this decision admitted.
*/
const clientRegistrationRemoval = (
parsed: ClientConfigurationDocument,
client: SetupClient,
): {
readonly removeNative: boolean;
readonly legacyPath: readonly string[] | undefined;
} => {
const name = PRODUCT_IDENTITY.mcpServerKey;
if (
parsed.dialect === "dsh" &&
dshDocument(parsed.document).hasUnknownStructure
)
return { removeNative: false, legacyPath: undefined };
const legacyPath = legacyClientServerPath(parsed, name);
return {
removeNative:
(parsed.dialect === "dsh" && dshDocument(parsed.document).carriesEntry) ||
(Object.hasOwn(parsed.servers, name) &&
isOwnedRegistration(parsed.servers[name], client)),
legacyPath:
legacyPath !== undefined &&
isOwnedRegistration(parsed.legacyServers[name], client)
? legacyPath
: undefined,
};
};
const removeClient = async (
client: SetupClient,
fileSystem: UninstallFileSystem,
writeBlocker?: () => string | undefined,
): Promise<UninstallItem> => {
const read = await readClientConfiguration(client, fileSystem);
if (read.kind === "item") return read.item;
const { transactionPath, original, parsed } = read;
const name = PRODUCT_IDENTITY.mcpServerKey;
// Beside a native OpenCode V2 table, OpenCode also loads a V1 `mcp.rea`.
const legacyPath = legacyClientServerPath(parsed, name);
const hasNative = Object.hasOwn(parsed.servers, name);
// Harness ownership is the stable entry id. A stale or malformed launcher
// still belongs to that id, and so does a direct patch that projects no row.
const carriesDshEntry =
parsed.dialect === "dsh" && dshDocument(parsed.document).carriesEntry;
if (
parsed.dialect === "dsh" &&
dshDocument(parsed.document).hasUnknownStructure
@@ -332,20 +440,21 @@ const removeClient = async (
"retained",
"A Cordis expression may produce registration rows, so the patch was retained without changes.",
);
if (!hasNative && legacyPath === undefined && !carriesDshEntry)
if (!registrationPresent(parsed))
return item(client.name, "skipped", "REA registration is absent.");
const removeNative =
carriesDshEntry ||
(hasNative && isOwnedRegistration(parsed.servers[name], client));
const removeLegacy =
legacyPath !== undefined &&
isOwnedRegistration(parsed.legacyServers[name], client);
const { removeNative, legacyPath } = clientRegistrationRemoval(
parsed,
client,
);
const removeLegacy = legacyPath !== undefined;
if (!removeNative && !removeLegacy)
return item(
client.name,
"retained",
"The rea-named registration is not REA-owned.",
);
const blocker = writeBlocker?.();
if (blocker !== undefined) return item(client.name, "failed", blocker);
const remaining = { ...parsed.servers };
if (removeNative) delete remaining[name];
const document = withClientServers(
@@ -355,7 +464,7 @@ const removeClient = async (
);
const editedPaths = [
...(removeNative ? [clientServerPath(parsed, name)] : []),
...(removeLegacy ? [legacyPath] : []),
...(legacyPath === undefined ? [] : [legacyPath]),
];
const backupPath = `${client.configPath}.rea.backup`;
try {
@@ -516,12 +625,13 @@ const removeManagedSkills = async (
fileSystem: UninstallFileSystem,
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
writeBlocker?: (path: string) => string | undefined,
): Promise<UninstallItem> => {
// Every destination shares one summary item, so each result is labeled by
// the directory it refers to.
const results = await Promise.all(
skillDestinations(home, undefined, environment, platform).map(({ path }) =>
removeManagedSkill(path, path, fileSystem),
removeManagedSkill(path, path, fileSystem, writeBlocker),
),
);
const failed = results.find(({ status }) => status === "failed");
@@ -552,11 +662,11 @@ const removeManagedSkills = async (
);
};
const removeManagedSkill = async (
const inspectManagedSkill = async (
path: string,
name: string,
fileSystem: UninstallFileSystem,
): Promise<UninstallItem> => {
): Promise<UninstallItem | undefined> => {
let root: ManagedPathStats;
try {
root = await fileSystem.stat(path);
@@ -594,6 +704,20 @@ const removeManagedSkill = async (
if (!isManagedSkillManifest(content))
return item(name, "retained", "Skill manifest is not REA-owned.");
return undefined;
};
const removeManagedSkill = async (
path: string,
name: string,
fileSystem: UninstallFileSystem,
writeBlocker?: (path: string) => string | undefined,
): Promise<UninstallItem> => {
const inspection = await inspectManagedSkill(path, name, fileSystem);
if (inspection !== undefined) return inspection;
const blocker = writeBlocker?.(path);
if (blocker !== undefined) return item(name, "failed", blocker);
const manifestName = "SKILL.md";
const otherFiles = MANAGED_SKILL_FILES.filter(
(relativePath) => relativePath !== manifestName,
@@ -12,7 +12,7 @@ import { jsonObjectSchema, type JsonValue } from "../../domain/jsonValue.js";
import { err, ok, type Result } from "../../domain/result.js";
import type { AnalysisProviderCandidate } from "../AnalysisProvider.js";
import type { AnalysisProviderCandidateStatus } from "./AnalysisProviderRegistry.js";
import { ABORTED, waitForAbortable } from "./AbortablePromise.js";
import { ABORTED, waitForAbortable } from "../../process/AbortablePromise.js";
/** Profile-resolution truth for one discovered provider candidate. */
export interface AnalysisProviderCandidateEvaluation {
@@ -5,7 +5,7 @@ import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import type { ProviderOperationHealth } from "../../domain/providerOperationHealth.js";
import { err, ok } from "../../domain/result.js";
import { ABORTED, waitForAbortable } from "./AbortablePromise.js";
import { ABORTED, waitForAbortable } from "../../process/AbortablePromise.js";
import type {
AnalysisClient,
AnalysisClientContext,
@@ -51,6 +51,9 @@ export const addElectronCallPaths = (
properties: {
path_id: pathId,
entry: path.entry,
...(path.entry_path === undefined
? {}
: { entry_path: [...path.entry_path] }),
entry_kind: path.entry_kind,
channel: path.channel,
terminal: path.terminal,
@@ -97,6 +100,9 @@ export const addElectronCallPaths = (
properties: {
path_id: pathId,
entry: path.entry,
...(path.entry_path === undefined
? {}
: { entry_path: [...path.entry_path] }),
resolution: "candidate",
},
});
@@ -119,6 +125,9 @@ export const addElectronCallPaths = (
properties: {
path_id: pathId,
entry: path.entry,
...(path.entry_path === undefined
? {}
: { entry_path: [...path.entry_path] }),
channel: path.channel,
resolution: "candidate",
conditions: path.conditions,
@@ -34,6 +34,9 @@ export function* projectElectronSemanticCallPaths(
properties: {
path_id: pathId,
entry: path.entry,
...(path.entry_path === undefined
? {}
: { entry_path: [...path.entry_path] }),
channel: path.channel,
terminal: path.terminal,
step_kind: step.kind,
@@ -62,6 +65,9 @@ export function* projectElectronSemanticCallPaths(
properties: {
path_id: pathId,
entry: path.entry,
...(path.entry_path === undefined
? {}
: { entry_path: [...path.entry_path] }),
channel: path.channel,
basis: "lexical-wrapper-substitution",
},
@@ -1,5 +1,6 @@
import type { BigIntStats, Stats } from "node:fs";
import type { FileHandle } from "node:fs/promises";
import { tmpdir } from "node:os";
import { afterEach, expect, it, vi } from "vitest";
import {
@@ -88,3 +89,36 @@ it("compares available nanosecond timestamps without rounding away source change
sameRegularFileState(before, { ...before, ctimeNs: before.ctimeNs + 1n }),
).toBe(false);
});
it.each([
["EACCES", -13, "keeps"],
["ENXIO", -6, "reclassifies"],
] as const)(
"%s from opening a non-regular path: admission %s the failure",
async (code, errno, outcome) => {
const failure = Object.assign(new Error(`open ${code}`), { code, errno });
mockOpen.mockRejectedValue(failure);
// The selected path itself is a directory that stat can still describe.
const cause = await openRegularFile(tmpdir(), { symlinks: "follow" }).catch(
(rejected: unknown) => rejected,
);
if (outcome === "keeps") expect(cause).toBe(failure);
else expect(cause).toBeInstanceOf(NonRegularFileReadError);
},
);
it("keeps cancellation that arrives during the non-regular metadata probe", async () => {
const controller = new AbortController();
const cancellation = new Error("cancelled during probe");
mockOpen.mockImplementation(async () => {
// The probe stats the path after this rejection; abort before it settles.
queueMicrotask(() => controller.abort(cancellation));
throw Object.assign(new Error("open ENXIO"), { code: "ENXIO", errno: -6 });
});
await expect(
openRegularFile(tmpdir(), {
symlinks: "follow",
signal: controller.signal,
}),
).rejects.toBe(cancellation);
});
+16
View File
@@ -36,6 +36,22 @@ const archiveWithOverlappingObjectRanges = (objectCount: number): Buffer => {
};
describe("NIBArchive decoder", () => {
it("keeps leading U+FEFF in length-prefixed keys and class names", () => {
const archive = encodeArchive({
classes: ["\uFEFFWidget"],
objects: [{ classIndex: 0, values: { count: 1, "\uFEFFcount": 2 } }],
});
expect(decodeNibArchive(archive).objects).toEqual([
{
id: 0,
class_name: "\uFEFFWidget",
values: { count: 1, "\uFEFFcount": 2 },
},
]);
const invalid = Buffer.from(archive);
invalid[invalid.indexOf(Buffer.from("\uFEFFcount"))] = 0xff;
expect(() => decodeNibArchive(invalid)).toThrow(/not valid UTF-8/u);
});
it("decodes bounded object, key, class, and reference tables", () => {
const archive = encodeArchive({
classes: ["NSView\0", "NSString\0"],
+23 -6
View File
@@ -14,6 +14,7 @@ export class BrowserStartupError extends Error {
readonly failure: BrowserStartupFailure;
readonly executable: string;
readonly elapsedMs: number;
readonly startupTimeoutMs: number;
readonly exitCode: number | null;
readonly signalCode: NodeJS.Signals | null;
readonly stderr: string;
@@ -23,6 +24,7 @@ export class BrowserStartupError extends Error {
readonly failure: BrowserStartupFailure;
readonly executable: string;
readonly elapsedMs: number;
readonly startupTimeoutMs: number;
readonly exitCode: number | null;
readonly signalCode: NodeJS.Signals | null;
readonly stderr: string;
@@ -33,12 +35,22 @@ export class BrowserStartupError extends Error {
this.failure = diagnostics.failure;
this.executable = diagnostics.executable;
this.elapsedMs = diagnostics.elapsedMs;
this.startupTimeoutMs = diagnostics.startupTimeoutMs;
this.exitCode = diagnostics.exitCode;
this.signalCode = diagnostics.signalCode;
this.stderr = diagnostics.stderr;
}
}
/**
* Single owner of the wait for Chrome to publish its DevToolsActivePort.
*
* Callers that need a different budget pass `timeoutMs`; nobody else should
* restate this number, because a per-caller literal silently changes how long
* a cold Chrome launch is tolerated before the failure names its ceiling.
*/
export const BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS = 60_000;
/** Owned child process and startup policy for Chrome CDP discovery. */
export interface BrowserStartupOptions {
readonly child: ChildProcess;
@@ -53,23 +65,23 @@ export interface BrowserStartupOptions {
export const waitForBrowserDevtoolsPort = async (
options: BrowserStartupOptions,
): Promise<number> => {
const timeoutMs = options.timeoutMs ?? 15_000;
const timeoutMs = options.timeoutMs ?? BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS;
const pollIntervalMs = options.pollIntervalMs ?? 25;
const startedAt = performance.now();
const terminal = childTermination(options, startedAt);
const terminal = childTermination(options, startedAt, timeoutMs);
const deadline = startedAt + timeoutMs;
while (true) {
const terminalState = currentTerminalState(options.child);
if (terminalState !== null)
throw startupError(options, startedAt, terminalState);
throw startupError(options, startedAt, timeoutMs, terminalState);
const port = await readDevtoolsPort(options.activePortPath);
if (port !== null) return port;
const remainingMs = deadline - performance.now();
if (remainingMs <= 0)
throw startupError(options, startedAt, { failure: "timeout" });
throw startupError(options, startedAt, timeoutMs, { failure: "timeout" });
const outcome = await Promise.race([
terminal,
@@ -88,11 +100,12 @@ type TerminalState =
const childTermination = (
options: BrowserStartupOptions,
startedAt: number,
startupTimeoutMs: number,
): Promise<BrowserStartupError> =>
new Promise((resolve) => {
options.child.once("error", (cause: unknown) => {
resolve(
startupError(options, startedAt, {
startupError(options, startedAt, startupTimeoutMs, {
failure: "spawn-error",
cause,
}),
@@ -103,6 +116,7 @@ const childTermination = (
startupError(
options,
startedAt,
startupTimeoutMs,
options.child.signalCode === null
? { failure: "exited" }
: { failure: "signalled" },
@@ -120,6 +134,7 @@ const currentTerminalState = (child: ChildProcess): TerminalState | null => {
const startupError = (
options: BrowserStartupOptions,
startedAt: number,
startupTimeoutMs: number,
state: TerminalState,
): BrowserStartupError =>
new BrowserStartupError(
@@ -127,6 +142,7 @@ const startupError = (
failure: state.failure,
executable: options.executable,
elapsedMs: Math.max(0, Math.round(performance.now() - startedAt)),
startupTimeoutMs,
exitCode: options.child.exitCode,
signalCode: options.child.signalCode,
stderr: options.stderr(),
@@ -156,9 +172,10 @@ const browserStartupMessage = (
diagnostics: {
readonly executable: string;
readonly elapsedMs: number;
readonly startupTimeoutMs: number;
readonly exitCode: number | null;
readonly signalCode: NodeJS.Signals | null;
readonly stderr: string;
},
): string =>
`Chrome CDP startup ${failure}; executable=${diagnostics.executable}; elapsed_ms=${String(diagnostics.elapsedMs)}; exit_code=${diagnostics.exitCode === null ? "null" : String(diagnostics.exitCode)}; signal=${diagnostics.signalCode ?? "null"}; stderr=${diagnostics.stderr.length === 0 ? "<empty>" : diagnostics.stderr}`;
`Chrome CDP startup ${failure}; executable=${diagnostics.executable}; elapsed_ms=${String(diagnostics.elapsedMs)}; startup_timeout_ms=${String(diagnostics.startupTimeoutMs)}; exit_code=${diagnostics.exitCode === null ? "null" : String(diagnostics.exitCode)}; signal=${diagnostics.signalCode ?? "null"}; stderr=${diagnostics.stderr.length === 0 ? "<empty>" : diagnostics.stderr}`;
+21
View File
@@ -289,4 +289,25 @@ describe("safe CDP response metadata referrer policy", () => {
expect(captured.response.policies.referrer_policy).toBe(expected);
expect(captured.response.policies.coop).toBe("same-origin");
});
it.each<[string | number | undefined, number | null]>([
["100", 100],
[" 0 ", 0],
[100, 100],
["-5", null],
["+12", null],
["0x10", null],
["1e3", null],
["9007199254740991", 9007199254740991],
["9007199254740992", null],
[undefined, null],
])("declares Content-Length %j only for decimal digits", (raw, expected) => {
const captured = safeResponseMetadata(
"request-length",
`${origin}/api`,
{ headers: raw === undefined ? {} : { "Content-Length": raw } },
new Set([origin]),
);
expect(captured.response.content_length).toBe(expected);
});
});
+8 -9
View File
@@ -1,10 +1,6 @@
import type { WebPageInspection } from "../domain/browserObservationSchemas.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import {
numberValue,
cdpStringValue,
type UnknownRecord,
} from "./CdpCaptureValues.js";
import { cdpStringValue, type UnknownRecord } from "./CdpCaptureValues.js";
type ResponseMetadata = WebPageInspection["metadata"]["responses"][number];
type LinkMetadata = ResponseMetadata["links"][number];
@@ -43,7 +39,7 @@ export const safeResponseMetadata = (
request_id: requestId,
url,
mime_type: boundedHeader(cdpStringValue(response.mimeType)),
content_length: nonnegativeInteger(headers.get("content-length")),
content_length: contentLength(headers.get("content-length")),
content_encoding: boundedHeader(headers.get("content-encoding")),
csp,
links,
@@ -343,9 +339,12 @@ const policyToken = (value: string | undefined): string | null => {
return /^[a-z][a-z0-9_.\x2d]*$/u.test(token) ? token : null;
};
const nonnegativeInteger = (value: string | undefined): number | null => {
const number = numberValue(value === undefined ? undefined : Number(value));
return number === undefined ? null : Math.max(0, Math.trunc(number));
// RFC 9110 section 8.6: Content-Length = 1*DIGIT. Other spellings declare no length.
const contentLength = (value: string | undefined): number | null => {
const token = (value ?? "").trim();
if (!/^[0-9]+$/u.test(token)) return null;
const length = Number(token);
return Number.isSafeInteger(length) ? length : null;
};
const boundedHeader = (value: string | undefined): string | null =>
@@ -164,7 +164,15 @@ it("keeps attached-target ownership after the cleanup response timeout", async (
cleanup: { reason: expect.stringContaining("timed out") },
});
await closeStarted.promise;
await vi.advanceTimersByTimeAsync(1_000);
let responseSettled = false;
void timedOutClose
.finally(() => {
responseSettled = true;
})
.catch(() => {});
await vi.advanceTimersByTimeAsync(29_999);
expect(responseSettled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await timeoutExpectation;
expect(settled).toEqual([]);
+8 -1
View File
@@ -11,6 +11,9 @@ import { BrowserObservationError } from "../domain/browserObservationError.js";
import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";
const OPERATION = "capture_browser_scenario" as const;
// Closing a real Chrome persistent context can take several seconds even when
// it succeeds. The shorter operation deadline must not misreport cleanup.
const CLEANUP_CONFIRMATION_TIMEOUT_MS = 30_000;
const throwIfScenarioCancelled = (signal: AbortSignal | undefined): void => {
if (signal?.aborted === true)
@@ -71,7 +74,11 @@ export class PlaywrightScenarioBrowserCleanupOwner {
signal?: AbortSignal,
): Promise<void> {
try {
await withPlaywrightExecutionBoundary(() => cleanup, 1_000, signal);
await withPlaywrightExecutionBoundary(
() => cleanup,
CLEANUP_CONFIRMATION_TIMEOUT_MS,
signal,
);
} catch (cause: unknown) {
throw new BrowserObservationError(OPERATION, "cleanup_failed", {
cause,
@@ -0,0 +1,130 @@
import { EventEmitter } from "node:events";
import type { Page } from "playwright-core";
import { expect, it } from "vitest";
import { browserScenarioSchema } from "../domain/browserScenario.js";
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import { PlaywrightScenarioEvents } from "./PlaywrightScenarioEvents.js";
it("omits a request without a frame in a shared context", () => {
const context = new EventEmitter();
const page = new EventEmitter() as unknown as Page;
const scenario = browserScenarioSchema.parse({
browser: { mode: "launch", executable_path: "/opt/chromium" },
start_url: { url: "https://app.example.test/" },
actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
capture: { events: ["network"] },
});
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
if (secrets === undefined) throw new Error("Expected resolved secrets");
const events = new PlaywrightScenarioEvents({
page,
context: context as never,
ownsContext: false,
enabled: new Set(["network"]),
secrets,
});
const unknownRequest = {
frame: () => {
throw new Error("Frame for this navigation request is unavailable");
},
url: () => "https://unrelated.example.test/private",
};
context.emit("request", unknownRequest);
expect(events.result().items).toEqual([]);
expect(events.limitations()).toContain(
"Shared-context network capture excludes requests without a known root or descendant Page frame.",
);
});
it("detaches root and popup listeners when a scenario finishes", async () => {
const context = new EventEmitter();
const page = new EventEmitter() as unknown as Page;
const popup = Object.assign(new EventEmitter(), {
url: () => "https://app.example.test/popup",
});
const scenario = browserScenarioSchema.parse({
browser: { mode: "launch", executable_path: "/opt/chromium" },
start_url: { url: "https://app.example.test/" },
actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
capture: { events: ["console", "popups"] },
});
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
if (secrets === undefined) throw new Error("Expected resolved secrets");
const events = new PlaywrightScenarioEvents({
page,
context: context as never,
ownsContext: false,
enabled: new Set(["console", "popups"]),
secrets,
});
(page as unknown as EventEmitter).emit("popup", popup);
expect((page as unknown as EventEmitter).listenerCount("console")).toBe(1);
expect(popup.listenerCount("console")).toBe(1);
// Popup closure is recorded, then its page-owned listeners are released.
expect(popup.listenerCount("close")).toBe(2);
await events.finish();
expect((page as unknown as EventEmitter).listenerCount("console")).toBe(0);
expect((page as unknown as EventEmitter).listenerCount("popup")).toBe(0);
expect(popup.listenerCount("console")).toBe(0);
expect(popup.listenerCount("popup")).toBe(0);
expect(popup.listenerCount("close")).toBe(0);
});
it("detaches worker and websocket listeners when a scenario finishes", async () => {
const context = new EventEmitter();
const page = new EventEmitter() as unknown as Page;
const socket = Object.assign(new EventEmitter(), {
url: () => "wss://app.example.test/socket",
});
const worker = Object.assign(new EventEmitter(), {
url: () => "https://app.example.test/worker.js",
});
const scenario = browserScenarioSchema.parse({
browser: { mode: "launch", executable_path: "/opt/chromium" },
start_url: { url: "https://app.example.test/" },
actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
capture: { events: ["websockets", "workers"] },
});
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
if (secrets === undefined) throw new Error("Expected resolved secrets");
const events = new PlaywrightScenarioEvents({
page,
context: context as never,
ownsContext: false,
enabled: new Set(["websockets", "workers"]),
secrets,
});
(page as unknown as EventEmitter).emit("websocket", socket);
(page as unknown as EventEmitter).emit("worker", worker);
expect(socket.listenerCount("framesent")).toBe(1);
expect(worker.listenerCount("close")).toBe(1);
await events.finish();
expect(socket.listenerCount("framesent")).toBe(0);
expect(socket.listenerCount("framereceived")).toBe(0);
expect(socket.listenerCount("close")).toBe(0);
expect(worker.listenerCount("close")).toBe(0);
});
it("detaches owned-context popup discovery when a scenario finishes", async () => {
const context = new EventEmitter();
const page = new EventEmitter() as unknown as Page;
const scenario = browserScenarioSchema.parse({
browser: { mode: "launch", executable_path: "/opt/chromium" },
start_url: { url: "https://app.example.test/" },
actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
capture: { events: ["console"] },
});
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
if (secrets === undefined) throw new Error("Expected resolved secrets");
const events = new PlaywrightScenarioEvents({
page,
context: context as never,
ownsContext: true,
enabled: new Set(["console"]),
secrets,
});
expect(context.listenerCount("page")).toBe(1);
await events.finish();
expect(context.listenerCount("page")).toBe(0);
});
+98 -33
View File
@@ -54,10 +54,11 @@ export class PlaywrightScenarioEvents {
private readonly enabled: ReadonlySet<EventName>;
private readonly secrets: BrowserScenarioSecrets;
private readonly ownsContext: boolean;
private readonly pages = new Set<Page>();
private pages = new WeakSet<Page>();
private readonly incompleteFamilies = new Set<EventName>();
private readonly network: PlaywrightScenarioNetwork | undefined;
private stopNetwork: (() => void) | undefined;
private readonly stopListeners = new Map<object, Set<() => void>>();
private sealed = false;
constructor(options: EventCaptureOptions) {
@@ -72,10 +73,12 @@ export class PlaywrightScenarioEvents {
this.secrets = options.secrets;
this.ownsContext = options.ownsContext === true;
this.pages.add(options.page);
if (this.ownsContext && this.enabled.size > 0)
(options.context ?? options.page.context()).on("page", (page) =>
this.popup(page),
);
if (this.ownsContext && this.enabled.size > 0) {
const context = options.context ?? options.page.context();
const onPage = (page: Page) => this.popup(page);
context.on("page", onPage);
this.retainListener(context, () => context.off("page", onPage));
}
if (this.enabled.has("network")) {
const context = options.context ?? options.page.context();
const collector = new PlaywrightScenarioNetwork({
@@ -138,6 +141,8 @@ export class PlaywrightScenarioEvents {
async finish(): Promise<void> {
this.stopNetwork?.();
this.stopNetwork = undefined;
for (const owner of this.stopListeners.keys()) this.releaseListeners(owner);
this.pages = new WeakSet<Page>();
try {
await this.network?.finish();
} finally {
@@ -184,34 +189,81 @@ export class PlaywrightScenarioEvents {
return this.sequence;
}
private retainListener(owner: object, stop: () => void): void {
let stops = this.stopListeners.get(owner);
if (stops === undefined) {
stops = new Set();
this.stopListeners.set(owner, stops);
}
stops.add(stop);
}
private releaseListeners(owner: object): void {
const stops = this.stopListeners.get(owner);
this.stopListeners.delete(owner);
for (const stop of stops ?? []) stop();
}
private observePage(page: Page): void {
if (this.enabled.has("console"))
page.on("console", (message) => this.console(message));
if (this.enabled.has("page-errors"))
page.on("pageerror", (error) => {
if (this.enabled.size > 0) {
const onClose = () => {
this.releaseListeners(page);
};
page.on("close", onClose);
this.retainListener(page, () => page.off("close", onClose));
}
if (this.enabled.has("console")) {
const onConsole = (message: ConsoleMessage) => this.console(message);
page.on("console", onConsole);
this.retainListener(page, () => page.off("console", onConsole));
}
if (this.enabled.has("page-errors")) {
const onError = (error: Error) => {
this.push({
kind: "page-error",
message: this.secrets.redact(error.message),
stack:
error.stack === undefined ? null : this.secrets.redact(error.stack),
});
});
if (this.enabled.has("websockets"))
page.on("websocket", (socket) => this.webSocket(socket));
};
page.on("pageerror", onError);
this.retainListener(page, () => page.off("pageerror", onError));
}
if (this.enabled.has("websockets")) {
const onWebSocket = (socket: WebSocket) => this.webSocket(socket);
page.on("websocket", onWebSocket);
this.retainListener(page, () => page.off("websocket", onWebSocket));
}
if (this.enabled.has("frames")) {
page.on("frameattached", (frame) => this.frame("frame-attached", frame));
page.on("framedetached", (frame) => this.frame("frame-detached", frame));
page.on("framenavigated", (frame) =>
this.frame("frame-navigated", frame),
);
const onAttached = (frame: Frame) => this.frame("frame-attached", frame);
const onDetached = (frame: Frame) => this.frame("frame-detached", frame);
const onNavigated = (frame: Frame) =>
this.frame("frame-navigated", frame);
page.on("frameattached", onAttached);
page.on("framedetached", onDetached);
page.on("framenavigated", onNavigated);
this.retainListener(page, () => page.off("frameattached", onAttached));
this.retainListener(page, () => page.off("framedetached", onDetached));
this.retainListener(page, () => page.off("framenavigated", onNavigated));
}
if (this.enabled.has("workers")) {
const onWorker = (worker: Worker) => this.worker(worker);
page.on("worker", onWorker);
this.retainListener(page, () => page.off("worker", onWorker));
}
if (this.enabled.has("workers"))
page.on("worker", (worker) => this.worker(worker));
// Any selected family needs descendant discovery in shared contexts.
// Popup lifecycle records remain gated on their own selector below.
if (this.enabled.size > 0) page.on("popup", (popup) => this.popup(popup));
if (this.enabled.has("downloads"))
page.on("download", (download) => this.download(download));
if (this.enabled.size > 0) {
const onPopup = (popup: Page) => this.popup(popup);
page.on("popup", onPopup);
this.retainListener(page, () => page.off("popup", onPopup));
}
if (this.enabled.has("downloads")) {
const onDownload = (download: Download) => this.download(download);
page.on("download", onDownload);
this.retainListener(page, () => page.off("download", onDownload));
}
}
private safeUrl(value: string) {
@@ -231,13 +283,20 @@ export class PlaywrightScenarioEvents {
private webSocket(socket: WebSocket): void {
const url = this.safeUrl(socket.url());
this.push({ kind: "websocket-opened", url });
socket.on("framesent", ({ payload }) =>
this.webSocketFrame("websocket-frame-sent", url, payload),
);
socket.on("framereceived", ({ payload }) =>
this.webSocketFrame("websocket-frame-received", url, payload),
);
socket.on("close", () => this.push({ kind: "websocket-closed", url }));
const onSent = ({ payload }: { payload: string | Buffer }) =>
this.webSocketFrame("websocket-frame-sent", url, payload);
const onReceived = ({ payload }: { payload: string | Buffer }) =>
this.webSocketFrame("websocket-frame-received", url, payload);
const onClose = () => {
this.push({ kind: "websocket-closed", url });
this.releaseListeners(socket);
};
socket.on("framesent", onSent);
socket.on("framereceived", onReceived);
socket.on("close", onClose);
this.retainListener(socket, () => socket.off("framesent", onSent));
this.retainListener(socket, () => socket.off("framereceived", onReceived));
this.retainListener(socket, () => socket.off("close", onClose));
}
private webSocketFrame(
@@ -286,7 +345,12 @@ export class PlaywrightScenarioEvents {
name: null,
};
this.push({ kind: "worker-created", ...details });
worker.on("close", () => this.push({ kind: "worker-closed", ...details }));
const onClose = () => {
this.push({ kind: "worker-closed", ...details });
this.releaseListeners(worker);
};
worker.on("close", onClose);
this.retainListener(worker, () => worker.off("close", onClose));
}
private popup(page: Page): void {
@@ -305,13 +369,14 @@ export class PlaywrightScenarioEvents {
};
if (this.enabled.has("popups")) {
this.push({ kind: "popup-opened", ...opened });
page.on("close", () =>
const onClose = () =>
this.push({
kind: "popup-closed",
url: page.url() === "" ? null : this.safeUrl(page.url()),
name: null,
}),
);
});
page.on("close", onClose);
this.retainListener(page, () => page.off("close", onClose));
}
this.observePage(page);
}
+2 -2
View File
@@ -175,7 +175,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
];
phase = "workspace";
root = await this.createRuntime();
this.#resources.retain(root, undefined, operation);
this.#resources.retain(root, undefined);
const snapshotPath = join(root.path, "capture");
const configurationPath = join(root.path, "configuration");
await mkdir(configurationPath, { mode: 0o700 });
@@ -406,7 +406,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
cause instanceof OwnedCommandFailure &&
cause.cleanupOwner !== undefined
)
this.#resources.retain(root, cause.cleanupOwner, operation);
this.#resources.retain(root, cause.cleanupOwner);
result = err(
this.#failure(
cause,
+12 -2
View File
@@ -99,13 +99,20 @@ export const registerAndroidCommands = (
}),
});
cli.command(CLI_COMMANDS.traceAndroidReferences, {
description: "Trace incoming APK class or unique-method references",
description:
"Trace incoming APK using nodes for a class or selected method",
args: z.object({ path, className }),
options: z.object({
methodName: z
.string()
.optional()
.describe("Unique declared method name; omit for class references"),
.describe("Declared method name; omit for class references"),
overloadIndex: z
.number()
.int()
.nonnegative()
.optional()
.describe("Index among same-name methods from inspect-android-class"),
}),
run: ({ args, options }) =>
execute(CLI_COMMANDS.traceAndroidReferences, "trace_android_references", {
@@ -114,6 +121,9 @@ export const registerAndroidCommands = (
...(options.methodName === undefined
? {}
: { method_name: options.methodName }),
...(options.overloadIndex === undefined
? {}
: { overload_index: options.overloadIndex }),
}),
});
};
+107 -80
View File
@@ -32,89 +32,116 @@ export const registerUtilityCommands = (
registerCapabilityCommands(cli, logger, analysis);
registerNativeCommands(cli, logger, runProviderAnalysis);
registerNativeCallCommands(cli, logger, runProviderAnalysis);
for (const [command, operation] of [
[CLI_COMMANDS.observeNativeUi, "observe_native_ui"],
[CLI_COMMANDS.captureNativeUiScenario, "capture_native_ui_scenario"],
] as const) {
cli.command(command, {
description:
"Observe or run a scenario in one exact native application window",
args: z.object({
path: z.string().describe("Local native executable or app path"),
}),
options: z.object({
pid: z.number().int().positive().describe("Existing application PID"),
windowId: z
.number()
.int()
.positive()
.describe("Exact selected application window ID"),
steps: z
.string()
.optional()
.describe("JSON array of declarative AX actions or waits"),
screenshot: z
.boolean()
.default(true)
.describe("Capture only the selected window"),
accessibility: z
.boolean()
.default(true)
.describe("Read the selected window accessibility tree"),
maxNodes: z
.number()
.int()
.positive()
.safe()
.default(500)
.describe("Maximum accessibility nodes per capture"),
}),
run: ({ args, options }) =>
logCliCommand(logger, command, async () => {
const parameters = {
pid: options.pid,
window_id: options.windowId,
screenshot: options.screenshot,
accessibility: options.accessibility,
max_nodes: options.maxNodes,
};
if (operation === "capture_native_ui_scenario") {
const decoded =
options.steps === undefined
? { ok: true as const, value: undefined }
: safeParseJson(options.steps);
if (!decoded.ok)
return invalidNativeUiScenarioInput(operation, [
{ path: ["steps"], reason: "invalid_format", expected: "JSON" },
]);
const parsed = nativeUiScenarioInputSchema.safeParse({
...parameters,
steps: decoded.value,
});
if (!parsed.success)
return invalidNativeUiScenarioInput(
operation,
projectInputIssues(parsed.error.issues, {
...parameters,
...(options.steps === undefined
? {}
: { steps: decoded.value }),
}),
);
return runProviderAnalysis(
args.path,
operation,
parsed.data,
logger,
);
}
return runProviderAnalysis(args.path, operation, parameters, logger);
}),
});
}
registerNativeUiCommands(cli, logger, runProviderAnalysis);
registerReferenceSourceCommand(cli, logger, environment);
};
const nativeUiScopeOptions = {
pid: z.number().int().positive().describe("Existing application PID"),
windowId: z
.number()
.int()
.positive()
.describe("Exact selected application window ID"),
screenshot: z
.boolean()
.default(true)
.describe("Capture only the selected window"),
accessibility: z
.boolean()
.default(true)
.describe("Read the selected window accessibility tree"),
maxNodes: z
.number()
.int()
.positive()
.safe()
.default(500)
.describe("Maximum accessibility nodes per capture"),
};
const nativeUiScope = (options: {
readonly pid: number;
readonly windowId: number;
readonly screenshot: boolean;
readonly accessibility: boolean;
readonly maxNodes: number;
}) => ({
pid: options.pid,
window_id: options.windowId,
screenshot: options.screenshot,
accessibility: options.accessibility,
max_nodes: options.maxNodes,
});
/**
* Passive observation and active scenarios have different input contracts.
* Only the scenario command accepts steps, so passive observation rejects
* them as an unknown flag instead of silently dropping them.
*/
const registerNativeUiCommands = (
cli: CliInstance,
logger: Logger,
runProviderAnalysis: DirectAnalysis["runProviderAnalysis"],
): void => {
const pathArgument = z.object({
path: z.string().describe("Local native executable or app path"),
});
cli.command(CLI_COMMANDS.observeNativeUi, {
description:
"Observe one already-running native application window by PID and window ID",
args: pathArgument,
options: z.object(nativeUiScopeOptions),
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.observeNativeUi, () =>
runProviderAnalysis(
args.path,
"observe_native_ui",
nativeUiScope(options),
logger,
),
),
});
const operation = "capture_native_ui_scenario";
cli.command(CLI_COMMANDS.captureNativeUiScenario, {
description:
"Run declarative AX actions or waits in one exact native application window",
args: pathArgument,
options: z.object({
...nativeUiScopeOptions,
steps: z
.string()
.optional()
.describe("JSON array of declarative AX actions or waits"),
}),
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.captureNativeUiScenario, async () => {
const parameters = nativeUiScope(options);
const decoded =
options.steps === undefined
? { ok: true as const, value: undefined }
: safeParseJson(options.steps);
if (!decoded.ok)
return invalidNativeUiScenarioInput(operation, [
{ path: ["steps"], reason: "invalid_format", expected: "JSON" },
]);
const parsed = nativeUiScenarioInputSchema.safeParse({
...parameters,
steps: decoded.value,
});
if (!parsed.success)
return invalidNativeUiScenarioInput(
operation,
projectInputIssues(parsed.error.issues, {
...parameters,
...(options.steps === undefined ? {} : { steps: decoded.value }),
}),
);
return runProviderAnalysis(args.path, operation, parsed.data, logger);
}),
});
};
const invalidNativeUiScenarioInput = (
operation: string,
issues: ConstructorParameters<typeof AnalysisInputError>[2],
@@ -51,7 +51,7 @@ export const ANDROID_TOOL_CONTRACTS = [
name: "inspect_android_class",
...toolContractMetadata("inspect_android_class"),
description:
"Inspect one exact Android class's parsed methods, fields and inner classes, including synthetic members. Returns display signatures and explicit unknown DEX descriptors without generating source. Overload indices remain consistent within the artifact and engine session.",
"Inspect one exact Android class's parsed methods, fields and inner classes, including synthetic members. Returns display signatures and exact DEX prototypes without generating source. A prototype is not a complete raw method ID; overload indices remain consistent within the artifact and engine session.",
kind: "android-provider",
inputSchema: androidInputSchemas.inspect_android_class,
outputSchema: evidenceResultOf(androidResultSchemas.inspect_android_class),
@@ -66,7 +66,7 @@ export const ANDROID_TOOL_CONTRACTS = [
name: "inspect_android_method",
...toolContractMetadata("inspect_android_method"),
description:
"Decompile one Android method with smali fallback. Requires explicit overload_index when multiple methods share a name. Reports representation, fallback markers and source truncation; never treats display signatures as exact DEX identities.",
"Decompile one Android method with smali fallback. Requires explicit overload_index when multiple methods share a name. Reports its DEX prototype, representation, fallback markers and source truncation; display signatures may be aliases.",
kind: "android-provider",
inputSchema: androidInputSchemas.inspect_android_method,
outputSchema: evidenceResultOf(androidResultSchemas.inspect_android_method),
@@ -85,7 +85,7 @@ export const ANDROID_TOOL_CONTRACTS = [
name: "trace_android_references",
...toolContractMetadata("trace_android_references"),
description:
"Trace incoming static references to an exact Android class or unique method. Overloaded method reference queries are explicitly unsupported by the current engine. Source lines and DEX offsets remain unknown; no runtime calls are inferred.",
"Trace incoming static using nodes to an exact Android class or selected method overload. The total counts containing nodes, not individual invoke instructions. Use inspect_android_class to choose an overload_index when names collide. Source lines and the containing node dex_offset remain unknown. direct_invokes carries exact DEX code-unit instruction offsets when available; direct_invokes_exhaustive false marks byte-bounded partial instruction evidence, and null means coverage is unknown. Using-node coverage remains separate; no runtime calls are inferred.",
kind: "android-provider",
inputSchema: androidInputSchemas.trace_android_references,
outputSchema: evidenceResultOf(
+11 -1
View File
@@ -16,7 +16,7 @@ const dossier = (text: string) =>
locals: [],
},
pseudocode: text,
assembly: [],
assembly: ["ret"],
comments: [],
callers: [],
callees: [],
@@ -27,6 +27,16 @@ const dossier = (text: string) =>
basic_blocks: [{ start: "0x1000", end: "0x1001", successors: [] }],
native_api: null,
native_value_flow: null,
facet_availability: {
pseudocode: { available: true },
assembly: { available: true },
comments: { available: true },
callers: { available: true },
callees: { available: true },
references: { available: true },
strings_names: { available: true },
cfg: { available: true },
},
limitations: ["The fixture omits native API and value-flow observations."],
});
@@ -792,3 +792,29 @@ it("rejects unsupported parent operations and incompatible collections", () => {
error: { _tag: "AnalysisInputError" },
});
});
it("preserves selected native facet unavailability instead of an exhausted empty page", () => {
const parent = nativeParent({
...functionDossierSchema.parse(ghidraFunctionDossier()),
facet_availability: {
comments: { available: false, reason: "Typed comments unavailable" },
references: { available: false, reason: "Typed references unavailable" },
},
});
for (const [facet, reason] of [
["comments", "Typed comments unavailable"],
["incoming_references", "Typed references unavailable"],
] as const) {
const result = projectAnalysisView(parent, {
kind: "native",
facet,
offset: 0,
limit: 8,
});
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
item: { available: false, reason },
unknowns: expect.arrayContaining([reason]),
});
}
});
@@ -110,6 +110,22 @@ export const projectNativeFunctionView = (
]),
);
const common = parentFields(parent, dossier, artifact);
const availabilityKeys: Readonly<Record<string, string>> = {
incoming_references: "references",
outgoing_references: "references",
referenced_strings: "strings_names",
referenced_names: "strings_names",
basic_blocks: "cfg",
};
const availabilityKey = availabilityKeys[view.facet] ?? view.facet;
const availability =
dossier.facet_availability?.[
availabilityKey as keyof NonNullable<
FunctionDossier["facet_availability"]
>
];
if (availability?.available === false)
common.unknowns = uniqueSorted([...common.unknowns, availability.reason]);
const singleton = (item: unknown): UnsignedAnalysisView => ({
kind: "native",
view,
@@ -117,6 +133,7 @@ export const projectNativeFunctionView = (
coverage: completeWithinViewCoverage(1, 1),
...common,
});
if (availability?.available === false) return ok(singleton(availability));
const flow = dossier.native_value_flow;
if (
view.facet === "procedure" ||
+35 -2
View File
@@ -40,7 +40,15 @@ export const androidInputSchemas = {
.min(1)
.optional()
.describe(
"Omit for class references; ambiguous overloaded methods are unsupported",
"Omit for class references; select ambiguous methods with overload_index",
),
overload_index: z
.number()
.int()
.nonnegative()
.optional()
.describe(
"Index among same-name methods from inspect_android_class; requires method_name",
),
}),
} as const;
@@ -90,12 +98,19 @@ const textCoverage = z.strictObject({
text: z.string(),
reported_total_bytes: z.number().int().nonnegative().nullable(),
});
/** A DEX prototype: parameter descriptors followed by the return descriptor. */
export const dexDescriptorSchema = z
.string()
.regex(
/^\((?:\[*(?:[ZBSCIJFD]|L[^;()]+;))*\)(?:V|\[*(?:[ZBSCIJFD]|L[^;()]+;))$/u,
);
const method = z.strictObject({
name: z.string(),
reported_signature: z.string(),
overload_index: z.number().int().nonnegative(),
is_constructor: z.boolean(),
dex_descriptor: z.null(),
dex_descriptor: dexDescriptorSchema,
});
const engine = z.strictObject({
name: z.string().min(1),
@@ -159,6 +174,9 @@ export const androidResultSchemas = {
...common,
class_name: z.string(),
method_name: z.string().nullable(),
overload_index: z.number().int().nonnegative().nullable(),
reported_signature: z.string().nullable(),
dex_descriptor: dexDescriptorSchema.nullable(),
total: z.number().int().nonnegative(),
references: z.array(
z.strictObject({
@@ -169,8 +187,23 @@ export const androidResultSchemas = {
top_class: z.string(),
source_line: z.null(),
dex_offset: z.null(),
/** false means transport-bounded instruction evidence; null/omitted is unknown. */
direct_invokes_exhaustive: z.boolean().nullable().default(null),
/** Raw direct invoke instructions inside this using node, when available. */
direct_invokes: z
.array(
z.strictObject({
dex_entry: z.string().min(1),
source_raw_method_id: z.string().min(1),
dex_code_unit_offset: z.number().int().nonnegative(),
dex_method_index: z.number().int().nonnegative(),
opcode: z.string().regex(/^INVOKE_/u),
}),
)
.nullable(),
}),
),
coverage: z.literal("complete"),
reference_unit: z.literal("using_node"),
}),
} as const;
+18
View File
@@ -15,6 +15,7 @@ const observe = (
readonly evidenceLimitations?: readonly string[];
readonly dossierLimitations?: readonly string[];
readonly relationshipCoverage?: RelationshipCoverage;
readonly calleeUnavailable?: string;
} = {},
): Evidence => {
const value = {
@@ -52,6 +53,13 @@ const observe = (
native_value_flow: null,
basic_blocks: [],
limitations: [...(options.dossierLimitations ?? [])],
...(options.calleeUnavailable === undefined
? {}
: {
facet_availability: {
callees: { available: false, reason: options.calleeUnavailable },
},
}),
} satisfies JsonValue;
return createEvidence(
{ path: "/tmp/a", sha256: "a".repeat(64), format: "mach-o" },
@@ -541,3 +549,13 @@ describe("call path evidence admission", () => {
);
});
});
it("keeps an absent path unknown when only callee facet availability is declared", () => {
const result = run([
observe("0x1000", [], "rea-workflow", {
calleeUnavailable: "Graph callees unavailable",
}),
]);
expect(result.status).toBe("unknown");
expect(result.limitations).toContain("Graph callees unavailable");
});
+5
View File
@@ -253,6 +253,11 @@ const inspectSearch = ({
// cannot add a path to the goal, so its dossier limits are contextual
// but do not make the searched start-to-goal closure incomplete.
if (node === goal) continue;
const callees = snapshot.dossier.facet_availability?.callees;
if (callees?.available === false) {
limitations.push(callees.reason);
incompleteExpandedCoverage = true;
}
// Explicit, Evidence-bound relationship coverage owns completeness;
// generic provider/dossier limitations remain contextual. Legacy Evidence
// without that metadata retains its conservative limitation-based rule.
+8
View File
@@ -2,6 +2,14 @@ import { expect, it } from "vitest";
import { evmInterfaceSchema } from "./evmInterface.js";
import { evmInterfaceFixture } from "../../../tests/fixtures/evm/interface.js";
it("accepts historical metadata omission as an unknown facet without changing the source", () => {
const value = evmInterfaceFixture();
const { metadata: _metadata, ...oldBytecode } = value.bytecode;
const old = { ...value, bytecode: oldBytecode };
expect(evmInterfaceSchema.parse(old).bytecode.metadata).toBeNull();
expect(old.bytecode).not.toHaveProperty("metadata");
});
it.each(["byte-count", "body-offset", "selector", "authenticity"])(
"rejects false interface evidence: %s",
(problem) => {
+19
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { localPathStringSchema } from "../localPath.js";
import { solidityMetadataSchema } from "./solidityMetadata.js";
const byteOffset = z.number().int().nonnegative();
const sha256 = z.string().regex(/^[a-f0-9]{64}$/);
@@ -34,6 +35,7 @@ export const evmInterfaceSchema = z
kind: z.literal("unknown"),
deployment_authenticity: z.literal("unknown"),
hardfork: z.literal("unknown"),
metadata: solidityMetadataSchema.nullable().default(null),
}),
evidence_kind: z.literal("inferred"),
functions: z.array(
@@ -62,6 +64,23 @@ export const evmInterfaceSchema = z
message:
"Selected byte count does not match the bytecode hex representation.",
});
const metadata = value.bytecode.metadata;
if (
metadata !== null &&
metadata.status !== "unavailable" &&
(metadata.bytecode_offset === null ||
metadata.cbor_bytes === null ||
metadata.bytecode_offset + metadata.cbor_bytes + 2 !==
value.bytecode.bytes ||
metadata.cbor_bytes !==
Number.parseInt(value.bytecode.hex.slice(-4), 16))
)
context.addIssue({
code: "custom",
path: ["bytecode", "metadata"],
message:
"Metadata range must match the terminal length suffix in selected bytecode.",
});
for (const [index, fn] of value.functions.entries())
if (fn.bytecode_offset >= value.bytecode.bytes)
context.addIssue({
+89
View File
@@ -0,0 +1,89 @@
import { z } from "zod";
/** Scalar view of CBOR; uninterpreted containers remain in original bytecode. */
export const solidityMetadataScalarSchema = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("text"), value: z.string().max(65535) }),
z.strictObject({
kind: z.literal("integer"),
value: z
.string()
.max(21)
.regex(/^-?(?:0|[1-9][0-9]*)$/),
}),
z.strictObject({
kind: z.literal("bytes"),
value: z
.string()
.max(131070)
.regex(/^(?:[a-f0-9]{2})*$/),
}),
z.strictObject({ kind: z.literal("boolean"), value: z.boolean() }),
z.strictObject({ kind: z.literal("null") }),
z.strictObject({
kind: z.literal("uninterpreted"),
container: z.enum(["array", "map"]),
}),
]);
/** A trailer candidate, not authentication of Solidity origin or deployment. */
export const solidityMetadataSchema = z
.strictObject({
profile: z.literal("terminal-cbor-scalars-v1"),
status: z.enum(["unavailable", "decoded", "partial", "not-decoded"]),
bytecode_offset: z.number().int().nonnegative().nullable(),
cbor_bytes: z.number().int().positive().max(65535).nullable(),
entries: z
.array(
z.strictObject({
key: solidityMetadataScalarSchema,
value: solidityMetadataScalarSchema,
}),
)
.max(32767),
compiler_version: z
.strictObject({
representation: z.enum(["release-bytes", "prerelease-text"]),
value: z.string().min(1).max(65535),
})
.nullable(),
diagnostic: z.string().max(512).nullable(),
})
.superRefine((value, context) => {
const unavailable = value.status === "unavailable";
if (
unavailable
? value.bytecode_offset !== null || value.cbor_bytes !== null
: value.bytecode_offset === null || value.cbor_bytes === null
)
context.addIssue({
code: "custom",
message: "Only unavailable metadata omits the candidate range.",
});
const unexamined = unavailable || value.status === "not-decoded";
if (
unexamined &&
(value.entries.length !== 0 || value.compiler_version !== null)
)
context.addIssue({
code: "custom",
message:
"Unavailable interpretation cannot report decoded entries or compiler identity.",
});
const uninterpreted = value.entries.some(
({ key, value: entryValue }) =>
key.kind === "uninterpreted" || entryValue.kind === "uninterpreted",
);
if (
(value.status === "decoded" && uninterpreted) ||
(value.status === "partial" && !uninterpreted)
)
context.addIssue({
code: "custom",
message: "Scalar coverage must preserve uninterpreted containers.",
});
});
export type SolidityMetadata = z.infer<typeof solidityMetadataSchema>;
export type SolidityMetadataScalar = z.infer<
typeof solidityMetadataScalarSchema
>;
+165 -25
View File
@@ -44,6 +44,16 @@ const dossier = (
referenced_names: [],
native_api: null,
native_value_flow: null,
facet_availability: {
pseudocode: { available: true },
assembly: { available: true },
comments: { available: true },
callers: { available: true },
callees: { available: true },
references: { available: true },
strings_names: { available: true },
cfg: { available: true },
},
basic_blocks: [
{
start: base,
@@ -118,34 +128,116 @@ const observe = (
},
);
describe("function comparison normalized identity", () => {
it("keeps differing generated names ambiguous and stable names mismatched", () => {
const named = (base: "0x1000" | "0x2000", name: string) =>
functionDossierSchema.parse({
...dossier("return 0;", base),
procedure: {
...procedure(base, name),
signature: "int helper(void)",
locals: [],
},
});
const generated = compareFunctions(
observe("1", named("0x1000", "sub_1000")),
observe("2", named("0x2000", "sub_2000")),
);
expect(generated.function_match.status).toBe("ambiguous");
expect(generated.status).toBe("unknown");
expect(
generated.dimensions.find(({ dimension }) => dimension === "identity"),
).toMatchObject({ status: "unknown" });
const rejectsMalformedFacetAvailability = (): void => {
expect(
functionDossierSchema.safeParse({
...dossier("return 0;", "0x1000"),
facet_availability: { cfg: { available: false, reason: "" } },
}).success,
).toBe(false);
expect(
functionDossierSchema.safeParse({
...dossier("return 0;", "0x1000"),
facet_availability: { cfg: undefined },
}).success,
).toBe(false);
};
const stable = compareFunctions(
observe("3", named("0x1000", "firstFunction")),
observe("4", named("0x2000", "secondFunction")),
const keepsGeneratedNamesAmbiguous = (): void => {
const named = (base: "0x1000" | "0x2000", name: string) =>
functionDossierSchema.parse({
...dossier("return 0;", base),
procedure: {
...procedure(base, name),
signature: "int helper(void)",
locals: [],
},
});
const generated = compareFunctions(
observe("1", named("0x1000", "sub_1000")),
observe("2", named("0x2000", "sub_2000")),
);
expect(generated.function_match.status).toBe("ambiguous");
expect(generated.status).toBe("unknown");
expect(
generated.dimensions.find(({ dimension }) => dimension === "identity"),
).toMatchObject({ status: "unknown" });
const stable = compareFunctions(
observe("3", named("0x1000", "firstFunction")),
observe("4", named("0x2000", "secondFunction")),
);
expect(stable.function_match.status).toBe("mismatched");
expect(stable.status).toBe("changed");
};
describe("function comparison normalized identity", () => {
it("retains unresolved call details alongside missing facet coverage", () => {
const value: Record<string, unknown> = {
...dossier("return 0;", "0x1000"),
unresolved_calls: [{ address: "0x1010", reason: "Unknown indirect target" }],
};
delete value.facet_availability;
const legacy = observe("a", functionDossierSchema.parse(value), "ida");
const calls = compareFunctions(legacy, legacy).dimensions.find(
({ dimension }) => dimension === "calls",
);
expect(stable.function_match.status).toBe("mismatched");
expect(stable.status).toBe("changed");
expect(calls).toMatchObject({
status: "unknown",
limitations: expect.arrayContaining([
"Left: Unresolved call at 0x1010: Unknown indirect target",
"Left: callers: Provider did not declare coverage for this empty facet.",
]),
});
});
it("keeps empty legacy facets without coverage declarations unknown", () => {
const value: Record<string, unknown> = {
...dossier("return 0;", "0x1000"),
basic_blocks: [],
};
delete value.facet_availability;
const legacy = observe("a", functionDossierSchema.parse(value), "ida");
const result = compareFunctions(legacy, legacy);
for (const dimension of [
"comments",
"references",
"strings_names",
"cfg",
"calls",
]) {
expect(
result.dimensions.find((item) => item.dimension === dimension),
).toMatchObject({ status: "unknown" });
}
});
it("keeps unavailable facets unknown even when one side supplies values", () => {
const left = observe(
"a",
functionDossierSchema.parse({
...dossier("return 0;", "0x1000"),
facet_availability: {
comments: { available: false, reason: "Not collected" },
},
comments: [
{ address: "0x1000", kind: "comment", text: "partial record" },
],
}),
);
const right = observe("b", dossier("return 0;", "0x2000"));
expect(
compareFunctions(left, right).dimensions.find(
({ dimension }) => dimension === "comments",
),
).toMatchObject({ status: "unknown", left_count: null, right_count: null });
});
it(
"rejects malformed facet availability instead of treating it as absence",
rejectsMalformedFacetAvailability,
);
it(
"keeps differing generated names ambiguous and stable names mismatched",
keepsGeneratedNamesAmbiguous,
);
it.each(["sub_deallocate", "sub_deadbeef_handler", "fcn.dispatch"])(
"recognizes the explicit symbol %s without a generated-name prefix false positive",
@@ -999,3 +1091,51 @@ const expectFunctionDimensionAlgebra = (
}).success,
).toBe(false);
};
it.each([
{ match: "mismatched", changedDimensions: false, expected: "changed" },
{ match: "ambiguous", changedDimensions: false, expected: "unknown" },
{ match: "ambiguous", changedDimensions: true, expected: "unknown" },
] as const)(
"validates $match match precedence with changed dimensions=$changedDimensions",
({ match, changedDimensions, expected }) => {
const result = compareFunctions(
FUNCTION_COMPARISON_EXAMPLE.left,
changedDimensions
? FUNCTION_COMPARISON_EXAMPLE.right
: FUNCTION_COMPARISON_EXAMPLE.left,
);
const candidate = {
...result,
function_match: {
status: match,
method: "explicit",
left_name: "main",
right_name: "other",
},
};
expect(
functionComparisonResultSchema.safeParse({
...candidate,
status: expected,
}).success,
).toBe(true);
for (const status of ["unchanged", "changed", "unknown"] as const) {
if (status === expected) continue;
const parsed = functionComparisonResultSchema.safeParse({
...candidate,
status,
});
expect(parsed.success).toBe(false);
if (!parsed.success)
expect(parsed.error.issues).toMatchObject([
{
path: ["status"],
code: "custom",
message:
"Function comparison status contradicts its dimensions or function match.",
},
]);
}
},
);
+61 -1
View File
@@ -52,7 +52,67 @@ export const compareDimensions = (
compareReferences(left, right, context),
compareStringsAndNames(left, right, context),
compareCfg(left, right, context),
];
].map((result) => {
const limitations = [
...facetLimitations(left, result.dimension).map(
(reason) => `Left: ${reason}`,
),
...facetLimitations(right, result.dimension).map(
(reason) => `Right: ${reason}`,
),
];
return limitations.length === 0
? result
: unresolvedDimension({
dimension: result.dimension,
links: context.links,
leftCount: null,
rightCount: null,
limitations: [...result.limitations, ...limitations],
});
});
};
/** An empty undeclared facet is not evidence of observed absence. */
const facetLimitations = (
snapshot: FunctionSnapshot,
dimension: DimensionName,
): string[] => {
const { dossier } = snapshot;
const fields = {
identity: [],
pseudocode: [["pseudocode", dossier.pseudocode.length]],
assembly: [["assembly", dossier.assembly.length]],
comments: [["comments", dossier.comments.length]],
calls: [
["callers", dossier.callers.length],
["callees", dossier.callees.length],
],
references: [
[
"references",
dossier.incoming_references.length + dossier.outgoing_references.length,
],
],
strings_names: [
[
"strings_names",
dossier.referenced_strings.length + dossier.referenced_names.length,
],
],
cfg: [["cfg", dossier.basic_blocks.length]],
} satisfies Record<
DimensionName,
[keyof NonNullable<typeof dossier.facet_availability>, number][]
>;
return fields[dimension].flatMap(([field, count]) => {
const availability = dossier.facet_availability?.[field];
if (availability?.available === false)
return [`${field}: ${availability.reason}`];
return availability === undefined && count === 0
? [`${field}: Provider did not declare coverage for this empty facet.`]
: [];
});
};
const compareText = (
+28 -14
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { overallStatus } from "./functionComparisonResults.js";
import { evidenceSchema } from "./evidence.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
@@ -79,20 +80,33 @@ const functionMatchSchema = z.union([
]);
/** Deterministic dimension-classified function comparison Evidence payload. */
export const functionComparisonResultSchema = z.object({
status: comparisonStatusSchema,
function_match: functionMatchSchema,
left_subject_sha256: digestSchema,
right_subject_sha256: digestSchema,
summary: z.object({
unchanged: z.number().int().min(0),
changed: z.number().int().min(0),
unknown: z.number().int().min(0),
}),
dimensions: z.array(functionDimensionSchema).length(8),
changes: z.array(functionDimensionSchema),
limitations: z.array(z.string()),
});
export const functionComparisonResultSchema = z
.object({
status: comparisonStatusSchema,
function_match: functionMatchSchema,
left_subject_sha256: digestSchema,
right_subject_sha256: digestSchema,
summary: z.object({
unchanged: z.number().int().min(0),
changed: z.number().int().min(0),
unknown: z.number().int().min(0),
}),
dimensions: z.array(functionDimensionSchema).length(8),
changes: z.array(functionDimensionSchema),
limitations: z.array(z.string()),
})
.superRefine((result, context) => {
if (
result.status !==
overallStatus(result.dimensions, result.function_match.status)
)
context.addIssue({
code: "custom",
path: ["status"],
message:
"Function comparison status contradicts its dimensions or function match.",
});
});
export type FunctionComparisonResult = z.infer<
typeof functionComparisonResultSchema
+18
View File
@@ -371,6 +371,11 @@ export const referenceEdgeSchema = z
.exactOptional(),
})
.strict();
const facetAvailabilitySchema = z.discriminatedUnion("available", [
z.object({ available: z.literal(true) }).strict(),
z.object({ available: z.literal(false), reason: z.string().min(1) }).strict(),
]);
export const functionDossierSchema = z
.object({
procedure: procedureIdentitySchema.safeExtend({
@@ -428,6 +433,19 @@ export const functionDossierSchema = z
),
native_api: nativeApiBoundarySchema.nullable(),
native_value_flow: nativeValueFlowSchema.nullable(),
facet_availability: z
.object({
pseudocode: facetAvailabilitySchema.exactOptional(),
assembly: facetAvailabilitySchema.exactOptional(),
comments: facetAvailabilitySchema.exactOptional(),
callers: facetAvailabilitySchema.exactOptional(),
callees: facetAvailabilitySchema.exactOptional(),
references: facetAvailabilitySchema.exactOptional(),
strings_names: facetAvailabilitySchema.exactOptional(),
cfg: facetAvailabilitySchema.exactOptional(),
})
.strict()
.exactOptional(),
limitations: z.array(z.string()),
})
.strict();
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vitest";
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
describe("child-process options detection", () => {
it("detects options without an args array", () => {
const ir = analyzeJavaScriptSemantics(`
import { spawn, execFile, fork } from "node:child_process";
spawn("tool", {
env: { A: "1" },
stdio: "pipe"
});
execFile("tool", {
env: { A: "1" }
});
fork("worker.js", {
env: { A: "1" },
stdio: ["pipe", "pipe", "pipe", "ipc"]
});
`);
expect(
ir.childProcessSpawns.map(
({ method, environmentSupplied, stdioMode, resolution }) => ({
method,
environmentSupplied,
stdioMode,
resolution,
}),
),
).toEqual([
{
method: "spawn",
environmentSupplied: true,
stdioMode: "pipe",
resolution: "complete",
},
{
method: "execFile",
environmentSupplied: true,
stdioMode: "default",
resolution: "complete",
},
{
method: "fork",
environmentSupplied: true,
stdioMode: "array",
resolution: "complete",
},
]);
});
it("preserves behavior with explicit args arrays", () => {
const ir = analyzeJavaScriptSemantics(`
import { spawn, execFile, fork } from "node:child_process";
spawn("tool", [], { env: { A: "1" }, stdio: "pipe" });
execFile("tool", [], { env: { A: "1" } });
fork("worker.js", [], {
env: { A: "1" },
stdio: ["pipe", "pipe", "pipe", "ipc"]
});
`);
expect(
ir.childProcessSpawns.map(({ environmentSupplied, stdioMode }) => ({
environmentSupplied,
stdioMode,
})),
).toEqual([
{ environmentSupplied: true, stdioMode: "pipe" },
{ environmentSupplied: true, stdioMode: "default" },
{ environmentSupplied: true, stdioMode: "array" },
]);
});
it("does not invent options when omitted", () => {
const ir = analyzeJavaScriptSemantics(`
import { spawn, execFile, fork } from "node:child_process";
spawn("tool");
execFile("tool");
fork("worker.js");
`);
expect(
ir.childProcessSpawns.every(
({ environmentSupplied, stdioMode }) =>
environmentSupplied === false && stdioMode === "default",
),
).toBe(true);
expect(ir.childProcessSpawns).toHaveLength(3);
});
});
@@ -219,6 +219,8 @@ export interface ElectronCallPathStep {
export interface ElectronCallPath {
readonly entry_kind: "bridge-member" | "ipc-handler";
readonly entry: string;
/** Exact bridge API and property segments; `entry` remains display text. */
readonly entry_path?: readonly string[];
readonly channel: string | null;
readonly terminal: string;
readonly resolution: "candidate";
@@ -153,6 +153,13 @@ const collectMembersAt = (
state.unknown += 1;
continue;
}
if (
t.isObjectProperty(property) &&
!property.computed &&
!property.shorthand &&
name === "__proto__"
)
continue;
const segments = [...prefix, name];
const path = segments.join(".");
state.members.push(path);
@@ -357,6 +357,83 @@ it("preserves guarded alternatives in direct exposed object literals", () => {
]),
);
});
it("preserves bridge member segments and excludes prototype setters", () => {
const result = analyzeJavaScriptStaticSource(`
const e=require("electron");
const write=()=>e.ipcRenderer.send("write");
e.contextBridge.exposeInMainWorld("desktop", {
"nested.write": write,
nested: { write },
__proto__: { inherited: write },
["__proto__"]: { own: write },
});
`);
expect(result.electron.call_paths).toEqual(
expect.arrayContaining([
expect.objectContaining({
entry: "desktop.nested.write",
entry_path: ["desktop", "nested.write"],
}),
expect.objectContaining({
entry: "desktop.nested.write",
entry_path: ["desktop", "nested", "write"],
}),
expect.objectContaining({
entry: "desktop.__proto__.own",
entry_path: ["desktop", "__proto__", "own"],
}),
]),
);
expect(result.electron.call_paths).not.toEqual(
expect.arrayContaining([
expect.objectContaining({
entry_path: ["desktop", "__proto__", "inherited"],
}),
]),
);
});
it("follows an explicit object-literal prototype lookup in a bridge wrapper", () => {
const result = analyzeJavaScriptStaticSource(`
const e=require("electron");
const prototype={send:()=>e.ipcRenderer.send("through-prototype")};
const object={__proto__:prototype};
e.contextBridge.exposeInMainWorld("desktop", {
action:()=>object.__proto__.send(),
});
`);
expect(result.electron.call_paths).toEqual(
expect.arrayContaining([
expect.objectContaining({
entry_path: ["desktop", "action"],
channel: "through-prototype",
}),
]),
);
});
it("does not spread a large nested bridge member list into function arguments", () => {
const members = Array.from(
{ length: 125_000 },
(_, index) => `m${index}(){}`,
).join(",");
const source = `const e=require("electron");e.contextBridge.exposeInMainWorld("desktop",{nested:{${members}}});`;
expect(() => analyzeJavaScriptStaticSource(source)).not.toThrow();
});
it("reports nested bridge depth truncation while retaining shallow paths", () => {
const nested =
Array.from({ length: 130 }, (_, index) => `level${index}:{`).join("") +
`deep:()=>e.ipcRenderer.send("deep")` +
"}".repeat(130);
const result = analyzeJavaScriptStaticSource(`
const e=require("electron");
e.contextBridge.exposeInMainWorld("desktop", {
shallow:()=>e.ipcRenderer.send("shallow"), ${nested}
});
`);
expect(result.electron.call_paths).toContainEqual(
expect.objectContaining({ entry: "desktop.shallow", channel: "shallow" }),
);
expect(result.limitations.join(" ")).toContain("depth 128");
});
it("preserves conditions when a wrapper dispatches through conditional external methods", () => {
const result = analyzeJavaScriptStaticSource(`
const e=require("electron");
@@ -44,6 +44,7 @@ const callLabel = (node: t.Node): string =>
interface PathContext {
readonly entryNode: t.Node;
readonly entry: string;
readonly entryPath?: readonly string[];
readonly entryKind: ElectronCallPath["entry_kind"] | null;
readonly channel: string | null;
readonly steps: readonly ElectronCallPathStep[];
@@ -122,6 +123,37 @@ export const collectElectronWrappedCallPaths = (
};
const hasConditions = (value: SymbolicValue): boolean =>
symbolicVariants(value).some((variant) => variant.conditions?.length);
function* bridgeMemberFunctions(
value: SymbolicValue,
segments: readonly string[] = [],
active = new Set<SymbolicValue>(),
): Generator<{
readonly name: string;
readonly path: readonly string[];
readonly fn: SymbolicFunction;
}> {
if (active.has(value)) return;
if (active.size >= 128) {
accumulator.unknownFindings += 1;
accumulator.electronCallPathLimitReached = true;
return;
}
const nested = new Set(active);
nested.add(value);
for (const member of [...resolver.members(value)].sort()) {
if (--remainingVisits < 0) return;
const path = [...segments, member];
const name = path.join(".");
for (const variant of symbolicVariants(
resolver.property(value, member),
)) {
if (variant.kind === "function") yield { name, path, fn: variant };
else if (resolver.members(variant).length > 0)
yield* bridgeMemberFunctions(variant, path, nested);
}
if (remainingVisits < 0) return;
}
}
const isolatedBridgeCall = (
node: t.CallExpression | t.OptionalCallExpression,
):
@@ -167,6 +199,10 @@ export const collectElectronWrappedCallPaths = (
const path: ElectronCallPath = {
entry_kind: context.entryKind,
entry: context.entry,
...(context.entryKind !== "bridge-member" ||
context.entryPath === undefined
? {}
: { entry_path: context.entryPath }),
channel,
terminal,
resolution: "candidate",
@@ -405,27 +441,25 @@ export const collectElectronWrappedCallPaths = (
offset: node.start ?? -1,
value: finding,
});
for (const name of members) {
const value = resolver.property(object, name);
for (const fn of symbolicVariants(value))
if (fn.kind === "function") {
const memberContext = metadataContext(keyContext, fn);
if (!memberContext) continue;
functionBody(
fn,
fn.node.params.map(() => symbolicUnknown("public API argument")),
{
...memberContext,
entryNode: node,
entryKind: "bridge-member",
entry: `${key.value}.${name}`,
channel: null,
steps: [step(node, "exposure", `${key.value}.${name}`)],
active: new Set(),
},
node,
);
}
for (const { name, path, fn } of bridgeMemberFunctions(object)) {
const memberContext = metadataContext(keyContext, fn);
if (!memberContext) continue;
const entry = `${key.value}.${name}`;
functionBody(
fn,
fn.node.params.map(() => symbolicUnknown("public API argument")),
{
...memberContext,
entryNode: node,
entryKind: "bridge-member",
entry,
entryPath: [key.value, ...path],
channel: null,
steps: [step(node, "exposure", entry)],
active: new Set(),
},
node,
);
}
};
const call = (
@@ -11,7 +11,10 @@ import {
} from "./javascriptApplicationGraph.fixture.js";
import { findApplicationFeatureSeeds } from "./javascriptFeatureSeed.js";
import { traceApplicationFeature } from "./javascriptFeatureTrace.js";
import type { ApplicationFeatureSeed } from "./javascriptFeatureTraceSchemas.js";
import {
applicationFeatureSeedSchema,
type ApplicationFeatureSeed,
} from "./javascriptFeatureTraceSchemas.js";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
import type { JsonValue } from "../jsonValue.js";
@@ -268,6 +271,32 @@ describe("feature seed selection controls", () => {
});
describe("public feature trace from contextBridge source members", () => {
it.each(["openProject", "missingProject"])(
"normalizes optional seed defaults before deriving trace identity for %s",
(value) => {
const input = {
sourceEvidenceId,
graph: contextBridgeGraph(),
nativeEvidence: [],
direction: "both" as const,
};
const omitted = traceApplicationFeature({
...input,
seed: { kind: "api", value },
});
const explicit = traceApplicationFeature({
...input,
seed: {
kind: "api",
value,
match: null,
case_sensitive: false,
},
});
expect(omitted).toEqual(explicit);
},
);
it("traces one exact member seed through the public feature workflow", () => {
const mode = {
value: "openProject",
@@ -381,12 +410,13 @@ const sourceEvidenceId = `ev_${"b".repeat(64)}`;
const seed = (
kind: ApplicationFeatureSeed["kind"],
value = "openProject",
): ApplicationFeatureSeed => ({
kind,
value,
match: "exact",
case_sensitive: true,
});
): ApplicationFeatureSeed =>
applicationFeatureSeedSchema.parse({
kind,
value,
match: "exact",
case_sensitive: true,
});
const memberNode = (
kind: ApplicationNode["kind"],
+20 -2
View File
@@ -52,10 +52,28 @@ const seedMatch = (
]
: [];
if (!kindMatches(node, seed.kind)) return [];
const requestedEntryPath =
seed.kind === "api" && "entry_path" in seed ? seed.entry_path : undefined;
if (
seed.kind === "api" &&
requestedEntryPath !== undefined &&
!node.observations.some(({ properties }) => {
const entryPath = properties.entry_path;
return (
Array.isArray(entryPath) &&
entryPath.length === requestedEntryPath.length &&
entryPath.every(
(segment, index) => segment === requestedEntryPath[index],
)
);
})
)
return [];
const mode = featureSeedMatchMode(seed);
const query = normalized(seed.value, seed.case_sensitive);
const caseSensitive = seed.case_sensitive;
const query = normalized(seed.value, caseSensitive);
const match = candidateFields(node, seed.kind).find((candidate) => {
const value = normalized(candidate.value, seed.case_sensitive);
const value = normalized(candidate.value, caseSensitive);
return mode === "exact" ? value === query : value.includes(query);
});
return match === undefined
@@ -12,6 +12,8 @@ import type {
} from "./javascriptApplicationGraphSchemas.js";
import {
applicationFeatureTraceResultSchema,
applicationFeatureSeedSchema,
type ApplicationFeatureSeedInput,
type ApplicationFeatureTraceResult,
type TraceApplicationFeatureInput,
} from "./javascriptFeatureTraceSchemas.js";
@@ -30,14 +32,18 @@ export interface ApplicationFeatureTraceProjectionInput {
readonly sourceEvidenceId: string;
readonly graph: JavaScriptApplicationGraph;
readonly nativeEvidence: readonly Evidence[];
readonly seed: TraceApplicationFeatureInput["seed"];
readonly seed: ApplicationFeatureSeedInput;
readonly direction: TraceApplicationFeatureInput["direction"];
}
/** Trace a literal feature through its complete reachable, authority-preserving JAG. */
export const traceApplicationFeature = (
input: ApplicationFeatureTraceProjectionInput,
source: ApplicationFeatureTraceProjectionInput,
): ApplicationFeatureTraceResult => {
const input = {
...source,
seed: applicationFeatureSeedSchema.parse(source.seed),
};
const allSeedMatches = findApplicationFeatureSeeds(
input.graph.nodes,
input.seed,
@@ -17,33 +17,65 @@ export const featureSeedMatchMode = (seed: {
}): "exact" | "contains" =>
seed.match ?? (seed.kind === "string" ? "contains" : "exact");
const literalSeedKinds = [
"route",
"string",
"api",
"channel",
"module",
"native-export",
] as const;
const apiSeedSchema = z.union([
z.strictObject({
kind: z.literal("api"),
value: boundedTextSchema,
match: z.enum(["exact", "contains"]).nullable().default(null),
case_sensitive: z.boolean().default(false),
}),
z.strictObject({
kind: z.literal("api"),
value: z.literal(""),
match: z.literal("exact"),
case_sensitive: z.boolean().default(false),
}),
]);
const apiPathSeedSchema = z.union([
z.strictObject({
kind: z.literal("api"),
value: boundedTextSchema,
match: z.enum(["exact", "contains"]).nullable().default(null),
case_sensitive: z.boolean().default(false),
entry_path: z.array(z.string()).min(1),
}),
z.strictObject({
kind: z.literal("api"),
value: z.literal(""),
match: z.literal("exact"),
case_sensitive: z.boolean().default(false),
entry_path: z.array(z.string()).min(1),
}),
]);
/**
* Literal starting point for one application feature trace. An empty value,
* such as the channel in `ipcMain.handle("")`, must be an explicit exact
* literal seed: empty containment would select every node.
*/
const applicationFeatureSeedSchema = z.union([
export const applicationFeatureSeedSchema = z.union([
z.strictObject({
kind: z.enum(["node-id", ...literalSeedKinds]),
kind: z.enum([
"node-id",
"route",
"string",
"channel",
"module",
"native-export",
]),
value: boundedTextSchema,
match: z.enum(["exact", "contains"]).nullable().default(null),
case_sensitive: z.boolean().default(false),
}),
z.strictObject({
kind: z.enum(literalSeedKinds),
kind: z.enum(["route", "string", "channel", "module", "native-export"]),
value: z.literal(""),
match: z.literal("exact"),
case_sensitive: z.boolean().default(false),
}),
apiSeedSchema,
apiPathSeedSchema,
]);
/** Check unique native identities before projecting an application trace. */
@@ -156,7 +188,10 @@ export const applicationFeatureTraceResultSchema = z.strictObject({
export type TraceApplicationFeatureInput = z.infer<
typeof traceApplicationFeatureInputSchema
>;
export type ApplicationFeatureSeed = z.infer<
export type ApplicationFeatureSeed = z.output<
typeof applicationFeatureSeedSchema
>;
export type ApplicationFeatureSeedInput = z.input<
typeof applicationFeatureSeedSchema
>;
export type ApplicationFeatureTraceResult = z.infer<
@@ -247,19 +247,24 @@ export function* classifyParsedJavaScriptRpcClientRootsSteps(
return roots;
}
/** Receiver identity facts for the overloaded `.open` syntax only. */
/**
* Receiver identity facts for the overloaded `.open` syntax, plus
* `configuration` for `.get` reads of a `getConfiguration(...)` result.
*/
export type JavaScriptOpenReceiverFact =
| "window"
| "indexed-db"
| "cache-storage"
| "local"
| "local-indexed-db"
| "local-cache-storage";
| "local-cache-storage"
| "configuration";
/**
* Resolve only the lexical receiver identity needed to distinguish browser
* `window.open` from XHR and global storage `.open` calls. This deliberately
* builds definitions without running semantic value or provenance analysis.
* `window.open` from XHR and global storage `.open` calls, and configuration
* `.get` reads from HTTP client calls. This deliberately builds definitions
* without running semantic value or provenance analysis.
*/
export const classifyParsedJavaScriptOpenReceivers = (
file: ParsedJavaScriptSource,
@@ -278,14 +283,19 @@ export function* classifyParsedJavaScriptOpenReceiversSteps(
if (
(!t.isCallExpression(node) && !t.isOptionalCallExpression(node)) ||
(!t.isMemberExpression(node.callee) &&
!t.isOptionalMemberExpression(node.callee)) ||
semanticStaticPropertyKey(
node.callee.property,
node.callee.computed,
) !== "open" ||
!t.isIdentifier(node.callee.object)
!t.isOptionalMemberExpression(node.callee))
)
return;
const method = semanticStaticPropertyKey(
node.callee.property,
node.callee.computed,
);
if (method === "get") {
if (isConfigurationReceiver(state, node.callee.object))
facts.set(node.start ?? -1, "configuration");
return;
}
if (method !== "open" || !t.isIdentifier(node.callee.object)) return;
const receiver = node.callee.object.name;
const binding = resolveSemanticBindingState(state, node, receiver);
if (binding === undefined) {
@@ -351,6 +361,82 @@ export function* classifyParsedJavaScriptOpenReceiversSteps(
return facts;
}
/**
* Whether a call spells VS Code's `workspace.getConfiguration(section)`, whose
* result `.get` reads setting keys rather than request paths. The `workspace`
* member is required: a bare or differently scoped `getConfiguration` may be
* an application's own HTTP client factory. Minifiers keep property names, so
* bundled `x.workspace.getConfiguration` still matches.
*/
const isConfigurationAccessorCall = (
state: JavaScriptSemanticAnalysisState,
node: t.Node,
): boolean => {
if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node))
return false;
const callee = node.callee;
if (
(!t.isMemberExpression(callee) && !t.isOptionalMemberExpression(callee)) ||
semanticStaticPropertyKey(callee.property, callee.computed) !==
"getConfiguration"
)
return false;
const host = callee.object;
const matchesSpelling = t.isIdentifier(host)
? host.name === "workspace"
: (t.isMemberExpression(host) || t.isOptionalMemberExpression(host)) &&
semanticStaticPropertyKey(host.property, host.computed) === "workspace";
if (!matchesSpelling) return false;
const root = t.isIdentifier(host)
? host
: t.isMemberExpression(host) || t.isOptionalMemberExpression(host)
? host.object
: undefined;
if (!t.isIdentifier(root)) return false;
const binding = resolveSemanticBindingState(state, root, root.name);
if (binding === undefined)
return !semanticResolutionBlocked(state, root, root.name);
const initializer = semanticStableInitializer(binding, state);
const origins = [
...binding.directOrigins,
...(initializer === undefined
? []
: [semanticRequireOrigin(initializer.node, state)?.origin]),
];
return origins.some(
(origin) =>
origin?.specifier === "vscode" &&
(t.isIdentifier(host)
? origin.importedPath.at(-1) === "workspace" ||
initializer?.projection.at(-1) === "workspace"
: origin.importedPath.length === 0 ||
(origin.importedPath.length === 1 &&
(origin.importedPath[0] === "*" ||
origin.importedPath[0] === "default"))),
);
};
/**
* Whether a `.get` receiver is a configuration accessor result, either inline
* or through a binding whose only visible write is one unconditional
* initializer. Minifiers emit `let` for such bindings, so declaration kind
* alone does not decide.
*/
const isConfigurationReceiver = (
state: JavaScriptSemanticAnalysisState,
receiver: t.Node,
): boolean => {
if (isConfigurationAccessorCall(state, receiver)) return true;
if (!t.isIdentifier(receiver)) return false;
const binding = resolveSemanticBindingState(state, receiver, receiver.name);
const initializer = semanticStableInitializer(binding, state);
return (
initializer !== undefined &&
initializer.projection.length === 0 &&
isConfigurationAccessorCall(state, initializer.node)
);
};
const openGlobalFact = (
name: string,
): JavaScriptOpenReceiverFact | undefined => {
@@ -324,13 +324,18 @@ const resolveChildCandidates = (
? []
: (spawnsByBinding.get(binding.bindingId) ?? []);
};
const spawnOptions = (candidate: SpawnCandidate): t.ObjectExpression | null => {
const index = candidate.method === "exec" ? 1 : 2;
const value = candidate.node.arguments[index];
const args = candidate.node.arguments;
const value =
candidate.method === "exec"
? args[1]
: t.isObjectExpression(args[1])
? args[1]
: args[2];
return t.isObjectExpression(value) ? value : null;
};
const spawnArgvCount = (candidate: SpawnCandidate): number | null => {
if (candidate.method === "exec") return null;
const args = candidate.node.arguments[1];
@@ -17,6 +17,7 @@ import {
semanticStaticPropertyName,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
import type { JavaScriptOpenReceiverFact } from "./javascriptSemanticAnalysis.js";
import {
compareUnicodeCodePoints,
compositeKey,
@@ -470,13 +471,7 @@ const xhrOpenUrl = (
name: string,
methodNode: t.Node | null | undefined,
urlNode: t.Node | null | undefined,
receiverFact?:
| "window"
| "indexed-db"
| "cache-storage"
| "local"
| "local-indexed-db"
| "local-cache-storage",
receiverFact?: JavaScriptOpenReceiverFact,
): string | undefined => {
const url = stringValue(urlNode);
if (url === undefined) return undefined;
@@ -555,13 +550,7 @@ export const endpointArgument = (
| t.ArgumentPlaceholder
)[],
callee: t.Node,
receiverFact?:
| "window"
| "indexed-db"
| "cache-storage"
| "local"
| "local-indexed-db"
| "local-cache-storage",
receiverFact?: JavaScriptOpenReceiverFact,
): string | undefined => {
if (receiverFact === "window") return undefined;
if (name === "fetch" || name.endsWith(".fetch") || name === "WebSocket")
@@ -575,10 +564,12 @@ export const endpointArgument = (
const value = stringValue(args[0]);
// Only get and delete also belong to the keyed-collection APIs, whose
// keys are header, field, and parameter names rather than URLs or paths.
// Configuration `get` reads setting keys.
return value !== undefined &&
(method === "get" || method === "delete") &&
!isRequestUrlLiteral(value) &&
isKeyedCollectionReceiver(callee)
(isKeyedCollectionReceiver(callee) ||
(method === "get" && receiverFact === "configuration"))
? undefined
: value;
}
@@ -1,4 +1,5 @@
import type * as t from "@babel/types";
import type { JavaScriptOpenReceiverFact } from "./javascriptSemanticAnalysis.js";
import type { JavaScriptRpcScan } from "./javascriptRpcEndpoints.js";
import type {
@@ -64,15 +65,7 @@ export interface JavaScriptFindingContext {
readonly rpcScan: JavaScriptRpcScan;
readonly source: string;
readonly accumulator: JavaScriptAnalysisAccumulator;
readonly openReceiverFacts?: ReadonlyMap<
number,
| "window"
| "indexed-db"
| "cache-storage"
| "local"
| "local-indexed-db"
| "local-cache-storage"
>;
readonly openReceiverFacts?: ReadonlyMap<number, JavaScriptOpenReceiverFact>;
/** Proven Electron export path segments by root offset. */
readonly electronBindings?: ReadonlyMap<number, readonly string[]>;
}
@@ -47,6 +47,14 @@ interface SymbolicReturnFlow {
readonly fallsThrough: boolean;
}
const emptyEnvironment: SymbolicEnvironment = { values: new Map() };
const isObjectPrototypeSetter = (
property: t.ObjectMethod | t.ObjectProperty,
name: string,
): boolean =>
t.isObjectProperty(property) &&
!property.computed &&
!property.shorthand &&
name === "__proto__";
/** Demand-driven substitutions for local bindings, closures and literal module tables. */
export class JavaScriptSymbolicBindings {
@@ -243,15 +251,30 @@ export class JavaScriptSymbolicBindings {
index = null;
break;
}
if (isObjectPrototypeSetter(property, name)) continue;
properties.set(name, property);
}
this.#literalPropertyIndex.set(value.node, index);
}
if (index !== null) {
const property = index.get(key);
return property === undefined
? symbolicUnknown("missing property")
: this.#objectPropertyValue(property, value.environment);
if (property !== undefined)
return this.#objectPropertyValue(property, value.environment);
if (key === "__proto__") {
const prototypeSetter = [...value.node.properties]
.reverse()
.filter(
(candidate): candidate is t.ObjectMethod | t.ObjectProperty =>
!t.isSpreadElement(candidate),
)
.find((candidate) => isObjectPrototypeSetter(candidate, key));
if (prototypeSetter !== undefined)
return this.#objectPropertyValue(
prototypeSetter,
value.environment,
);
}
return symbolicUnknown("missing property");
}
for (const p of [...value.node.properties].reverse()) {
if (t.isSpreadElement(p)) {
@@ -314,7 +337,8 @@ export class JavaScriptSymbolicBindings {
t.isSpreadElement(p)
? this.members(this.evaluate(p.argument, value.environment), active)
: [semanticStaticPropertyKey(p.key, p.computed)].filter(
(k): k is string => k !== null,
(k): k is string =>
k !== null && !isObjectPrototypeSetter(p, k),
),
),
),
@@ -192,3 +192,75 @@ it("keeps filesystem comparison unknown without coverage and reports observed ch
}),
).toMatchObject({ filesystem: "changed", status: "changed" });
});
it.each([
[500, "interaction", 6],
[4, "process", 4],
] as const)(
"orders an interaction difference by its dispatch time (process sample at %i ms)",
(processTime, dimension, at) => {
const capture = (side: "left" | "right") => {
const base = emptyCapture();
const journal = [
{ collection: "filesystem_checkpoints" as const, index: 0 },
...(processTime < 6
? [{ collection: "process_samples" as const, index: 0 }]
: []),
{ collection: "interaction_events" as const, index: 0 },
...(processTime >= 6
? [{ collection: "process_samples" as const, index: 0 }]
: []),
{ collection: "lifecycle" as const, index: 0 },
{ collection: "lifecycle" as const, index: 1 },
{ collection: "filesystem_checkpoints" as const, index: 1 },
].map((entry, capture_order) => ({ ...entry, capture_order }));
return {
...base,
manifest: {
...base.manifest,
completed_at: "2026-01-01T00:00:01.000Z",
},
settlement: { ...base.settlement, elapsed_ms: 1000 },
filesystem_checkpoints: base.filesystem_checkpoints.map(
(checkpoint, index) => ({
...checkpoint,
at_ms: index === 0 ? 0 : 1000,
}),
),
interaction_events: [
{
sequence: 0,
scheduled_at_ms: 5,
dispatched_at_ms: 6,
type: "input" as const,
data: "hello",
outcome:
side === "left" ? ("dispatched" as const) : ("failed" as const),
},
],
process_samples: [
{
at_ms: processTime,
pid: 2,
parent_pid: 1,
command: side === "left" ? "worker-a" : "worker-b",
process_group_id: 1,
session_id: 1,
},
],
event_journal: journal,
};
};
const comparison = compareFullyObserved(capture("left"), capture("right"));
expect(comparison).toMatchObject({
interaction: "changed",
process: "changed",
first_divergence: {
status: "found",
dimension,
left_at_ms: at,
right_at_ms: at,
},
});
},
);
@@ -839,3 +839,27 @@ it("requires compatible contracts and enforces capture age through a clock seam"
}),
);
});
it("requires interaction dispatch times to follow their sequence", () => {
const capture = emptyCapture();
const interaction = (sequence: number, dispatched: number) => ({
sequence,
scheduled_at_ms: 0,
dispatched_at_ms: dispatched,
type: "input" as const,
data: "x",
outcome: "dispatched" as const,
});
const issues = (dispatched: readonly number[]) =>
processCaptureIssues({
...capture,
interaction_events: dispatched.map((at, index) => interaction(index, at)),
}).filter(({ message }) => message.includes("dispatch timestamps"));
expect(issues([5, 5, 10])).toEqual([]);
expect(issues([10, 5])).toEqual([
{
path: "interaction_events",
message: expect.stringContaining("dispatch timestamps must be ordered"),
},
]);
});
+11 -6
View File
@@ -17,12 +17,10 @@ type RequireInvariant = (
message: string,
) => void;
const orderedTimestamps = (
values: readonly { readonly at_ms: number }[],
): boolean =>
const orderedTimestamps = (values: readonly number[]): boolean =>
values.every((value, index) => {
const previous = values[index - 1];
return previous === undefined || value.at_ms >= previous.at_ms;
return previous === undefined || value >= previous;
});
const validateCommitments = (
@@ -66,7 +64,14 @@ const validateOrdering = (
["rendered_frames", capture.rendered_frames],
["process_samples", capture.process_samples],
] as const)
require(orderedTimestamps(values), name, "timestamps must be ordered");
require(orderedTimestamps(
values.map(({ at_ms }) => at_ms),
), name, "timestamps must be ordered");
// Interactions are dispatched in sequence, so their recorded dispatch
// times cannot decrease; comparison ranks a changed interaction by it.
require(orderedTimestamps(
capture.interaction_events.map(({ dispatched_at_ms }) => dispatched_at_ms),
), "interaction_events", "dispatch timestamps must be ordered");
};
const validateEventJournal = (
@@ -242,7 +247,7 @@ const validateLifecycle = (
require(capture.filesystem_checkpoints.map(({ name }) => name).join(",") ===
"before,after_settlement", "filesystem_checkpoints", "capture must include initial and final filesystem snapshots");
require(orderedTimestamps(
capture.filesystem_checkpoints,
capture.filesystem_checkpoints.map(({ at_ms }) => at_ms),
), "filesystem_checkpoints", "filesystem snapshot times must be ordered");
require(!capture.filesystem_checkpoints.some(({ truncated }) => truncated) ||
capture.truncated, "truncated", "filesystem snapshot truncation must propagate to the capture");
+21 -13
View File
@@ -165,17 +165,25 @@ type DivergenceDimension = Exclude<
{ readonly status: "none" | "unknown" }
>["dimension"];
const eventTime = (value: unknown): number | null => {
if (
typeof value === "object" &&
value !== null &&
"at_ms" in value &&
typeof value.at_ms === "number" &&
Number.isSafeInteger(value.at_ms) &&
value.at_ms >= 0
)
return value.at_ms;
return null;
// Interactions record when their outcome was observed as the dispatch time;
// every other timed observation uses at_ms.
const EVENT_TIME_FIELD: Readonly<Record<DivergenceDimension, string>> = {
terminal: "at_ms",
interaction: "dispatched_at_ms",
exit: "at_ms",
filesystem: "at_ms",
process: "at_ms",
};
const eventTime = (
dimension: DivergenceDimension,
value: unknown,
): number | null => {
if (typeof value !== "object" || value === null) return null;
const time: unknown = Reflect.get(value, EVENT_TIME_FIELD[dimension]);
return typeof time === "number" && Number.isSafeInteger(time) && time >= 0
? time
: null;
};
const firstCollectionDivergence = (
@@ -195,8 +203,8 @@ const firstCollectionDivergence = (
status: "found",
dimension,
index,
left_at_ms: eventTime(leftValue),
right_at_ms: eventTime(rightValue),
left_at_ms: eventTime(dimension, leftValue),
right_at_ms: eventTime(dimension, rightValue),
left: jsonValueSchema.parse(leftValue),
right: jsonValueSchema.parse(rightValue),
};
+57
View File
@@ -320,6 +320,63 @@ describe("web bundle API classification parity", () => {
"users",
]);
});
});
describe("web bundle configuration and navigation parity", () => {
it("keeps configuration setting reads out of endpoints in both analyzers", () => {
const source = `
import vscodeDefault from "vscode";
vscodeDefault.workspace.getConfiguration("git").get("default-setting");
vscode.workspace.getConfiguration("git").get("autofetch");
workspace.getConfiguration("git").get("enabled", true);
const config = vscode.workspace.getConfiguration("git");
config.get("autofetchPeriod", 180);
config.get("/v1/settings");
let c = Mt.workspace.getConfiguration("git", uri), l = c.get("timeline.date");
let changed = vscode.workspace.getConfiguration("git");
changed = api;
changed.get("reassigned");
const maybe = flag ? vscode.workspace.getConfiguration("git") : api;
maybe.get("conditional");
{
const config = api;
config.get("shadowed");
}
api.get("users");
const client = getConfiguration("/api/v1");
client.get("accounts");
http.getConfiguration(baseUrl).get("orders");
{
const workspace = { getConfiguration: () => api };
workspace.getConfiguration("/api").get("local-users");
}
{
const vscode = { workspace: { getConfiguration: () => api } };
vscode.workspace.getConfiguration("/api").get("local-orders");
}
`;
const expected = [
"/v1/settings",
"accounts",
"conditional",
"local-orders",
"local-users",
"orders",
"reassigned",
"shadowed",
"users",
];
expect(
analyzeCapturedWebBundle(inspection(source))
.observations.endpoints.map(({ value }) => value)
.sort(),
).toEqual(expected);
expect(
analyzeJavaScriptStaticSource(source)
.endpoints.map(({ value }) => value)
.sort(),
).toEqual(expected);
});
it("recognizes loadURL endpoints like static analysis", () => {
const result = analyzeCapturedWebBundle(
+3
View File
@@ -30,6 +30,7 @@ import {
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { InspectEvmInterfaceInput } from "../domain/evm/evmInterface.js";
import { evmInterfaceSchema } from "../domain/evm/evmInterface.js";
import { solidityMetadataSchema } from "../domain/evm/solidityMetadata.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -67,6 +68,7 @@ const replySchema = z.discriminatedUnion("ok", [
sha256: z.string().regex(/^[a-f0-9]{64}$/),
bytes: z.number().int().nonnegative(),
hex: z.string().regex(/^(?:[a-f0-9]{2})*$/),
metadata: solidityMetadataSchema.optional(),
}),
raw: evmoleInterfaceReplySchema,
}),
@@ -331,6 +333,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort {
"Recovered selectors, argument strings and mutability are upstream inferences, not verified ABI signatures or names. Empty results do not prove the absence of callable dispatch.",
"Bytecode kind, hardfork and deployed-contract authenticity are unknown. This inspection performs no target runtime execution, chain/RPC lookup or network request.",
"Original carrier and decoded bytecode SHA-256 are distinct identities; SHA-256 is not the Ethereum Keccak code hash.",
"Terminal CBOR metadata is an independently decoded candidate, not proof of Solidity origin, source identity or deployment. Nested or unsupported values retain explicit unavailable interpretation and original byte ranges.",
"The owned worker has a 256 MiB JavaScript heap, 3 GiB virtual address-space limit and 30-second deadline. Virtual address space is distinct from resident memory; limits fail without partial success.",
];
const validated = evmInterfaceSchema.safeParse({
+2
View File
@@ -6,6 +6,7 @@ import {
EvmCarrierFailure,
} from "./EvmBytecodeCarrier.js";
import { projectEvmoleInterface } from "./EvmoleInterfaceAdapter.js";
import { inspectSolidityMetadata } from "./SolidityMetadata.js";
import {
EVM_INTERFACE_LIMITS,
EVM_FILE_SIZE_FAILURE_EXIT,
@@ -64,6 +65,7 @@ const main = async (): Promise<void> => {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
hex: Buffer.from(bytes).toString("hex"),
metadata: inspectSolidityMetadata(bytes),
},
raw: inferred.raw,
};
+96
View File
@@ -0,0 +1,96 @@
import { expect, it } from "vitest";
import { inspectSolidityMetadata } from "./SolidityMetadata.js";
const bytecode = (hex: string) => {
const payload = Buffer.from(hex, "hex");
const length = Buffer.alloc(2);
length.writeUInt16BE(payload.length);
return Buffer.concat([Buffer.from("00", "hex"), payload, length]);
};
it("reads a compiler version from actual trailer bytes without a magic-prefix assumption", () => {
const result = inspectSolidityMetadata(bytecode("a164736f6c634300081e"));
expect(result).toMatchObject({
status: "decoded",
bytecode_offset: 1,
cbor_bytes: 10,
compiler_version: { representation: "release-bytes", value: "0.8.30" },
entries: [
{
key: { kind: "text", value: "solc" },
value: { kind: "bytes", value: "00081e" },
},
],
});
});
it("preserves integer and non-text key precision beyond Number", () => {
expect(
inspectSolidityMetadata(bytecode("a1011bffffffffffffffff")).entries,
).toEqual([
{
key: { kind: "integer", value: "1" },
value: { kind: "integer", value: "18446744073709551615" },
},
]);
expect(
inspectSolidityMetadata(bytecode("a1003bffffffffffffffff")).entries[0]
?.value,
).toEqual({
kind: "integer",
value: "-18446744073709551616",
});
});
it("retains opaque nested values as partial rather than fabricating scalar values", () => {
expect(inspectSolidityMetadata(bytecode("a161788100"))).toMatchObject({
status: "partial",
entries: [
{
key: { kind: "text", value: "x" },
value: { kind: "uninterpreted", container: "array" },
},
],
});
});
it("preserves a UTF-8 BOM inside a CBOR text value rather than stripping it", () => {
expect(
inspectSolidityMetadata(bytecode("a1617864efbbbf61")).entries[0]?.value,
).toEqual({
kind: "text",
value: "\ufeffa",
});
expect(
inspectSolidityMetadata(bytecode("a167efbbbf736f6c634300081e"))
.compiler_version,
).toBeNull();
});
it.each([
["invalid text", "a1617861ff"],
["truncated value", "a16178"],
["unsupported tag", "a16178c000"],
["floating point", "a16178fa3f800000"],
["duplicate key", "a2617801617802"],
["excessive nesting", "a16178" + "81".repeat(65) + "00"],
["impossible collection", "a161788a00"],
])("keeps exact ranges and unavailable interpretation for %s", (_name, hex) => {
expect(inspectSolidityMetadata(bytecode(hex))).toMatchObject({
status: "not-decoded",
bytecode_offset: 1,
entries: [],
compiler_version: null,
});
});
it.each(["", "60006000f3", "000000", "00010001"])(
"does not claim absent Solidity metadata for an unavailable trailer: %s",
(hex) =>
expect(inspectSolidityMetadata(Buffer.from(hex, "hex"))).toMatchObject({
status: "unavailable",
bytecode_offset: null,
cbor_bytes: null,
entries: [],
}),
);
+158
View File
@@ -0,0 +1,158 @@
import { decode, Tokenizer, Type, type Token } from "cborg";
import type {
SolidityMetadata,
SolidityMetadataScalar,
} from "../domain/evm/solidityMetadata.js";
const PROFILE = "terminal-cbor-scalars-v1";
const MAX_DEPTH = 64;
const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
const decodeOptions = {
useMaps: true,
allowBigInt: true,
allowIndefinite: false,
allowUndefined: false,
allowInfinity: false,
allowNaN: false,
rejectDuplicateMapKeys: true,
retainStringBytes: true,
} as const;
/** Bound recursive decoder entry before collection interpretation/allocation. */
class BoundedMetadataTokenizer extends Tokenizer {
readonly remaining: number[] = [];
constructor(bytes: Uint8Array) {
super(bytes, decodeOptions);
}
override next(): Token {
while (this.remaining.at(-1) === 0) this.remaining.pop();
const token = super.next();
if (
Type.equals(token.type, Type.tag) ||
Type.equals(token.type, Type.float)
)
throw new Error(
"CBOR tags and floating-point values are outside this metadata profile.",
);
if (Type.equals(token.type, Type.string)) {
if (token.byteValue === undefined)
throw new Error(
"CBOR text bytes were unavailable for strict UTF-8 validation.",
);
token.value = utf8.decode(token.byteValue);
}
const parent = this.remaining.length - 1;
if (parent >= 0) this.remaining[parent]!--;
if (
Type.equals(token.type, Type.map) ||
Type.equals(token.type, Type.array)
) {
const count: unknown = token.value;
const children =
typeof count === "number"
? count * (Type.equals(token.type, Type.map) ? 2 : 1)
: NaN;
if (
!Number.isSafeInteger(children) ||
children < 0 ||
children > this.data.length
)
throw new Error(
"Declared CBOR collection exceeds the encoded item-byte bound.",
);
if (this.remaining.length >= MAX_DEPTH)
throw new Error("CBOR nesting exceeds the 64-level metadata profile.");
this.remaining.push(children);
}
return token;
}
}
const scalar = (value: unknown): SolidityMetadataScalar => {
if (typeof value === "string") return { kind: "text", value };
if (typeof value === "bigint")
return { kind: "integer", value: value.toString() };
if (typeof value === "number" && Number.isSafeInteger(value))
return { kind: "integer", value: String(value) };
if (typeof value === "boolean") return { kind: "boolean", value };
if (value === null) return { kind: "null" };
if (value instanceof Uint8Array)
return { kind: "bytes", value: Buffer.from(value).toString("hex") };
if (value instanceof Map) return { kind: "uninterpreted", container: "map" };
if (Array.isArray(value))
return { kind: "uninterpreted", container: "array" };
throw new Error(
"CBOR decoder returned a value outside the admitted profile.",
);
};
/** Parse only a plausible terminal root-map candidate; never establish absence. */
export const inspectSolidityMetadata = (
bytes: Uint8Array,
): SolidityMetadata => {
const empty: SolidityMetadata = {
profile: PROFILE,
status: "unavailable",
bytecode_offset: null,
cbor_bytes: null,
entries: [],
compiler_version: null,
diagnostic:
"No plausible terminal CBOR map was identified; Solidity origin and metadata absence remain unknown.",
};
if (bytes.length < 3) return empty;
const length = bytes[bytes.length - 2]! * 256 + bytes[bytes.length - 1]!;
const offset = bytes.length - 2 - length;
if (length === 0 || offset < 0 || bytes[offset]! >> 5 !== 5) return empty;
const selected = bytes.subarray(offset, bytes.length - 2);
const result: SolidityMetadata = {
...empty,
status: "not-decoded",
bytecode_offset: offset,
cbor_bytes: length,
};
try {
const raw: unknown = decode(selected, {
...decodeOptions,
tokenizer: new BoundedMetadataTokenizer(selected),
});
if (!(raw instanceof Map))
throw new Error("Terminal CBOR candidate did not decode to a root map.");
for (const [key, value] of raw as Map<unknown, unknown>)
result.entries.push({ key: scalar(key), value: scalar(value) });
result.status = result.entries.some(
({ key, value }) =>
key.kind === "uninterpreted" || value.kind === "uninterpreted",
)
? "partial"
: "decoded";
result.diagnostic =
result.status === "partial"
? "Nested containers are uninterpreted; their exact bytes remain at the recorded range in original bytecode."
: null;
const version: unknown = raw.get("solc");
if (version instanceof Uint8Array && version.length === 3)
result.compiler_version = {
representation: "release-bytes",
value: [...version].join("."),
};
else if (typeof version === "string" && version.length > 0)
result.compiler_version = {
representation: "prerelease-text",
value: version,
};
return result;
} catch (cause: unknown) {
return {
...result,
status: "not-decoded",
entries: [],
compiler_version: null,
diagnostic: (cause instanceof Error
? cause.message
: String(cause)
).slice(0, 512),
};
}
};
+48 -2
View File
@@ -1,6 +1,7 @@
import { constants } from "node:fs";
import { constants as osConstants } from "node:os";
import type { BigIntStats, Stats } from "node:fs";
import { lstat, open, type FileHandle } from "node:fs/promises";
import { lstat, open, stat, type FileHandle } from "node:fs/promises";
import { OwnedFileHandle } from "./OwnedFileHandle.js";
@@ -66,7 +67,17 @@ export const openRegularFile = async (
(constants.O_NONBLOCK ?? 0) |
(constants.O_NOCTTY ?? 0) |
(options.symlinks === "reject" ? (constants.O_NOFOLLOW ?? 0) : 0),
);
).catch(async (cause: unknown) => {
const nonRegular = await nonRegularOpenFailure(
path,
options.symlinks,
cause,
);
if (nonRegular === undefined) throw cause;
// Cancellation during the metadata probe outranks the reclassification.
options.signal?.throwIfAborted();
throw nonRegular;
});
const owner = new OwnedFileHandle(handle);
try {
options.signal?.throwIfAborted();
@@ -95,6 +106,41 @@ export const openRegularFile = async (
}
};
/**
* Some non-regular files cannot be opened at all: a Unix socket fails with
* ENXIO on Linux and EOPNOTSUPP on macOS. Confirm such a failure against the
* path's own metadata before reporting a non-regular selection.
*/
const nonRegularOpenFailure = async (
path: string,
symlinks: "follow" | "reject",
cause: unknown,
): Promise<NonRegularFileReadError | undefined> => {
// Only errors meaning "this file type cannot be opened" are reclassified;
// permission, symlink-rejection and resource failures keep their codes.
if (!isUnopenableFileTypeError(cause)) return undefined;
const metadata = await (symlinks === "reject" ? lstat : stat)(path).catch(
() => undefined,
);
if (metadata === undefined || metadata.isFile()) return undefined;
return new NonRegularFileReadError(path, metadata.isDirectory());
};
// Match by errno: libuv has no name for macOS EOPNOTSUPP (102) and reports
// "Unknown system error -102" as its code.
const errnos: Partial<Record<string, number>> = osConstants.errno;
const UNOPENABLE_FILE_TYPE_ERRNOS: ReadonlySet<number> = new Set(
[errnos.ENXIO, errnos.EOPNOTSUPP, errnos.ENOTSUP].flatMap((errno) =>
errno === undefined ? [] : [-errno],
),
);
const isUnopenableFileTypeError = (cause: unknown): boolean =>
cause instanceof Error &&
"errno" in cause &&
typeof cause.errno === "number" &&
UNOPENABLE_FILE_TYPE_ERRNOS.has(cause.errno);
/** Compare one regular file's identity and mutable metadata across a read. */
export const sameRegularFileState = (
expected: Stats | BigIntStats,
+91
View File
@@ -6,6 +6,7 @@ import {
buildElf64Image,
buildStrippedElf64Image,
snapshotSection,
appendElfRanges,
} from "./FlutterBuild.fixture.js";
const readElfSymbol = async (bytes: Buffer, name: string) => {
@@ -143,6 +144,96 @@ describe("readElfSymbol", () => {
});
describe("ELF symbol-table ownership", () => {
it.each([
{ address: 0x400, offset: 0x700, size: 52 },
{ address: 0x410, offset: 0x710, size: 4 },
{ address: 0x3f0, offset: 0x6f0, size: 20 },
])(
"rejects conflicting interpretations of any symbol byte: %j",
async (range) => {
const image = appendElfRanges(imageWithSections(), "program", [
{ type: 1, ...range },
]);
const names = ["_kDartVmSnapshotData", "_kDartIsolateSnapshotData"];
const result = await readElfSymbols(image, names);
expect(result.symbols).toEqual([
{ name: names[1], offset: 0x800, size: 52 },
]);
expect(result.failures).toContainEqual({
reason: expect.stringContaining("conflicting PT_LOAD"),
});
const phoff = Number(image.readBigUInt64LE(0x20));
const first = Buffer.from(image.subarray(phoff, phoff + 56));
image.copy(image, phoff, phoff + 56, phoff + 112);
first.copy(image, phoff + 56);
expect(await readElfSymbols(image, names)).toEqual(result);
},
);
it("accepts equivalent overlaps and excludes adjacent unrelated mappings", async () => {
const image = appendElfRanges(imageWithSections(), "program", [
{ type: 1, address: 0x410, offset: 0x410, size: 4 },
{ type: 1, address: 0x400 + 52, offset: 0x700, size: 4 },
]);
expect(await readElfSymbols(image, ["_kDartVmSnapshotData"])).toEqual({
symbols: [{ name: "_kDartVmSnapshotData", offset: 0x400, size: 52 }],
failures: [],
});
});
it("does not publish an earlier definition when another definition has unresolved mapping", async () => {
const image = imageWithSections();
const shoff = Number(image.readBigUInt64LE(0x28));
const symbols = Number(image.readBigUInt64LE(shoff + 64 + 0x18));
image.writeUInt32LE(image.readUInt32LE(symbols), symbols + 24);
const conflict = appendElfRanges(image, "program", [
{ type: 1, address: 0x810, offset: 0x710, size: 4 },
]);
const result = await readElfSymbols(conflict, ["_kDartVmSnapshotData"]);
expect(result.symbols).toEqual([]);
expect(result.failures).toEqual([
{
reason: "Symbol _kDartVmSnapshotData has conflicting PT_LOAD mappings",
},
]);
});
it("handles zero-width symbols at a unique segment end without choosing a conflicting shared endpoint", async () => {
const image = imageWithSections();
const shoff = Number(image.readBigUInt64LE(0x28));
const symbols = Number(image.readBigUInt64LE(shoff + 64 + 0x18));
const at = Number(image.readBigUInt64LE(64 + 0x20));
image.writeBigUInt64LE(BigInt(at), symbols + 8);
image.writeBigUInt64LE(0n, symbols + 16);
expect(
(await readElfSymbols(image, ["_kDartVmSnapshotData"])).symbols,
).toEqual([{ name: "_kDartVmSnapshotData", offset: at, size: 0 }]);
const ambiguous = appendElfRanges(image, "program", [
{ type: 1, address: at, offset: 0x700, size: 4 },
]);
expect(
(await readElfSymbols(ambiguous, ["_kDartVmSnapshotData"])).symbols,
).toEqual([]);
});
it.each(["hash", "symbols", "strings"] as const)(
"rejects partially conflicting dynamic %s mappings",
async (table) => {
const image = strippedImageWithSections();
const dynamic = Number(image.readBigUInt64LE(64 + 56 + 8));
const tagIndex = table === "hash" ? 4 : table === "symbols" ? 0 : 1;
const at = Number(image.readBigUInt64LE(dynamic + tagIndex * 16 + 8));
const conflict = appendElfRanges(image, "program", [
{ type: 1, address: at + 1, offset: 0x700, size: 1 },
]);
const result = await readElfSymbols(conflict, ["_kDartVmSnapshotData"]);
expect(result.symbols).toEqual([]);
expect(result.failures).toContainEqual({
reason: expect.stringContaining("conflicting PT_LOAD"),
});
},
);
it.each([false, true])(
"keeps a symbol terminator inside dynstr (stripped: %s)",
async (stripped) => {
+48 -44
View File
@@ -1,5 +1,6 @@
import { Buffer } from "node:buffer";
import { setImmediate as yieldToEventLoop } from "node:timers/promises";
import { createElfLoadMap } from "./ElfLoadMap.js";
import {
SNAPSHOT_HASH_LENGTH,
SNAPSHOT_HASH_OFFSET,
@@ -205,6 +206,7 @@ export const readElfSymbols = async (
vaddr === null ||
offset === null ||
filesz === null ||
!Number.isSafeInteger(vaddr + filesz) ||
offset > bytes.length ||
filesz > bytes.length - offset
)
@@ -214,17 +216,7 @@ export const readElfSymbols = async (
return failure("Multiple PT_DYNAMIC segments are ambiguous");
else dynamicSegment = { offset, filesz };
}
const toOffset = (vaddr: number, size: number): number | null => {
const segment = segments.find(
(candidate) =>
vaddr >= candidate.vaddr &&
vaddr - candidate.vaddr <= candidate.filesz &&
size <= candidate.filesz - (vaddr - candidate.vaddr),
);
return segment === undefined
? null
: segment.offset + vaddr - segment.vaddr;
};
const toOffset = await createElfLoadMap(segments, signal);
if (segments.length === 0)
return failure("ELF image has no PT_LOAD segments");
const tables: {
@@ -335,26 +327,25 @@ export const readElfSymbols = async (
const gnu = tags.get(0x6ffffef5);
if (sysv !== undefined) {
const at = toOffset(sysv, 8);
if (at === null) return failure("DT_HASH header is not file-backed");
const buckets = reader.u32(at)!;
count = reader.u32(at + 4)!;
if (toOffset(sysv, 8 + 4 * (buckets + count)) === null)
return failure("DT_HASH table is truncated");
if (!at.ok) return failure(`DT_HASH header ${at.error.reason}`);
const buckets = reader.u32(at.value)!;
count = reader.u32(at.value + 4)!;
const table = toOffset(sysv, 8 + 4 * (buckets + count));
if (!table.ok) return failure(`DT_HASH table ${table.error.reason}`);
} else if (gnu !== undefined) {
const at = toOffset(gnu, 16);
if (at === null) return failure("DT_GNU_HASH header is not file-backed");
const buckets = reader.u32(at)!;
const firstSymbol = reader.u32(at + 4)!;
const bloomWords = reader.u32(at + 8)!;
if (!at.ok) return failure(`DT_GNU_HASH header ${at.error.reason}`);
const buckets = reader.u32(at.value)!;
const firstSymbol = reader.u32(at.value + 4)!;
const bloomWords = reader.u32(at.value + 8)!;
const prefixBytes = 16 + bloomWords * (is64 ? 8 : 4) + buckets * 4;
if (
buckets === 0 ||
bloomWords === 0 ||
toOffset(gnu, prefixBytes) === null
)
if (buckets === 0 || bloomWords === 0)
return failure("DT_GNU_HASH buckets are malformed");
const prefix = toOffset(gnu, prefixBytes);
if (!prefix.ok)
return failure(`DT_GNU_HASH buckets ${prefix.error.reason}`);
let last = 0;
const bucketsAt = at + 16 + bloomWords * (is64 ? 8 : 4);
const bucketsAt = at.value + 16 + bloomWords * (is64 ? 8 : 4);
for (let index = 0; index < buckets; index += 1) {
if (index % 4096 === 0) {
await yieldToEventLoop();
@@ -374,9 +365,10 @@ export const readElfSymbols = async (
signal?.throwIfAborted();
}
const span = prefixBytes + (index - firstSymbol + 1) * 4;
if (toOffset(gnu, span) === null)
return failure("DT_GNU_HASH chain is unterminated");
const chain = reader.u32(at + span - 4)!;
const range = toOffset(gnu, span);
if (!range.ok)
return failure(`DT_GNU_HASH chain ${range.error.reason}`);
const chain = reader.u32(at.value + span - 4)!;
index += 1;
if ((chain & 1) !== 0) {
count = index;
@@ -388,14 +380,22 @@ export const readElfSymbols = async (
return failure("Stripped ELF has no DT_HASH or DT_GNU_HASH symbol count");
const offset = toOffset(sym, count * entrySize);
const stringOffset = toOffset(str, stringSize);
if (offset === null || stringOffset === null)
return failure("Dynamic symbol or string table is not file-backed");
tables.push({ offset, count, stringOffset, stringSize });
if (!offset.ok)
return failure(`Dynamic symbol table ${offset.error.reason}`);
if (!stringOffset.ok)
return failure(`Dynamic string table ${stringOffset.error.reason}`);
tables.push({
offset: offset.value,
count,
stringOffset: stringOffset.value,
stringSize,
});
}
const wanted = new Set(symbolNames);
const symbols = new Map<string, ElfSymbol>();
const ambiguous = new Set<string>();
const failures: ElfParseFailure[] = [];
const unresolved = new Set<string>();
const failures = new Set<string>();
for (const table of tables) {
for (let index = 0; index < table.count; index += 1) {
if (index % 4096 === 0) {
@@ -419,33 +419,37 @@ export const readElfSymbols = async (
const value = is64 ? reader.u64(base + 8) : reader.u32(base + 4);
const size = is64 ? reader.u64(base + 16) : reader.u32(base + 8);
if (value === null || size === null) {
failures.push({ reason: `Symbol ${name} has unrepresentable bounds` });
failures.add(`Symbol ${name} has unrepresentable bounds`);
unresolved.add(name);
continue;
}
const offset = toOffset(value, size);
if (offset === null) {
failures.push({ reason: `Symbol ${name} has no file-backed range` });
if (!offset.ok) {
failures.add(`Symbol ${name} ${offset.error.reason}`);
unresolved.add(name);
continue;
}
const previous = symbols.get(name);
if (
previous !== undefined &&
(previous.offset !== offset || previous.size !== size)
(previous.offset !== offset.value || previous.size !== size)
)
ambiguous.add(name);
else symbols.set(name, { name, offset, size });
else symbols.set(name, { name, offset: offset.value, size });
}
}
for (const name of ambiguous) {
symbols.delete(name);
failures.push({ reason: `Symbol ${name} has conflicting definitions` });
failures.add(`Symbol ${name} has conflicting definitions`);
}
for (const name of unresolved) symbols.delete(name);
for (const name of wanted)
if (!symbols.has(name))
failures.push({
reason: `symbol ${name} is not in the dynamic symbol table`,
});
return { symbols: [...symbols.values()], failures };
if (!symbols.has(name) && !ambiguous.has(name) && !unresolved.has(name))
failures.add(`symbol ${name} is not in the dynamic symbol table`);
return {
symbols: [...symbols.values()],
failures: [...failures].map((reason) => ({ reason })),
};
};
/** Read one Dart snapshot section header from its file offset. */
+18 -4
View File
@@ -8,6 +8,9 @@ import {
const MAX_METADATA_BYTES = 8 * 1024 * 1024;
const MAX_BUILD_IDS = 64;
// Range bookkeeping and separate positional reads need a budget independent
// of payload bytes: tiny/overlapping declarations can otherwise fan out I/O.
const MAX_NOTE_RANGES = 1024;
export interface ElfBuildIds {
readonly candidates: readonly string[];
@@ -21,9 +24,10 @@ export const readElfBuildIds = async (
signal: AbortSignal | undefined,
): Promise<ElfBuildIds> => {
const candidates = new Set<string>();
const failures: ElfParseFailure[] = [];
const failure = (reason: string): ElfBuildIds => ({
candidates: [...candidates],
failures: [{ reason }],
failures: [...failures, { reason }],
});
let examined = 0;
const read = async (offset: number, size: number): Promise<Buffer | null> => {
@@ -59,7 +63,7 @@ export const readElfBuildIds = async (
if (parsed.failure !== undefined) return failure(parsed.failure.reason);
const h = parsed.header;
const ranges = new Map<string, { offset: number; size: number }>();
for (const table of [
tables: for (const table of [
{
offset: h.e_phoff,
width: h.e_phentsize,
@@ -105,7 +109,17 @@ export const readElfBuildIds = async (
size > totalBytes - offset
)
return failure("ELF note range is not file-backed");
ranges.set(`${offset}:${size}`, { offset, size });
if (size === 0) continue;
const key = `${offset}:${size}`;
if (ranges.has(key)) continue;
if (ranges.size === MAX_NOTE_RANGES) {
failures.push({
reason:
"ELF notes exceed the 1024-range note-range inventory/read budget",
});
break tables;
}
ranges.set(key, { offset, size });
}
}
const align4 = (value: number): number => Math.ceil(value / 4) * 4;
@@ -154,5 +168,5 @@ export const readElfBuildIds = async (
}
}
signal?.throwIfAborted();
return { candidates: [...candidates], failures: [] };
return { candidates: [...candidates], failures };
};
+101
View File
@@ -0,0 +1,101 @@
import { setImmediate as yieldToEventLoop } from "node:timers/promises";
import { err, ok, type Result } from "../domain/result.js";
interface LoadSegment {
readonly vaddr: number;
readonly offset: number;
readonly filesz: number;
}
/** Normalize overlapping file-backed interpretations once, before any lookups. */
export const createElfLoadMap = async (
segments: readonly LoadSegment[],
signal?: AbortSignal,
): Promise<
(address: number, size: number) => Result<number, { reason: string }>
> => {
const events = segments
.filter((segment) => segment.filesz > 0)
.flatMap((segment) => [
{ at: segment.vaddr, delta: segment.offset - segment.vaddr, change: 1 },
{
at: segment.vaddr + segment.filesz,
delta: segment.offset - segment.vaddr,
change: -1,
},
])
.sort((left, right) => left.at - right.at);
const active = new Map<number, number>();
const spans: { start: number; end: number; delta: number | null }[] = [];
let previous = 0;
for (let index = 0; index < events.length; index += 1) {
if (index % 4096 === 0) {
await yieldToEventLoop();
signal?.throwIfAborted();
}
const event = events[index]!;
if (event.at > previous && active.size > 0) {
const delta = active.size === 1 ? active.keys().next().value! : null;
const last = spans.at(-1);
if (last?.end === previous && last.delta === delta) last.end = event.at;
else spans.push({ start: previous, end: event.at, delta });
}
const count = (active.get(event.delta) ?? 0) + event.change;
if (count === 0) active.delete(event.delta);
else active.set(event.delta, count);
previous = event.at;
}
// Prefix counts keep growing GNU-hash range checks logarithmic even with
// many load segments. Null denotes conflicting interpretations, not a hole.
const conflicts = [0];
for (const span of spans)
conflicts.push(conflicts.at(-1)! + Number(span.delta === null));
const locate = (address: number): number => {
let low = 0,
high = spans.length;
while (low < high) {
const middle = Math.floor((low + high) / 2);
if (spans[middle]!.start <= address) low = middle + 1;
else high = middle;
}
return low - 1;
};
signal?.throwIfAborted();
return (address, size) => {
const missing = () =>
err({ reason: "has no contiguous file-backed PT_LOAD range" });
const ambiguous = () => err({ reason: "has conflicting PT_LOAD mappings" });
if (
!Number.isSafeInteger(address) ||
!Number.isSafeInteger(size) ||
address < 0 ||
size < 0 ||
!Number.isSafeInteger(address + size)
)
return missing();
const first = locate(address);
const span = spans[first];
if (span === undefined || (size > 0 && address >= span.end))
return missing();
if (size === 0) {
// A zero-width symbol at a shared endpoint still needs one file offset.
if (address > span.end) return missing();
const left = spans[first - 1];
if (
span.delta === null ||
(span.start === address &&
left?.end === address &&
left.delta !== span.delta)
)
return ambiguous();
return ok(address + span.delta);
}
const last = locate(address + size - 1);
if (conflicts[last + 1]! !== conflicts[first]!) return ambiguous();
return span.delta !== null &&
address < span.end &&
size <= span.end - address
? ok(address + span.delta)
: missing();
};
};
+47
View File
@@ -265,3 +265,50 @@ export const engineFixtureImage = (options: {
labels.copy(image, noteAt + options.notes.length);
return image;
};
/** Relocate one table and append declarations without disturbing payload bytes. */
export const appendElfRanges = (
image: Buffer,
table: "program" | "section",
ranges: readonly {
type: number;
offset: number;
size: number;
address?: number;
}[],
): Buffer => {
const is64 = image[4] === 2;
const program = table === "program";
const offsetAt = program ? (is64 ? 0x20 : 0x1c) : is64 ? 0x28 : 0x20;
const widthAt = program ? (is64 ? 0x36 : 0x2a) : is64 ? 0x3a : 0x2e;
const countAt = widthAt + 2;
const oldOffset = is64
? Number(image.readBigUInt64LE(offsetAt))
: image.readUInt32LE(offsetAt);
const oldWidth = image.readUInt16LE(widthAt);
const oldCount = image.readUInt16LE(countAt);
const width = oldWidth || (is64 ? 64 : 40);
const count = oldCount || 1; // A section table starts with its null entry.
const offset = Math.ceil(image.length / 8) * 8;
const result = Buffer.alloc(offset + (count + ranges.length) * width);
image.copy(result);
image.copy(result, offset, oldOffset, oldOffset + oldCount * oldWidth);
const word = (value: number, at: number): void => {
if (is64) result.writeBigUInt64LE(BigInt(value), at);
else result.writeUInt32LE(value, at);
};
word(offset, offsetAt);
result.writeUInt16LE(width, widthAt);
result.writeUInt16LE(count + ranges.length, countAt);
ranges.forEach((range, index) => {
const at = offset + (count + index) * width;
result.writeUInt32LE(range.type, at + (program ? 0 : 4));
word(range.offset, at + (program ? (is64 ? 8 : 4) : is64 ? 0x18 : 0x10));
word(
range.size,
at + (program ? (is64 ? 0x20 : 0x10) : is64 ? 0x20 : 0x14),
);
if (program) word(range.address ?? 0, at + (is64 ? 0x10 : 8));
});
return result;
};
+16 -2
View File
@@ -33,6 +33,7 @@ import {
import { ZipArtifactReader } from "../artifacts/ZipArtifactReader.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import {
NonRegularFileReadError,
openRegularFile,
RegularFileAdmissionFailure,
sameRegularFileState,
@@ -181,16 +182,29 @@ const mapInputFailure = (
{ max_metadata_read_bytes: APK_METADATA_READ_MAX_BYTES },
{ cause },
);
const message = cause instanceof Error ? cause.message : String(cause);
return new AnalysisInputError(operation, { cause }, [
{
path: ["path"],
reason: "invalid_format",
message: `The APK could not be read as a package: ${path}: ${message}`,
message: inputFailureMessage(path, cause),
},
]);
};
/** Name a missing or non-file selection instead of blaming package bytes. */
const inputFailureMessage = (path: string, cause: unknown): string => {
if (
cause instanceof Error &&
"code" in cause &&
(cause.code === "ENOENT" || cause.code === "ENOTDIR")
)
return `Selected APK does not exist: ${path}`;
if (cause instanceof NonRegularFileReadError)
return `Selected APK is not a regular file: ${path}`;
const message = cause instanceof Error ? cause.message : String(cause);
return `The APK could not be read as a package: ${path}: ${message}`;
};
/** Provider-owned storage failures must never be attributed to caller input. */
const mapOwnedIoFailure = (
operation: string,
+31
View File
@@ -70,6 +70,37 @@ describe("SnapshotHashScanner", () => {
});
});
it.each([49, 50, 51])(
"finds a section %i bytes after a rejected record at any chunking",
(start) => {
// A stray magic whose hash field is not hex, then a real section that
// starts inside the stray record's magic-to-hash span.
const payload = new Uint8Array(start + 52);
payload.set([0xf5, 0xf5, 0xdc, 0xdc], 0);
payload.set(
realSnapshotSection("65817c30a78bb44c3dc3771876b6010a"),
start,
);
const whole = new SnapshotHashScanner();
whole.push(payload);
expect(whole.result()).toEqual({
capped: false,
sources: 1,
candidates: ["65817c30a78bb44c3dc3771876b6010a"],
});
for (let split = 1; split < payload.length; split += 1) {
const scanner = new SnapshotHashScanner();
scanner.push(payload.subarray(0, split));
scanner.push(payload.subarray(split));
expect(scanner.result(), `split at ${split}`).toEqual(whole.result());
}
const bytewise = new SnapshotHashScanner();
for (let offset = 0; offset < payload.length; offset += 1)
bytewise.push(payload.subarray(offset, offset + 1));
expect(bytewise.result()).toEqual(whole.result());
},
);
it("ignores a magic without a following hash", () => {
const scanner = new SnapshotHashScanner();
scanner.push(Uint8Array.from([0xf5, 0xf5, 0xdc, 0xdc, 0xff, 0xff, 0xff]));
+6 -14
View File
@@ -58,17 +58,16 @@ export class SnapshotHashScanner {
private readonly candidates: string[] = [];
private readonly candidateSet = new Set<string>();
#buffer = new Uint8Array(0);
/** Absolute stream offset from which unprocessed bytes begin. */
#base = 0;
#absoluteScanFrom = 0;
push(chunk: Uint8Array): void {
const joined = new Uint8Array(this.#buffer.length + chunk.length);
joined.set(this.#buffer, 0);
joined.set(chunk, this.#buffer.length);
// Resume after the last fully processed hash so carried bytes are not
// counted twice across chunk boundaries.
let offset = Math.max(0, this.#absoluteScanFrom - this.#base);
// Carried bytes are an unprocessed pending magic or too short to hold a
// magic, so rescanning them never counts a record twice. Within a chunk
// the scan resumes after each magic, so a magic inside a previous
// record's span is found wherever the chunk boundaries fall.
let offset = 0;
let pendingMagic: number | null = null;
for (;;) {
const magic = findBytes(joined, DART_SNAPSHOT_MAGIC, offset);
@@ -96,21 +95,14 @@ export class SnapshotHashScanner {
// magic record whose field is not lowercase hex is not a source.
if (isValidHash) this.#sources += 1;
offset = magic + DART_SNAPSHOT_MAGIC.length;
this.#absoluteScanFrom =
this.#base + magic + SNAPSHOT_HASH_OFFSET + SNAPSHOT_HASH_LENGTH;
}
// Keep a pending magic for the next chunk; otherwise keep only the
// trailing bytes where a magic could still begin, so magic-free
// streams never accumulate.
const keepFrom =
pendingMagic ??
Math.max(
this.#absoluteScanFrom - this.#base,
joined.length - (DART_SNAPSHOT_MAGIC.length - 1),
);
Math.max(0, joined.length - (DART_SNAPSHOT_MAGIC.length - 1));
this.#buffer = joined.slice(keepFrom);
this.#base += keepFrom;
if (pendingMagic !== null) this.#absoluteScanFrom = this.#base;
}
result(): SnapshotHashScan {
+7 -5
View File
@@ -15,7 +15,7 @@ import { err, ok, type Result } from "../domain/result.js";
import type { GhidraInstallationInspection } from "./GhidraInstallation.js";
import {
ghidraMipsProfileParameters,
ghidraMipsSharedLanguageOverride,
ghidraMipsLanguageOverride,
} from "./GhidraMipsProfile.js";
import {
ghidraRiscvLanguageOverride,
@@ -44,8 +44,7 @@ import {
export const ghidraPinnedLanguage = (
target: BinaryTarget,
): GhidraLanguageOverride | undefined =>
ghidraMipsSharedLanguageOverride(target) ??
ghidraRiscvLanguageOverride(target);
ghidraMipsLanguageOverride(target) ?? ghidraRiscvLanguageOverride(target);
/** Resolve version-bound, deterministic semantics before Ghidra imports a target. */
export const resolveGhidraAnalysisProfile = async (
@@ -168,7 +167,7 @@ export const resolveGhidraAnalysisProfile = async (
`The caller-selected processor or compiler specification is outside the verified ${
target.architecture === "riscv"
? "generic little-endian RISC-V"
: "endian-matched MIPS32 shared-image"
: "endian-matched MIPS32"
} profile. The requested override has not been changed.`,
),
);
@@ -207,6 +206,9 @@ export const resolveGhidraAnalysisProfile = async (
...(target.availableArchitectures ?? []),
].sort(),
import_mode: "ephemeral-source-immutable",
...(target.format === "pe"
? { pdb_observations: "program-info-v1" }
: {}),
annotation_policy: "atomic-function-entry-metadata-v1",
load_image_observations: "source-mappings-entry-context-v2",
function_body_evidence: "complete-inclusive-ranges-v1",
@@ -273,7 +275,7 @@ export const resolveGhidraAnalysisProfile = async (
}
: {}),
...analyzerParameters,
...ghidraMipsProfileParameters(target),
...ghidraMipsProfileParameters(target, languageOverride),
...ghidraRiscvProfileParameters(target),
...(pspExtension?.ok === true
? {
+2
View File
@@ -117,7 +117,9 @@ describe("Ghidra function-analysis result values", () => {
});
},
);
});
describe("Ghidra reference and value-flow completeness", () => {
it.each(["reference_kinds_available", "unresolved_calls"])(
"rejects omitted %s instead of inventing complete reference observations",
(field) => {
+178 -1
View File
@@ -10,10 +10,17 @@ import { HopperProvider } from "../hopper/HopperProvider.js";
import { hopperLoaderArgsForTarget } from "../hopper/HopperAnalysisProfile.js";
import { IdaProvider } from "../ida/IdaProvider.js";
import { GhidraProvider } from "./GhidraProvider.js";
import {
ghidraMipsProfileParameters,
ghidraPinnedMipsLanguage,
} from "./GhidraMipsProfile.js";
import type { GhidraInstallationHost } from "./GhidraInstallation.js";
import { GHIDRA_SESSION_CAPABILITIES } from "./GhidraSessionValues.js";
import type { GhidraMipsSoftFloatReport } from "./GhidraMipsProfile.js";
import { ghidraProfileLanguageOverride } from "./GhidraAnalysisProfile.js";
import {
ghidraPinnedLanguage,
ghidraProfileLanguageOverride,
} from "./GhidraAnalysisProfile.js";
// Fake installation inspection tests admission/profile contracts, not Ghidra.
const host: GhidraInstallationHost = {
@@ -161,6 +168,126 @@ describe("bounded Ghidra MIPS admission", () => {
});
});
describe("recordless legacy MIPS32 admission", () => {
it("keeps recordless relocatable objects off the inferred-o32 lane", async () => {
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
const object = target({
flags: 0x50000001,
abiFlags: null,
type: 1,
});
expect(ghidra.inspectTargetSupport(object)).toMatchObject({
status: "unsupported",
});
const resolved = await ghidra.resolveAnalysisProfile(object);
expect(resolved.ok).toBe(false);
});
it.each([
[{ flags: 0x50000001 }, "EF_MIPS_ARCH_32"],
[{ flags: 0x70000001 }, "EF_MIPS_ARCH_32R2"],
] satisfies [Partial<MipsElfMetadata>, string][])(
"admits a recordless legacy header (%s) with a pinned 32-bit language",
async (change) => {
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
const little = target({ ...change, abiFlags: null });
const big = target({ ...change, abiFlags: null, byteOrder: "big" });
expect(ghidra.inspectTargetSupport(little).status).toBe("supported");
expect(ghidra.inspectTargetSupport(big).status).toBe("supported");
const resolved = await ghidra.resolveAnalysisProfile(little);
if (!resolved.ok) throw resolved.error;
expect(resolved.value.profile?.parameters).toMatchObject({
mips_support_lane: "elf32-exec-arch32-legacy-pinned-v1",
mips_abi_basis: "inferred-o32-assumption-v1",
language_id: "MIPS:LE:32:default",
compiler_spec_id: "default",
language_selection: "provider-pinned-v1",
});
const resolvedBig = await ghidra.resolveAnalysisProfile(big);
if (!resolvedBig.ok) throw resolvedBig.error;
expect(resolvedBig.value.profile?.parameters).toMatchObject({
language_id: "MIPS:BE:32:default",
});
},
);
it("requires an inspected absence; a merely unobserved record stays refused", () => {
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
const withRecord = target({ flags: 0x50000001 }) as BinaryTarget & {
mips: MipsElfMetadata;
};
const { abiFlags: _record, ...unobservedMips } = withRecord.mips;
void _record;
expect(
ghidra.inspectTargetSupport({
...withRecord,
mips: unobservedMips,
} as BinaryTarget),
).toMatchObject({
status: "unsupported",
reason: expect.stringContaining("recordless legacy header"),
});
});
it.each([
[{ flags: 0x50000021 }, "n32"],
[{ flags: 0x50000041 }, "EF_MIPS_ABI_ON32"],
[{ flags: 0x50000101 }, "EF_MIPS_32BITMODE"],
[{ flags: 0x70000101 }, "EF_MIPS_32BITMODE"],
[
{ flags: 0x50001001 },
"EF_MIPS_ARCH_32R2 for headers that declare an ABI",
],
[{ flags: 0x50000201 }, "EF_MIPS_FP64"],
[{ flags: 0x50000401 }, "EF_MIPS_NAN2008"],
[{ flags: 0x60000001 }, "32R2"],
[
{
flags: 0x50000001,
limitations: [
"MIPS section header table at file offset 96 extends beyond the captured file: examined 2 of 5 complete headers. ABI declarations in unavailable headers remain unknown.",
],
},
"complete ABI-record inspection",
],
] satisfies [Partial<MipsElfMetadata>, string][])(
"keeps refusing unverified recordless variants %j",
(change, reason) => {
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
expect(
ghidra.inspectTargetSupport(target({ ...change, abiFlags: null })),
).toMatchObject({
status: "unsupported",
reason: expect.stringContaining(reason),
});
},
);
it("a caller-selected language wins over the provider pin", () => {
const parameters = ghidraMipsProfileParameters(
target({ flags: 0x50000001, abiFlags: null }),
{ languageId: "MIPS:LE:32:default", compilerSpecId: "default" },
);
expect(parameters.language_selection).toBeUndefined();
expect(parameters.language_id).toBeUndefined();
expect(parameters).toMatchObject({
mips_support_lane: "elf32-exec-arch32-legacy-pinned-v1",
});
});
it("reads the pinned import language back only from pinned profiles", () => {
const pinned = ghidraMipsProfileParameters(
target({ flags: 0x50000001, abiFlags: null }),
);
expect(ghidraPinnedMipsLanguage(pinned)).toEqual({
languageId: "MIPS:LE:32:default",
compilerSpecId: "default",
});
const standard = ghidraMipsProfileParameters(target());
expect(ghidraPinnedMipsLanguage(standard)).toBeUndefined();
});
});
const report: GhidraMipsSoftFloatReport = {
policy: "o32-soft-float-prototype-v1",
functions: 5,
@@ -218,6 +345,56 @@ const session = async (
};
};
describe("legacy profile bindings", () => {
it("refuses a legacy endian pin committed for a different target", async () => {
const { counts, client } = await session(
target({ flags: 0x50000001, abiFlags: null, byteOrder: "big" }),
undefined,
target({ flags: 0x50000001, abiFlags: null, byteOrder: "little" }),
);
expect((await client.execute("health", {})).ok).toBe(false);
expect(counts.starts).toBe(0);
});
it.each([0x50000201, 0x50000401, 0x54000001, 0x50910001])(
"refuses unsupported same-endian legacy flags %i before startup",
async (flags) => {
const value = target({ flags, abiFlags: null });
expect(ghidraPinnedLanguage(value)).toBeUndefined();
const { counts, client } = await session(
value,
undefined,
target({ flags: 0x50000001, abiFlags: null }),
);
expect((await client.execute("health", {})).ok).toBe(false);
expect(counts.starts).toBe(0);
},
);
const unpinnedTargets: BinaryTarget[] = [
target(),
{
path: "/fixture.elf",
sha256: "a".repeat(64),
kind: "executable",
format: "elf",
architecture: "x86_64",
availableArchitectures: ["x86_64"],
},
];
it.each(unpinnedTargets)(
"refuses a pinned profile for an unpinned target $architecture",
async (value) => {
expect(ghidraPinnedLanguage(value)).toBeUndefined();
const { counts, client } = await session(
value,
undefined,
target({ flags: 0x50000001, abiFlags: null }),
);
expect((await client.execute("health", {})).ok).toBe(false);
expect(counts.starts).toBe(0);
},
);
});
describe("MIPS16 shared-image profile", () => {
const shared = (change: Partial<MipsElfMetadata> = {}) =>
target({
+115 -12
View File
@@ -1,6 +1,6 @@
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
const MIPS_FP_ABI_SOFT = 3;
const MIPS_ET_REL = 1;
@@ -15,17 +15,56 @@ const isGhidraMips16SharedTarget = (target: BinaryTarget): boolean =>
target.mips.type === MIPS_ET_DYN &&
(target.mips.flags & 0x0f000000) === MIPS16_HEADER_ASE;
/** Generic MIPS32 permits per-function ISA_MODE; a global 16e processor does not. */
export const ghidraMipsSharedLanguageOverride = (
/** Derive the verified MIPS32 import pin from this target's observed byte order. */
export const ghidraMipsLanguageOverride = (
target: BinaryTarget,
): GhidraLanguageOverride | undefined =>
isGhidraMips16SharedTarget(target) && target.architecture === "mips"
(isGhidraMips16SharedTarget(target) || hasLegacyMipsHeaderShape(target)) &&
ghidraMipsUnsupportedReason(target) === null &&
target.architecture === "mips"
? {
languageId: `MIPS:${target.mips.byteOrder === "little" ? "LE" : "BE"}:32:default`,
compilerSpecId: "default",
}
: undefined;
/**
* Recordless legacy ELF32 MIPS admission: the header declares no ABI field and
* carries no ABI flags record, so o32 is an analysis assumption derived from
* ELF32/ET_EXEC structure, never a declared fact. Ghidra's header
* auto-selection picks a 64-bit language for exactly these files, so the lane
* pins the 32-bit language instead.
*/
const hasLegacyMipsHeaderShape = (target: BinaryTarget): boolean => {
if (
target.kind !== "executable" ||
target.architecture !== "mips" ||
target.format !== "elf" ||
target.mips === undefined
)
return false;
const { flags, abiFlags, limitations } = target.mips;
const arch = flags & 0xf0000000;
return (
// The lane and its verification cover executable firmware images only;
// recordless relocatable objects stay outside the inferred-o32 assumption.
target.mips.elfClass === 32 &&
target.mips.type === MIPS_ET_EXEC &&
(arch === 0x50000000 || arch === 0x70000000) &&
(flags & 0x0000f000) === 0 &&
(flags & 0x20) === 0 &&
// EF_MIPS_ABI_ON32 (bit 0x40) declares the old n32 ABI; it is not an
// unspecified-ABI header and must not inherit the o32 assumption.
(flags & 0x40) === 0 &&
(flags & 0x100) === 0 &&
// Undefined means the record was not inspected; only an inspected
// absence establishes the recordless legacy admission. An inspection
// that could not examine every declaration source stays unknown.
abiFlags === null &&
(limitations === undefined || limitations.length === 0)
);
};
/** Keep family recognition separate from the deliberately bounded Ghidra lane. */
export const ghidraMipsUnsupportedReason = (
target: BinaryTarget,
@@ -48,13 +87,41 @@ export const ghidraMipsUnsupportedReason = (
return "MIPS16, microMIPS and other ASE encodings are outside this standard-instruction MIPS lane.";
if ((metadata.flags & 0x00ff0000) !== 0)
return "Machine-specific MIPS variants, including PSP Allegrex, need a separately supported processor profile.";
if ((metadata.flags & 0xf0000000) !== 0x70000000)
return "This Ghidra MIPS lane requires EF_MIPS_ARCH_32R2; other ISA revisions need separate verification.";
const arch = metadata.flags & 0xf0000000;
if (arch !== 0x70000000 && arch !== 0x50000000)
return "This Ghidra MIPS lane requires EF_MIPS_ARCH_32R2 or a recordless legacy EF_MIPS_ARCH_32 header; other ISA revisions need separate verification.";
const recordlessShape =
(metadata.flags & 0x0000f000) === 0 &&
(metadata.flags & 0x20) === 0 &&
metadata.abiFlags === null;
if (recordlessShape) {
if ((metadata.flags & 0x100) !== 0)
return "EF_MIPS_32BITMODE declares code for a 64-bit processor in 32-bit mode; it is outside the recordless MIPS32 admission.";
if ((metadata.flags & 0x40) !== 0)
return "EF_MIPS_ABI_ON32 declares the n32 ABI; recordless headers carrying it are outside the recordless legacy admission.";
if ((metadata.flags & 0x00000200) !== 0)
return "EF_MIPS_FP64 requires separate verification of 64-bit floating-point register semantics in this Ghidra lane.";
if ((metadata.flags & 0x00000400) !== 0)
return "EF_MIPS_NAN2008 requires separate verification of NaN encoding semantics in this Ghidra lane.";
if (hasLegacyMipsHeaderShape(target)) return null;
// A recordless relocatable object is not an incomplete inspection; the
// lane is scoped to executable firmware images by design.
if (metadata.type !== MIPS_ET_EXEC)
return "The recordless legacy admission covers ET_EXEC firmware images only; recordless relocatable objects need their own verified build, and the declared-ABI lane requires an ABI flags record.";
// The inspection could not examine every ABI declaration source, so the
// recordless admission is not established for this header.
return [
"This recordless legacy admission requires a complete ABI-record inspection; ABI declarations in unavailable headers remain unknown.",
...(metadata.limitations ?? []),
].join(" ");
}
if (
(metadata.flags & 0x0000f000) !== 0x00001000 ||
(metadata.flags & 0x20) !== 0
)
return "This Ghidra MIPS lane requires an explicit o32 ABI; unspecified, n32 and EABI targets remain unsupported.";
return "This Ghidra MIPS lane requires an explicit o32 ABI or a recordless legacy header with an unspecified ABI; n32, EABI and mixed declarations remain unsupported.";
if (arch !== 0x70000000)
return "This Ghidra MIPS lane requires EF_MIPS_ARCH_32R2 for headers that declare an ABI; EF_MIPS_ARCH_32 headers are admitted only through the recordless legacy admission.";
if ((metadata.flags & 0x00000200) !== 0)
return "EF_MIPS_FP64 requires separate verification of 64-bit floating-point register semantics in this Ghidra lane.";
if ((metadata.flags & 0x00000400) !== 0)
@@ -98,6 +165,11 @@ export const ghidraMipsUnsupportedReason = (
return null;
};
/** A legacy lane is established only after every MIPS declaration is admitted. */
export const isLegacyMipsAdmission = (target: BinaryTarget): boolean =>
hasLegacyMipsHeaderShape(target) &&
ghidraMipsUnsupportedReason(target) === null;
/** Soft-float prototype policy applied by ReaGhidraMipsSoftFloat.java after analysis. */
export const GHIDRA_MIPS_SOFT_FLOAT_STORAGE = "o32-soft-float-prototype-v1";
@@ -174,6 +246,7 @@ export const ghidraMipsSharedLimitations = (
/** Commit source ELF interpretation without confusing target ISA with host CPU. */
export const ghidraMipsProfileParameters = (
target: BinaryTarget,
languageOverride?: GhidraLanguageOverride,
): Readonly<Record<string, JsonValue>> => {
if (
target.kind !== "executable" ||
@@ -182,6 +255,18 @@ export const ghidraMipsProfileParameters = (
)
return {};
const abi = target.mips.abiFlags;
// A deliberate caller-selected language wins over the legacy pin; the pin
// exists because header auto-selection misselects a 64-bit language.
const legacy = isLegacyMipsAdmission(target);
const language = ghidraMipsLanguageOverride(target);
const pinnedLanguage =
legacy && languageOverride === undefined && language !== undefined
? {
language_id: language.languageId,
compiler_spec_id: language.compilerSpecId ?? "default",
language_selection: "provider-pinned-v1",
}
: {};
return {
mips_elf: {
elf_class: target.mips.elfClass,
@@ -231,10 +316,28 @@ export const ghidraMipsProfileParameters = (
? { mips_soft_float_storage: GHIDRA_MIPS_SOFT_FLOAT_STORAGE }
: {}),
instruction_context_evidence: "per-address-isa-mode-v1",
mips_support_lane: isGhidraMips16SharedTarget(target)
? "elf32-dyn-o32-arch32r2-mips16-local-rel32-v1"
: target.mips.type === MIPS_ET_REL
? "elf32-rel-o32-arch32r2-standard-v1"
: "elf32-exec-o32-arch32r2-standard-v3",
mips_support_lane: legacy
? "elf32-exec-arch32-legacy-pinned-v1"
: isGhidraMips16SharedTarget(target)
? "elf32-dyn-o32-arch32r2-mips16-local-rel32-v1"
: target.mips.type === MIPS_ET_REL
? "elf32-rel-o32-arch32r2-standard-v1"
: "elf32-exec-o32-arch32r2-standard-v3",
...(legacy ? { mips_abi_basis: "inferred-o32-assumption-v1" } : {}),
...pinnedLanguage,
};
};
/** Read the provider-pinned import language back from a resolved legacy profile. */
export const ghidraPinnedMipsLanguage = (
parameters: Readonly<Record<string, unknown>>,
): GhidraLanguageOverride | undefined => {
if (parameters.language_selection !== "provider-pinned-v1") return undefined;
const languageId = parameters.language_id;
const compilerSpecId = parameters.compiler_spec_id;
if (typeof languageId !== "string" || typeof compilerSpecId !== "string")
return undefined;
return compilerSpecId === "language-default"
? { languageId }
: { languageId, compilerSpecId };
};
+107
View File
@@ -1541,6 +1541,113 @@ const sessionInfo = () => ({
},
});
describe("Ghidra PDB coverage", () => {
it.each([
{ name: "missing bridge report", pdb: undefined, warns: true },
{
name: "report without a PDB reference",
pdb: {
file: null,
guid: null,
age: null,
signature: null,
version: null,
loaded: null,
},
warns: false,
},
])("distinguishes $name in direct PE searches", async ({ pdb, warns }) => {
const ghidra = provider(installationHost(), () => ({
start: () =>
Promise.resolve(
ok(pdb === undefined ? sessionInfo() : { ...sessionInfo(), pdb }),
),
callTool: () => Promise.resolve(ok([])),
close: () => Promise.resolve(ok(null)),
}));
const target = executableTarget("pe", "x86_64");
const resolved = await ghidra.resolveAnalysisProfile(target);
if (!resolved.ok || resolved.value.profile === null)
throw new Error("Expected a PE profile");
const client = ghidra.createClient(target, resolved.value.profile);
try {
const searched = await client.execute("search_procedures", {
pattern: "add_numbers",
});
if (!searched.ok) throw searched.error;
expect(searched.value.result).toEqual([]);
const warnings = searched.value.limitations.filter((limitation) =>
limitation.includes("PDB"),
);
expect(warnings).toEqual(
warns
? [
"Ghidra did not report PDB attributes; debug-symbol coverage is unknown.",
]
: [],
);
} finally {
await client.close();
}
});
const pdb = {
file: "C:\\build\\fixture.pdb",
guid: "01234567-89AB-CDEF-0123-456789ABCDEF",
age: "a",
signature: null,
version: "RSDS",
loaded: false as boolean | null,
};
it.each([false, null, true])(
"carries PDB load state %s into direct search and health Evidence",
async (loaded) => {
let starts = 0;
const ghidra = provider(installationHost(), () => ({
start: () => {
starts += 1;
return Promise.resolve(
ok({ ...sessionInfo(), pdb: { ...pdb, loaded } }),
);
},
callTool: () => Promise.resolve(ok([])),
close: () => Promise.resolve(ok(null)),
}));
const target = executableTarget("pe", "x86_64");
const resolved = await ghidra.resolveAnalysisProfile(target);
if (!resolved.ok || resolved.value.profile === null)
throw new Error("Expected a PE profile");
const client = ghidra.createClient(target, resolved.value.profile);
// No preceding health call: a name search must establish symbol coverage itself.
const searched = await client.execute("search_procedures", {
pattern: "add_numbers",
});
expect(starts).toBe(1);
if (!searched.ok) throw searched.error;
expect(searched.value.result).toEqual([]);
const health = await client.execute("health", {});
if (!health.ok) throw health.error;
expect(health.value.result).toMatchObject({ pdb: { ...pdb, loaded } });
for (const observation of [searched.value, health.value]) {
const limitations = observation.limitations.join("\n");
if (loaded === true) {
expect(limitations).toContain("loaded PDB");
expect(limitations).toContain("not an independent PDB identity");
expect(limitations).toContain("empty name search does not prove");
} else {
expect(limitations).toContain(pdb.file);
expect(limitations).toContain(pdb.guid);
expect(limitations).toContain("age (hex) a");
expect(limitations).toContain("list_procedures");
expect(limitations).toContain(
loaded === null ? "unknown" : "not loaded",
);
}
}
await client.close();
},
);
});
const executableTarget = (
format: "mach-o" | "elf" | "pe",
architecture: Extract<BinaryTarget, { format: "pe" }>["architecture"],
+70 -17
View File
@@ -20,6 +20,7 @@ import {
sameGhidraDisabledAnalyzers,
sameGhidraLanguageOverride,
} from "./GhidraAnalysisProfile.js";
import { ghidraPinnedMipsLanguage } from "./GhidraMipsProfile.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import {
@@ -77,10 +78,7 @@ import {
parseNativeAotPe,
type NativeAotPeResult,
} from "../domain/native/nativeAotPe.js";
import {
ABORTED,
waitForAbortable,
} from "../application/binary/AbortablePromise.js";
import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js";
import { nativeLoadImageObservationSchema } from "../domain/native/nativeLoadImage.js";
import {
GHIDRA_PROVIDER_IDENTITY,
@@ -90,7 +88,10 @@ import {
relationshipCoverageFor,
} from "./GhidraProviderCapabilities.js";
import type { GhidraSessionError } from "./GhidraSessionError.js";
import type { GhidraSessionInfo } from "./GhidraSessionValues.js";
import {
ghidraPdbLimitations,
type GhidraSessionInfo,
} from "./GhidraSessionValues.js";
import { ghidraExtensionFailure } from "./extensions/GhidraExtensionFailures.js";
import {
ghidraExtensionSchema,
@@ -449,13 +450,39 @@ export const createGhidraProviderClient = (input: {
}),
);
const seeds = seedProfile.data;
const languageOverride = ghidraProfileLanguageOverride(
const parameterLanguage = ghidraProfileLanguageOverride(
committedProfile.parameters,
);
const pinnedLanguage = ghidraPinnedMipsLanguage(committedProfile.parameters);
const targetLanguage = ghidraPinnedLanguage(target);
if (pinnedLanguage !== undefined && targetLanguage === undefined)
return unavailableClient(
new ProviderAdapterError("ghidra", "open_binary", {
diagnostics: {
reason:
"The committed profile pins a MIPS language that the current target does not establish; reopen an admitted target to resolve a new profile.",
},
}),
);
// Provider-pinned profiles declare their language through the same
// parameter slot caller-configured profiles use, so only an environment
// override conflicts with the legacy pin; the slot itself carries it.
if (
pinnedLanguage !== undefined &&
config.ghidraLanguageOverride !== undefined
)
return unavailableClient(
new ProviderAdapterError("ghidra", "open_binary", {
diagnostics: {
reason:
"The committed legacy MIPS profile pins its import language; REA_GHIDRA_LANGUAGE_ID/REA_GHIDRA_COMPILER_SPEC_ID cannot be combined with it. Reopen the target without the override.",
},
}),
);
if (
!sameGhidraLanguageOverride(
languageOverride,
config.ghidraLanguageOverride ?? ghidraPinnedLanguage(target),
parameterLanguage,
config.ghidraLanguageOverride ?? targetLanguage,
)
)
return unavailableClient(
@@ -466,6 +493,9 @@ export const createGhidraProviderClient = (input: {
},
}),
);
// Both caller-selected and provider-pinned languages use the validated
// committed slot; the profile cannot supply its own applicability proof.
const importLanguage = parameterLanguage;
const disabledAnalyzers = ghidraProfileDisabledAnalyzers(
committedProfile.parameters,
);
@@ -483,6 +513,7 @@ export const createGhidraProviderClient = (input: {
},
}),
);
const invalidProfile = validateGhidraExtensionProfile(
extensions,
config,
@@ -498,6 +529,7 @@ export const createGhidraProviderClient = (input: {
let extensionFailure: AnalysisError | undefined;
// Replaced by the reported outcome once the session handshake is checked.
const seedLimitations: string[] = [...ghidraSeedLimitations(seeds)];
const pdbLimitations: string[] = [];
// Replaced by the reported storage outcome once the handshake is checked.
const softFloatLimitations: string[] = [
...ghidraMipsSoftFloatLimitations(softFloat),
@@ -523,6 +555,13 @@ export const createGhidraProviderClient = (input: {
...(target.kind === "executable" && target.architecture === "mips"
? (target.mips.limitations ?? [])
: []),
...(committedProfile.parameters.mips_abi_basis ===
"inferred-o32-assumption-v1"
? [
"The ELF header declares no ABI field and no ABI flags record was observed; o32 calling conventions are an analysis assumption of this lane, not a declared fact.",
"Floating-point ABI semantics are unverified for this recordless legacy admission.",
]
: []),
...ghidraMipsRelocatableLimitations(target),
...ghidraMipsSharedLimitations(target),
...ghidraRiscvLimitations(target),
@@ -563,7 +602,9 @@ export const createGhidraProviderClient = (input: {
baseAddr: target.entryPoint,
},
}),
...(languageOverride === undefined ? {} : { languageOverride }),
...(importLanguage === undefined
? {}
: { languageOverride: importLanguage }),
...(config.ghidraDisabledAnalyzers === undefined
? {}
: { disabledAnalyzers: config.ghidraDisabledAnalyzers }),
@@ -588,13 +629,13 @@ export const createGhidraProviderClient = (input: {
expectedCompilerSpecId: "default",
}
: rawLanguage === undefined
? languageOverride === undefined
? importLanguage === undefined
? {}
: {
expectedLanguageId: languageOverride.languageId,
...(languageOverride.compilerSpecId === undefined
expectedLanguageId: importLanguage.languageId,
...(importLanguage.compilerSpecId === undefined
? {}
: { expectedCompilerSpecId: languageOverride.compilerSpecId }),
: { expectedCompilerSpecId: importLanguage.compilerSpecId }),
}
: {
expectedLanguageId: rawLanguage.languageId,
@@ -609,10 +650,16 @@ export const createGhidraProviderClient = (input: {
...(context === undefined ? {} : { runId: context.runId }),
logger: logger.child({ layer: "ghidra-bridge" }),
});
const checkExtensions = async (
const checkSessionObservations = async (
operation: AnalysisOperation,
info: GhidraSessionInfo,
): Promise<AnalysisError | undefined> => {
if (target.format === "pe")
pdbLimitations.splice(
0,
pdbLimitations.length,
...ghidraPdbLimitations(info.pdb),
);
const softFloatReason = ghidraMipsSoftFloatFailure(
softFloat,
info.mips_soft_float_storage,
@@ -664,6 +711,7 @@ export const createGhidraProviderClient = (input: {
...softFloatLimitations,
...ghidraExtensionLimitations(extensions),
...seedLimitations,
...pdbLimitations,
...(releaseLimitation === undefined ? [] : [releaseLimitation]),
];
const nativeAotOwner =
@@ -735,7 +783,7 @@ export const createGhidraProviderClient = (input: {
config.ghidraStartupTimeoutMs,
),
);
const failed = await checkExtensions(operation, started.value);
const failed = await checkSessionObservations(operation, started.value);
if (failed !== undefined) return err(failed);
return ok(
createAnalysisExecution(started.value, committedProfile.provider, {
@@ -748,7 +796,12 @@ export const createGhidraProviderClient = (input: {
? parseGhidraFunctionInput(operation, parameters)
: parseGhidraInventoryInput(operation, parameters);
if (!input.ok) return input;
if (extensions.length > 0 || seeds !== undefined || softFloat) {
if (
target.format === "pe" ||
extensions.length > 0 ||
seeds !== undefined ||
softFloat
) {
const started = await client.start(options?.signal, options?.progress);
if (!started.ok)
return err(
@@ -758,7 +811,7 @@ export const createGhidraProviderClient = (input: {
config.ghidraStartupTimeoutMs,
),
);
const failed = await checkExtensions(operation, started.value);
const failed = await checkSessionObservations(operation, started.value);
if (failed !== undefined) return err(failed);
}
const called = await client.callTool(operation, input.value, {
+43
View File
@@ -52,6 +52,49 @@ describe("Ghidra DOS import commitment", () => {
});
});
describe("Ghidra PDB observations", () => {
const pdb = {
file: "C:\\build\\fixture.pdb",
guid: "01234567-89AB-CDEF-0123-456789ABCDEF",
age: "a",
signature: null,
version: "RSDS",
loaded: false,
};
it("retains the referenced identity and observed load state", () => {
const parsed = parseGhidraSessionInfo({ ...session(), pdb }, expected);
if (!parsed.ok) throw parsed.error;
expect(parsed.value.pdb).toEqual(pdb);
});
it("preserves missing attributes as unknown", () => {
const unknown = Object.fromEntries(
Object.keys(pdb).map((key) => [key, null]),
);
const parsed = parseGhidraSessionInfo(
{ ...session(), pdb: unknown },
expected,
);
if (!parsed.ok) throw parsed.error;
expect(parsed.value.pdb).toEqual(unknown);
});
it.each([
{ ...pdb, loaded: "false" },
{ ...pdb, age: 1 },
{
guid: pdb.guid,
age: pdb.age,
signature: null,
version: "RSDS",
loaded: false,
},
{ ...pdb, matched: true },
])("rejects malformed PDB reports", (report) => {
expect(
parseGhidraSessionInfo({ ...session(), pdb: report }, expected).ok,
).toBe(false);
});
});
describe("Ghidra MIPS soft-float storage report", () => {
const valid = {
policy: "o32-soft-float-prototype-v1",
+71
View File
@@ -25,6 +25,13 @@ export const GHIDRA_MUTATING_OPERATIONS: ReadonlySet<string> = new Set([
...GHIDRA_NAMING_OPERATIONS,
]);
// Shared wire budget: Java bounds the aggregate before serializing the handshake.
const PDB_ATTRIBUTE_UTF16_BUDGET = 4096;
const pdbAttributeSchema = z
.string()
.max(PDB_ATTRIBUTE_UTF16_BUDGET)
.nullable();
const capabilitySchema = z.enum(GHIDRA_SESSION_CAPABILITIES);
const sessionInfoSchema = z
@@ -41,6 +48,39 @@ const sessionInfoSchema = z
read_only: z.boolean(),
analysis_complete: z.boolean(),
analysis_timed_out: z.boolean(),
/** Program Information attributes; absent load state remains unknown. */
pdb: z
.strictObject({
file: pdbAttributeSchema,
guid: pdbAttributeSchema,
/** Ghidra stores CodeView age as a hexadecimal string. */
age: pdbAttributeSchema,
signature: pdbAttributeSchema,
version: pdbAttributeSchema,
loaded: z.boolean().nullable(),
resource_limit: z
.strictObject({
utf16_budget: z.literal(PDB_ATTRIBUTE_UTF16_BUDGET),
omitted_attributes: z
.array(z.enum(["file", "guid", "age", "signature", "version"]))
.min(1)
.max(5),
})
.optional(),
})
.refine(
(pdb) =>
[
pdb.file,
pdb.guid,
pdb.age,
pdb.signature,
pdb.version,
].reduce<number>((sum, value) => sum + (value?.length ?? 0), 0) <=
PDB_ATTRIBUTE_UTF16_BUDGET,
"PDB attributes exceed the aggregate wire budget",
)
.optional(),
analysis_extensions: z.array(ghidraExtensionResultSchema).optional(),
analysis_seeds: ghidraSeedReportSchema.optional(),
mips_soft_float_storage: z
@@ -68,6 +108,37 @@ const sessionInfoSchema = z
/** Authenticated metadata produced after Ghidra finishes auto-analysis. */
export type GhidraSessionInfo = z.infer<typeof sessionInfoSchema>;
/** Describe missing PDB authority without claiming all names are generated. */
export const ghidraPdbLimitations = (
pdb: GhidraSessionInfo["pdb"],
): readonly string[] => {
if (pdb === undefined)
return [
"Ghidra did not report PDB attributes; debug-symbol coverage is unknown.",
];
const limitations: string[] = [];
if (pdb.resource_limit !== undefined)
limitations.push(
`PDB attributes ${pdb.resource_limit.omitted_attributes.join(", ")} were omitted because the handshake's ${pdb.resource_limit.utf16_budget}-UTF-16-unit PDB attribute budget was exhausted. Omitted values remain unknown; they were not truncated or reported as absent.`,
);
if (pdb.loaded === true)
return [
...limitations,
"Ghidra reports a loaded PDB; this is not an independent PDB identity or complete symbol/type-coverage attestation. Original names and types may still be missing; an empty name search does not prove a procedure is absent. Use list_procedures and address-based analysis to inspect recovered functions.",
];
if (
[pdb.file, pdb.guid, pdb.age, pdb.signature, pdb.version].every(
(value) => value === null,
)
)
return limitations;
const state = pdb.loaded === false ? "not loaded" : "load state unknown";
return [
...limitations,
`The target references PDB ${pdb.file ?? "(file unknown)"} (GUID ${pdb.guid ?? "unknown"}, age (hex) ${pdb.age ?? "unknown"}, signature ${pdb.signature ?? "unknown"}, version ${pdb.version ?? "unknown"}); Ghidra reports ${state}. Original names and types may be missing; an empty name search does not prove a procedure is absent. Use list_procedures and address-based analysis to inspect recovered functions. REA does not admit a caller-selected PDB companion.`,
];
};
/** Require exact run, provider, and profile identity from the Java bridge. */
export const parseGhidraSessionInfo = (
value: JsonValue,
+32 -3
View File
@@ -13,6 +13,7 @@ import { z } from "zod";
import type { IdaConfiguration } from "./IdaConfiguration.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
/** Injectable MCP boundary used by the provider and transport conformance tests. */
export interface IdaMcpConnection {
@@ -142,8 +143,30 @@ export const createIdaMcpConnection = (
environment: Readonly<NodeJS.ProcessEnv>,
): IdaMcpConnection => {
const client = new Client({ name: "rea-ida-provider", version: "1" });
let stderr = Buffer.alloc(0);
let stderrBytes = 0;
const transportFailure = (cause: unknown): never => {
throw redactIdaTransportFailure(cause, config);
const failure = redactIdaTransportFailure(cause, config);
if (stderrBytes === 0) throw failure;
let start = 0;
// The byte tail may start inside a UTF-8 code point. Retain whole units.
if (stderrBytes > stderr.length)
while (start < stderr.length && (stderr[start]! & 0xc0) === 0x80) start++;
const diagnostic = redactIdaTransportFailure(
new Error(stderr.subarray(start).toString("utf8")),
config,
).message;
throw new ProviderAdapterError("ida", "transport", {
cause: failure,
diagnostics: { reason: failure.message },
capturedOutput: {
stdout: "",
stderr: diagnostic,
truncated: stderrBytes > stderr.length - start,
stdout_bytes: 0,
stderr_bytes: stderrBytes,
},
});
};
const transport =
"command" in config
@@ -169,9 +192,15 @@ export const createIdaMcpConnection = (
: new StreamableHTTPClientTransport(new URL(config.url), {
requestInit: { headers: config.headers, redirect: "error" },
});
// Drain proxy diagnostics without persisting ambient environment or transport credentials.
// Keep a bounded diagnostic tail for genuine failures; never persist ambient variables.
if (transport instanceof StdioClientTransport)
transport.stderr?.on("data", () => undefined);
transport.stderr?.on("data", (chunk: Buffer) => {
stderrBytes += chunk.length;
const combined = Buffer.concat([stderr, chunk]);
stderr = Buffer.from(
combined.subarray(Math.max(0, combined.length - 16_384)),
);
});
return {
async connect() {
await client
+4
View File
@@ -243,6 +243,10 @@ describe("native IDA provider observations", () => {
expect(dossier.value.result).toMatchObject({
callers: [],
callees: [{ address: "0x2000", name: "puts" }],
facet_availability: {
callers: { available: false },
callees: { available: true },
},
});
if (more)
expect(dossier.value.limitations).toContain(
+46 -2
View File
@@ -70,6 +70,9 @@ const identity = (fn: IdaFunction) => ({
interface IdaRelationships {
readonly items: ReturnType<typeof identity>[];
readonly coverage: RelationshipCoverage;
readonly availability:
| { readonly available: true }
| { readonly available: false; readonly reason: string };
}
/** The only lookup answers upstream reports for a name or address that is not a function. */
@@ -469,7 +472,14 @@ export class IdaOperationRunner {
};
if (this.readsCallGraph(direction)) {
coverage = await this.addCallGraphCallees(fn, result);
return { items: [...result.values()], coverage };
return {
items: [...result.values()],
coverage,
availability:
coverage.status === "unknown"
? { available: false, reason: coverage.reason }
: { available: true },
};
}
if (this.protocol === "legacy") {
const value = await this.call(
@@ -491,6 +501,10 @@ export class IdaOperationRunner {
);
return {
items: [],
availability: {
available: false,
reason: "Upstream xrefs do not establish direct caller relationships.",
},
coverage: {
status: "unknown",
reason:
@@ -555,7 +569,11 @@ export class IdaOperationRunner {
result.set(resolved.address, resolved);
}
}
return { items: [...result.values()], coverage };
return {
items: [...result.values()],
coverage,
availability: { available: true },
};
}
async run(
@@ -694,6 +712,32 @@ export class IdaOperationRunner {
basic_blocks: [],
native_api: null,
native_value_flow: null,
facet_availability: {
pseudocode:
pseudocode === null
? { available: false, reason: "IDA did not supply pseudocode." }
: { available: true },
assembly: { available: true },
comments: {
available: false,
reason: "IDA adapter does not expose typed comments.",
},
callers: callers.availability,
callees: callees.availability,
references: {
available: false,
reason: "IDA adapter does not expose typed reference edges.",
},
strings_names: {
available: false,
reason:
"IDA adapter does not expose function-referenced strings and names.",
},
cfg: {
available: false,
reason: "IDA adapter does not expose basic blocks.",
},
},
limitations: [
...IDA_LIMITATIONS,
...this.limitations,
+231
View File
@@ -9,6 +9,7 @@ import {
import { IdaSessionClient } from "./IdaSessionClient.js";
import { functionDossierSchema } from "../domain/hopperValues.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
const roots: string[] = [];
@@ -31,6 +32,7 @@ const LIVE_PEER = {
const fixture = async (
mode: "attached" | "headless" = "attached",
timeoutMs = 1000,
protocol?: "native",
) => {
const { root, target } = await createIdaTarget();
roots.push(root);
@@ -41,6 +43,7 @@ const fixture = async (
args: [],
env: {},
mode,
...(protocol === undefined ? {} : { protocol }),
timeoutMs,
workspaceRoot: root,
},
@@ -709,6 +712,74 @@ describe("headless IDA non-busy health payloads", () => {
});
});
describe("IDA compatibility profile mismatch", () => {
it("reports the native profile for an incompatible catalog", async () => {
const { producer, client } = await fixture("attached", 1000, "native");
producer.tools = [];
const result = await client.execute("health", {});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected incompatible native catalog");
expect(projectAnalysisError(result.error).details).toMatchObject({
diagnostics: {
mode: "attached",
expected_profile: "native",
missing_tools: expect.arrayContaining(["decompile"]),
},
});
expect(producer.calls).toEqual([]);
expect((await client.close()).ok).toBe(true);
});
it("names every missing tool so the caller can identify the upstream profile", async () => {
const { producer, client } = await fixture("headless");
producer.tools = [
"idb_open",
"idb_list",
"server_health",
"list_funcs",
"lookup_funcs",
"find_regex",
"decompile",
"disasm",
"callees",
"xrefs_to",
];
const result = await client.execute("health", {});
expect(result.ok, "an incomplete profile cannot serve analysis").toBe(
false,
);
if (result.ok) return;
const projected = projectAnalysisError(result.error);
expect(
projected.details,
"the absent tool and the expected profile are both reported",
).toMatchObject({
provider_id: "ida",
diagnostics: {
mode: "headless",
expected_profile: "database-supervisor",
missing_tools: ["idb_close"],
},
});
});
it("reports the legacy profile when an attached producer serves modern tools", async () => {
const { producer, client } = await fixture("attached");
producer.tools = ["server_health", "lookup_funcs", "decompile", "disasm"];
const result = await client.execute("health", {});
expect(result.ok, "an incomplete profile cannot serve analysis").toBe(
false,
);
if (result.ok) return;
expect(
projectAnalysisError(result.error).details,
"attached mode names the legacy profile it expected",
).toMatchObject({
diagnostics: { mode: "attached", expected_profile: "legacy-1.4" },
});
});
});
describe("headless IDA lifecycle boundaries", () => {
it("never closes an unowned worker even when open echoes the requested private identity", async () => {
const { producer, client } = await fixture("headless");
@@ -1006,6 +1077,7 @@ describe("headless IDA cleanup diagnostics", () => {
backend: "worker",
owned: false,
input_path: producer.inputPath,
is_active: false,
},
),
);
@@ -1296,3 +1368,162 @@ describe("headless IDA cleanup verification", () => {
expect(await readdir(root)).toEqual(["target.elf"]);
});
});
it("retains a conflicting requested session ID during pre-close recovery", async () => {
const { producer, client, root } = await fixture("headless");
producer.overrideCall = (name) =>
name === "idb_list"
? {
sessions: [
{
session_id: String(producer.database),
input_path: "/conflicting/input",
owned: true,
backend: "worker",
is_active: false,
},
],
}
: undefined;
expect((await client.execute("health", {})).ok).toBe(false);
const requested = String(producer.database);
const result = await client.close();
expect(result).toMatchObject(
reportsSessions({
session_id: requested,
input_path: "/conflicting/input",
owned: true,
backend: "worker",
is_active: false,
}),
);
expect(producer.calls.some(({ name }) => name === "idb_close")).toBe(false);
expect(
(await readdir(root)).some((name) => name.startsWith("rea-ida-")),
).toBe(true);
});
it.each(["unavailable", "malformed"] as const)(
"does not invent a worker after explicit rejection and %s inventory",
async (kind) => {
const { producer, client } = await fixture("headless");
producer.overrideCall = (name) =>
name === "idb_open"
? { error: "rejected before worker creation" }
: name === "idb_list" && kind === "malformed"
? {}
: undefined;
expect((await client.execute("health", {})).ok).toBe(false);
producer.beforeCall = async (name) => {
if (name === "idb_list" && kind === "unavailable")
throw new Error("inventory unavailable");
};
const result = await client.close();
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected retained cleanup");
expect(result.error).not.toHaveProperty("diagnostics.upstream_sessions");
},
);
it.each(["idb_close", "idb_list", "connection_close"])(
"preserves transport stderr through cleanup at %s",
async (stage) => {
const { producer, client } = await fixture("headless");
expect((await client.execute("health", {})).ok).toBe(true);
const failure = new ProviderAdapterError("ida", "transport", {
diagnostics: {
reason: "upstream transport closed",
},
capturedOutput: {
stdout: "",
stderr: "IDA shutdown diagnostic",
truncated: false,
},
});
const originalClose = producer.close.bind(producer);
producer.beforeCall = async (name) => {
if (name === stage) throw failure;
};
if (stage === "connection_close")
producer.close = async () => {
throw failure;
};
try {
const result = await client.close();
if (result.ok) throw new Error("expected cleanup failure");
expect(result.error.capturedOutput?.stderr).toBe(
"IDA shutdown diagnostic",
);
expect(result.error.diagnostics).toMatchObject({
failure_reason: "upstream transport closed",
});
expect(result.error.cleanupIncomplete).toBe(true);
} finally {
delete producer.beforeCall;
producer.close = originalClose;
await client.close();
}
},
);
it("binds retained transport diagnostics to the requested operation and recovery", async () => {
const { producer, client } = await fixture("attached");
await client.execute("health", {});
producer.beforeCall = async (name) => {
if (name === "list_functions")
throw new ProviderAdapterError("ida", "transport", {
diagnostics: { reason: "upstream closed" },
capturedOutput: {
stdout: "",
stderr: "IDA diagnostic",
truncated: false,
},
});
};
const result = await client.execute("list_procedures", {});
if (result.ok) throw new Error("expected upstream failure");
expect(projectAnalysisError(result.error)).toMatchObject({
details: {
operation: "list_procedures",
diagnostics: {
reason: "upstream closed",
recovery: expect.stringContaining("docs/ida-provider.md"),
},
captured_output: { stderr: "IDA diagnostic" },
},
});
await client.close();
});
it("retains transport diagnostics on a cancellation regardless of stderr", async () => {
const { producer, client } = await fixture("attached");
await client.execute("health", {});
const controller = new AbortController();
producer.beforeCall = async (name) => {
if (name === "list_functions") {
controller.abort();
throw new ProviderAdapterError("ida", "transport", {
diagnostics: { reason: "upstream closed after cancellation" },
capturedOutput: {
stdout: "",
stderr: "shutdown diagnostic",
truncated: false,
},
});
}
};
const result = await client.execute(
"list_procedures",
{},
{ signal: controller.signal },
);
if (result.ok) throw new Error("expected cancellation");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cancelled",
details: {
diagnostics: { reason: "upstream closed after cancellation" },
captured_output: { stderr: "shutdown diagnostic" },
},
});
await client.close();
});
+88 -22
View File
@@ -1,8 +1,5 @@
import { z } from "zod";
import {
ABORTED,
waitForAbortable,
} from "../application/binary/AbortablePromise.js";
import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js";
import {
createAnalysisExecution,
type AnalysisClient,
@@ -101,6 +98,8 @@ interface UpstreamSession {
readonly owned: boolean | null;
/** Last inventoried input binding; null until upstream reports it. */
readonly input_path: string | null;
/** Last inventoried activity; null before upstream reports it. */
readonly is_active: boolean | null;
}
/** A failed cleanup retains its private workspace and reports the remaining resource. */
@@ -114,10 +113,18 @@ class IdaCleanupError extends ProviderAdapterError {
) {
super("ida", "close", {
cause,
capturedOutput:
cause instanceof AnalysisError ? cause.capturedOutput : undefined,
diagnostics: {
...(cause instanceof AnalysisError ? cause.diagnostics : undefined),
reason:
"IDA cleanup could not be verified; the remaining connection or private workspace is retained for retry.",
failure_reason: cause instanceof Error ? cause.message : String(cause),
failure_reason:
cause instanceof AnalysisError
? (cause.diagnostics?.reason ?? cause.message)
: cause instanceof Error
? cause.message
: String(cause),
workspace: path,
...(sessions === undefined
? {}
@@ -125,15 +132,16 @@ class IdaCleanupError extends ProviderAdapterError {
upstream_sessions: {
state: "unverified",
sessions: sessions.map(
({ session_id, backend, owned, input_path }) => ({
({ session_id, backend, owned, input_path, is_active }) => ({
session_id,
backend,
owned,
input_path,
is_active,
}),
),
reason:
"Release of upstream sessions matching the requested session ID or private input was not confirmed; input_path preserves the last observed binding and is null when no inventory has reported it. A worker outlives its supervisor and may keep running until it finishes and reaches its idle timeout; exiting REA does not stop it. A gui session belongs to an IDA instance REA does not control. An empty session_id means upstream reported none; owned is null when no inventory has reported ownership; an empty list means the requested worker's close was confirmed but no inventory has identified any remaining session.",
"Release of upstream sessions matching the requested session ID or private input was not confirmed; input_path preserves the last observed binding and is null when no inventory has reported it. is_active preserves registry activity and is null when unknown; it does not establish process liveness. A worker outlives its supervisor and may keep running until it finishes and reaches its idle timeout; exiting REA does not stop it. A gui session belongs to an IDA instance REA does not control. An empty session_id means upstream reported none; owned is null when no inventory has reported ownership; an empty list means the requested worker's close was confirmed but no inventory has identified any remaining session.",
},
}),
},
@@ -378,15 +386,47 @@ export class IdaSessionClient implements AnalysisClient {
context: IdaOperationFailureContext,
) {
let failure: AnalysisError;
if (
if (wasCancelled(options))
failure = new AnalysisCancelledError(operation, {
cause,
...(cause instanceof AnalysisError
? {
capturedOutput: cause.capturedOutput,
diagnostics: cause.diagnostics,
partialObservation: cause.partialObservation,
cleanup:
cause.cleanup ??
(cause.cleanupIncomplete
? {
reason: cause.message,
resources: cause.cleanupResources,
}
: undefined),
}
: {}),
});
else if (
cause instanceof ProviderAdapterError &&
cause.operation === "transport"
)
failure = new ProviderAdapterError("ida", operation, {
cause,
capturedOutput: cause.capturedOutput,
partialObservation: cause.partialObservation,
cleanup: cause.cleanup,
diagnostics: {
...cause.diagnostics,
recovery:
"Check the configured upstream MCP registration and selected target; see docs/ida-provider.md.",
},
});
else if (
cause instanceof AnalysisError &&
(cause.partialObservation !== undefined ||
cause.cleanupIncomplete ||
cause.capturedOutput !== undefined)
)
failure = cause;
else if (wasCancelled(options))
failure = new AnalysisCancelledError(operation);
else if (cause instanceof AnalysisError) failure = cause;
else if (cause instanceof z.ZodError)
failure = new AnalysisOutputError(
@@ -483,10 +523,27 @@ export class IdaSessionClient implements AnalysisClient {
? legacyTools
: modernTools;
const missing = expected.filter((name) => !tools.has(name));
if (missing.length > 0)
throw new AnalysisProtocolError(
`IDA MCP ${this.config.protocol === "native" ? "native attached" : this.config.mode} compatibility profile is missing tools: ${missing.join(", ")}. Native attached mode requires the native IDA MCP tool catalog; legacy attached mode requires the legacy 1.4 profile; headless mode requires the database supervisor profile. See docs/ida-provider.md.`,
);
if (missing.length > 0) {
const summary = `IDA MCP ${this.config.protocol === "native" ? "native attached" : this.config.mode} compatibility profile is missing tools: ${missing.join(", ")}. Native attached mode requires the native IDA MCP tool catalog; legacy attached mode requires the legacy 1.4 profile; headless mode requires the database supervisor profile. See docs/ida-provider.md.`;
// The caller cannot act on a profile mismatch it never sees, so the
// missing names travel as adapter diagnostics rather than a bare message.
throw new ProviderAdapterError("ida", "initialize", {
userMessage: summary,
diagnostics: {
reason: summary,
mode: this.config.mode,
expected_profile:
this.config.protocol === "native"
? "native"
: this.config.mode === "attached"
? "legacy-1.4"
: "database-supervisor",
missing_tools: [...missing],
recovery:
"Install an IDA MCP build that serves the selected profile; see docs/ida-provider.md.",
},
});
}
if (this.config.mode === "headless") {
this.#workspace = await IdaWorkspace.allocate(
this.target,
@@ -637,7 +694,12 @@ export class IdaSessionClient implements AnalysisClient {
*/
#unreleasedSessions(): readonly UpstreamSession[] | undefined {
if (this.#blockingSessions !== undefined) return this.#blockingSessions;
if (!this.#openAttempted || this.#workspace === undefined) return undefined;
if (
!this.#openAttempted ||
this.#workspace === undefined ||
this.#openRejected
)
return undefined;
return this.#databaseCloseCompleted
? []
: [
@@ -646,6 +708,7 @@ export class IdaSessionClient implements AnalysisClient {
backend: "worker",
owned: null,
input_path: null,
is_active: null,
},
];
}
@@ -665,12 +728,15 @@ export class IdaSessionClient implements AnalysisClient {
): boolean {
this.#blockingSessions =
entries.length > 0
? entries.map(({ session_id, backend, owned, input_path }) => ({
session_id,
backend,
owned,
input_path,
}))
? entries.map(
({ session_id, backend, owned, input_path, is_active }) => ({
session_id,
backend,
owned,
input_path,
is_active,
}),
)
: undefined;
return entries.length > 0;
}
@@ -727,7 +793,7 @@ export class IdaSessionClient implements AnalysisClient {
);
if (this.#database === undefined && blocked)
throw new AnalysisProtocolError(
"An unowned worker still uses the private workspace; it was retained.",
"A registered session still matches the requested ID or private input without a verified private worker binding; the workspace was retained.",
);
if (
this.#database === undefined &&
@@ -83,6 +83,7 @@ export class JavaScriptAnalysisWorker {
readonly #resultBudgetBytes: number;
/** Null when the runtime enforces the V8 heap flags instead. */
readonly #processMemoryLimitBytes: number | null;
readonly #onStdinError = (): void => {};
readonly #onStdout = (chunk: Buffer | string): void => {
try {
this.#pending +=
@@ -784,20 +785,40 @@ export class JavaScriptAnalysisWorker {
if (this.#supervisor !== undefined) {
const supervisor = this.#supervisor;
const stopped = await supervisor.stop();
supervisor.launch.process.stdout?.off("data", this.#onStdout);
if (stopped.status === "incomplete") {
try {
const stdin = supervisor.launch.process.stdin;
if (
stdin !== undefined &&
stdin !== null &&
!stdin.destroyed &&
!stdin.writableEnded
) {
stdin.off("error", this.#onStdinError);
stdin.once("error", this.#onStdinError);
stdin.end();
}
} catch {
// Cooperative protocol stdin may already be closed or broken.
}
this.#resetState();
pendingCleanup.add(this);
return this.#cleanupError(stopped.reason, original);
}
supervisor.launch.process.stdout?.off("data", this.#onStdout);
supervisor.dispose();
this.#supervisor = undefined;
}
this.#resetState();
return undefined;
}
#resetState(): void {
this.#ready = false;
this.#frames = [];
this.#pending = "";
this.#decoder = new StringDecoder("utf8");
this.#protocolFailure = undefined;
return undefined;
}
}
@@ -157,6 +157,7 @@ const electron = z
z.strictObject({
entry_kind: z.enum(["bridge-member", "ipc-handler"]),
entry: z.string(),
entry_path: strings.optional(),
channel: z.string().nullable(),
terminal: z.string(),
resolution: z.literal("candidate"),
@@ -181,6 +182,13 @@ const electron = z
),
}),
)
.transform((paths) =>
paths.map(({ entry_kind, entry, entry_path, ...rest }) =>
entry_path === undefined
? { entry_kind, entry, ...rest }
: { entry_kind, entry, entry_path, ...rest },
),
)
.optional(),
browser_windows: z.array(
z.union([
@@ -267,11 +267,6 @@ const inspectLeaf = (
consumeRecords(budget, Array.isArray(rawNames) ? rawNames.length : 0);
consumeRecords(budget, Array.isArray(rawContents) ? rawContents.length : 0);
options.check?.();
if (options.profile === "browser-collection" && !Array.isArray(rawNames))
throw new SourceMapFormatFailure(
"format",
"Source-map leaf requires a names array.",
);
if (
options.profile === "browser-collection" &&
!hasValidSourceMapContents(

Some files were not shown because too many files have changed in this diff Show More