fix(setup): reconcile client plans and native registration fields

This commit is contained in:
REA Maintainers
2026-10-13 22:55:53 +08:00
449 changed files with 24660 additions and 3385 deletions
+30
View File
@@ -810,6 +810,36 @@ exit 1`,
expect(result.error.message).toContain("overwrite");
});
it.each([
["offline", false, "error: device offline"],
["unauthorized", false, "error: device unauthorized"],
["offline", true, "error: device offline"],
] as const)(
"reports the %s device state when the push existence probe cannot run (overwrite %s)",
async (state, overwrite, stderr) => {
const { binary, root } = await writeAdbStub(
(stubRoot) => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
if [ "$1" = "-s" ]; then printf '%s\\n' "$3" >> "${stubRoot}/calls"; printf '%s\\n' "${stderr}" >&2; exit 1; fi`,
);
const localFile = join(root, "payload.bin");
await writeFile(localFile, "x");
const projected = await refusedBy(providerOver(binary), {
operation: "push_adb_file",
input: {
serial: "emulator-5554",
local_path: localFile,
device_path: "/data/local/tmp/payload.bin",
overwrite,
},
});
// Existence is unknown, so nothing is claimed about the path and no push runs.
expect(projected).toMatchObject({ code: "unsupported_target" });
expect(projected.message).toContain(state);
expect(projected.message).not.toContain("already exists");
expect(await readFile(join(root, "calls"), "utf8")).toBe("shell\n");
},
);
it("reports a local push source that does not exist", async () => {
const { binary } = await writeAdbStub(
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
+8 -10
View File
@@ -1623,17 +1623,15 @@ export class AdbProvider {
{ timeoutMs: SETTINGS_TIMEOUT_MS, maxOutputBytes: 1024 },
signal,
);
let deviceExists: boolean;
if (existsProbe.ok) deviceExists = true;
else if (existsProbe.error instanceof AnalysisProtocolError)
deviceExists = false;
else if (existsProbe.error instanceof AnalysisTimeoutError)
// `test -e` exits nonzero with no adb diagnosis when the path is absent.
// Any other probe failure leaves existence unknown, so it is reported as
// is rather than read as an existing path or followed by a push.
if (
!existsProbe.ok &&
!(existsProbe.error instanceof AnalysisProtocolError)
)
return existsProbe;
else if (existsProbe.error instanceof AnalysisCancelledError)
return existsProbe;
else if (existsProbe.error instanceof AnalysisResourceConstraintError)
return existsProbe;
else deviceExists = true; // authorization/refusal states surface on push instead
const deviceExists = existsProbe.ok;
if (deviceExists && !input.overwrite)
return err(
new AnalysisOutputError(
+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) {
+11
View File
@@ -50,6 +50,13 @@ export interface AnalysisExecution {
readonly limitations: readonly string[];
/** Provider-owned completeness assessment for caller/callee observations. */
readonly relationshipCoverage?: RelationshipCoverage;
/**
* Whether the provider capped an `xrefs` read: true when it reported a
* truncation, false when it explicitly reported none. Absent when it reports
* nothing, which is not a completeness claim. Never part of Evidence or tool
* output.
*/
readonly referencesTruncated?: boolean;
readonly locations: readonly EvidenceLocation[];
readonly subject: EvidenceSubjectTarget | null;
}
@@ -59,6 +66,7 @@ interface CreateAnalysisExecutionOptions {
readonly analysisProfile?: AnalysisProfileCommitment;
readonly limitations?: readonly string[];
readonly relationshipCoverage?: RelationshipCoverage;
readonly referencesTruncated?: boolean;
readonly locations?: readonly EvidenceLocation[];
readonly subject?: EvidenceSubjectTarget;
}
@@ -103,6 +111,9 @@ export function createAnalysisExecution(
options.relationshipCoverage,
),
}),
...(options.referencesTruncated === undefined
? {}
: { referencesTruncated: options.referencesTruncated }),
locations: [...(options.locations ?? [])],
subject: options.subject ?? null,
};
+7 -5
View File
@@ -76,6 +76,8 @@ export const parseBinaryTarget = async (
await access(candidate, constants.R_OK);
throwIfTargetResolutionCancelled(signal);
const canonical = await realpath(candidate);
// Windows native admission must inspect the caller-selected reparse components.
const sourcePath = process.platform === "win32" ? candidate : canonical;
throwIfTargetResolutionCancelled(signal);
const resolved = await resolveAppBundle(canonical);
throwIfTargetResolutionCancelled(signal);
@@ -113,7 +115,7 @@ export const parseBinaryTarget = async (
);
return ok({
path,
sourcePath: canonical,
sourcePath,
sha256: await sha256Handle(handle, path, metadata, signal),
kind: "executable",
format: "raw-binary",
@@ -152,7 +154,7 @@ export const parseBinaryTarget = async (
);
return ok({
path,
sourcePath: canonical,
sourcePath,
sha256: await sha256Handle(handle, path, metadata, signal),
kind: "executable",
format: "dos-com",
@@ -166,7 +168,7 @@ export const parseBinaryTarget = async (
)
return ok({
path,
sourcePath: process.platform === "win32" ? candidate : canonical,
sourcePath,
sha256: await sha256Handle(handle, path, metadata, signal),
kind: "database",
format: "analysis-database",
@@ -175,7 +177,7 @@ export const parseBinaryTarget = async (
if (artifactFormat !== undefined) {
const identity = {
path,
sourcePath: process.platform === "win32" ? candidate : canonical,
sourcePath,
sha256: await sha256Handle(handle, path, metadata, signal),
};
return isArchiveFormat(artifactFormat)
@@ -195,7 +197,7 @@ export const parseBinaryTarget = async (
);
return ok({
path,
sourcePath: process.platform === "win32" ? candidate : canonical,
sourcePath,
...bundle,
sha256: await sha256Handle(handle, path, metadata, signal),
kind: "executable",
@@ -497,3 +497,71 @@ it("reports host denial before target mismatch but keeps composed workflow prere
).reason,
).toBe("target_required");
});
describe("trace_feature requirements", () => {
const capabilities = (operations: readonly string[]) =>
operations.map((operation) => ({
operation,
available: true,
reason: null,
}));
it("needs the search operations the workflow actually calls", () => {
expect(
entry(
"trace_feature",
status({
open: true,
kind: "executable",
capabilities: capabilities([
"search_strings",
"search_procedures",
"xrefs",
"resolve_containing_procedure",
]),
}),
),
).toMatchObject({ available: true, reason: "available" });
});
it.each(["search_strings", "search_procedures"])(
"is unavailable without %s",
(missing) => {
const operations = [
"search_strings",
"search_procedures",
"xrefs",
"resolve_containing_procedure",
].filter((operation) => operation !== missing);
expect(
entry(
"trace_feature",
status({
open: true,
kind: "executable",
capabilities: capabilities(operations),
}),
),
).toMatchObject({ available: false, reason: "provider_missing" });
},
);
it("is unavailable when only the list operations exist", () => {
expect(
entry(
"trace_feature",
status({
open: true,
kind: "executable",
capabilities: capabilities([
"list_strings",
"list_procedures",
"xrefs",
"resolve_containing_procedure",
]),
}),
),
).toMatchObject({ available: false, reason: "provider_missing" });
});
});
+3 -2
View File
@@ -121,8 +121,8 @@ const ENHANCED_REQUIREMENTS: Readonly<Record<string, readonly string[]>> = {
analyze_function: ["analyze_function"],
inspect_native_api: ["analyze_function"],
trace_feature: [
"list_strings",
"list_procedures",
"search_strings",
"search_procedures",
"xrefs",
"resolve_containing_procedure",
],
@@ -141,6 +141,7 @@ const FRIDA_OPERATION_NAMES: ReadonlySet<string> = new Set(
/** Native contracts defined only for an active Mach-O executable. */
const MACHO_TARGET_OPERATIONS: ReadonlySet<string> = new Set([
"inspect_signature",
"inspect_macho",
"list_architectures",
"observe_native_calls",
@@ -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);
+14 -12
View File
@@ -1,9 +1,5 @@
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
import {
parse as parseYaml,
parseDocument as parseYamlDocument,
stringify as stringifyYaml,
} from "yaml";
import { stringify as stringifyYaml } from "yaml";
import { isDeepStrictEqual } from "node:util";
import {
@@ -12,6 +8,10 @@ import {
editDshDocument,
dshClientRegistrationEntry,
} from "./DshCordisPatch.js";
import {
editHermesConfigurationYaml,
parseHermesConfigurationYaml,
} from "./HermesConfigurationYaml.js";
import {
applyEdits,
findNodeAtLocation,
@@ -120,7 +120,10 @@ const parseDocument = (
if (isEmptyClientConfigurationText(text)) return {};
// Hermes stores MCP servers in `mcp_servers` inside a YAML document.
if (format === "hermes")
return requireObject(parseYaml(text), "The configuration root");
return requireObject(
parseHermesConfigurationYaml(text),
"The configuration root",
);
// ZCode loads nonempty native files with strict JSON.parse.
if (format === "zcode")
return requireObject(JSON.parse(text), "The configuration root");
@@ -1421,12 +1424,11 @@ const serializeHermesConfiguration = (
typeof servers === "object" && servers !== null
? (servers as Record<string, unknown>)[PRODUCT_IDENTITY.mcpServerKey]
: undefined;
const yamlDocument = parseYamlDocument(originalText);
if (entry === undefined)
yamlDocument.deleteIn([serversKey, PRODUCT_IDENTITY.mcpServerKey]);
else yamlDocument.setIn([serversKey, PRODUCT_IDENTITY.mcpServerKey], entry);
// Editing REA must not reflow unrelated user prompts or other YAML scalars.
return yamlDocument.toString({ lineWidth: 0 });
return editHermesConfigurationYaml(
originalText,
[serversKey, PRODUCT_IDENTITY.mcpServerKey],
entry,
);
};
/** Build the stdio entry shape expected by one client's configuration dialect. */
@@ -22,6 +22,9 @@ export const registrationSchema = z
const codexRegistrationSchema = registrationSchema.extend({
tool_timeout_sec: z.number().optional(),
required: z.boolean().optional(),
cwd: z.string().optional(),
env_vars: z.array(z.string()).optional(),
enabled_tools: z.array(z.string()).optional(),
disabled_tools: z.array(z.string()).optional(),
});
+27 -23
View File
@@ -145,7 +145,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(
@@ -181,7 +181,7 @@ export const readClientRegistrationInspections = async (
});
continue;
}
record(unavailableStatus(client.name, client.configPath, "missing"));
record(unavailableStatus(client, "missing"));
continue;
}
const registration = parseRegistration(raw, client);
@@ -192,8 +192,7 @@ export const readClientRegistrationInspections = async (
const activation = registrationActivation(registration, client, parsed);
record(
configuredStatus(
client.name,
client.configPath,
client,
command,
activation === "enabled" &&
registrationAligned(
@@ -212,11 +211,7 @@ export const readClientRegistrationInspections = async (
);
} catch (cause: unknown) {
record(
unavailableStatus(
client.name,
client.configPath,
isMissing(cause) ? "missing" : "invalid",
),
unavailableStatus(client, isMissing(cause) ? "missing" : "invalid"),
);
}
}
@@ -344,36 +339,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> => {
+6
View File
@@ -23,6 +23,7 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { access } from "node:fs/promises";
import { readAnalysisSnapshot } from "./binary/AnalysisSnapshotFiles.js";
import { requiresNativeSourceAdmissionBeforeReplay } from "./binary/AnalysisSnapshotCache.js";
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import {
@@ -254,9 +255,14 @@ const runAnalysis = async (
const route = preview.value.route;
const bindingProfile = route.profile ?? undefined;
const evidenceProfile = analysisProfileForRoute(route, tool);
// A parsed Windows path does not prove Ghidra's native snapshot owner
// admitted the selected source; CLI replay must wait for that client.
if (
bindingProfile !== undefined &&
evidenceProfile !== undefined &&
!requiresNativeSourceAdmissionBeforeReplay(
route.binding?.identity.id,
) &&
allowsSnapshotReplay(route, tool)
) {
const cached = snapshotEvidenceForQuery(snapshot, {
+1 -1
View File
@@ -413,7 +413,7 @@ export const describeDshRegistrationRetention = (
.filter((key) => Object.hasOwn(entry, key))
.sort((left, right) => left.localeCompare(right))
.map((key) => `${key} with ${JSON.stringify(entry[key])}`);
return `Other fields on the existing Cordis server are kept, except the row-level disabled flag is removed to activate the registration. Setup replaces ${replaced.join(", ")}. Environment overrides are merged.`;
return `Other fields on the existing Cordis server are kept, except the row-level disabled flag is removed to activate the registration and name is set to ${JSON.stringify(DSH_CLIENT_PACKAGE)}. Setup replaces ${replaced.join(", ")}. Environment overrides are merged.`;
};
export const dshClientRegistrationEntry = (
+47 -17
View File
@@ -1,5 +1,8 @@
import { z } from "zod";
import type { AnalysisOperation } from "./AnalysisProvider.js";
import type {
AnalysisExecution,
AnalysisOperation,
} from "./AnalysisProvider.js";
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { JsonValue } from "../domain/jsonValue.js";
@@ -16,6 +19,12 @@ type AnalysisCall = (
signal?: AbortSignal,
) => Promise<Result<JsonValue, AnalysisError>>;
type ObserveCall = (
name: AnalysisOperation,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
) => Promise<Result<AnalysisExecution, AnalysisError>>;
type LiteralSearchSource = readonly [
"search_strings" | "search_procedures",
"string" | "procedure",
@@ -39,6 +48,7 @@ export interface LiteralTraceInput {
/** Trace matching strings and procedures through provider xrefs. */
export const traceLiteralFeature = async (
call: AnalysisCall,
observe: ObserveCall,
input: LiteralTraceInput,
signal?: AbortSignal,
): EnhancedResult => {
@@ -49,7 +59,7 @@ export const traceLiteralFeature = async (
signal,
);
if (!searched.ok) return searched;
const traced = await traceReferences(call, {
const traced = await traceReferences(call, observe, {
matches: searched.value.matches,
...(signal === undefined ? {} : { signal }),
});
@@ -59,8 +69,8 @@ export const traceLiteralFeature = async (
search_mode: "literal",
matches: searched.value.matches,
references: traced.value.references,
truncated: false,
residual_unknowns: [],
truncated: traced.value.residual.length > 0,
residual_unknowns: traced.value.residual,
});
};
@@ -126,24 +136,39 @@ const addPageMatches = (input: {
const traceReferences = async (
call: AnalysisCall,
observe: ObserveCall,
request: ReferenceTraceRequest,
): Promise<Result<{ references: TraceReference[] }, AnalysisError>> => {
): Promise<
Result<{ references: TraceReference[]; residual: string[] }, AnalysisError>
> => {
const references: TraceReference[] = [];
const residual: string[] = [];
// A source address is resolved once however many matches reference it.
const containing = new Map<string, JsonValue>();
for (const match of request.matches) {
const xrefs = await call(
const observed = await observe(
"xrefs",
{ address: match.address },
request.signal,
);
if (!xrefs.ok) return xrefs;
if (!Array.isArray(xrefs.value))
if (!observed.ok) return observed;
// Only an explicit producer report of truncation is a coverage gap; a
// provider that reports nothing keeps its previous, unqualified result.
const unknown = `References to ${match.address} were truncated by the provider; additional references may exist.`;
if (
observed.value.referencesTruncated === true &&
!residual.includes(unknown)
)
residual.push(unknown);
const sources = observed.value.result;
if (!Array.isArray(sources))
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-array result",
),
);
for (const source of xrefs.value) {
for (const source of sources) {
if (typeof source !== "string")
return err(
new AnalysisOutputError(
@@ -151,18 +176,23 @@ const traceReferences = async (
"provider returned a non-address value",
),
);
const resolved = await call(
"resolve_containing_procedure",
{ address: source },
request.signal,
);
if (!resolved.ok) return resolved;
let containingProcedure = containing.get(source);
if (containingProcedure === undefined) {
const resolved = await call(
"resolve_containing_procedure",
{ address: source },
request.signal,
);
if (!resolved.ok) return resolved;
containingProcedure = resolved.value;
containing.set(source, containingProcedure);
}
references.push({
target_address: match.address,
source_address: source,
containing_procedure: resolved.value,
containing_procedure: containingProcedure,
});
}
}
return ok({ references });
return ok({ references, residual });
};
+2
View File
@@ -163,6 +163,8 @@ export class EnhancedTools {
return traceLiteralFeature(
(name, arguments_, operationSignal) =>
this.#call(name, arguments_, operationSignal),
(name, arguments_, operationSignal) =>
this.#observe(name, arguments_, operationSignal),
call.input,
signal,
);
+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;
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import {
editHermesConfigurationYaml,
parseHermesConfigurationYaml,
} from "./HermesConfigurationYaml.js";
describe("Hermes configuration YAML", () => {
it("writes an edited number from its new value", () => {
expect(
editHermesConfigurationYaml("mode: 0600\nmask: 0x1F\n", ["mode"], 384),
).toBe("mode: 384\nmask: 0x1F\n");
});
it("accepts keys Hermes reads as distinct and rejects a repeated key", () => {
expect(() =>
parseHermesConfigurationYaml("0600: octal\n600: decimal\n"),
).not.toThrow();
expect(() => parseHermesConfigurationYaml('a: 1\n"a": 2\n')).toThrow();
});
});
@@ -0,0 +1,74 @@
import {
isScalar,
parse,
parseDocument,
type ParsedNode,
type ScalarTag,
type Tags,
} from "yaml";
const NUMBER_TAGS = new Set([
"tag:yaml.org,2002:int",
"tag:yaml.org,2002:float",
]);
/**
* Write a parsed number with its source spelling while that spelling still
* reads as the node's value. Hermes reads config.yaml as YAML 1.1 with exact
* integers, so re-printing a JavaScript number changes what it reads: a
* Discord channel ID loses its low digits, `0600` (octal) becomes `600`, and
* `0.0000001` becomes `1e-7`, which YAML 1.1 does not define as a float.
*/
const keepNumberSource = (tag: Tags[number]): Tags[number] => {
if (typeof tag === "string" || tag.collection !== undefined) return tag;
const { stringify } = tag;
if (!NUMBER_TAGS.has(tag.tag) || stringify === undefined) return tag;
return {
...tag,
stringify: (item, context, ...rest) => {
const { source } = item;
if (source === undefined) return stringify(item, context, ...rest);
const reader = context.doc.schema.tags.find(
(candidate): candidate is ScalarTag =>
candidate.default === true && candidate.test?.test(source) === true,
);
const read = reader?.resolve(
source,
() => undefined,
context.doc.options,
);
return Object.is(isScalar(read) ? read.value : read, item.value)
? source
: stringify(item, context, ...rest);
},
};
};
const HERMES_YAML_OPTIONS = {
customTags: (tags: Tags) => tags.map(keepNumberSource),
// Hermes keeps integers exact, so IDs that round to one double, or `0600`
// and `600`, are distinct keys.
uniqueKeys: (a: ParsedNode, b: ParsedNode) =>
a === b ||
(isScalar(a) &&
isScalar(b) &&
a.value === b.value &&
a.source === b.source),
};
/** Parse a Hermes `config.yaml`. */
export const parseHermesConfigurationYaml = (text: string): unknown =>
parse(text, HERMES_YAML_OPTIONS);
/** Set or delete one value in a Hermes `config.yaml`, keeping the rest as written. */
export const editHermesConfigurationYaml = (
text: string,
path: readonly string[],
value: unknown,
): string => {
const document = parseDocument(text, HERMES_YAML_OPTIONS);
if (value === undefined) document.deleteIn(path);
else document.setIn(path, value);
// Editing REA must not reflow unrelated user prompts or other YAML scalars.
return document.toString({ lineWidth: 0 });
};
+3 -1
View File
@@ -20,7 +20,9 @@ export const workflowAnalysisProfile = (
upstream_analysis_profile: upstream,
...(operation === "binary_overview"
? { workflow_revision: 3 }
: operation === "batch_decompile" || operation === "get_call_graph"
: operation === "batch_decompile" ||
operation === "get_call_graph" ||
operation === "trace_feature"
? { workflow_revision: 2 }
: {}),
});
+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")
);
}
};
@@ -97,18 +97,22 @@ const resolveInternalSpecifier = (
);
if (logicalPathEscapesRoot(normalized))
return { to: normalized, resolution: "unresolved" };
// Preserve directory intent before normalization removes terminal dot segments.
const directoryReference =
specifier.endsWith("/") || [".", ".."].includes(posix.basename(specifier));
const suffixes = ["", ".ts", ".js", ".mjs", ".cjs", ".tsx", ".jsx"];
const candidates = suffixes.flatMap((suffix) => [
`${normalized}${suffix}`,
`${normalized}/index${suffix}`,
...(directoryReference ? [] : [`${normalized}${suffix}`]),
posix.join(normalized, `index${suffix}`),
]);
// Retain present runtime files first; substitute only a missing counterpart.
// Counterparts cover explicit filenames, not directory/index resolution.
candidates.push(
...typescriptEmittedSourceCandidates(fromPath, normalized).map(
({ path }) => path,
),
);
if (!directoryReference)
candidates.push(
...typescriptEmittedSourceCandidates(fromPath, normalized).map(
({ path }) => path,
),
);
const match = lookupPath.resolveCandidates(candidates);
return match === undefined
? { to: normalized, resolution: "unresolved" }
+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;
+1 -1
View File
@@ -295,7 +295,7 @@ describe("setup approval disclosure", () => {
const [executable = "rea", ...args] = host.registrationCommand;
expect(detail).toContain(
"Other fields on the existing Cordis server are kept.",
'Other fields on the existing Cordis server are kept, except the row-level disabled flag is removed to activate the registration and name is set to "@deepseek-ai/dsh-mcp-client".',
);
expect(detail).toContain(`serverName with ${JSON.stringify("rea")}`);
expect(detail).toContain(`transport with ${JSON.stringify("stdio")}`);
+31 -1
View File
@@ -31,6 +31,7 @@ import { clientRegistrationEnvironment } from "./ClientRegistrationEnvironment.j
import { PRODUCT_IDENTITY } from "../identity.js";
import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js";
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
import { packageReadTargetChanged } from "./MsixPackageStorage.js";
import {
readRegularFile,
readRegularFileText,
@@ -42,7 +43,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(
@@ -189,6 +193,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;
@@ -360,6 +371,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 -38
View File
@@ -13,12 +13,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";
@@ -166,12 +172,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,
@@ -190,27 +242,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: {
@@ -268,12 +299,7 @@ const setupPlan = (input: {
label: client.displayName ?? client.name,
target: client.configPath,
detail: clientConfigurationDetail(
{
name: client.name,
label: client.displayName ?? client.name,
format: client.format,
...(dialect === undefined ? {} : { dialect }),
},
{ ...client, ...(dialect === undefined ? {} : { dialect }) },
input.command,
input.providerEnvironment,
input.installHopper,
@@ -317,12 +343,7 @@ const majorVersion = (version: string): number =>
Number.parseInt(version.split(".")[0] ?? "0", 10);
const clientConfigurationDetail = (
client: {
readonly name: string;
readonly label: string;
readonly format: SetupClient["format"];
readonly dialect?: ClientRegistrationDialect;
},
client: SetupClient & { readonly dialect?: ClientRegistrationDialect },
command: readonly string[],
environment: SetupProviderEnvironment,
installHopper: boolean,
@@ -348,5 +369,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.label}; 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
@@ -26,7 +26,12 @@ export type ClientConfigurationResult =
}
| {
readonly status: "failed";
readonly reason: "path" | "backup" | "write" | "readback";
readonly reason:
| "path"
| "target_changed"
| "backup"
| "write"
| "readback";
}
| {
readonly status: "failed";
@@ -62,6 +67,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>;
+154 -35
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 =>
@@ -135,6 +168,9 @@ const codexDirectory = ({ home, env }: ClientPathContext): string =>
const qoderDirectory = ({ home, env }: ClientPathContext): string =>
env.QODER_CONFIG_DIR || join(home, ".qoder");
const factoryDirectory = ({ home }: ClientPathContext): string =>
join(home, ".factory");
/** Match Qwen Code's home override, including tilde and cwd-relative paths. */
const qwenCodeDirectory = ({ home, env }: ClientPathContext): string => {
const override = env.QWEN_HOME;
@@ -157,8 +193,27 @@ const qwenCodeDirectory = ({ home, env }: ClientPathContext): string => {
const grokDirectory = ({ home, env }: ClientPathContext): string =>
env.GROK_HOME || join(home, ".grok");
/** Match Harness home-paths for both independent roots; trim only to detect blanks. */
const dshDirectory = (
home: string,
override: string | undefined,
fallback: string,
): string => {
const selected =
override !== undefined && override.trim().length > 0
? override
: join(home, fallback);
const expanded =
selected === "~"
? home
: selected.startsWith("~/") || selected.startsWith("~\\")
? join(home, selected.slice(2))
: selected;
return resolve(expanded);
};
const dshHomeDirectory = ({ home, env }: ClientPathContext): string =>
env.DSH_HOME ?? join(home, ".dsh");
dshDirectory(home, env.DSH_HOME, ".dsh");
const dshPatchDirectory = (context: ClientPathContext): string =>
join(dshHomeDirectory(context), "cordis.patch.yml");
@@ -189,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;
@@ -386,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",
},
{
@@ -539,6 +642,16 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
markerPath: qoderDirectory,
format: "json",
},
{
name: "droid",
displayName: "Factory Droid",
skillPath: (context: ClientPathContext) =>
join(factoryDirectory(context), "skills"),
configPath: (context: ClientPathContext) =>
join(factoryDirectory(context), "mcp.json"),
markerPath: factoryDirectory,
format: "json",
},
{
name: "zcode",
zcodeFallbackPath: ({ home }: ClientPathContext) =>
@@ -555,7 +668,7 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
// The home Cordis patch applies to every profile; the skill directory is
// shared agent storage Harness discovers.
skillPath: ({ home, env }: ClientPathContext) =>
join(env.DSH_AGENTS_HOME ?? join(home, ".agents"), "skills"),
join(dshDirectory(home, env.DSH_AGENTS_HOME, ".agents"), "skills"),
configPath: dshPatchDirectory,
markerPath: dshHomeDirectory,
format: "dsh",
@@ -595,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,
@@ -605,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,
@@ -643,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 {
@@ -661,3 +661,52 @@ it("does not replay pre-envelope call graphs under the revised workflow profile"
}).success,
).toBe(false);
});
describe("executions that report truncated references", () => {
const record = (referencesTruncated: boolean | undefined) => {
const cache = new AnalysisSnapshotCache();
const parameters = { address: "0x1000", document: "fixture" };
cache.record({
target: ANALYSIS_SNAPSHOT_TARGET,
profile: ANALYSIS_SNAPSHOT_PROFILE,
operation: "xrefs",
parameters,
execution: createAnalysisExecution(
["0x2000"],
ANALYSIS_SNAPSHOT_PROVIDER,
{
subject: ANALYSIS_SNAPSHOT_TARGET,
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
...(referencesTruncated === undefined ? {} : { referencesTruncated }),
},
),
});
return cache.lookup(
ANALYSIS_SNAPSHOT_TARGET,
ANALYSIS_SNAPSHOT_PROFILE,
"xrefs",
parameters,
);
};
it("are not replayed, because a replay would lose the truncation", () => {
expect(record(true)).toBeUndefined();
});
it("do not stop an execution that is complete or silent from being replayed", () => {
expect(record(false)?.result).toEqual(["0x2000"]);
expect(record(undefined)?.result).toEqual(["0x2000"]);
});
});
it("revises the trace_feature workflow profile so earlier results are not replayed", () => {
const profile = ANALYSIS_SNAPSHOT_PROFILE;
expect(workflowAnalysisProfile(profile, "trace_feature")).not.toEqual(
workflowAnalysisProfile(profile),
);
expect(
workflowAnalysisProfile(profile, "trace_call_path"),
"other workflows keep their profile",
).toEqual(workflowAnalysisProfile(profile));
});
@@ -84,6 +84,11 @@ export const isSnapshotCacheable = (
descriptor.effects.mayWriteFilesystem === false) &&
descriptor.effects.changesPermissions === false;
/** Windows Ghidra must admit the selected source through its native snapshot owner. */
export const requiresNativeSourceAdmissionBeforeReplay = (
providerId: string | undefined,
): boolean => process.platform === "win32" && providerId === "ghidra";
/** Bounded in-memory cache for one immutable binary identity. */
export class AnalysisSnapshotCache {
readonly #entries = new Map<string, AnalysisSnapshotEntry>();
@@ -337,6 +342,9 @@ export class AnalysisSnapshotCache {
}): void {
const { target, profile, operation, parameters, execution } = input;
this.select(target, profile);
// The snapshot format does not carry reference truncation; a replay would
// present a capped read as complete, so it is not recorded.
if (execution.referencesTruncated === true) return;
const queryId = analysisQueryId(
snapshotTarget(target),
snapshotBinding(profile),
+12
View File
@@ -58,6 +58,7 @@ interface SessionBinding {
readonly profile: AnalysisProfileCommitment | null;
readonly route: SessionProviderRoute;
readonly runId: string;
nativeSourceAdmitted: boolean;
}
/**
@@ -323,6 +324,7 @@ export class BinarySession
profile,
route,
runId,
nativeSourceAdmitted: false,
};
this.#clearRuntimeAvailability();
this.resetSnapshotInvalidation();
@@ -609,6 +611,7 @@ export class BinarySession
active: this.#active,
operation: name,
parameters: arguments_,
nativeSourceAdmitted: this.#active?.nativeSourceAdmitted === true,
unboundOperationError: (operation, route) =>
this.#providerRouter.unboundOperationError(operation, route),
lookupSnapshot: (target, profile, operation, parameters) =>
@@ -645,6 +648,14 @@ export class BinarySession
},
})
: profiled;
// A successful Ghidra operation proves this client's native source snapshot
// was admitted; a composite health response and parsed path do not.
if (
execution.ok &&
capability.provider.id === "ghidra" &&
this.#active === active
)
this.#active.nativeSourceAdmitted = true;
this.#observeRuntimeAvailability(name, execution);
if (
execution.ok &&
@@ -838,6 +849,7 @@ export class BinarySession
profile: previous.profile,
route: previous.route,
runId,
nativeSourceAdmitted: false,
};
return ok(null);
}
@@ -13,7 +13,10 @@ import type {
AnalysisOperation,
CapabilityDescriptor,
} from "../AnalysisProvider.js";
import { isSnapshotCacheable } from "./AnalysisSnapshotCache.js";
import {
isSnapshotCacheable,
requiresNativeSourceAdmissionBeforeReplay,
} from "./AnalysisSnapshotCache.js";
import type { SessionProviderRoute } from "./SessionProviderRouter.js";
interface ActiveExecutionBinding {
@@ -35,6 +38,7 @@ interface PrepareSessionExecutionInput {
readonly active: ActiveExecutionBinding | undefined;
readonly operation: AnalysisOperation;
readonly parameters: Readonly<Record<string, JsonValue>>;
readonly nativeSourceAdmitted: boolean;
readonly unboundOperationError: (
operation: AnalysisOperation,
route: SessionProviderRoute,
@@ -55,6 +59,7 @@ export const prepareSessionExecution = (
active,
operation,
parameters,
nativeSourceAdmitted,
unboundOperationError,
lookupSnapshot,
} = input;
@@ -79,9 +84,12 @@ export const prepareSessionExecution = (
const cacheable =
profile !== undefined &&
isSnapshotCacheable(operation, capability, parameters);
const cached = cacheable
? lookupSnapshot(active.target, profile, operation, parameters)
: undefined;
const cached =
cacheable &&
(!requiresNativeSourceAdmissionBeforeReplay(capability.provider.id) ||
nativeSourceAdmitted)
? lookupSnapshot(active.target, profile, operation, parameters)
: undefined;
return ok({ active, capability, profile, cacheable, cached });
};
+12 -6
View File
@@ -92,9 +92,7 @@ export const resolveSessionTarget = async (
input: ResolveSessionTargetInput,
): Promise<Result<ResolvedSessionOpen, AnalysisError>> => {
const { router, current, target, options } = input;
const sameTarget =
current?.target.path === target.path &&
snapshotMatchesTarget(snapshotTarget(current.target), target);
const sameTarget = sameSessionTarget(current?.target, target);
const resolvedRoute =
sameTarget && options.providerId === undefined && current !== undefined
? ({ ok: true, value: current.route } as const)
@@ -113,9 +111,7 @@ export const validateResolvedSessionTarget = (
},
): Result<ResolvedSessionOpen, AnalysisError> => {
const { current, target, route, options, stagedSnapshotMatches } = input;
const sameTarget =
current?.target.path === target.path &&
snapshotMatchesTarget(snapshotTarget(current.target), target);
const sameTarget = sameSessionTarget(current?.target, target);
const snapshotError = validateSnapshot({
snapshot: options.snapshot,
target,
@@ -127,6 +123,16 @@ export const validateResolvedSessionTarget = (
return { ok: true, value: { target, route, sameTarget } };
};
const sameSessionTarget = (
current: BinaryTarget | undefined,
target: BinaryTarget,
): boolean =>
current !== undefined &&
current.path === target.path &&
// Native admission is bound to the requested path, not just its realpath.
(current.sourcePath ?? current.path) === (target.sourcePath ?? target.path) &&
snapshotMatchesTarget(snapshotTarget(current), target);
interface ValidateSnapshotInput {
readonly snapshot: AnalysisSnapshot | undefined;
readonly target: BinaryTarget;
@@ -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",
},
+10 -2
View File
@@ -40,6 +40,7 @@ import { ArtifactResourceScope } from "./ArtifactResourceScope.js";
import { artifactCapabilities } from "./ArtifactProviderMetadata.js";
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
import { createEvidence } from "../domain/evidence.js";
import { freezeJsonSnapshot } from "../domain/immutableJson.js";
import { createArtifactInspection } from "../domain/artifactInspection.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
@@ -341,7 +342,11 @@ class ArtifactClient implements AnalysisClient {
total: 1,
message: "inventory substep started",
});
const inventory = await this.inventory(inventoryParameters, options);
// The freshly parsed inventory is exclusively owned here. Sealing it lets
// the nested Evidence share it instead of cloning and re-digesting it.
const inventory = freezeJsonSnapshot(
await this.inventory(inventoryParameters, options),
);
const subject = subjectFor(
this.target.sourcePath ?? this.target.path,
inventory.manifest,
@@ -355,7 +360,10 @@ class ArtifactClient implements AnalysisClient {
// The nested inventory already names every occurrence's logical path.
locations: [],
});
const result = createArtifactInspection(inventoryEvidence);
// The returned execution and its Evidence then reuse this owned report.
const result = freezeJsonSnapshot(
createArtifactInspection(inventoryEvidence),
);
await options?.progress?.report({
phase: "inspect_artifact.inventory",
completed: 1,
+2 -2
View File
@@ -8,7 +8,7 @@ import {
type NativeCommandRunner,
} from "../native/CommandRunner.js";
import {
parseLipoArchitectures,
parseLipoOutput,
type LipoArchitecture,
} from "../native/parsers/lipo.js";
import type { MachoSlice } from "../domain/apple/dylibResolution.js";
@@ -114,7 +114,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
};
await this.#verifySource(source);
const fileSize = source.initial.size;
const architectures = parseLipoArchitectures(captured.value.stdout);
const { architectures } = parseLipoOutput(captured.value.stdout, this.path);
const structural = await readStructuralSlices(source.handle, fileSize);
await this.#verifySource(source);
if (structural.status === "malformed")
@@ -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);
});
+79 -6
View File
@@ -2,7 +2,29 @@ import type { FileHandle } from "node:fs/promises";
import { PassThrough, type Readable } from "node:stream";
import { once } from "node:events";
import { Reader, ZipReader, type Entry, type FileEntry } from "@zip.js/zip.js";
import {
ERR_AMBIGUOUS_ARCHIVE,
ERR_BAD_FORMAT,
ERR_CENTRAL_DIRECTORY_NOT_FOUND,
ERR_ENCRYPTED_CENTRAL_DIRECTORY,
ERR_ENTRY_DATA_OUT_OF_BOUNDS,
ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND,
ERR_EOCDR_NOT_FOUND,
ERR_EXTRAFIELD_ZIP64_NOT_FOUND,
ERR_INVALID_COMPRESSED_DATA,
ERR_INVALID_CRC32,
ERR_INVALID_UNCOMPRESSED_SIZE,
ERR_LOCAL_FILE_HEADER_NOT_FOUND,
ERR_OVERLAPPING_ENTRY,
ERR_SPLIT_ZIP_FILE,
ERR_UNSUPPORTED_COMPRESSION,
ERR_UNSUPPORTED_ENCRYPTION,
ERR_UNSUPPORTED_UINT64,
Reader,
ZipReader,
type Entry,
type FileEntry,
} from "@zip.js/zip.js";
import {
ArtifactReaderFailure,
@@ -159,9 +181,9 @@ export class ZipArtifactReader implements ArtifactReader {
let index = 0;
// A traversal owns its accounting, including overlapping or repeated passes.
let declaredFileBytes = 0;
for await (const entry of this.#reader.getEntriesGenerator({
decodeText: decodeZipEntryText,
})) {
for await (const entry of typedZipFailures(
this.#reader.getEntriesGenerator({ decodeText: decodeZipEntryText }),
)) {
abortIfNeeded(signal);
// ZIP member identity is its directory occurrence, not its filename.
// Logical path uniqueness belongs to the artifact inventory boundary.
@@ -327,7 +349,7 @@ const extractStream = (entry: FileEntry, signal?: AbortSignal): Readable => {
output.end();
},
abort: (reason) => {
output.destroy(toError(reason));
output.destroy(toError(typedZipFailure(reason)));
},
});
void entry
@@ -337,10 +359,61 @@ const extractStream = (entry: FileEntry, signal?: AbortSignal): Readable => {
checkOverlappingEntry: true,
onprogress: () => abortIfNeeded(signal),
})
.catch((cause: unknown) => output.destroy(toError(cause)));
.catch((cause: unknown) => output.destroy(toError(typedZipFailure(cause))));
return output;
};
/** zip.js reports archive faults as plain errors identified by message. */
const ZIP_FAILURE_REASONS: ReadonlyMap<string, "format" | "unavailable"> =
new Map([
...[
ERR_AMBIGUOUS_ARCHIVE,
ERR_BAD_FORMAT,
ERR_CENTRAL_DIRECTORY_NOT_FOUND,
ERR_ENTRY_DATA_OUT_OF_BOUNDS,
ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND,
ERR_EOCDR_NOT_FOUND,
ERR_EXTRAFIELD_ZIP64_NOT_FOUND,
ERR_INVALID_COMPRESSED_DATA,
ERR_INVALID_CRC32,
ERR_INVALID_UNCOMPRESSED_SIZE,
ERR_LOCAL_FILE_HEADER_NOT_FOUND,
ERR_OVERLAPPING_ENTRY,
ERR_UNSUPPORTED_UINT64,
].map((message) => [message, "format"] as const),
...[
ERR_ENCRYPTED_CENTRAL_DIRECTORY,
ERR_SPLIT_ZIP_FILE,
ERR_UNSUPPORTED_COMPRESSION,
ERR_UNSUPPORTED_ENCRYPTION,
].map((message) => [message, "unavailable"] as const),
]);
/** Type a zip.js archive fault so consumers do not report it as file I/O. */
const typedZipFailure = (cause: unknown): unknown => {
if (!(cause instanceof Error) || cause instanceof ArtifactReaderFailure)
return cause;
const reason = ZIP_FAILURE_REASONS.get(cause.message);
if (reason === undefined) return cause;
return new ArtifactReaderFailure(
reason,
reason === "format"
? `ZIP archive is malformed: ${cause.message}`
: `ZIP archive uses an unsupported feature: ${cause.message}`,
{ cause },
);
};
async function* typedZipFailures<T>(
source: AsyncIterable<T>,
): AsyncIterable<T> {
try {
yield* source;
} catch (cause: unknown) {
throw typedZipFailure(cause);
}
}
const isSymlink = (entry: Entry): boolean =>
entry.unixMode !== undefined && (entry.unixMode & 0o170000) === 0o120000;
@@ -56,6 +56,7 @@ export const analyzeInterfaceBuilderBundle = async (input: {
const omittedArchives: Array<{ path: string; reason: string }> = [];
let unreportedOmittedArchives = 0;
const incompleteHierarchies = new Map<string, number>();
const unresolvedConnections = new Map<string, number>();
const prototypeKeyOmissions = new Map<string, number | null>();
let omitted = 0;
let attempted = 0;
@@ -136,6 +137,8 @@ export const analyzeInterfaceBuilderBundle = async (input: {
: { value: nib.raw, omittedPrototypeKeys: 0 };
if (nib !== null && nib.omitted > 0)
incompleteHierarchies.set(entry.path, nib.omitted);
if (nib !== null && nib.unresolvedConnections > 0)
unresolvedConnections.set(entry.path, nib.unresolvedConnections);
if (omittedPrototypeKeys !== 0)
prototypeKeyOmissions.set(entry.path, omittedPrototypeKeys);
const documentHash = createHash("sha256").update(bytes).digest("hex");
@@ -170,6 +173,7 @@ export const analyzeInterfaceBuilderBundle = async (input: {
});
return finalizeHierarchyCoverage(result, {
incompleteHierarchies,
unresolvedConnections,
prototypeKeyOmissions,
invalid,
omittedArchives,
@@ -237,6 +241,7 @@ const finalizeHierarchyCoverage = (
result: ReturnType<typeof buildInterfaceBuilderAnalysis>,
counts: {
incompleteHierarchies: ReadonlyMap<string, number>;
unresolvedConnections: ReadonlyMap<string, number>;
prototypeKeyOmissions: ReadonlyMap<string, number | null>;
invalid: readonly string[];
omittedArchives: readonly { path: string; reason: string }[];
@@ -247,6 +252,7 @@ const finalizeHierarchyCoverage = (
) => {
const {
incompleteHierarchies,
unresolvedConnections,
prototypeKeyOmissions,
invalid,
omittedArchives,
@@ -260,6 +266,13 @@ const finalizeHierarchyCoverage = (
...result,
documents: result.documents.map((document) => ({
...document,
// The dictionary parser only sees connectors that were projected, so the
// omission recorded where an ownerless connector was dropped has to be
// added here for this producer to report the same document count as the
// keyed-archive producer for the same recognized connector.
connection_count:
document.connection_count +
(unresolvedConnections.get(document.relative_path) ?? 0),
hierarchy_complete:
document.hierarchy_complete &&
!incompleteHierarchies.has(document.relative_path),
@@ -268,15 +281,32 @@ const finalizeHierarchyCoverage = (
...result.graph,
coverage: [
...result.graph.coverage.map((facet) => {
const omitted = incompleteHierarchies.get(
const omittedHierarchy = incompleteHierarchies.get(
facet.facet.replace(/^hierarchy:/u, ""),
);
return facet.facet.startsWith("hierarchy:") && omitted !== undefined
if (
facet.facet.startsWith("hierarchy:") &&
omittedHierarchy !== undefined
)
return {
...facet,
status: "partial" as const,
reason: "serialized_view_hierarchy_incomplete",
omitted: facet.omitted + omittedHierarchy,
};
const omittedConnection = unresolvedConnections.get(
facet.facet.replace(/^connections:/u, ""),
);
return facet.facet.startsWith("connections:") &&
omittedConnection !== undefined
? {
...facet,
status: "partial" as const,
reason: "serialized_view_hierarchy_incomplete",
omitted: facet.omitted + omitted,
// A connection dropped by the limit is recoverable by raising
// it, so that cause keeps the reason the graph already named.
// Only a facet with no other cause reports the omission.
reason: facet.reason ?? "connection_unresolved",
omitted: facet.omitted + omittedConnection,
}
: facet;
}),
@@ -306,7 +336,8 @@ const finalizeHierarchyCoverage = (
result.graph.truncated ||
counts.omitted > 0 ||
archiveDecodePartial ||
incompleteHierarchies.size > 0,
incompleteHierarchies.size > 0 ||
unresolvedConnections.size > 0,
},
limitations: [
...result.limitations,
@@ -316,6 +347,11 @@ const finalizeHierarchyCoverage = (
: [
"Some serialized hierarchy links could not be projected within the bounded hierarchy; their parentage remains unknown.",
]),
...(unresolvedConnections.size === 0
? []
: [
"Some recognized NIBArchive connectors declare no resolvable owner; they carry no connection evidence and are reported as omissions.",
]),
...(invalid.length === 0
? []
: [
@@ -496,6 +532,10 @@ const projectNibArchive = (
);
const connections: Record<string, JsonValue[]> = {};
const hierarchy: NibHierarchyNode[] = [];
// A recognized connector whose owner reference cannot be resolved produces no
// connection entry, so the omission has to be counted here: the projected
// dictionary carries no trace of it for a downstream consumer to find.
let unresolvedConnections = 0;
const reference = (value: JsonValue | undefined): number | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
@@ -512,7 +552,10 @@ const projectNibArchive = (
const values = object.values;
const connectionFields = interfaceBuilderConnectionFieldNames(className);
const source = reference(values[connectionFields.source]);
if (source === null) continue;
if (source === null) {
unresolvedConnections += 1;
continue;
}
const destination = reference(values[connectionFields.destination]);
const label = referencedString(values[connectionFields.label]);
const type = className.includes("Outlet")
@@ -608,6 +651,7 @@ const projectNibArchive = (
);
return {
omitted: viewHierarchy.omitted + hierarchyOmitted + merged.omitted,
unresolvedConnections,
raw: jsonValueSchema.parse({
"com.apple.ibtool.document.objects": objects,
"com.apple.ibtool.document.connections": connections,
+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"],
@@ -0,0 +1,103 @@
import { describe, expect, it } from "vitest";
import { CPU, fatImage, machoImage } from "../apple/MachoImage.fixture.js";
import { classifyArtifactContent } from "./ArtifactGraphConstruction.js";
const fat = (wide = false): Buffer =>
Buffer.from(fatImage([{ cpu: CPU.arm64, bytes: machoImage({}) }], wide));
describe("bounded FAT inventory classification", () => {
it("requires the complete table but not slice bytes in the retained prefix", () => {
const bytes = fat();
for (const length of [4, 7, 8, 27]) {
expect(
classifyArtifactContent(
"native",
bytes.subarray(0, length),
bytes.length,
),
).toEqual({ kind: "unknown", format: "unknown" });
}
expect(
classifyArtifactContent(
"native.class",
bytes.subarray(0, 28),
bytes.length,
),
).toEqual({ kind: "executable", format: "mach-o-universal" });
});
it.each([
["empty table", (bytes: Buffer) => bytes.writeUInt32BE(0, 4)],
["slice overlapping table", (bytes: Buffer) => bytes.writeUInt32BE(0, 16)],
["empty slice", (bytes: Buffer) => bytes.writeUInt32BE(0, 20)],
[
"slice beyond file",
(bytes: Buffer) => bytes.writeUInt32BE(bytes.length, 20),
],
["unaligned slice", (bytes: Buffer) => bytes.writeUInt32BE(4097, 16)],
["unsupported alignment", (bytes: Buffer) => bytes.writeUInt32BE(53, 24)],
] as const)("keeps %s unknown", (_label, mutate) => {
const bytes = fat();
mutate(bytes);
expect(classifyArtifactContent("native", bytes)).toEqual({
kind: "unknown",
format: "unknown",
});
});
it("does not infer Mach-O from an out-of-bounds architecture count", () => {
const bytes = fat();
bytes.writeUInt32BE(0xffffffff, 4);
expect(classifyArtifactContent("native", bytes)).toEqual({
kind: "resource",
format: "file",
});
});
it("does not lose unsafe FAT64 range values to number conversion", () => {
const bytes = fat(true);
bytes.writeBigUInt64BE(BigInt(Number.MAX_SAFE_INTEGER) + 1n, 16);
expect(classifyArtifactContent("native", bytes)).toEqual({
kind: "unknown",
format: "unknown",
});
});
it("requires valid ranges for every declared slice", () => {
const bytes = Buffer.from(
fatImage([
{ cpu: CPU.arm64, bytes: machoImage({}) },
{ cpu: CPU.x86_64, bytes: machoImage({ cpu: CPU.x86_64 }) },
]),
);
bytes.writeUInt32BE(bytes.length, 40);
expect(classifyArtifactContent("native", bytes)).toEqual({
kind: "unknown",
format: "unknown",
});
});
it("requires observed slice magic for an unknown CPU type", () => {
const cpu = { type: 0x12345678, subtype: 0 };
const bytes = Buffer.from(fatImage([{ cpu, bytes: machoImage({ cpu }) }]));
expect(
classifyArtifactContent("native", bytes.subarray(0, 28), bytes.length),
).toEqual({ kind: "unknown", format: "unknown" });
expect(classifyArtifactContent("native", bytes)).toEqual({
kind: "executable",
format: "mach-o-universal",
});
});
it.each([NaN, Infinity, -1, 8.5, Number.MAX_SAFE_INTEGER + 1, 27])(
"keeps invalid or contradictory file size %s unknown",
(size) => {
const bytes = fat();
expect(classifyArtifactContent("native", bytes, size)).toEqual({
kind: "unknown",
format: "unknown",
});
},
);
});
@@ -37,6 +37,7 @@ interface ExpectedFile {
interface ExpectedContainer {
readonly hash_status: ArtifactOccurrence["hash_status"];
readonly format: ArtifactOccurrence["artifact_format"];
readonly inventory: JavaScriptArtifactContainer | null;
}
@@ -219,6 +220,9 @@ const visitReader = async (
"integrity",
`Nested ASAR was not integrity-verified: ${path}`,
);
// Inventory expands an ASAR-named file only when its bytes are an
// ASAR. One it recorded as ordinary bytes has no members to read.
if (container.format !== "asar") continue;
const inventory = container.inventory;
if (inventory === null)
throw new ArtifactReaderFailure(
@@ -395,6 +399,7 @@ const expectedInventory = (
if (isNestedAsar)
containers.set(occurrence.logical_path, {
hash_status: occurrence.hash_status,
format: occurrence.artifact_format,
inventory: null,
});
continue;
@@ -412,6 +417,7 @@ const expectedInventory = (
if (isNestedAsar)
containers.set(occurrence.logical_path, {
hash_status: occurrence.hash_status,
format: occurrence.artifact_format,
inventory: {
path: occurrence.logical_path,
sha256: node.sha256,
+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}`;
+247 -37
View File
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
import { captureDom } from "./CdpCaptureDocuments.js";
import { capturedSvgNodeKind } from "./CdpCaptureDomSvg.js";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
const origin = "https://app.example.test";
const documentUrl = `${origin}/screens/app`;
@@ -50,8 +52,11 @@ const snapshot = (
],
});
const capture = (value: ReturnType<typeof snapshot>) =>
captureDom(value, new Set([origin]), input);
const capture = (value: ReturnType<typeof snapshot>) => {
const step = captureDom(value, new Set([origin]), input).next();
if (!step.done) throw new Error("Unexpected SVG identity query");
return step.value;
};
describe("DOM metadata document base URLs", () => {
it("resolves links, actions and agent hints against the captured document base", () => {
@@ -282,6 +287,7 @@ interface SvgSnapshotNode {
readonly name: string;
readonly parent: number;
readonly attributes?: readonly (readonly [string, string])[];
readonly svg?: boolean;
}
const svgDocument = (
@@ -300,7 +306,13 @@ const svgDocument = (
const nodeValue = [intern("")];
const parentIndex = [-1];
const attributes: number[][] = [[]];
const backendNodeId = [1];
const svgNodeKinds = new Map<string, boolean>();
for (const element of elements) {
const id = backendNodeId.length + 1;
backendNodeId.push(id);
if (element.svg !== undefined)
svgNodeKinds.set(`${String(id)}:${element.name}`, element.svg);
nodeType.push(1);
nodeName.push(intern(element.name));
nodeValue.push(intern(""));
@@ -316,14 +328,35 @@ const svgDocument = (
{
documentURL: 0,
baseURL: 1,
nodes: { nodeType, nodeName, nodeValue, parentIndex, attributes },
nodes: {
nodeType,
nodeName,
nodeValue,
parentIndex,
attributes,
backendNodeId,
},
svgNodeKinds,
},
],
};
};
const captureSvg = (value: ReturnType<typeof svgDocument>) =>
captureDom(value, new Set([origin]), input);
const captureSvg = (value: ReturnType<typeof svgDocument>) => {
const kinds = new Map(
value.documents.flatMap((document) => [...document.svgNodeKinds]),
);
const capture = captureDom(value, new Set([origin]), input);
let step = capture.next();
while (!step.done) {
step = capture.next(
step.value.map((query) =>
kinds.get(`${String(query.backendNodeId)}:${query.nodeName}`),
),
);
}
return step.value;
};
const urlFor = (
result: ReturnType<typeof captureSvg>,
@@ -331,6 +364,136 @@ const urlFor = (
): (typeof result.urls)[number] | undefined =>
result.urls.find((url) => url.node_index === nodeIndex);
describe("browser SVG identity", () => {
const query = { backendNodeId: 42, nodeName: "a" };
const node = { ...query, nodeType: 1 };
it("uses only a matching described element's SVG flag", () => {
expect(capturedSvgNodeKind(query, { node: { ...node, isSVG: true } })).toBe(
true,
);
expect(
capturedSvgNodeKind(query, { node: { ...node, isSVG: false } }),
).toBe(false);
expect(capturedSvgNodeKind(query, { node })).toBe(false);
for (const invalid of [
{},
{ node: { ...node, backendNodeId: 43, isSVG: true } },
{ node: { ...node, nodeName: "A", isSVG: true } },
{ node: { ...node, nodeType: 3, isSVG: true } },
{ node: { ...node, isSVG: "true" } },
])
expect(capturedSvgNodeKind(query, invalid)).toBeUndefined();
});
it("distinguishes identically named SVG and MathML elements regardless of parent", () => {
const result = captureSvg(
svgDocument([
{ name: "svg", parent: 0 },
{ name: "desc", parent: 1 },
{
name: "a",
svg: true,
parent: 2,
attributes: [["xlink:href", "/svg"]],
},
{
name: "a",
svg: false,
parent: 2,
attributes: [["xlink:href", "/math"]],
},
{
name: "A",
svg: false,
parent: 1,
attributes: [["xlink:href", "/html"]],
},
{
name: "a",
svg: true,
parent: 0,
attributes: [["xlink:href", "/orphan"]],
},
]),
);
expect(result.urls.map(({ url }) => url)).toEqual([
`${origin}/svg`,
`${origin}/orphan`,
]);
});
it("records unresolved identity without inventing a destination or hiding attributes", () => {
const value = svgDocument([
{ name: "a", parent: 0, attributes: [["xlink:href", "/unknown"]] },
]);
const completeness = new CdpCaptureCompleteness();
const capture = captureDom(value, new Set([origin]), input, completeness);
expect(capture.next()).toEqual({
done: false,
value: [{ backendNodeId: 2, nodeName: "a" }],
});
const step = capture.next([undefined]);
expect(step.done).toBe(true);
if (!step.done) throw new Error("Unexpected second query");
expect(step.value.unresolvedSvgNodes).toBe(1);
expect(step.value.urls).toEqual([]);
expect(step.value.nodes[1]?.attribute_names).toEqual(["xlink:href"]);
expect(completeness.snapshot().excluded).toEqual(
expect.arrayContaining([
expect.objectContaining({
section: "metadata",
reason: "provider_unavailable",
count: 1,
}),
]),
);
});
});
it("keeps batched SVG identities aligned around missing IDs and ordinary links", () => {
const value = svgDocument([
{ name: "a", parent: 0, attributes: [["xlink:href", "/svg"]] },
{ name: "A", parent: 0, attributes: [["href", "/ordinary"]] },
{ name: "a", parent: 0, attributes: [["xlink:href", "/missing-id"]] },
{ name: "a", parent: 0, attributes: [["xlink:href", "/non-svg"]] },
]);
const completeness = new CdpCaptureCompleteness();
const capture = captureDom(
{
...value,
documents: value.documents.map((document) => ({
...document,
nodes: { ...document.nodes, backendNodeId: [1, 2, 3, null, 5] },
})),
},
new Set([origin]),
input,
completeness,
);
expect(capture.next()).toEqual({
done: false,
value: [
{ backendNodeId: 2, nodeName: "a" },
{ backendNodeId: 5, nodeName: "a" },
],
});
const step = capture.next([true, false]);
if (!step.done) throw new Error("Unexpected second batch");
expect(
step.value.urls.map(({ node_index, url }) => [node_index, url]),
).toEqual([
[1, `${origin}/svg`],
[2, `${origin}/ordinary`],
]);
expect(step.value.unresolvedSvgNodes).toBe(1);
expect(completeness.snapshot().excluded).toContainEqual({
section: "metadata",
reason: "provider_unavailable",
count: 1,
});
});
describe("SVG xlink:href destinations", () => {
it("reports an SVG anchor that only has xlink:href, keeping the first value", () => {
const result = captureSvg(
@@ -339,6 +502,7 @@ describe("SVG xlink:href destinations", () => {
{ name: "g", parent: 1 },
{
name: "a",
svg: true,
parent: 2,
attributes: [
["xlink:href", "/xl-s2h"],
@@ -371,6 +535,7 @@ describe("SVG xlink:href destinations", () => {
{ name: "svg", parent: 0 },
{
name: "a",
svg: true,
parent: 1,
attributes: [
[first, valueFor(first)],
@@ -395,18 +560,21 @@ describe("SVG xlink:href destinations", () => {
svgDocument([
{
name: "A",
svg: false,
parent: 0,
attributes: [["xlink:href", "/xl-html"]],
},
{ name: "math", parent: 0 },
{
name: "mrow",
svg: false,
parent: 2,
attributes: [["xlink:href", "/xl-math"]],
},
{ name: "svg", parent: 0 },
{
name: "a",
svg: true,
parent: 4,
attributes: [["xlink:href", "/xl-s2h"]],
},
@@ -425,6 +593,7 @@ describe("SVG xlink:href destinations", () => {
{ name: "svg", parent: 0 },
{
name: "a",
svg: true,
parent: 1,
attributes: [["xlink:href", "https://cdn.example.test/out"]],
},
@@ -444,8 +613,18 @@ describe("SVG xlink:href destinations", () => {
const result = captureSvg(
svgDocument([
{ name: "svg", parent: 0 },
{ name: "image", parent: 1, attributes: [["xlink:href", "guide"]] },
{ name: "use", parent: 1, attributes: [["xlink:href", "icon.svg"]] },
{
name: "image",
svg: true,
parent: 1,
attributes: [["xlink:href", "guide"]],
},
{
name: "use",
svg: true,
parent: 1,
attributes: [["xlink:href", "icon.svg"]],
},
]),
);
expect(result.urls).toEqual([
@@ -466,14 +645,24 @@ describe("SVG xlink:href destinations", () => {
});
describe("SVG xlink:href context", () => {
it("keeps forward ancestor context local to each document", () => {
it("binds SVG identity to the selected element across documents", () => {
const svg = svgDocument([
{ name: "a", parent: 2, attributes: [["xlink:href", "/svg-link"]] },
{
name: "a",
svg: true,
parent: 2,
attributes: [["xlink:href", "/svg-link"]],
},
{ name: "g", parent: 3 },
{ name: "svg", parent: 0 },
]);
const html = svgDocument([
{ name: "A", parent: 2, attributes: [["xlink:href", "/html-link"]] },
{
name: "A",
svg: false,
parent: 2,
attributes: [["xlink:href", "/html-link"]],
},
{ name: "DIV", parent: 3 },
{ name: "BODY", parent: 0 },
]);
@@ -507,32 +696,39 @@ describe("SVG xlink:href context", () => {
]);
});
it("stops SVG context at foreignObject and resumes it for a nested svg", () => {
const result = captureSvg(
svgDocument([
{ name: "svg", parent: 0 },
{ name: "foreignObject", parent: 1 },
{
name: "A",
parent: 2,
attributes: [["xlink:href", "/xl-html-fo"]],
},
{ name: "svg", parent: 2 },
{
name: "a",
parent: 4,
attributes: [["xlink:href", "/xl-nested"]],
},
]),
);
expect(urlFor(result, 3)).toBeUndefined();
expect(urlFor(result, 5)).toMatchObject({
attribute: "href",
url: `${origin}/xl-nested`,
destination_scope: "approved",
});
});
it.each(["foreignObject", "desc", "title"])(
"preserves browser SVG identity across %s HTML integration points",
(integrationPoint) => {
const result = captureSvg(
svgDocument([
{ name: "svg", parent: 0 },
{ name: integrationPoint, parent: 1 },
{
name: "A",
svg: false,
parent: 2,
attributes: [["xlink:href", "/xl-html-fo"]],
},
{ name: "svg", parent: 2 },
{
name: "a",
svg: true,
parent: 4,
attributes: [["xlink:href", "/xl-nested"]],
},
]),
);
expect(urlFor(result, 3)).toBeUndefined();
expect(urlFor(result, 5)).toMatchObject({
attribute: "href",
url: `${origin}/xl-nested`,
destination_scope: "approved",
});
},
);
});
describe("SVG XLink precedence and unknown identity", () => {
it("keeps an empty href ahead of xlink:href", () => {
const baseUrl = `${origin}/screens/assets/`;
const result = captureSvg(
@@ -541,6 +737,7 @@ describe("SVG xlink:href context", () => {
{ name: "svg", parent: 0 },
{
name: "a",
svg: true,
parent: 1,
attributes: [
["href", ""],
@@ -567,6 +764,7 @@ describe("SVG xlink:href context", () => {
{ name: "svg", parent: 0 },
{
name: "a",
svg: true,
parent: 1,
attributes: [["xlink:href", "javascript:void(0)"]],
},
@@ -582,7 +780,7 @@ describe("SVG xlink:href context", () => {
]);
});
it("does not treat a cyclic or dangling parent chain as SVG", () => {
it("keeps an unavailable SVG identity unknown despite ancestor names", () => {
const cyclic = captureSvg(
svgDocument([
{ name: "g", parent: 2 },
@@ -652,7 +850,12 @@ describe("XML SVG roots and namespace scope restoration", () => {
["xmlns:p", XLINK_NAMESPACE],
],
},
{ name: "a", parent: 1, attributes: [["p:href", "/linked"]] },
{
name: "a",
svg: true,
parent: 1,
attributes: [["p:href", "/linked"]],
},
]),
);
expect(result.urls).toEqual([approvedHref(2, `${origin}/linked`)]);
@@ -764,6 +967,7 @@ describe("XHTML and XML SVG namespace prefixes", () => {
{ name: "svg:foreignObject", parent: 2 },
{
name: "a",
svg: true,
parent: 3,
attributes: [["xlink:href", "/xl-html-fo"]],
},
@@ -799,6 +1003,7 @@ describe("XHTML and XML SVG namespace prefixes", () => {
},
{
name: "a",
svg: true,
parent: 2,
attributes: [
["xlink:href", "/not-xlink"],
@@ -918,11 +1123,13 @@ describe("XHTML SVG exclusions, HTML documents, and prefix scope", () => {
},
{
name: "a",
svg: true,
parent: 2,
attributes: [["xlink:href", "/xl-literal"]],
},
{
name: "a",
svg: true,
parent: 2,
attributes: [["x:href", "/xl-custom-html"]],
},
@@ -937,6 +1144,7 @@ describe("XHTML SVG exclusions, HTML documents, and prefix scope", () => {
},
{
name: "A",
svg: false,
parent: 1,
attributes: [["xlink:href", "/xl-html-anchor"]],
},
@@ -944,7 +1152,9 @@ describe("XHTML SVG exclusions, HTML documents, and prefix scope", () => {
);
expect(result.urls).toEqual([approvedHref(3, `${origin}/xl-literal`)]);
});
});
describe("XML namespace resolution ordering and capacity", () => {
it("applies an element's own xmlns declarations to its name and href", () => {
const result = captureSvg(
svgDocument([
+128 -32
View File
@@ -11,7 +11,11 @@ import {
} from "./CdpCaptureValues.js";
import { exclusionReasonForUrl } from "./CdpCaptureEventHelpers.js";
import type { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import { createDocumentSvgAncestry, domSvgLink } from "./CdpCaptureDomSvg.js";
import {
createDocumentSvgAncestry,
domSvgLink,
type DomSvgNodeQuery,
} from "./CdpCaptureDomSvg.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
export type CapturedResource = Omit<
@@ -135,18 +139,39 @@ export const walkFrameTrees = function* (
}
};
export const captureDom = (
interface DomMetadataCapture {
readonly urls: WebPageInspection["metadata"]["dom_urls"];
readonly agentHints: WebPageInspection["metadata"]["agent_hints"];
readonly excludedUrls: number;
readonly unresolvedSvgNodes: number;
}
export interface DomCapture extends DomMetadataCapture {
readonly total: number;
readonly nodes: WebPageInspection["dom"]["nodes"];
}
// Bound retained projections and outstanding CDP reads independently of page size.
// Eight leaves room for the session's other cancellation listeners.
const DOM_METADATA_BATCH_SIZE = 8;
interface PendingDomMetadata {
readonly options: DomMetadataOptions;
// Undefined means no query is needed; null means the candidate has no valid ID.
readonly svgQuery: DomSvgNodeQuery | null | undefined;
}
/** Project one snapshot, requesting bounded batches of SVG identity facts. */
export function* captureDom(
result: unknown,
allowedOrigins: ReadonlySet<string>,
input: InspectWebPageInput,
completeness?: CdpCaptureCompleteness,
): {
readonly total: number;
readonly nodes: WebPageInspection["dom"]["nodes"];
readonly urls: WebPageInspection["metadata"]["dom_urls"];
readonly agentHints: WebPageInspection["metadata"]["agent_hints"];
readonly excludedUrls: number;
} => {
): Generator<
readonly DomSvgNodeQuery[],
DomCapture,
readonly (boolean | undefined)[]
> {
const root = requiredRecord(result);
const strings = Array.isArray(root.strings)
? root.strings.map((value) => cdpStringValue(value) ?? "")
@@ -156,6 +181,7 @@ export const captureDom = (
const agentHints: WebPageInspection["metadata"]["agent_hints"] = [];
let excludedUrls = 0;
let total = 0;
let unresolvedSvgNodes = 0;
for (const document of recordsValue(root.documents)) {
const documentUrl = indexedString(strings, document.documentURL);
if (allowedSanitizedUrl(documentUrl, allowedOrigins) === undefined) {
@@ -172,6 +198,9 @@ export const captureDom = (
const attributes = Array.isArray(documentNodes.attributes)
? documentNodes.attributes
: [];
const backendNodeIds = Array.isArray(documentNodes.backendNodeId)
? documentNodes.backendNodeId
: [];
const baseIndex = nodes.length;
const ancestry = createDocumentSvgAncestry({
nodeTypes,
@@ -181,12 +210,29 @@ export const captureDom = (
attributes,
});
total += nodeTypes.length;
const pendingMetadata: PendingDomMetadata[] = [];
for (let index = 0; index < nodeTypes.length; index += 1) {
const attributeIndexes = numberArray(attributes[index]);
const parent = Math.trunc(parents[index] ?? -1);
const nodeIndex = nodes.length;
const nodeName = indexedString(strings, nodeNames[index]);
const attributeNames = uniqueAttributeNames(attributeIndexes, strings);
const svgLink = domSvgLink(ancestry, index);
let svgQuery: DomSvgNodeQuery | null | undefined;
if (
!svgLink.xmlDocument &&
nodeTypes[index] === 1 &&
attributeNames.includes("xlink:href") &&
!attributeNames.includes("href")
) {
const backendNodeId = numberValue(backendNodeIds[index]);
svgQuery =
backendNodeId !== undefined &&
Number.isSafeInteger(backendNodeId) &&
backendNodeId > 0
? { backendNodeId, nodeName }
: null;
}
nodes.push({
index: nodeIndex,
parent_index: parent < 0 ? -1 : baseIndex + parent,
@@ -195,30 +241,34 @@ export const captureDom = (
node_value_length: indexedString(strings, nodeValues[index]).length,
attribute_names: attributeNames,
});
const metadata = domMetadata({
strings,
attributes: attributeIndexes,
// The BASE element itself resolves against the document fallback URL.
baseUrl: nodeName.toLowerCase() === "base" ? documentUrl : baseUrl,
documentUrl,
nodeIndex,
nodeName,
allowedOrigins,
...domSvgLink(ancestry, index),
pendingMetadata.push({
svgQuery,
options: {
strings,
attributes: attributeIndexes,
// The BASE element itself resolves against the document fallback URL.
baseUrl: nodeName.toLowerCase() === "base" ? documentUrl : baseUrl,
documentUrl,
nodeIndex,
nodeName,
allowedOrigins,
...svgLink,
},
});
for (const url of metadata.urls) {
urls.push(url);
if (url.destination_scope !== "approved") {
excludedUrls += 1;
completeness?.exclude(
"metadata",
url.destination_scope === "outside_policy"
? "disallowed_origin"
: "unsupported_url",
);
}
if (
pendingMetadata.length === DOM_METADATA_BATCH_SIZE ||
index === nodeTypes.length - 1
) {
const metadata = yield* captureDomMetadata(
pendingMetadata,
completeness,
);
urls.push(...metadata.urls);
agentHints.push(...metadata.agentHints);
excludedUrls += metadata.excludedUrls;
unresolvedSvgNodes += metadata.unresolvedSvgNodes;
pendingMetadata.length = 0;
}
agentHints.push(...metadata.agentHints);
}
}
return {
@@ -227,8 +277,54 @@ export const captureDom = (
urls,
agentHints,
excludedUrls,
unresolvedSvgNodes,
};
};
}
function* captureDomMetadata(
pending: readonly PendingDomMetadata[],
completeness: CdpCaptureCompleteness | undefined,
): Generator<
readonly DomSvgNodeQuery[],
DomMetadataCapture,
readonly (boolean | undefined)[]
> {
const queries = pending.flatMap(({ svgQuery }) =>
svgQuery == null ? [] : [svgQuery],
);
const kinds = queries.length > 0 ? yield queries : [];
const urls: DomMetadataCapture["urls"] = [];
const agentHints: DomMetadataCapture["agentHints"] = [];
let queryIndex = 0;
let unresolvedSvgNodes = 0;
let excludedUrls = 0;
for (const { options, svgQuery } of pending) {
let svgElement = options.svgElement;
if (svgQuery !== undefined) {
const kind = svgQuery === null ? undefined : kinds[queryIndex++];
svgElement = kind === true;
if (kind === undefined) {
unresolvedSvgNodes += 1;
completeness?.exclude("metadata", "provider_unavailable");
}
}
const metadata = domMetadata({ ...options, svgElement });
for (const url of metadata.urls) {
urls.push(url);
if (url.destination_scope !== "approved") {
excludedUrls += 1;
completeness?.exclude(
"metadata",
url.destination_scope === "outside_policy"
? "disallowed_origin"
: "unsupported_url",
);
}
}
agentHints.push(...metadata.agentHints);
}
return { urls, agentHints, unresolvedSvgNodes, excludedUrls };
}
export const captureAccessibility = (
results: readonly unknown[],
+27 -47
View File
@@ -1,4 +1,4 @@
import { numberValue } from "./CdpCaptureValues.js";
import { numberValue, recordValue } from "./CdpCaptureValues.js";
const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
const XLINK_NAMESPACE = "http://www.w3.org/1999/xlink";
@@ -18,11 +18,34 @@ interface XmlSvgLink {
interface DocumentSvgAncestry {
readonly xml: boolean;
readonly nodes: DomSnapshotNodes;
readonly svgContexts: Map<number, boolean>;
readonly xmlLinks: Map<number, XmlSvgLink>;
}
export interface DomSvgNodeQuery {
readonly backendNodeId: number;
readonly nodeName: string;
}
/** Bind the browser's SVG flag to the exact snapshotted element. */
export const capturedSvgNodeKind = (
query: DomSvgNodeQuery,
result: unknown,
): boolean | undefined => {
const node = recordValue(recordValue(result)?.node);
if (
node?.backendNodeId !== query.backendNodeId ||
node.nodeName !== query.nodeName ||
node.nodeType !== 1
)
return undefined;
// CDP omits isSVG for non-SVG nodes. Other values are malformed, not false.
return node.isSVG === undefined
? false
: typeof node.isSVG === "boolean"
? node.isSVG
: undefined;
};
interface DomSvgLink {
readonly svgElement: boolean;
readonly xmlDocument: boolean;
@@ -79,8 +102,6 @@ export const createDocumentSvgAncestry = (
const xml = xmlDocument(nodes);
return {
xml,
nodes,
svgContexts: new Map(),
xmlLinks: xml ? resolveXmlElements(nodes) : new Map(),
};
};
@@ -91,11 +112,7 @@ export const domSvgLink = (
): DomSvgLink => {
if (!ancestry.xml) {
return {
svgElement: elementInSvgContext(
index,
ancestry.nodes,
ancestry.svgContexts,
),
svgElement: false,
xmlDocument: false,
xlinkHref: undefined,
};
@@ -108,43 +125,6 @@ export const domSvgLink = (
};
};
// Chrome's HTML parser records SVG local names (`svg`, `foreignObject`).
// Descendants of foreignObject are HTML until a nested `svg`.
const elementInSvgContext = (
index: number,
nodes: DomSnapshotNodes,
contexts: Map<number, boolean>,
): boolean => {
let current = index;
const seen = new Set<number>();
let inSvg = false;
while (
current >= 0 &&
current < nodes.nodeNames.length &&
!seen.has(current)
) {
const cached = contexts.get(current);
if (cached !== undefined) {
inSvg = cached;
break;
}
seen.add(current);
if (stringAt(nodes.strings, nodes.nodeNames[current]) === "svg") {
inSvg = true;
break;
}
const parent = Math.trunc(nodes.parents[current] ?? -1);
if (parent < 0 || parent === current) break;
if (stringAt(nodes.strings, nodes.nodeNames[parent]) === "foreignObject")
break;
current = parent;
}
// Cache the entire examined chain, including forward references and cycles,
// so shared ancestors are examined once per document.
for (const node of seen) contexts.set(node, inSvg);
return inSvg;
};
interface NamespaceRestore {
readonly prefix: string;
readonly previous: string | undefined;
+49 -5
View File
@@ -17,8 +17,10 @@ import {
captureFrames,
captureResources,
type CapturedResource,
type DomCapture,
mainFrameUrl,
} from "./CdpCaptureDocuments.js";
import { capturedSvgNodeKind } from "./CdpCaptureDomSvg.js";
import {
allowedSanitizedUrl,
delayWithCancellation,
@@ -52,7 +54,7 @@ interface CaptureState {
interface CapturedSections {
readonly attachedUrl: string;
readonly frames: WebPageInspection["frames"];
readonly dom: ReturnType<typeof captureDom>;
readonly dom: DomCapture;
readonly accessibility: ReturnType<typeof captureAccessibility>;
readonly scripts: WebPageInspection["scripts"];
readonly resources: WebPageInspection["resources"];
@@ -260,9 +262,7 @@ const authorizeObservationWindow = async (
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
};
const capturePageDom = async (
state: CaptureState,
): Promise<ReturnType<typeof captureDom>> => {
const capturePageDom = async (state: CaptureState): Promise<DomCapture> => {
const { context, allowedOrigins } = state;
const result = await context.connection.send(
"DOMSnapshot.captureSnapshot",
@@ -274,12 +274,56 @@ const capturePageDom = async (
context.sessionId,
context.signal,
);
return captureDom(
const capture = captureDom(
result,
allowedOrigins,
context.input,
state.events.completeness,
);
let step = capture.next();
let descriptionUnavailable = false;
const pendingController = new AbortController();
const signal =
context.signal === undefined
? pendingController.signal
: AbortSignal.any([context.signal, pendingController.signal]);
while (!step.done) {
const pending = step.value.map(async (query) => {
if (descriptionUnavailable) return undefined;
try {
return capturedSvgNodeKind(
query,
await context.connection.send(
"DOM.describeNode",
{ backendNodeId: query.backendNodeId, depth: 0 },
context.sessionId,
signal,
),
);
} catch (cause: unknown) {
// A detached node can disappear between snapshot and description.
// Preserve partial metadata, but propagate transport/cancellation errors.
if (!(cause instanceof CdpCommandRejection)) throw cause;
if (cause.code === -32_601) descriptionUnavailable = true;
else if (cause.code !== -32_000) throw cause;
return undefined;
}
});
try {
// Promise.all preserves snapshot order even when CDP replies out of order.
step = capture.next(await Promise.all(pending));
} catch (cause: unknown) {
// Stop and settle this bounded batch before the session can be detached.
pendingController.abort();
await Promise.allSettled(pending);
throw cause;
}
}
if (step.value.unresolvedSvgNodes > 0)
state.limitations.push(
`SVG identity was unavailable for ${String(step.value.unresolvedSvgNodes)} snapshotted XLink candidate nodes; their URL destinations remain unknown.`,
);
return step.value;
};
const normalizedInspection = (
+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 }),
}),
});
};
+3 -2
View File
@@ -216,8 +216,9 @@ export const createCliResultOutput = (
: filtered === undefined
? { ok: true, meta }
: { ok: true, data: filtered, meta }
: filtered === undefined ||
filtered === null ||
: // A selected null is a value; only a selection with no JSON value
// falls back to the empty document.
filtered === undefined ||
typeof filtered === "function" ||
typeof filtered === "symbol"
? {}
+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],
+29 -3
View File
@@ -9,7 +9,7 @@ export type CliOutputArgumentValidation =
| {
readonly ok: false;
readonly format: StructuredOutputFormat;
readonly code: "UNSUPPORTED_OUTPUT_COMBINATION";
readonly code: "UNSUPPORTED_OUTPUT_COMBINATION" | "INVALID_OUTPUT_FILTER";
readonly message: string;
};
@@ -89,13 +89,39 @@ export const parseCliOutputArguments = (
return parsed(false);
};
/** Reject text-window controls that would corrupt a structured document. */
/** Reject slices that cannot advance within Incur's comma-delimited paths. */
const hasUnclosedFilterSlice = (expression: string): boolean => {
let depth = 0;
let unclosed = false;
for (const character of expression) {
if (character === "[") {
depth += 1;
unclosed = true;
} else if (character === "]") {
depth -= 1;
// Incur consumes everything through the next closing bracket, including
// nested opening brackets. Do not impose a different filter grammar.
unclosed = false;
} else if (character === "," && depth === 0 && unclosed) return true;
}
return unclosed;
};
/** Reject output controls that cannot safely produce a complete result. */
export const validateCliOutputArguments = (
arguments_: readonly string[],
): CliOutputArgumentValidation => {
const { format, parseError, tokenWindow } =
const { filterOutput, format, parseError, tokenWindow } =
parseCliOutputArguments(arguments_);
if (parseError) return { ok: true };
if (filterOutput !== undefined && hasUnclosedFilterSlice(filterOutput))
return {
ok: false,
format: format === "yaml" || format === "jsonl" ? format : "json",
code: "INVALID_OUTPUT_FILTER",
message:
"The --filter-output expression has a slice without a closing ]. Close the slice or remove --filter-output.",
};
if (
tokenWindow &&
(format === "json" || format === "jsonl" || format === "yaml")
@@ -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."],
});
+1 -1
View File
@@ -107,7 +107,7 @@ export const NATIVE_TOOL_CONTRACTS = [
),
native(
"inspect_signature",
"Inspect the active artifact's code-signing identity, hashes, authorities, requirements, entitlements, hardened-runtime state, and exact command provenance.",
"Inspect the active Mach-O executable's code-signing identity, hashes, authorities, requirements, entitlements, hardened-runtime state, and exact command provenance.",
z.object({}),
),
native(
+2 -2
View File
@@ -149,12 +149,12 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"procedure_callees",
"Return the provider's resolved direct callees for one procedure identified by symbol or address. Unresolved indirect calls may be absent; use analyze_function and typed references to preserve available edge uncertainty.",
"Return the provider's resolved direct callees for one procedure identified by symbol or address. Unresolved indirect calls may be absent; use analyze_function and typed references to preserve available edge uncertainty. Ghidra terminal-call assumptions that may cut the analyzed body are reported in Evidence limitations.",
z.object({ procedure, document }),
),
official(
"procedure_callers",
"Return the provider's resolved direct callers for one procedure identified by symbol or address. Results reflect completed static analysis and may omit unresolved indirect references.",
"Return the provider's resolved direct callers for one procedure identified by symbol or address. Results reflect completed static analysis and may omit unresolved indirect references. Ghidra terminal-call assumptions that may cut the analyzed body are reported in Evidence limitations.",
z.object({ procedure, document }),
),
official(
@@ -6,6 +6,34 @@ import { z } from "zod";
import { toolContract } from "./toolContracts.js";
import { toolOutputSchemaWithMetadata } from "./toolSchemaMetadata.js";
import { createEvidence } from "../domain/evidence.js";
it.each(["draft-2020-12", "draft-07"] as const)(
"advertises the raw-only 6502 Evidence subject constraint in %s",
(target) => {
const valid = createEvidence(
{
path: "/fixture/image.bin",
sha256: "a".repeat(64),
format: "raw-binary",
architecture: "6502",
},
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "address_name", parameters: {}, result: "entry" },
);
const advertised = toolOutputSchemaWithMetadata(
toolContract("address_name"),
)["~standard"].jsonSchema.output({ target });
const validate = new AjvJsonSchemaValidator().getValidator(advertised);
expect(validate(valid).valid).toBe(true);
expect(
validate({
...valid,
subject: { ...valid.subject, format: "pe" },
}).valid,
).toBe(false);
},
);
it("keeps dialect-specific validators distinct after JSON schema serialization", () => {
const contract = {
+1 -1
View File
@@ -444,11 +444,11 @@ const lifecycleTargetFields = {
path: z.string(),
kind: targetKindSchema,
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
};
const detectedLifecycleTargetSchema = z.object({
...lifecycleTargetFields,
format: targetFormatSchema.exclude(["raw-binary"]),
architecture: z.enum(BINARY_ARCHITECTURES).exclude(["6502"]).nullable(),
});
const rawLifecycleTargetSchema = z.object({
...lifecycleTargetFields,
+65 -2
View File
@@ -52,7 +52,7 @@ const snapshotWithHistoricalEvidence = () => {
};
return {
current,
snapshot: {
snapshot: analysisSnapshotSchema.parse({
target,
binding,
entries: [entry],
@@ -66,11 +66,32 @@ const snapshotWithHistoricalEvidence = () => {
result: { summary: "unprofiled" },
}),
]),
} satisfies AnalysisSnapshot,
}),
};
};
describe("analysis snapshot target identity", () => {
it("keeps 6502 confined to executable raw snapshots", () => {
const target = {
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
kind: "executable",
architecture: "6502",
};
expect(
analysisSnapshotSchema.shape.target.safeParse({
...target,
format: "pe",
}).success,
).toBe(false);
expect(
analysisSnapshotSchema.shape.target.safeParse({
...target,
format: "raw-binary",
entry_point: "0x8001",
}).success,
).toBe(true);
});
it("partitions raw snapshots and query identities by the canonical entry", () => {
const target: BinaryTarget = {
path: "/fixture/image.bin",
@@ -120,6 +141,48 @@ describe("analysis snapshot target identity", () => {
});
});
describe("analysis snapshot nested subject contract", () => {
it("rejects raw-only 6502 in nested detected execution subjects", () => {
const { snapshot } = snapshotWithHistoricalEvidence();
const entry = snapshot.entries[0];
if (entry === undefined) throw new Error("Fixture has no snapshot entry");
const malformedSubject = {
...entry.execution.subject,
format: "pe",
architecture: "6502",
};
expect(
analysisSnapshotSchema.safeParse({
...snapshot,
entries: [
{
...entry,
execution: {
...entry.execution,
subject: malformedSubject,
},
},
],
}).success,
).toBe(false);
expect(
analysisSnapshotSchema.safeParse({
...snapshot,
workflow_entries: [
{
...entry,
execution: {
...entry.execution,
analysis_profile: snapshot.binding.analysis_profile,
subject: malformedSubject,
},
},
],
}).success,
).toBe(false);
});
});
describe("analysis snapshot contract", () => {
it.each([
["dos-mz", "x86"],
+47 -28
View File
@@ -41,7 +41,10 @@ import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { canonicalJsonDigestSteps } from "./canonicalJsonDigestSteps.js";
import { freezeJsonSnapshot } from "./immutableJson.js";
import { rawBinaryEntryPointSchema } from "./rawBinary.js";
import {
binaryArchitectureSchema,
rawBinaryEntryPointSchema,
} from "./rawBinary.js";
import {
relationshipCoverageSchema,
type RelationshipCoverage,
@@ -73,20 +76,30 @@ const formatSchema = z.enum([
"source-map",
]);
const kindSchema = z.enum(["executable", "database", "archive", "artifact"]);
const subjectSchema = z.object({
const subjectBaseSchema = z.object({
path: localPathStringSchema,
sha256: digestSchema,
format: z.enum([
...formatSchema.options,
"hopper",
"directory",
"file",
"unknown",
"javascript-bundle",
"entitlements",
]),
architecture: architectureSchema.nullable(),
});
const subjectFormatSchema = z.enum([
...formatSchema.options,
"hopper",
"directory",
"file",
"unknown",
"javascript-bundle",
"entitlements",
]);
// Snapshot entries retain the same raw-only architecture boundary as targets.
const subjectSchema = z.discriminatedUnion("format", [
subjectBaseSchema.extend({
format: subjectFormatSchema.exclude(["raw-binary"]),
architecture: architectureSchema.exclude(["6502"]).nullable(),
}),
subjectBaseSchema.extend({
format: z.literal("raw-binary"),
architecture: architectureSchema.nullable(),
}),
]);
const targetIdentitySchema = z.object({
sha256: digestSchema,
kind: kindSchema,
@@ -97,9 +110,12 @@ const targetSchema = z.discriminatedUnion("format", [
format: z.enum(
formatSchema.options.filter((format) => format !== "raw-binary"),
),
architecture: architectureSchema.exclude(["6502"]).nullable(),
}),
targetIdentitySchema.extend({
format: z.literal("raw-binary"),
kind: z.literal("executable"),
architecture: binaryArchitectureSchema,
entry_point: rawBinaryEntryPointSchema,
}),
]);
@@ -332,18 +348,21 @@ const canonicalJson = (value: unknown): string => {
};
/** Project a binary into the path-free identity used for cache invalidation. */
export const snapshotTarget = (
target: BinaryTarget,
): AnalysisSnapshotTarget => {
const identity = {
sha256: target.sha256,
kind: target.kind,
architecture: target.architecture ?? null,
};
return target.format === "raw-binary"
? { ...identity, format: target.format, entry_point: target.entryPoint }
: { ...identity, format: target.format };
};
export const snapshotTarget = (target: BinaryTarget): AnalysisSnapshotTarget =>
target.format === "raw-binary"
? {
sha256: target.sha256,
kind: target.kind,
architecture: target.architecture,
format: target.format,
entry_point: target.entryPoint,
}
: {
sha256: target.sha256,
kind: target.kind,
architecture: target.architecture ?? null,
format: target.format,
};
/** Build the immutable provider/profile binding used by a cached snapshot. */
export const snapshotBinding = (
@@ -475,10 +494,10 @@ export const createAnalysisSnapshotWorkflowEntry = (input: {
subject:
execution.subject === null
? null
: {
: subjectSchema.parse({
...execution.subject,
architecture: execution.subject.architecture ?? null,
},
}),
},
};
};
@@ -538,10 +557,10 @@ export const createAnalysisSnapshotEntry = (input: {
subject:
execution.subject === null
? null
: {
: subjectSchema.parse({
...execution.subject,
architecture: execution.subject.architecture ?? null,
},
}),
},
};
};
+45 -1
View File
@@ -169,7 +169,8 @@ it("pages every retained dossier collection and the native API record", () => {
| "comments"
| "unresolved_calls"
| "referenced_strings"
| "referenced_names",
| "referenced_names"
| "swift_string_literals",
result: unknown = original,
) => {
const view = projectAnalysisView(nativeParent(result), {
@@ -195,6 +196,23 @@ it("pages every retained dossier collection and the native API record", () => {
}),
).toMatchObject({ item: [{ text: "entry" }] });
expect(page("referenced_names")).toMatchObject({ coverage: { total: 0 } });
const literal = {
source_address: "0x401004",
value: "SleepDisabled",
representation: "small",
address: null,
registers: ["x0", "x1"],
words: ["0x7369447065656c53", "0xed000064656c6261"],
};
expect(
page("swift_string_literals", {
...original,
swift_string_literals: [literal],
}),
).toMatchObject({ item: [literal], coverage: { total: 1 } });
expect(page("swift_string_literals")).toMatchObject({
item: { available: false, reason: "not recorded" },
});
const { unresolved_calls: _omitted, ...withoutUnresolved } = original;
expect(
page("unresolved_calls", {
@@ -774,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]),
});
}
});
+2
View File
@@ -160,6 +160,8 @@ const nativeViewSchema = z.strictObject({
"unresolved_calls",
"referenced_strings",
"referenced_names",
"swift_string_literals",
"swift_string_literal_omissions",
"native_api",
"value_flow_summary",
"value_flow_operations",
+21 -1
View File
@@ -79,6 +79,8 @@ const nativeRows = (
unresolved_calls: dossier.unresolved_calls,
referenced_strings: dossier.referenced_strings,
referenced_names: dossier.referenced_names,
swift_string_literals: dossier.swift_string_literals,
swift_string_literal_omissions: dossier.swift_string_literal_omissions,
value_flow_operations: flow?.operations,
value_flow_def_use: flow?.def_use,
value_flow_effects: flow?.effects,
@@ -108,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,
@@ -115,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" ||
@@ -163,7 +182,8 @@ export const projectNativeFunctionView = (
singleton({
available: false,
// Only value-flow facets inherit the value-flow failure reason; an
// older dossier simply has no unresolved_calls record.
// older dossier simply has no unresolved_calls record, and a target
// whose provider does not decode Swift literals has no such record.
reason:
view.facet.startsWith("value_flow_") && flow?.available === false
? flow.reason
+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;
@@ -510,6 +510,106 @@ describe("AppKit keyed archive connectors", () => {
});
});
describe("keyed archive unresolved connectors", () => {
// A rooted UIKit archive whose only connector is UID 3, with UID 1 as the
// owner, UID 2 as the destination and UID 7 as the "view" label.
const rootedOutletArchive = (connection: Record<string, unknown>) => ({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: [
"$null",
{ $class: { CF$UID: 4 } },
{ $class: { CF$UID: 5 } },
{ $class: { CF$UID: 6 }, ...connection },
{
$classname: "UIViewController",
$classes: ["UIViewController", "UIResponder", "NSObject"],
},
{ $classname: "UIView", $classes: ["UIView", "UIResponder", "NSObject"] },
{
$classname: "UIRuntimeOutletConnection",
$classes: [
"UIRuntimeOutletConnection",
"UIRuntimeConnection",
"NSObject",
],
},
"view",
{
$class: { CF$UID: 11 },
"NS.objects": [{ CF$UID: 1 }, { CF$UID: 2 }, { CF$UID: 3 }],
},
{ $class: { CF$UID: 11 }, "NS.objects": [{ CF$UID: 3 }] },
{
$class: { CF$UID: 11 },
"NS.objects": [{ CF$UID: 1 }, { CF$UID: 2 }],
},
{ $classname: "NSArray", $classes: ["NSArray", "NSObject"] },
],
$top: {
root: { CF$UID: 8 },
UINibConnectionsKey: { CF$UID: 9 },
UINibObjectsKey: { CF$UID: 10 },
UINibTopLevelObjectsKey: { CF$UID: 10 },
},
});
const project = (raw: unknown) =>
buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath: "Main.nib",
archiveSha256: hash,
documentKind: "nib",
raw,
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
it("covers a resolvable connector as a complete examined connection", () => {
const raw = rootedOutletArchive({
UISource: { CF$UID: 1 },
UIDestination: { CF$UID: 2 },
UILabel: { CF$UID: 7 },
});
expect(parseInterfaceBuilderRecords(raw).unresolvedConnections).toBe(0);
expect(project(raw).graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Main.nib",
status: "complete",
examined: 1,
omitted: 0,
}),
);
});
it("reports a recognized connector with no resolvable owner as unresolved", () => {
const raw = rootedOutletArchive({
UIDestination: { CF$UID: 2 },
UILabel: { CF$UID: 7 },
});
expect(parseInterfaceBuilderRecords(raw).unresolvedConnections).toBe(1);
const analysis = project(raw);
expect(analysis.graph.nodes.some(({ kind }) => kind === "outlet")).toBe(
false,
);
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Main.nib",
status: "partial",
reason: "connection_unresolved",
examined: 0,
omitted: 1,
}),
);
expect(analysis.graph.truncated).toBe(true);
});
});
it("names the archive once per evidence record", () => {
const relativePath = "Views/Main.storyboardc/scene.nib/objects.nib";
const result = buildInterfaceBuilderAnalysis({
+18 -5
View File
@@ -410,18 +410,26 @@ export const buildInterfaceBuilderAnalysis = (input: {
const connectionsTruncated =
parserOmittedConnections > 0 ||
parsed.connections.length > input.limits.max_connections;
// A recognized connector the parser could not attach to an owner produces
// no connection record, so its coverage is partial with its own reason
// rather than absent or truncated.
const connectionsUnresolved = parsed.unresolvedConnections > 0;
omittedObjects +=
parsed.omittedObjects +
Math.max(0, parsed.objects.length - documentObjectCount);
omittedConnections +=
Math.max(0, parsed.connections.length - input.limits.max_connections) +
parserOmittedConnections;
parserOmittedConnections +
parsed.unresolvedConnections;
summaries.push({
relative_path: document.relativePath,
archive_sha256: document.archiveSha256,
document_kind: document.documentKind,
object_count: parsed.objectCount,
connection_count: parsed.connections.length + parserOmittedConnections,
connection_count:
parsed.connections.length +
parserOmittedConnections +
parsed.unresolvedConnections,
hierarchy_complete:
parsed.hierarchy.length > 0 &&
!truncated &&
@@ -440,13 +448,17 @@ export const buildInterfaceBuilderAnalysis = (input: {
{
facet: `connections:${document.relativePath}`,
status:
connectionsTruncated || documentOmittedConnections > 0
connectionsTruncated ||
documentOmittedConnections > 0 ||
connectionsUnresolved
? "partial"
: "complete",
reason:
connectionsTruncated || documentOmittedConnections > 0
? "connection_limit_reached"
: null,
: connectionsUnresolved
? "connection_unresolved"
: null,
examined: Math.min(
parsed.connections.length,
input.limits.max_connections,
@@ -457,7 +469,8 @@ export const buildInterfaceBuilderAnalysis = (input: {
parsed.connections.length - input.limits.max_connections,
) +
documentOmittedConnections +
parserOmittedConnections,
parserOmittedConnections +
parsed.unresolvedConnections,
},
{
facet: `hierarchy:${document.relativePath}`,
@@ -55,6 +55,7 @@ export const parseInterfaceBuilderRecords = (
readonly objectCount: number;
readonly omittedObjects: number;
readonly omittedConnections: number;
readonly unresolvedConnections: number;
readonly omittedHierarchyReferences: number;
} => {
const root = record(value);
@@ -135,6 +136,7 @@ export const parseInterfaceBuilderRecords = (
objectCount: objectEntries.length,
omittedObjects: Math.max(0, objectEntries.length - 20_000),
omittedConnections,
unresolvedConnections: 0,
omittedHierarchyReferences: 0,
};
};
@@ -320,6 +322,7 @@ const parseKeyedArchive = (
const connections: InterfaceBuilderConnection[] = [];
let objectCount = 0;
let omittedConnections = 0;
let unresolvedConnections = 0;
for (const [index, raw] of objectTable.entries()) {
if (index === 0) continue;
const resolved = record(resolve(raw));
@@ -371,7 +374,13 @@ const parseKeyedArchive = (
controlAction ? fields.to : fields.from,
controlAction ? fields.target : fields.owner,
);
if (source === null) continue;
if (source === null) {
// A recognized connector that cannot name its owner is an unresolved
// connection, not an absent one, and cannot be represented as a
// connection because connection identity requires a source.
unresolvedConnections += 1;
continue;
}
const kind = controlAction ? "action" : classifyConnection(className);
const parsedConnection = connection.parse({
id: `archive:${objectId}`,
@@ -426,6 +435,7 @@ const parseKeyedArchive = (
objectCount,
omittedObjects: Math.max(0, objectCount - 20_000),
omittedConnections,
unresolvedConnections,
omittedHierarchyReferences: hierarchy.omittedReferences,
};
};
+5
View File
@@ -63,6 +63,11 @@ export const readFatContainerHeader = (
const magic = view.getUint32(0, false);
if (![FAT_MAGIC, FAT_MAGIC_64, FAT_CIGAM, FAT_CIGAM_64].includes(magic))
return { state: "not-fat" };
if (!Number.isSafeInteger(fileSize) || fileSize < bytes.byteLength)
return {
state: "malformed",
reason: "FAT file size is invalid or contradicts retained bytes",
};
if (bytes.byteLength < 8) {
return fileSize < 8
? { state: "malformed", reason: "FAT header is truncated" }
+9 -3
View File
@@ -278,8 +278,12 @@ export const parsePeRecord = (
record.toString("binary", 0, 4) !== "PE\u0000\u0000"
)
return err("invalid or truncated PE header");
const machine = decodePeMachine(record.readUInt16LE(4));
if (machine === undefined) return err("unsupported PE architecture");
const machineType = record.readUInt16LE(4);
const machine = decodePeMachine(machineType);
if (machine === undefined)
return err(
`unsupported PE architecture (COFF machine 0x${machineType.toString(16).padStart(4, "0")})`,
);
const { architecture } = machine;
const optionalHeaderSize = record.readUInt16LE(20);
if (optionalHeaderSize > 4096 || record.length < 24 + optionalHeaderSize)
@@ -347,7 +351,9 @@ const machArchitecture = (cpu: number): HeaderArchitecture | undefined => {
return undefined;
};
const elfArchitecture = (machine: number): BinaryArchitecture | undefined => {
const elfArchitecture = (
machine: number,
): Exclude<BinaryArchitecture, "6502"> | undefined => {
switch (machine) {
case 3:
return "x86";
+13 -3
View File
@@ -1,12 +1,13 @@
import type { ZipPackageFormat } from "./zipPackageFormat.js";
/** Provider-neutral CPU families detected from supported executable headers. */
/** Provider-neutral CPU families detected from headers or explicitly selected raw loads. */
export const BINARY_ARCHITECTURES = [
"x86",
"x86_64",
"arm",
"arm64",
"mips",
"6502",
"riscv",
] as const;
export type BinaryArchitecture = (typeof BINARY_ARCHITECTURES)[number];
@@ -40,7 +41,7 @@ export const isElfMetadataArchitecture = (
/** Recognized family with no ELF metadata member; the header alone is the fact. */
export type HeaderArchitecture = Exclude<
BinaryArchitecture,
ElfMetadataArchitecture
ElfMetadataArchitecture | "6502"
>;
/** Raw ELF facts; family recognition does not establish ISA or ABI support. */
@@ -144,8 +145,17 @@ export type BinaryTarget =
readonly executableRole?: never;
readonly managed?: never;
})
| (ExecutableTarget & {
| (BinaryTargetIdentity & {
readonly kind: "executable";
readonly format: "raw-binary";
readonly architecture: Exclude<
BinaryArchitecture,
ElfMetadataArchitecture
>;
readonly availableArchitectures: readonly Exclude<
BinaryArchitecture,
ElfMetadataArchitecture
>[];
readonly entryPoint: string;
readonly entryPointSource: string;
readonly executableRole?: never;
+101
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { buildCallPath } from "./callPath.js";
import { combineFunctionRelationshipCoverage } from "./functionCallCoverage.js";
import { callPathResultSchema, type CallPathInput } from "./callPathSchemas.js";
import { createEvidence, type Evidence } from "./evidence.js";
import type { JsonValue } from "./jsonValue.js";
@@ -14,6 +15,7 @@ const observe = (
readonly evidenceLimitations?: readonly string[];
readonly dossierLimitations?: readonly string[];
readonly relationshipCoverage?: RelationshipCoverage;
readonly calleeUnavailable?: string;
} = {},
): Evidence => {
const value = {
@@ -51,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" },
@@ -396,6 +405,60 @@ describe("explicit call relationship coverage", () => {
expect(result.limitations).toEqual([reason]);
});
it("establishes not_found when only caller coverage is unknown", () => {
const reason =
"Callers: Upstream xrefs do not establish direct caller relationships.";
const result = run([
observe("0x1000", ["0x2000"], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
observe("0x2000", [], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
]);
expect(result).toMatchObject({
status: "not_found",
search_scope: { exhaustive: true },
});
expect(result.limitations).toContain(reason);
});
it("stays unknown when callee coverage is unknown", () => {
const reason =
"Callees: Upstream callees capped results at 500; additional callees remain unknown.";
const result = run([
observe("0x1000", ["0x2000"], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
observe("0x2000", [], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
]);
expect(result).toMatchObject({
status: "unknown",
search_scope: { exhaustive: false },
});
expect(result.limitations).toContain(reason);
});
it("stays unknown when both caller and callee coverage are unknown", () => {
const reason =
"Callers: Upstream xrefs do not establish direct caller relationships. Callees: Upstream callees are not observed.";
const result = run([
observe("0x1000", ["0x2000"], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
observe("0x2000", [], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
]);
expect(result).toMatchObject({
status: "unknown",
search_scope: { exhaustive: false },
});
expect(result.limitations).toContain(reason);
});
it("ignores incomplete relationship coverage outside the reachable search closure", () => {
const reason = "An unrelated function's callees were not observed.";
const result = run([
@@ -415,6 +478,34 @@ describe("explicit call relationship coverage", () => {
});
});
describe("IDA-capped callee coverage beside unknown callers", () => {
it("keeps the search non-exhaustive for the combined coverage value", () => {
const combined = combineFunctionRelationshipCoverage(
{
status: "unknown",
reason: "Upstream xrefs do not establish direct caller relationships.",
},
{
status: "partial",
limitations: [
"Upstream callees capped results at 500; additional callees remain unknown.",
],
},
);
expect(combined.status).toBe("unknown");
const result = run([
observe("0x1000", [], "rea-workflow", { relationshipCoverage: combined }),
observe("0x4000", []),
]);
expect(result).toMatchObject({
status: "unknown",
search_scope: { exhaustive: false },
shortest_hops: null,
paths: [],
});
});
});
describe("call path evidence admission", () => {
it("normalizes hex addresses and rejects duplicates and mixed providers", () => {
expect(
@@ -458,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");
});
+11 -1
View File
@@ -10,6 +10,7 @@ import {
parseFunctionEvidence,
type FunctionSnapshot,
} from "./functionDossierEvidence.js";
import { isCallerOnlyUnknownCoverage } from "./functionCallCoverage.js";
import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js";
/** Minimal directed caller-to-callee adjacency for call-path search. */
@@ -252,13 +253,22 @@ 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.
// The search only expands callee edges, so coverage that is unknown
// solely because callers are unobservable does not make the searched
// callee closure incomplete; the caller caveat stays in limitations.
if (
coverage === null
? snapshot.limitations.length > 0
: coverage.status !== "complete"
: coverage.status !== "complete" &&
!isCallerOnlyUnknownCoverage(coverage)
)
incompleteExpandedCoverage = true;
} else if (node === goal) {
+27
View File
@@ -19,6 +19,33 @@ const TARGET: BinaryTarget = {
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
const PROFILE = createAnalysisProfile(PROVIDER, { loader: "default" });
it("rejects a detected Evidence subject with the raw-only 6502 architecture", () => {
const selected = {
path: TARGET.path,
sha256: TARGET.sha256,
format: "raw-binary" as const,
architecture: "6502" as const,
};
expect(
createEvidence(selected, PROVIDER, {
operation: "inspect",
parameters: {},
result: null,
}).subject,
).toMatchObject({ format: "raw-binary", architecture: "6502" });
const malformed = {
...selected,
format: "pe" as const,
};
expect(() =>
createEvidence(malformed, PROVIDER, {
operation: "inspect",
parameters: {},
result: null,
}),
).toThrow();
});
it("preserves omitted relationship diagnostics and authenticates reported diagnostics", () => {
const observation = {
operation: "procedure_callees",
+43 -33
View File
@@ -38,42 +38,52 @@ export const providerSchema = z.strictObject({
name: z.string().min(1),
version: z.string().nullable(),
});
const subjectSchema = z.strictObject({
const subjectFormatSchema = z.enum([
"hopper",
"analysis-database",
"mach-o",
"elf",
"pe",
"dos-mz",
"dos-com",
"raw-binary",
"zip",
"ipa",
"apk",
"msix",
"appx",
"hap",
"hsp",
"app-pack",
"asar",
"dmg",
"pkg",
"plist",
"javascript",
"source-map",
"directory",
"file",
"unknown",
"mach-o-universal",
"javascript-bundle",
"entitlements",
]);
const subjectBaseSchema = z.strictObject({
name: z.string().min(1),
digest: z.strictObject({ sha256: digestSchema }),
format: z.enum([
"hopper",
"analysis-database",
"mach-o",
"elf",
"pe",
"dos-mz",
"dos-com",
"raw-binary",
"zip",
"ipa",
"apk",
"msix",
"appx",
"hap",
"hsp",
"app-pack",
"asar",
"dmg",
"pkg",
"plist",
"javascript",
"source-map",
"directory",
"file",
"unknown",
"mach-o-universal",
"javascript-bundle",
"entitlements",
]),
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
local_path: nulFreeStringSchema,
});
// The format owns the architecture claim, including nested Evidence subjects.
const subjectSchema = z.discriminatedUnion("format", [
subjectBaseSchema.extend({
format: subjectFormatSchema.exclude(["raw-binary"]),
architecture: z.enum(BINARY_ARCHITECTURES).exclude(["6502"]).nullable(),
}),
subjectBaseSchema.extend({
format: z.literal("raw-binary"),
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
}),
]);
/** Source location attached to an evidence observation. */
/** Source-location schema shared by evidence-bearing persistence formats. */
export const evidenceLocationSchema = z.discriminatedUnion("kind", [
@@ -186,7 +196,7 @@ const immutableResultSchema = z
});
export type EvidenceLocation = z.infer<typeof evidenceLocationSchema>;
/** Minimal immutable local artifact identity accepted by Evidence. */
/** Candidate local artifact identity validated by the Evidence subject schema. */
export interface EvidenceSubjectTarget {
readonly path: string;
readonly sha256: string;
+13 -10
View File
@@ -16,14 +16,17 @@ import {
} from "./residualUnknown.js";
import { freezeJsonSnapshot } from "./immutableJson.js";
const artifactManifestSchema = evidenceSchema.shape.subject
.unwrap()
.pick({
digest: true,
format: true,
architecture: true,
})
.strict();
const [detectedSubjectSchema, rawSubjectSchema] =
evidenceSchema.shape.subject.unwrap().options;
const manifestFields = {
digest: true,
format: true,
architecture: true,
} as const;
const artifactManifestSchema = z.discriminatedUnion("format", [
detectedSubjectSchema.pick(manifestFields),
rawSubjectSchema.pick(manifestFields),
]);
const providerManifestSchema = providerSchema;
const environmentManifestSchema = evidenceSchema.shape.environment.unwrap();
const scenarioManifestSchema = z.strictObject({
@@ -85,11 +88,11 @@ export const createEvidenceBundle = (
subject === null
? []
: [
{
artifactManifestSchema.parse({
digest: subject.digest,
format: subject.format,
architecture: subject.architecture,
},
}),
],
),
),
+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
>;
+64
View File
@@ -0,0 +1,64 @@
import { describe, expect, it } from "vitest";
import {
combineFunctionRelationshipCoverage,
isCallerOnlyUnknownCoverage,
} from "./functionCallCoverage.js";
import type { RelationshipCoverage } from "./relationshipCoverage.js";
const unknownCallers: RelationshipCoverage = {
status: "unknown",
reason: "Upstream xrefs do not establish direct caller relationships.",
};
const unknownCallees: RelationshipCoverage = {
status: "unknown",
reason: "Upstream callees are not observed in this profile.",
};
const cappedCallees: RelationshipCoverage = {
status: "partial",
limitations: [
"Upstream callees capped results at 500; additional callees remain unknown.",
],
};
const complete: RelationshipCoverage = { status: "complete" };
describe("isCallerOnlyUnknownCoverage", () => {
it("detects unknown callers beside complete callees", () => {
const combined = combineFunctionRelationshipCoverage(
unknownCallers,
complete,
);
expect(combined.status).toBe("unknown");
expect(isCallerOnlyUnknownCoverage(combined)).toBe(true);
});
it("rejects unknown callees beside complete callers", () => {
const combined = combineFunctionRelationshipCoverage(
complete,
unknownCallees,
);
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
});
it("rejects unknown coverage on both sides", () => {
const combined = combineFunctionRelationshipCoverage(
unknownCallers,
unknownCallees,
);
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
});
it("rejects unknown callers beside IDA-capped callees", () => {
const combined = combineFunctionRelationshipCoverage(
unknownCallers,
cappedCallees,
);
expect(combined.status).toBe("unknown");
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
});
it("rejects complete coverage", () => {
const combined = combineFunctionRelationshipCoverage(complete, complete);
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
});
});
+20 -2
View File
@@ -2,6 +2,9 @@ import type { RelationshipCoverage } from "./relationshipCoverage.js";
import type { FunctionDossier } from "./hopperValues.js";
import { uniqueSorted } from "./canonicalOrdering.js";
const callerCoveragePrefix = "Callers: ";
const calleeCoveragePrefix = "Callees: ";
/** Combine caller and callee read outcomes without losing either explanation. */
export const combineFunctionRelationshipCoverage = (
callers: RelationshipCoverage | undefined,
@@ -20,7 +23,8 @@ export const combineFunctionRelationshipCoverage = (
);
const details = diagnostics.length > 0 ? { diagnostics } : {};
const reasons = reads.flatMap(({ direction, coverage }) => {
const label = direction === "callers" ? "Callers" : "Callees";
const label =
direction === "callers" ? callerCoveragePrefix : calleeCoveragePrefix;
const limitations =
coverage === undefined
? ["Provider did not report relationship coverage."]
@@ -29,7 +33,7 @@ export const combineFunctionRelationshipCoverage = (
: coverage.status === "partial"
? coverage.limitations
: [];
return limitations.map((reason) => `${label}: ${reason}`);
return limitations.map((reason) => `${label}${reason}`);
});
if (
reads.some(
@@ -50,6 +54,20 @@ export const combineFunctionRelationshipCoverage = (
return { status: "complete", ...details };
};
/**
* Whether combined relationship coverage is unknown only on the caller side.
* The combine helper above prefixes each direction's reasons, so a reason
* that carries the caller prefix and no callee prefix records observed
* callees with unobservable callers. Forward (callee-edge) searches stay
* exhaustive under that caveat; the caller reason remains a limitation.
*/
export const isCallerOnlyUnknownCoverage = (
coverage: RelationshipCoverage,
): boolean =>
coverage.status === "unknown" &&
coverage.reason.startsWith(callerCoveragePrefix) &&
!coverage.reason.includes(calleeCoveragePrefix);
/** Explain why two resolved call sets cannot establish call-set equality. */
export const functionCallCoverageLimitations = (
coverage: RelationshipCoverage | null,

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