chore: merge current main into PR #2816

This commit is contained in:
morluto
2026-10-14 00:06:29 +08:00
189 changed files with 8189 additions and 1101 deletions
+62
View File
@@ -1127,6 +1127,68 @@ exit 1`,
expect(projected.message).toContain("not installed for 0");
});
// adb exits 1 on a refused package change: `adb install` after printing the
// status line to stderr, `cmd package uninstall` after printing it to stdout.
it("preserves the device's install refusal when adb exits nonzero", async () => {
const { binary, root } = await writeAdbStub(
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
if [ "$1" = "-s" ] && [ "$3" = "install" ]; then
printf 'Performing Streamed Install\\n'
printf 'adb: failed to install app.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install com.example without first uninstalling.]\\n' >&2
exit 1
fi
exit 1`,
);
const apk = join(root, "app.apk");
await writeFile(apk, "apk");
const projected = await refusedBy(providerOver(binary), {
operation: "install_adb_package",
input: { serial: "emulator-5554", apk_path: apk, replace: false },
});
expect(projected).toMatchObject({
code: "unsupported_target",
details: {
reason:
"INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install com.example without first uninstalling.",
},
});
expect(projected.message).toContain(
"INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install com.example without first uninstalling.",
);
});
it("preserves the device's uninstall refusal when adb exits nonzero", async () => {
const { binary } = await writeAdbStub(
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
if [ "$1" = "-s" ] && [ "$3" = "uninstall" ]; then printf 'Failure [not installed for 0]\\n'; exit 1; fi
exit 1`,
);
const projected = await refusedBy(providerOver(binary), {
operation: "uninstall_adb_package",
input: { serial: "emulator-5554", package: "com.absent" },
});
expect(projected).toMatchObject({
code: "unsupported_target",
details: { reason: "not installed for 0" },
});
expect(projected.message).toContain("not installed for 0");
});
it("keeps a nonzero install without a device verdict as an unreadable result", async () => {
const { binary, root } = await writeAdbStub(
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
if [ "$1" = "-s" ] && [ "$3" = "install" ]; then printf 'adb: failed to install app.apk: closed\\n' >&2; exit 1; fi
exit 1`,
);
const apk = join(root, "app.apk");
await writeFile(apk, "apk");
const projected = await refusedBy(providerOver(binary), {
operation: "install_adb_package",
input: { serial: "emulator-5554", apk_path: apk, replace: false },
});
expect(projected).toMatchObject({ code: "unreadable_output" });
});
it("starts an app through resolved launcher component and force-stops it", async () => {
const { binary } = await writeAdbStub(
shellStub({
+36 -2
View File
@@ -71,6 +71,7 @@ import {
parseBugreportCopiedPath,
parseDumpsysPackageOutput,
parseFeatureListOutput,
packageChangeFailureReason,
parsePackageChangeOutput,
parseProcessListOutput,
parsePngDimensions,
@@ -248,6 +249,31 @@ const runAdb = async (
});
};
/**
* adb exits nonzero when the device refuses a package change, printing the
* `Failure [...]` verdict to stderr (install) or stdout (uninstall). Read the
* refusal from that failed run so it is not reported as unreadable output.
*/
const packageChangeRefusal = (
operation: string,
serial: string,
error: AnalysisError,
): Result<never, AnalysisError> | undefined => {
if (!(error instanceof AnalysisProtocolError)) return undefined;
const failure = execFileOutputFailure(error.cause);
if (failure === undefined) return undefined;
const reason = packageChangeFailureReason(
`${failure.stdout}\n${failure.stderr}`,
);
return reason === null
? undefined
: err(
new AnalysisUnsupportedTargetError(operation, serial, reason, {
cause: error,
}),
);
};
const clientIdentityResult = (
selection: AdbBinarySelection,
identity: AdbClientIdentity,
@@ -1754,7 +1780,11 @@ export class AdbProvider {
{ timeoutMs: PULL_TIMEOUT_MS, maxOutputBytes: PULL_MAX_OUTPUT_BYTES },
signal,
);
if (!installed.ok) return installed;
if (!installed.ok)
return (
packageChangeRefusal(operation, input.serial, installed.error) ??
installed
);
const verdict = parsePackageChangeOutput(installed.value.stdout);
if (verdict.status === "failure")
return err(
@@ -1803,7 +1833,11 @@ export class AdbProvider {
},
signal,
);
if (!uninstalled.ok) return uninstalled;
if (!uninstalled.ok)
return (
packageChangeRefusal(operation, input.serial, uninstalled.error) ??
uninstalled
);
const verdict = parsePackageChangeOutput(uninstalled.value.stdout);
if (verdict.status === "failure")
return err(
+7 -2
View File
@@ -293,6 +293,10 @@ export const parseBugreportCopiedPath = (stdout: string): string | null => {
return match === null ? null : match[1]!;
};
/** Read the device's `Failure [REASON]` verdict from package-change output. */
export const packageChangeFailureReason = (output: string): string | null =>
/Failure \[([^\]]+)\]/u.exec(output)?.[1] ?? null;
/**
* Parse `adb install`/`adb uninstall` output. adb can print `Failure [...]`
* with a zero exit code, so the text decides, not the exit status.
@@ -305,10 +309,11 @@ export const parsePackageChangeOutput = (
} => {
const text = stdout.trim();
if (/^Success$/mu.test(text)) return { status: "success", reason: null };
const failure = /Failure \[([^\]]+)\]/u.exec(text);
return {
status: "failure",
reason: failure?.[1] ?? (text === "" ? null : text.slice(0, 512)),
reason:
packageChangeFailureReason(text) ??
(text === "" ? null : text.slice(0, 512)),
};
};
@@ -0,0 +1,34 @@
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { resolveAppBundleExecutable } from "./AppBundleExecutable.js";
describe("app bundle Info.plist magic", () => {
it("does not decode a high-bit fold of bplist as a binary Info.plist", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-bplist-fold-"));
try {
const bundle = join(root, "Fixture.app");
const plistPath = join(bundle, "Contents", "Info.plist");
await mkdir(join(bundle, "Contents"), { recursive: true });
const plist = Buffer.from("bplist00");
plist[0] = (plist[0] ?? 0) | 0x80;
await writeFile(plistPath, plist);
let decoded = false;
const result = await resolveAppBundleExecutable(bundle, {
readFile: async () => plist,
realpath: async (path) => path,
decodeBinaryPlist: async () => {
decoded = true;
return "Fixture";
},
});
expect(decoded).toBe(false);
expect(result.ok).toBe(false);
} finally {
await rm(root, { recursive: true, force: true });
}
});
});
+3 -2
View File
@@ -161,11 +161,12 @@ export const parseBinaryTarget = async (
availableArchitectures: ["x86"],
});
}
// Explicit database selection owns routing; a suffix is only a fallback.
// Probe content before suffix-only database routing; an explicit
// database selection keeps the caller's chosen interpretation.
const artifactFormat =
targetKind === "database"
? undefined
: await detectArtifactFormat(path, handle, metadata, signal);
: await detectArtifactFormat(path, handle, signal);
if (
targetKind === "database" ||
(targetKind === undefined &&
+12 -2
View File
@@ -110,9 +110,12 @@ const parseDocument = (
return requireObject(parseToml(text), "The configuration root");
// Pi loads `mcp.json` with a strict `JSON.parse` and no BOM tolerance, so
// comments, trailing commas, a BOM, or an empty existing file must be
// rejected instead of registering into a document Pi cannot load.
if (format === "pi")
// rejected instead of registering into a document the client cannot load.
// Kimi also reads mcp.json with JSON.parse and an empty-file fallback.
if (format === "pi" || format === "kimi") {
if (format === "kimi" && text.trim().length === 0) return {};
return requireObject(JSON.parse(text), "The configuration root");
}
// An empty file, which some clients create before any server is added,
// holds no settings to preserve.
if (isEmptyClientConfigurationText(text)) return {};
@@ -1446,6 +1449,13 @@ export const clientRegistrationEntry = (
? {}
: { environment: { ...environment } }),
};
case "kimi":
// Kimi infers stdio from command; it uses `transport`, not `type`.
return {
command: executable,
args,
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
};
case "opencode_v2":
// V2 connects servers unless `disabled` is true.
return {
+26 -8
View File
@@ -66,6 +66,8 @@ const registrationSchema = z
command: z.string().min(1),
args: z.array(z.string()).default([]),
startup_timeout_sec: z.number().positive().optional(),
startupTimeoutMs: z.number().positive().optional(),
toolTimeoutMs: z.number().positive().optional(),
type: z.string().optional(),
transport: z.string().optional(),
serverName: z.string().optional(),
@@ -258,6 +260,21 @@ const registrationAligned = (
MCP_STARTUP_POLICY.codexStartupTimeoutSeconds
)
return false;
if (
client.name === "kimi" &&
(registration.startupTimeoutMs !==
MCP_STARTUP_POLICY.kimiStartupTimeoutMs ||
registration.toolTimeoutMs !== MCP_STARTUP_POLICY.kimiToolTimeoutMs)
)
return false;
if (
(client.format === "kimi" ||
client.format === "omp" ||
client.format === "pi") &&
registration.type !== undefined &&
registration.type !== "stdio"
)
return false;
if (client.format === "vscode" && registration.type !== "stdio") return false;
// A Harness registration only connects as the rea stdio server; another
// server name or transport leaves the session without REA tools.
@@ -266,13 +283,6 @@ const registrationAligned = (
(registration.serverName !== "rea" || registration.transport !== "stdio")
)
return false;
// OMP and Pi infer stdio for a command entry without an explicit type.
if (
(client.format === "omp" || client.format === "pi") &&
registration.type !== undefined &&
registration.type !== "stdio"
)
return false;
if (
client.format === "copilot_cli" &&
(registration.type !== "stdio" ||
@@ -331,6 +341,12 @@ const parseRegistration = (
});
}
const registration = registrationSchema.parse(value);
if (
client.format === "kimi" &&
registration.transport !== undefined &&
registration.transport !== "stdio"
)
throw new TypeError("Expected an stdio registration");
if (
(client.format === "vscode" || client.format === "copilot_cli") &&
registration.type !== "stdio"
@@ -339,7 +355,9 @@ const parseRegistration = (
if (client.format === "commandcode" && registration.transport !== "stdio")
throw new TypeError("Expected an stdio registration");
if (
(client.format === "omp" || client.format === "pi") &&
(client.format === "kimi" ||
client.format === "omp" ||
client.format === "pi") &&
registration.type !== undefined &&
registration.type !== "stdio"
)
+1
View File
@@ -60,6 +60,7 @@ type DirectAnalysisTool =
| "annotate_native_function"
| "inspect_native_load_image"
| "read_bytes"
| "search_bytes"
| "address_to_file_offset"
| "binary_overview"
| "procedure_pseudo_code"
+32 -8
View File
@@ -74,7 +74,7 @@ describe("doctor", () => {
),
).toEqual({
node: `Install ${SUPPORTED_NODE_VERSION_PROSE}.`,
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, Omarchy, and the experimental Windows x64 Ghidra P0 boundary.",
host: "REA supports macOS 12+, Linux distributions with a recognized apt, dnf, or pacman package family, and the experimental Windows x64 Ghidra P0 boundary; automated Hopper setup additionally requires Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, or Omarchy.",
hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
target: "Supply a readable local app or program path.",
});
@@ -418,10 +418,9 @@ describe("doctor scoped readiness", () => {
platform: "linux",
linuxDistribution: () =>
Promise.resolve({
id: "debian",
versionId: "13",
packageFamily: "deb",
supported: false,
id: "nixos",
packageFamily: undefined,
hopperSetupSupported: false,
}),
clientRegistrations: () =>
Promise.resolve([
@@ -451,6 +450,31 @@ describe("doctor scoped readiness", () => {
);
});
it("accepts a Debian-family host that has no tested Hopper package", async () => {
const result = await runDoctor(
undefined,
host({
platform: "linux",
macosVersion: () => Promise.resolve(undefined),
linuxDistribution: () =>
Promise.resolve({
id: "kali",
versionId: "2026.3",
packageFamily: "deb",
hopperSetupSupported: false,
}),
}),
);
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "host",
ok: true,
detail: "kali 2026.3",
}),
);
});
it("requires explicitly selected providers instead of any available provider", async () => {
const ghidra = {
id: "ghidra",
@@ -502,7 +526,7 @@ describe("doctor Linux and Hopper discovery", () => {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
hopperSetupSupported: true,
}),
configuredHopperPath: path,
executable: (candidate) => Promise.resolve(candidate === path),
@@ -522,7 +546,7 @@ describe("doctor Linux and Hopper discovery", () => {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
hopperSetupSupported: true,
}),
linuxDemoRuntimeCheck: () =>
Promise.resolve({
@@ -554,7 +578,7 @@ describe("doctor Linux and Hopper discovery", () => {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
hopperSetupSupported: true,
}),
executable: (candidate) => Promise.resolve(candidate === path),
supportedLinuxHopper: () => Promise.resolve(false),
+3 -3
View File
@@ -2,7 +2,7 @@ import {
SUPPORTED_NODE_VERSION_PROSE,
supportsNodeVersion,
} from "../domain/runtimeVersion.js";
import { linuxHopperLauncherPath } from "./LinuxHopper.js";
import { linuxHopperLauncherPath, supportsReaHost } from "./LinuxHopper.js";
import type {
DoctorCheck,
DoctorHost,
@@ -129,7 +129,7 @@ const hostCheck = async (host: DoctorHost): Promise<DoctorCheck> => {
host.platform === "linux" ? await host.linuxDistribution() : undefined;
const supported =
(host.platform === "darwin" && parseMajor(macosVersion) >= 12) ||
(host.platform === "linux" && linuxDistribution?.supported === true) ||
(host.platform === "linux" && supportsReaHost(linuxDistribution)) ||
(host.platform === "win32" && host.architecture === "x64");
const detail =
macosVersion ??
@@ -138,7 +138,7 @@ const hostCheck = async (host: DoctorHost): Promise<DoctorCheck> => {
: `${linuxDistribution.id} ${linuxDistribution.versionId ?? "unknown"}`);
return check("host", supported, detail, {
remediation:
"REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, Omarchy, and the experimental Windows x64 Ghidra P0 boundary.",
"REA supports macOS 12+, Linux distributions with a recognized apt, dnf, or pacman package family, and the experimental Windows x64 Ghidra P0 boundary; automated Hopper setup additionally requires Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, or Omarchy.",
classification: "unsupported_host",
});
};
+10 -4
View File
@@ -8,6 +8,7 @@ import { CordisExpression, DshCordisYaml } from "./DshCordisYaml.js";
export const DSH_ENTRY_ID = "rea-mcp";
export const DSH_CLIENT_PACKAGE = "@deepseek-ai/dsh-mcp-client";
const LAUNCHER_KEYS = new Set(["serverName", "transport", "command", "args"]);
const SELECTOR_KEYS = new Set(["id", "name"]);
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" &&
value !== null &&
@@ -295,10 +296,15 @@ export class DshCordisDocument {
carried = true;
return [this.#entry(desired, invalidated)] as typeof inserted.items;
});
replacements.set(
op.source,
inserted.items.length === 0 ? undefined : copy,
);
if (inserted.items.length === 0) copy.delete("insert");
// An emptied operation keeps caller fields unless it would patch REA's row.
const kept =
inserted.items.length > 0 ||
(this.#id(op.map) !== DSH_ENTRY_ID &&
copy.items.some(
(pair) => !SELECTOR_KEYS.has(this.#yaml.value(pair.key) as string),
));
replacements.set(op.source, kept ? copy : undefined);
}
const output = this.#yaml.document.clone();
const outputRoot = output.contents;
+31 -6
View File
@@ -7,6 +7,7 @@ import {
linuxPackageManagerCommands,
linuxSharedLibrariesAvailable,
parseLinuxDistribution,
supportsReaHost,
type LinuxDistribution,
type LinuxHopperDownload,
type LinuxHopperInstallHost,
@@ -19,7 +20,7 @@ class RecordingLinuxHost implements LinuxHopperInstallHost {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
hopperSetupSupported: true,
};
archive = new Uint8Array([1, 2, 3]);
archiveOk = true;
@@ -66,7 +67,7 @@ describe("Linux Hopper host classification", () => {
(document, family) => {
expect(parseLinuxDistribution(document)).toMatchObject({
packageFamily: family,
supported: true,
hopperSetupSupported: true,
});
},
);
@@ -99,8 +100,32 @@ describe("Linux Hopper host classification", () => {
"ID=garuda\nID_LIKE=arch\n",
"ID=omarchy\n",
"ID=omarchy\nID_LIKE=debian\n",
])("rejects unsupported vendor/version combinations", (document) => {
expect(parseLinuxDistribution(document).supported).toBe(false);
])(
"rejects vendor/version combinations without a tested Hopper installer",
(document) => {
expect(parseLinuxDistribution(document).hopperSetupSupported).toBe(false);
},
);
it.each([
'ID=kali\nVERSION_ID="2026.3"\nID_LIKE=debian\n',
'ID=debian\nVERSION_ID="13"\nID_LIKE=debian\n',
'ID=linuxmint\nVERSION_ID="22.1"\nID_LIKE="ubuntu debian"\n',
"ID=manjaro\nID_LIKE=arch\n",
"ID=derivative\nID_LIKE='debian'\n",
"ID='debian'\nVERSION_ID='13'\n",
])(
"hosts REA on a distribution Hopper has no tested package for: %s",
(document) => {
const distribution = parseLinuxDistribution(document);
expect(distribution.hopperSetupSupported).toBe(false);
expect(supportsReaHost(distribution)).toBe(true);
},
);
it("withholds host support from a distribution with no package family", () => {
expect(supportsReaHost(parseLinuxDistribution("ID=nixos\n"))).toBe(false);
expect(supportsReaHost(undefined)).toBe(false);
});
});
@@ -166,7 +191,7 @@ describe("Linux Hopper installation", () => {
host.distributionValue = {
id: family,
packageFamily: family,
supported: true,
hopperSetupSupported: true,
};
const result = await installFixture(host);
expect(result).toEqual({
@@ -194,7 +219,7 @@ describe("Linux Hopper installation", () => {
host.distributionValue = {
id: "debian",
packageFamily: "deb",
supported: false,
hopperSetupSupported: false,
};
if (scenario === "package request failure") host.archiveOk = false;
if (scenario === "checksum mismatch") host.archive = new Uint8Array([9]);
+31 -12
View File
@@ -76,19 +76,35 @@ interface LinuxDistributionIdentity {
readonly versionId?: string;
}
/** Parsed Linux distribution information used for support and package selection. */
/**
* Parsed Linux distribution information used for package selection.
*
* `hopperSetupSupported` is the automated Hopper installer's tested list. It is
* narrower than the hosts where REA itself runs, which {@link supportsReaHost}
* answers from the package family.
*/
export type LinuxDistribution = LinuxDistributionIdentity &
(
| {
readonly packageFamily: LinuxPackageFamily;
readonly supported: true;
readonly hopperSetupSupported: true;
}
| {
readonly packageFamily: LinuxPackageFamily | undefined;
readonly supported: false;
readonly hopperSetupSupported: false;
}
);
/**
* Whether REA's analysis providers run on this distribution. A recognized
* package family means a glibc host with a known package layout, which is what
* the providers need; downloading and installing the official Hopper package
* additionally requires a distribution on its tested list.
*/
export const supportsReaHost = (
distribution: LinuxDistribution | undefined,
): boolean => distribution?.packageFamily !== undefined;
/** Download response kept independent of Node's global fetch implementation. */
export interface LinuxHopperDownload {
readonly ok: boolean;
@@ -141,16 +157,19 @@ export const parseLinuxDistribution = (text: string): LinuxDistribution => {
const key = match[1];
const encoded = match[2];
if (key === undefined || encoded === undefined) continue;
const value =
encoded.startsWith('"') && encoded.endsWith('"')
? encoded.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
: encoded;
const quote = encoded[0];
const quoted = (quote === "'" || quote === '"') && encoded.endsWith(quote);
const value = !quoted
? encoded
: quote === "'"
? encoded.slice(1, -1)
: encoded.slice(1, -1).replace(/\\(["\\$`])/gu, "$1");
fields.set(key, value);
}
const id = (fields.get("ID") ?? "unknown").toLowerCase();
const versionId = fields.get("VERSION_ID");
const packageFamily = packageFamilyFor(id, fields.get("ID_LIKE"));
const supported =
const hopperSetupSupported =
packageFamily !== undefined &&
(id === "arch" ||
id === "cachyos" ||
@@ -162,9 +181,9 @@ export const parseLinuxDistribution = (text: string): LinuxDistribution => {
id,
...(versionId === undefined ? {} : { versionId }),
};
return supported
? { ...identity, packageFamily, supported: true }
: { ...identity, packageFamily, supported: false };
return hopperSetupSupported
? { ...identity, packageFamily, hopperSetupSupported: true }
: { ...identity, packageFamily, hopperSetupSupported: false };
};
/** Read and classify the current Linux distribution. */
@@ -193,7 +212,7 @@ export const installLinuxHopper = async (
if (options.signal?.aborted === true)
return { status: "failed", reason: "cancelled" };
const distribution = await host.distribution();
if (distribution?.supported !== true)
if (distribution?.hopperSetupSupported !== true)
return { status: "failed", reason: "unsupported_host" };
let temporary: string | undefined;
try {
+16 -4
View File
@@ -43,7 +43,7 @@ export const executeProviderOperation = async <
provider: ProviderOperationPort<TRequest>,
confidence: "observed" | "derived",
): Promise<Result<Evidence, AnalysisError>> => {
if (options?.signal?.aborted === true)
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(operation));
const request = schema.safeParse({ operation, input });
if (!request.success)
@@ -51,8 +51,10 @@ export const executeProviderOperation = async <
const executed = await provider.execute(request.data, options);
if (!executed.ok) return executed;
const execution = executed.value;
return ok(
createEvidence(execution.subject ?? undefined, execution.provider, {
const evidence = createEvidence(
execution.subject ?? undefined,
execution.provider,
{
operation,
parameters: jsonObjectSchema.parse(request.data.input),
result: execution.result,
@@ -60,6 +62,16 @@ export const executeProviderOperation = async <
limitations: execution.limitations,
locations: execution.locations,
confidence,
}),
},
);
// A provider that cannot observe the signal may finish its work after the
// caller cancelled, so re-check rather than reporting a completed operation
// the caller no longer wants. The observation it completed is still this
// provider's Evidence, so the cancellation carries it as the partial
// observation instead of discarding a finished result.
if (options?.signal?.aborted)
return err(
new AnalysisCancelledError(operation, { partialObservation: evidence }),
);
return ok(evidence);
};
+2 -2
View File
@@ -57,7 +57,7 @@ describe("setup workflow", () => {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
hopperSetupSupported: true,
};
host.hopper = "/opt/hopper/bin/Hopper";
host.linuxDemoRuntimeMissing = true;
@@ -79,7 +79,7 @@ describe("setup workflow", () => {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
hopperSetupSupported: true,
};
host.hopper = "/custom/Hopper";
host.unsupportedHopperVersion = true;
+3 -3
View File
@@ -70,7 +70,7 @@ describe("setup workflow", () => {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
hopperSetupSupported: true,
};
const result = await runSetup(
{ ...options(false), structured: false },
@@ -162,7 +162,7 @@ describe("setup workflow", () => {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
hopperSetupSupported: true,
};
const result = await runSetup(options(true, true), host);
expect(result.appliedActions).toEqual(["installed_hopper"]);
@@ -236,7 +236,7 @@ describe("setup workflow lifecycle and provider planning", () => {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
hopperSetupSupported: true,
};
host.ghidra = "/opt/ghidra_12.1.4_PUBLIC";
host.javaHome = "/usr/lib/jvm/jdk-21";
+2 -2
View File
@@ -310,7 +310,7 @@ describe("setup scoped readiness", () => {
id: "debian",
versionId: "13",
packageFamily: "deb",
supported: false,
hopperSetupSupported: false,
};
const result = await runSetup(options(true, true), host);
expect(result.status).toBe("needs_human");
@@ -326,7 +326,7 @@ describe("setup scoped readiness", () => {
id: "debian",
versionId: "13",
packageFamily: "deb",
supported: false,
hopperSetupSupported: false,
};
host.ghidra = "/opt/ghidra_12.1.4_PUBLIC";
host.javaHome = "/usr/lib/jvm/jdk-21";
@@ -704,6 +704,14 @@ const clientConfigurationDesired = (
launcher,
environment.value,
);
const previous = parsed?.servers[PRODUCT_IDENTITY.mcpServerKey];
if (
client.name === "kimi" &&
typeof previous === "object" &&
previous !== null &&
"enabledTools" in previous
)
registration.enabledTools = previous.enabledTools;
return {
...registration,
...(client.name === "codex" || client.name === "grok_build"
@@ -711,5 +719,11 @@ const clientConfigurationDesired = (
startup_timeout_sec: MCP_STARTUP_POLICY.codexStartupTimeoutSeconds,
}
: {}),
...(client.name === "kimi"
? {
startupTimeoutMs: MCP_STARTUP_POLICY.kimiStartupTimeoutMs,
toolTimeoutMs: MCP_STARTUP_POLICY.kimiToolTimeoutMs,
}
: {}),
};
};
+2 -1
View File
@@ -124,7 +124,8 @@ export const hostRemediation = async (
? "Upgrade to macOS 12 or newer."
: undefined;
}
if ((await host.linuxDistribution())?.supported === true) return undefined;
if ((await host.linuxDistribution())?.hopperSetupSupported === true)
return undefined;
return "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, and Omarchy; configure an existing supported provider instead.";
};
+2 -1
View File
@@ -56,7 +56,8 @@ export const discoverSetupState = async (input: {
const hopperInstallSupported =
(input.host.platform === "darwin" &&
majorVersion((await input.host.macosVersion()) ?? "0") >= 12) ||
(input.host.platform === "linux" && linuxDistribution?.supported === true);
(input.host.platform === "linux" &&
linuxDistribution?.hopperSetupSupported === true);
const installHopper =
input.forceHopperInstall ||
(hopperInstallSupported &&
+40 -16
View File
@@ -72,6 +72,15 @@ interface CanonicalSkillFile {
readonly original: SkillFileState | undefined;
}
const canonicalSkillContent = (relativePath: string): Promise<string> =>
readFile(
new URL(
`../../skills/${PRODUCT_IDENTITY.skillName}/${relativePath}`,
import.meta.url,
),
"utf8",
);
export interface SkillInstallFileOperations {
readonly mkdir: (path: string) => Promise<void>;
readonly backup: (source: string, destination: string) => Promise<void>;
@@ -244,19 +253,36 @@ const canonicalSkillFiles = async (
const destination = join(root, relativePath);
return {
destination,
content: await readFile(
new URL(
`../../skills/${PRODUCT_IDENTITY.skillName}/${relativePath}`,
import.meta.url,
),
"utf8",
),
content: await canonicalSkillContent(relativePath),
original: await readOptionalSkillState(destination, resources),
};
}),
),
);
const canonicalSkillNeedsInstallByReading = async (
home: string,
clientIds: readonly string[],
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
resources?: ArtifactResourceScope,
): Promise<boolean> => {
for (const { path: root } of skillDestinations(
home,
clientIds,
environment,
platform,
)) {
for (const relativePath of MANAGED_SKILL_FILES) {
const destination = join(root, relativePath);
const content = await canonicalSkillContent(relativePath);
const original = await readOptionalSkillState(destination, resources);
if (original?.content !== content) return true;
}
}
return false;
};
/** Report whether setup would change any file in the managed REA skill bundle. */
export const canonicalSkillNeedsInstall = async (
home: string,
@@ -266,15 +292,13 @@ export const canonicalSkillNeedsInstall = async (
resources?: ArtifactResourceScope,
): Promise<boolean> => {
try {
return (
await canonicalSkillFiles(
home,
clientIds,
environment,
platform,
resources,
)
).some(({ content, original }) => original?.content !== content);
return await canonicalSkillNeedsInstallByReading(
home,
clientIds,
environment,
platform,
resources,
);
} catch (cause: unknown) {
if (
cause instanceof RegularFileCleanupFailure ||
+14 -1
View File
@@ -45,6 +45,7 @@ export interface SetupClient {
| "grok"
| "omp"
| "pi"
| "kimi"
| "hermes"
| "zcode"
| "dsh"
@@ -165,6 +166,10 @@ const claudeCodeMarkerDirectory = ({ home, env }: ClientPathContext): string =>
const codexDirectory = ({ home, env }: ClientPathContext): string =>
env.CODEX_HOME || join(home, ".codex");
/** Kimi Code stores MCP declarations beside the rest of its home data. */
const kimiDirectory = ({ home, env }: ClientPathContext): string =>
env.KIMI_CODE_HOME || join(home, ".kimi-code");
const qoderDirectory = ({ home, env }: ClientPathContext): string =>
env.QODER_CONFIG_DIR || join(home, ".qoder");
@@ -534,7 +539,7 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
configPath: ({ home, platform, env }: ClientPathContext) =>
join(devinDirectory({ home, platform, env }), "mcp_config.json"),
markerPath: devinDirectory,
format: "json",
format: "devin",
},
{
name: "opencode",
@@ -576,6 +581,14 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
markerPath: qwenCodeDirectory,
format: "json",
},
{
name: "kimi",
displayName: "Kimi Code",
configPath: (context: ClientPathContext) =>
join(kimiDirectory(context), "mcp.json"),
markerPath: kimiDirectory,
format: "kimi",
},
{
name: "vscode",
displayName: "VS Code",
+9 -4
View File
@@ -627,11 +627,16 @@ const removeManagedSkills = async (
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.
// Every destination shares one summary item; preserve both client and path.
const results = await Promise.all(
skillDestinations(home, undefined, environment, platform).map(({ path }) =>
removeManagedSkill(path, path, fileSystem, writeBlocker),
skillDestinations(home, undefined, environment, platform).map(
({ client, path }) =>
removeManagedSkill(
path,
`${client} (${path})`,
fileSystem,
writeBlocker,
),
),
);
const failed = results.find(({ status }) => status === "failed");
@@ -83,3 +83,37 @@ it("preserves cancellation before execution", async () => {
if (result.ok) return;
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
});
it("preserves a cancellation that races a completed observation", async () => {
const controller = new AbortController();
const racingPort: ApktoolResourceAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute() {
// The provider may finish its work before the abort is delivered, so a
// successful result is not by itself proof the caller still wants it.
controller.abort();
return ok(execution);
},
};
const result = await new ApktoolResourceAnalysisService(racingPort).execute(
"decode_android_resources",
{ path: "/targets/app.apk", include_strings: true },
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
// The observation the provider completed is retained on the cancellation, so
// a session still records the Evidence instead of losing finished work.
const retained = parseEvidence(result.error.partialObservation);
expect(retained.operation).toBe("decode_android_resources");
expect(retained.provider).toEqual(identity);
expect(retained.parameters).toEqual({
path: "/targets/app.apk",
include_strings: true,
});
expect(retained.confidence).toBe("observed");
});
+3 -1
View File
@@ -283,7 +283,9 @@ export class BinarySession
previous.route.identity.id,
);
if (!closed.ok) {
this.clearSessionRecords();
// A failed open retires the provider cache, not the investigation.
// Preserve Evidence and Unknown history for export and recovery.
this.clearSnapshot();
this.#clearRuntimeAvailability();
return closed;
}
@@ -30,6 +30,29 @@ it("labels an envelope containing debugger-derived maps as derived", async () =>
expect(evidence.raw_result).toBeNull();
});
it.each([
["x86_64-little-endian", "x86_64"],
["aarch64-little-endian", "arm64"],
] as const)(
"names the CPU family carried by a %s core on created Evidence",
async (architecture, expected) => {
const fixture = recordedCrashFixture("/selected.core", architecture);
const service = new RecordedCrashService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(fixture)),
});
const result = await service.inspect({
path: fixture.artifact.path,
include_debugger_context: false,
});
if (!result.ok) throw result.error;
expect(parseEvidence(result.value).subject?.architecture).toBe(expected);
},
);
it.each([
{ path: "relative.elf" },
{ path: "/selected.core", approval: true },
@@ -10,6 +10,7 @@ import {
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import {
inspectRecordedCrashInputSchema,
RECORDED_LINUX_CORE_PROFILES,
recordedCrashSchema,
} from "../../domain/native/recordedCrash.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
@@ -101,7 +102,9 @@ export class RecordedCrashService {
{
path: value.artifact.path,
format: "elf",
architecture: "x86_64",
architecture:
RECORDED_LINUX_CORE_PROFILES[value.architecture]
.evidenceArchitecture,
sha256: value.artifact.sha256,
},
this.provider.identity,
@@ -100,4 +100,10 @@ const parameters = (
...(input.source_paths === undefined
? {}
: { source_paths: input.source_paths }),
...(input.max_heap_mb === undefined
? {}
: { max_heap_mb: input.max_heap_mb }),
...(input.analysis_timeout_ms === undefined
? {}
: { analysis_timeout_ms: input.analysis_timeout_ms }),
});
@@ -62,26 +62,7 @@ export const analyzeJavaScriptApplicationValidated = async (
});
await checkpointJavaScriptAnalysis(options.signal);
reconstructed = await reconstructJavaScriptArtifact(
{
input_path: input.input_path,
format: input.format,
integrity_policy: input.integrity_policy,
...(input.max_semantic_nodes === undefined
? {}
: { max_semantic_nodes: input.max_semantic_nodes }),
...(input.max_semantic_nodes_per_file === undefined
? {}
: { max_semantic_nodes_per_file: input.max_semantic_nodes_per_file }),
...(input.source_paths === undefined
? {}
: { source_paths: input.source_paths }),
...(input.max_heap_mb === undefined
? {}
: { max_heap_mb: input.max_heap_mb }),
...(input.analysis_timeout_ms === undefined
? {}
: { analysis_timeout_ms: input.analysis_timeout_ms }),
},
input,
scope,
options.signal,
options.progress,
@@ -553,10 +553,10 @@ const collectSourceMapOriginals = (
if (!Array.isArray(names))
return invalidSourceMap(file, "Source map has no sources array.");
const contents = map.sourcesContent;
if (!hasValidSourceMapContents(names.length, contents))
if (!hasValidSourceMapContents(contents))
return invalidSourceMap(
file,
"Source map sourcesContent must contain one string or null entry per source.",
"Source map sourcesContent must be an array of strings or null entries.",
);
if (map.sourceRoot != null && typeof map.sourceRoot !== "string")
return invalidSourceMap(
@@ -457,9 +457,8 @@ const bareModuleCandidate = (
dependencyDirectory = posix.dirname(confined);
}
const source = input.files.get(input.sourcePath);
let directory = posix.dirname(input.sourcePath);
let nearestNotFound: CandidateResolution | null = null;
while (true) {
for (const directory of packageLookupDirectories(input)) {
const candidate = posix.join(directory, dependencyDirectory);
const metadata = readPackageMetadata(input, candidate);
const continueCommonJsLookup =
@@ -487,8 +486,6 @@ const bareModuleCandidate = (
nearestNotFound ??= packageResolution;
} else return packageResolution;
}
if (directory === "." || directory === "") break;
directory = posix.dirname(directory);
}
if (nearestNotFound !== null) return nearestNotFound;
return unresolvedCandidate("external", [
@@ -496,6 +493,21 @@ const bareModuleCandidate = (
]);
};
function* packageLookupDirectories(
input: ResolveArtifactPathInput,
): Generator<string> {
let directory = posix.dirname(input.sourcePath);
while (true) {
if (
input.moduleKind !== "require" ||
posix.basename(directory) !== "node_modules"
)
yield directory;
if (directory === "." || directory === "") return;
directory = posix.dirname(directory);
}
}
/**
* Nearest same-container package.json, stopping at a `node_modules` directory
* so a nested package cannot inherit an ancestor's map.
@@ -960,15 +972,29 @@ const resolveCandidate = (
candidate: string,
packageChain: ReadonlySet<string>,
emittedSourceCandidates: readonly TypeScriptEmittedSourceCandidate[] = [],
): CandidateResolution =>
resolveFileCandidates(input, fileCandidates(candidate, input.moduleKind)) ??
resolveRuntimeSourceCandidates(input, candidate, emittedSourceCandidates) ??
resolveDirectory(
): CandidateResolution => {
if (!commonJsDirectoryRequest(input)) {
const file =
resolveFileCandidates(
input,
fileCandidates(candidate, input.moduleKind),
) ??
resolveRuntimeSourceCandidates(input, candidate, emittedSourceCandidates);
if (file !== null) return file;
}
return resolveDirectory(
input,
candidate,
readPackageMetadata(input, candidate),
packageChain,
);
};
const commonJsDirectoryRequest = (input: ResolveArtifactPathInput): boolean =>
input.context === "module-specifier" &&
input.moduleKind === "require" &&
(input.declaredPath.endsWith("/") ||
/(?:^|\/)\.{1,2}$/u.test(input.declaredPath));
const resolveDirectory = (
input: ResolveArtifactPathInput,
@@ -277,15 +277,9 @@ export const reconstructJavaScriptArtifact = async (
limitations: completed.graph.limitations,
}),
);
const { max_heap_mb, analysis_timeout_ms, ...coreInput } = input;
const parameters = {
...coreInput,
...(max_heap_mb === undefined ? {} : { max_heap_mb }),
...(analysis_timeout_ms === undefined ? {} : { analysis_timeout_ms }),
};
const evidence =
await createOwnedJavaScriptApplicationEvidenceCooperatively(
parameters,
input,
partial,
);
throw interruption.retainPartialObservation(evidence);
@@ -199,6 +199,49 @@ const testAnalysis = (
});
describe("native UI action trace", () => {
it("retains Hopper targetless call evidence alongside fallback callee routes", async () => {
const result = await new EnhancedTools(
testAnalysis({
procedure_address: () => execution("procedure_address", "0x1000"),
procedure_references: (parameters) =>
ok(
createAnalysisExecution(
{
reference_kinds_available: false,
references: [],
unresolved_calls:
parameters.procedure === "0x1000"
? [{ address: "0x1008", reason: "No static target" }]
: [],
},
{ id: "hopper", name: "Hopper", version: "fixture" },
),
),
}),
).execute("trace_native_ui_action", { action: "0x1000" });
if (!result.ok) throw result.error;
const trace = nativeInvestigationTraceSchema.parse(result.value);
expect(trace.edges).toContainEqual(
expect.objectContaining({
relation: "provider_call",
to: "native:function:0x2000",
}),
);
expect(trace.unresolved).toContainEqual(
expect.objectContaining({
from: "native:function:0x1000",
to: null,
reason: "No static target",
evidence: [
expect.objectContaining({
description: "Hopper reported an unresolved call: No static target",
location: { address: "0x1008", file_offset: null },
artifact_sha256: target,
}),
],
}),
);
});
it("accepts an explicit native seed without an authored UI connection", async () => {
const result = await new EnhancedTools(
testAnalysis({
@@ -7,6 +7,59 @@ import { err, ok } from "../../domain/result.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
const provider = { id: "fixture", name: "Fixture", version: "1" };
describe("untyped native call route fallback", () => {
it.each([{ callees: [] }, { callees: ["0x2000"] }])(
"preserves targetless calls and their provider when fallback callees are $callees",
async ({ callees }) => {
const calls: string[] = [];
const referenceProvider = { ...provider, id: "hopper", name: "Hopper" };
const fallbackProvider = { ...provider, id: "fallback" };
const signal = new AbortController().signal;
const unknown = { address: "0x1008", reason: "No static target" };
const result = await readNativeCallRoutes(
{
execute: async (operation, parameters, options) => {
calls.push(operation);
expect(parameters.procedure).toBe("0x1000");
expect(options).toEqual({ signal, selectorOrigin: "provider" });
return ok(
createAnalysisExecution(
operation === "procedure_references"
? {
reference_kinds_available: false,
references: [],
unresolved_calls: [unknown],
}
: callees,
operation === "procedure_references"
? referenceProvider
: fallbackProvider,
),
);
},
},
"0x1000",
signal,
"provider",
);
expect(calls).toEqual(["procedure_references", "procedure_callees"]);
expect(result).toEqual({
ok: true,
value: {
provider: fallbackProvider,
routes: callees.map((address) => ({
address,
site: "0x1000",
relation: "provider_call",
resolution: "inferred",
})),
unknowns: [{ ...unknown, provider: referenceProvider }],
},
});
},
);
});
describe("typed native call routes", () => {
it("preserves computed targets, ambiguity and targetless call sites", async () => {
const reference = jsonValueSchema.parse(ghidraReferenceEdge());
+57 -36
View File
@@ -2,12 +2,12 @@ import { z } from "zod";
import type {
AnalysisOperationPort,
ExecutionOptions,
ProviderIdentity,
} from "../AnalysisProvider.js";
import {
parseRelatedAddresses,
referenceKindSchema,
} from "../../domain/hopperValues.js";
import { err, ok } from "../../domain/result.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
const referencesSchema = z.object({
@@ -40,15 +40,29 @@ export const readNativeCallRoutes = async (
{ procedure, direction: "outgoing" },
options,
);
let unknowns: Array<{
address: string;
reason: string;
provider: ProviderIdentity;
}> = [];
if (execution.ok) {
const parsed = referencesSchema.safeParse(execution.value.result);
if (!parsed.success)
return err(
new AnalysisOutputError(
return {
ok: false as const,
error: new AnalysisOutputError(
"procedure_references",
"Invalid typed call references",
),
);
unknowns,
};
// Missing detailed reference flags do not invalidate observed targetless
// calls. Keep their producing provider even if another provider supplies
// the fallback callee inventory.
unknowns = parsed.data.unresolved_calls.map((call) => ({
...call,
provider: execution.value.provider,
}));
const references = parsed.data.references;
if (
parsed.data.reference_kinds_available === true ||
@@ -64,45 +78,52 @@ export const readNativeCallRoutes = async (
targets.add(call.target_address);
countBySite.set(call.source_address, targets);
}
return ok({
provider: execution.value.provider,
routes: calls.map((call) => ({
address: call.target_procedure?.address ?? call.target_address,
site: call.source_address,
relation:
call.kind.available && (call.kind.computed || call.kind.indirect)
? ("indirect_call" as const)
: ("direct_call" as const),
resolution:
(countBySite.get(call.source_address)?.size ?? 0) > 1
? ("ambiguous" as const)
: call.kind.available &&
(call.kind.computed || call.kind.indirect)
? ("resolved" as const)
: ("observed" as const),
})),
unknowns: parsed.data.unresolved_calls,
});
return {
ok: true as const,
value: {
provider: execution.value.provider,
routes: calls.map((call) => ({
address: call.target_procedure?.address ?? call.target_address,
site: call.source_address,
relation:
call.kind.available && (call.kind.computed || call.kind.indirect)
? ("indirect_call" as const)
: ("direct_call" as const),
resolution:
(countBySite.get(call.source_address)?.size ?? 0) > 1
? ("ambiguous" as const)
: call.kind.available &&
(call.kind.computed || call.kind.indirect)
? ("resolved" as const)
: ("observed" as const),
})),
unknowns,
},
};
}
} else if (execution.error._tag !== "AnalysisCapabilityUnavailableError")
return err(execution.error);
return { ok: false as const, error: execution.error, unknowns };
const callees = await analysis.execute(
"procedure_callees",
{ procedure },
options,
);
if (!callees.ok) return callees;
if (!callees.ok)
return { ok: false as const, error: callees.error, unknowns };
const parsed = parseRelatedAddresses(callees.value.result, "callees");
return parsed.ok
? ok({
provider: callees.value.provider,
routes: parsed.value.map((address) => ({
address,
site: procedure,
relation: "provider_call" as const,
resolution: "inferred" as const,
})),
unknowns: [],
})
: parsed;
? {
ok: true as const,
value: {
provider: callees.value.provider,
routes: parsed.value.map((address) => ({
address,
site: procedure,
relation: "provider_call" as const,
resolution: "inferred" as const,
})),
unknowns,
},
}
: { ok: false as const, error: parsed.error, unknowns };
};
+38 -28
View File
@@ -414,9 +414,44 @@ const addDirectCallees = async (input: {
"provider",
);
examined += 1;
if (!execution.ok && execution.error._tag === "AnalysisCancelledError")
return { error: execution.error };
const unknowns = execution.ok
? execution.value.unknowns
: execution.unknowns;
for (const [index, unknown] of unknowns.entries()) {
if (edges.size >= input.input.max_edges) {
truncated = true;
omitted += unknowns.length - index;
break;
}
const id = `unknown-dispatch:${current.address}:${unknown.address}`;
edges.set(id, {
id,
from: current.node.id,
to: null,
relation: "indirect_call",
resolution: "unresolved",
reason: unknown.reason,
evidence: [
{
kind: "reference",
provider: unknown.provider,
description: `${unknown.provider.name} reported an unresolved call: ${unknown.reason}`,
location: { address: unknown.address, file_offset: null },
artifact_path: null,
artifact_sha256: input.targetSha256,
},
],
limitations: [],
});
}
if (!execution.ok) {
if (execution.error._tag === "AnalysisCancelledError")
return { error: execution.error };
if (edges.size >= input.input.max_edges) {
truncated = true;
omitted += 1;
continue;
}
const id = `unknown-callees:${current.address}`;
edges.set(id, {
id,
@@ -432,32 +467,6 @@ const addDirectCallees = async (input: {
});
continue;
}
for (const unknown of execution.value.unknowns) {
if (edges.size >= input.input.max_edges) {
truncated = true;
omitted++;
break;
}
const id = `unknown-dispatch:${current.address}:${unknown.address}`;
edges.set(id, {
id,
from: current.node.id,
to: null,
relation: "indirect_call",
resolution: "unresolved",
reason: unknown.reason,
evidence: [
{
kind: "reference",
description: unknown.reason,
location: { address: unknown.address, file_offset: null },
artifact_path: null,
artifact_sha256: input.targetSha256,
},
],
limitations: [],
});
}
for (const [index, route] of execution.value.routes.entries()) {
const address = route.address;
if (edges.size >= input.input.max_edges) {
@@ -469,6 +478,7 @@ const addDirectCallees = async (input: {
const evidence = [
{
kind: "reference" as const,
provider: execution.value.provider,
description: `${execution.value.provider.name} reported ${route.relation} from ${current.address} to ${address}`,
location: { address: route.site, file_offset: null },
artifact_path: null,
@@ -0,0 +1,198 @@
import { expect, it } from "vitest";
import { createEvidence } from "../../domain/evidence.js";
import { wasmInterfaceComparisonSchema } from "../../contracts/wasm/wasmComparisonContracts.js";
import { compareWasmInterfaces } from "./WasmInterfaceComparisonService.js";
import type { WasmInterface } from "../../domain/wasm/wasmInterface.js";
import { wasmArtifactFixture } from "../../../tests/fixtures/wasm/artifact.js";
const facts = (
name: string,
parameter: "i32" | "i64" = "i32",
): WasmInterface => ({
state: "complete",
issues: [],
entries: [
{
direction: "export",
module: null,
name,
kind: "func",
index: 0,
signature: { kind: "func", params: [parameter], results: [] },
wat_form: `(export "${name}" (func 0))`,
issue: null,
},
],
});
const evidence = (interfaceFacts?: WasmInterface) => {
const report = wasmArtifactFixture();
if (interfaceFacts !== undefined) report.interface = interfaceFacts;
return createEvidence(
{
path: report.artifact.path,
sha256: report.artifact.sha256,
format: "file",
},
{ id: "fixture", name: "typed fixture", version: "1" },
{
operation: "inspect_wasm_artifact",
parameters: { path: report.artifact.path },
result: report,
confidence: "observed",
},
);
};
const compare = async (
left: ReturnType<typeof evidence>,
right: ReturnType<typeof evidence>,
) => {
const result = await compareWasmInterfaces({ left, right, scope: "both" });
if (!result.ok) throw result.error;
return wasmInterfaceComparisonSchema.parse(result.value.normalized_result);
};
it("reports all five comparison states, including duplicate ambiguity and explicit selected scope", async () => {
const left = facts("changed");
const right = facts("changed", "i64");
left.entries.push(
...facts("unchanged").entries,
...facts("removed").entries,
...facts("dup").entries,
...facts("dup").entries,
);
right.entries.push(
...facts("unchanged").entries,
...facts("added").entries,
...facts("dup").entries,
);
const report = await compare(evidence(left), evidence(right));
expect(report.summary).toEqual({
changed: 1,
unchanged: 1,
removed: 1,
added: 1,
unknown: 1,
});
expect(report.changes.find((c) => c.name === "dup")).toMatchObject({
state: "unknown",
left: [expect.anything(), expect.anything()],
right: [expect.anything()],
});
const selected = await compareWasmInterfaces({
left: evidence(left),
right: evidence(right),
scope: "imports",
});
if (!selected.ok) throw selected.error;
expect(selected.value.normalized_result).toMatchObject({
changes: [],
coverage: "complete-within-inputs",
});
});
it("withholds absence claims for historical or partial inventories and unsupported signatures", async () => {
const known = facts("f");
const absent = await compare(evidence(), evidence(known));
expect(absent).toMatchObject({
coverage: "partial",
changes: [{ state: "unknown" }],
});
const partial: WasmInterface = {
state: "partial",
issues: ["unread import table"],
entries: [],
};
expect(await compare(evidence(partial), evidence(known))).toMatchObject({
changes: [{ state: "unknown" }],
});
const unsupported = facts("f");
unsupported.entries[0]!.signature = null;
expect(await compare(evidence(known), evidence(unsupported))).toMatchObject({
changes: [{ state: "unknown" }],
});
const partialMatch = facts("f");
partialMatch.state = "partial";
partialMatch.issues = ["Later imports were not examined"];
expect(await compare(evidence(partialMatch), evidence(known))).toMatchObject({
changes: [{ state: "unknown" }],
});
expect(await compare(evidence(), evidence())).toMatchObject({
coverage: "unknown",
changes: [],
});
});
it("authenticates semantic Evidence and binds display subject and selection identity", async () => {
const left = JSON.parse(JSON.stringify(evidence(facts("f"))));
left.normalized_result.interface.entries[0].name = "tampered";
expect(
await compareWasmInterfaces({
left,
right: evidence(facts("f")),
scope: "both",
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
const rebound = JSON.parse(JSON.stringify(evidence(facts("f"))));
rebound.subject.local_path = "/other.wasm";
expect(
await compareWasmInterfaces({
left: rebound,
right: evidence(facts("f")),
scope: "both",
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
});
it("resolves exact retained references and permits cancellation between comparison batches", async () => {
const left = evidence(facts("f"));
const right = evidence(facts("f", "i64"));
const references = {
left: { kind: "retained-evidence", evidence_id: left.evidence_id },
right: { kind: "retained-evidence", evidence_id: right.evidence_id },
scope: "both",
};
expect(await compareWasmInterfaces(references)).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
const result = await compareWasmInterfaces(references, {}, (id) =>
id === left.evidence_id ? left : right,
);
if (!result.ok) throw result.error;
expect(result.value.evidence_links).toEqual([
left.evidence_id,
right.evidence_id,
]);
const large = facts("f");
large.entries.push(
...Array.from({ length: 2000 }, (_, i) => facts(`f${i}`).entries[0]!),
);
const controller = new AbortController();
const pending = compareWasmInterfaces(
{ left: evidence(large), right: evidence(large), scope: "both" },
{ signal: controller.signal },
);
setImmediate(() => controller.abort());
expect(await pending).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
});
it.each([false, true])(
"keeps a one-sided unsupported interface unknown with reverse=%s",
async (reverse) => {
const empty: WasmInterface = { state: "complete", issues: [], entries: [] };
const unsupported = facts("exception");
unsupported.entries[0]!.signature = null;
unsupported.entries[0]!.issue = "Unsupported exnref global type";
const sides = reverse ? [unsupported, empty] : [empty, unsupported];
expect(await compare(evidence(sides[0]), evidence(sides[1]))).toMatchObject(
{
coverage: "partial",
summary: { added: 0, removed: 0, unknown: 1 },
changes: [{ state: "unknown" }],
},
);
},
);
@@ -0,0 +1,250 @@
import {
WASM_INTERFACE_REPRESENTATION_BYTES,
wasmInterfaceEntryRepresentationBytes,
} from "../../domain/wasm/wasmInterface.js";
import { setImmediate } from "node:timers/promises";
import {
compareWasmInterfacesInputSchema,
wasmInterfaceComparisonSchema,
} from "../../contracts/wasm/wasmComparisonContracts.js";
import {
createEvidence,
parseEvidence,
type Evidence,
} from "../../domain/evidence.js";
import {
wasmArtifactSchema,
type WasmArtifact,
} from "../../domain/wasm/wasmArtifact.js";
import type { WasmInterfaceEntry } from "../../domain/wasm/wasmInterface.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
import { ARTIFACT_COMPARISON_PROVIDER } from "../InvestigationProviders.js";
import {
resolvePairedEvidenceRequest,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { z } from "zod";
const OPERATION = "compare_wasm_interfaces";
const parseInspection = (
raw: unknown,
): { evidence: Evidence; result: WasmArtifact } => {
const evidence = parseEvidence(raw);
if (evidence.operation !== "inspect_wasm_artifact")
throw new TypeError("Expected complete inspect_wasm_artifact Evidence");
const result = wasmArtifactSchema.parse(evidence.normalized_result);
if (
evidence.subject?.digest.sha256 !== result.artifact.sha256 ||
evidence.subject.local_path !== result.artifact.path ||
evidence.parameters.path !== result.artifact.path
)
throw new TypeError(
"WASM Evidence subject/selection does not match normalized artifact identity",
);
return { evidence, result };
};
/** Compare only producer-owned typed facts; no raw WAT or original file is reread. */
export const compareWasmInterfaces = async (
rawInput: unknown,
options?: ExecutionOptions,
lookup?: EvidenceLookup,
): Promise<Result<Evidence, AnalysisError>> => {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const parsed = compareWasmInterfacesInputSchema.safeParse(rawInput);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(OPERATION, parsed.error.issues, rawInput),
);
const resolved = resolvePairedEvidenceRequest(parsed.data, lookup);
if (!resolved.ok) return resolved;
try {
await setImmediate();
options?.signal?.throwIfAborted();
const left = parseInspection(resolved.value.left);
const right = parseInspection(resolved.value.right);
const scope = parsed.data.scope;
const selected = (entry: WasmInterfaceEntry): boolean =>
scope === "both" ||
entry.direction === (scope === "imports" ? "import" : "export");
const groups = new Map<
string,
{
left: WasmInterfaceEntry[];
right: WasmInterfaceEntry[];
entry: WasmInterfaceEntry;
}
>();
let work = 0;
for (const [side, inspection] of [
["left", left],
["right", right],
] as const) {
for (const entry of inspection.result.interface?.entries ?? []) {
if (++work % 256 === 0) {
await setImmediate();
options?.signal?.throwIfAborted();
}
if (!selected(entry)) continue;
const key = JSON.stringify([entry.direction, entry.module, entry.name]);
let group = groups.get(key);
if (group === undefined) {
group = { left: [], right: [], entry };
groups.set(key, group);
}
group[side].push(entry);
}
}
const knownInventory = (inspection: typeof left): boolean =>
inspection.result.interface?.state === "complete";
const changes: z.infer<typeof wasmInterfaceComparisonSchema>["changes"] =
[];
const summary = {
added: 0,
removed: 0,
changed: 0,
unchanged: 0,
unknown: 0,
};
let remaining = WASM_INTERFACE_REPRESENTATION_BYTES;
for (const group of groups.values()) {
remaining -=
512 +
group.left.reduce(
(sum, entry) => sum + wasmInterfaceEntryRepresentationBytes(entry),
0,
) +
group.right.reduce(
(sum, entry) => sum + wasmInterfaceEntryRepresentationBytes(entry),
0,
);
if (remaining < 0)
throw new AnalysisResourceConstraintError(
OPERATION,
"capacity",
"WASM comparison exceeds typed interface representation capacity",
{ maximum_bytes: WASM_INTERFACE_REPRESENTATION_BYTES },
);
if (++work % 256 === 0) {
await setImmediate();
options?.signal?.throwIfAborted();
}
let state: keyof typeof summary;
let reason: string | null = null;
const l = group.left[0];
const r = group.right[0];
if (group.left.length > 1 || group.right.length > 1) {
state = "unknown";
reason =
"Duplicate interface names are ambiguous; all occurrences retained";
} else if (!knownInventory(left) || !knownInventory(right)) {
state = "unknown";
reason =
"Incomplete interface inventories cannot establish per-key uniqueness or absence";
} else if (
[l, r].some(
(entry) =>
entry !== undefined &&
(entry.signature === null ||
entry.issue !== null ||
entry.kind === "unknown"),
)
) {
state = "unknown";
reason =
"Signature/type semantics were not admitted for every present entry";
} else if (l === undefined) state = "added";
else if (r === undefined) state = "removed";
else if (l.kind !== r.kind) state = "changed";
else
state =
JSON.stringify(l.signature) === JSON.stringify(r.signature)
? "unchanged"
: "changed";
summary[state]++;
changes.push({
direction: group.entry.direction,
module: group.entry.module,
name: group.entry.name,
state,
left: group.left,
right: group.right,
reason,
});
}
const compareText = (a: string, b: string): number =>
a < b ? -1 : a > b ? 1 : 0;
changes.sort(
(a, b) =>
compareText(a.direction, b.direction) ||
compareText(a.module ?? "", b.module ?? "") ||
compareText(a.name, b.name),
);
const coverage =
left.result.interface === undefined &&
right.result.interface === undefined
? "unknown"
: !knownInventory(left) || !knownInventory(right) || summary.unknown > 0
? "partial"
: "complete-within-inputs";
const limitations = [
"Exact declared interface equality is not runtime/ABI compatibility, successful linking or original-source identity.",
"Typed facts come from the selected validated WABT decoding; unsupported signature semantics and duplicate names remain unknown.",
];
const report = wasmInterfaceComparisonSchema.parse({
left: {
evidence_id: left.evidence.evidence_id,
artifact: left.result.artifact,
},
right: {
evidence_id: right.evidence.evidence_id,
artifact: right.result.artifact,
},
scope,
coverage,
changes,
summary,
limitations,
});
await setImmediate();
options?.signal?.throwIfAborted();
return ok(
createEvidence(undefined, ARTIFACT_COMPARISON_PROVIDER, {
operation: OPERATION,
predicateType: "rea.wasm-interface-comparison",
parameters: {
left_evidence_id: left.evidence.evidence_id,
right_evidence_id: right.evidence.evidence_id,
scope,
},
result: report,
confidence: "derived",
authority: "analyst-inference",
limitations,
evidenceLinks: [left.evidence.evidence_id, right.evidence.evidence_id],
}),
);
} catch (cause: unknown) {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
if (cause instanceof AnalysisError) return err(cause);
return err(
new AnalysisInputError(OPERATION, { cause }, [
{
path: [],
reason: "invalid_value",
message: cause instanceof Error ? cause.message : String(cause),
},
]),
);
}
};
-25
View File
@@ -1,25 +0,0 @@
import { describe, expect, it } from "vitest";
import { orderAsarListing } from "./AsarArtifactReader.js";
describe("orderAsarListing", () => {
it("orders host-spelled listings by their portable archive path", () => {
const posix = orderAsarListing(["/a0", "/a", "/a/b"], "/");
const windows = orderAsarListing(["\\a0", "\\a", "\\a\\b"], "\\");
// "/" (0x2F) precedes "0" (0x30); "\" (0x5C) would follow it.
expect(posix.map(({ path }) => path)).toEqual(["a", "a/b", "a0"]);
expect(windows.map(({ path }) => path)).toEqual(["a", "a/b", "a0"]);
expect(windows.map(({ listed }) => listed)).toEqual([
"\\a",
"\\a\\b",
"\\a0",
]);
});
it("keeps POSIX backslashes as literal filename characters", () => {
expect(orderAsarListing(["/a\\b"], "/")).toEqual([
{ listed: "/a\\b", path: "a\\b" },
]);
});
});
+21 -53
View File
@@ -13,7 +13,7 @@ import { isAbsolute, join, relative, sep } from "node:path";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { listPackage, statFile, uncache } from "@electron/asar";
import { getRawHeader, uncache } from "@electron/asar";
import {
ArtifactReaderFailure,
@@ -26,7 +26,11 @@ import { closeAsarHandle, readValidatedAsarEntry } from "./AsarEntryStream.js";
import { admitAsarHeader } from "./AsarHeader.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import {
readAsarListing,
type AsarListedEntry,
type AsarMetadata,
} from "./AsarListing.js";
/**
* Official Electron ASAR adapter with range-streamed member reads.
@@ -51,7 +55,7 @@ export class AsarArtifactReader implements ArtifactReader {
) {}
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
let paths: readonly AsarListedPath[];
let paths: readonly AsarListedEntry[];
try {
await this.prepareContainer(undefined, signal);
paths = await this.#withSnapshotOperation(async () => {
@@ -62,8 +66,9 @@ export class AsarArtifactReader implements ArtifactReader {
this.#archiveSize = admitted.archiveBytes;
this.#headerSize = admitted.headerBytes;
abortIfNeeded(signal);
const ordered = orderAsarListing(
listPackage(snapshotPath, { isPack: false }),
const ordered = await readAsarListing(
getRawHeader(snapshotPath).header,
signal,
);
const archiveMetadata = await lstat(snapshotPath);
if (!archiveMetadata.isFile() || archiveMetadata.isSymbolicLink())
@@ -77,34 +82,25 @@ export class AsarArtifactReader implements ArtifactReader {
} catch (cause: unknown) {
throw asarFailure(this.path, "inventory", cause);
}
for (const { listed, path } of paths) {
for (const { metadata, path } of paths) {
abortIfNeeded(signal);
if (path.length === 0) continue;
const providerPath = listed.startsWith(sep)
? listed.slice(sep.length)
: listed;
let metadata: ReturnType<typeof statFile>;
try {
metadata = statFile(this.#snapshotPath(), providerPath, false);
} catch (cause: unknown) {
throw asarFailure(this.path, `stat ${path}`, cause);
}
const providerPath = path.split("/").join(sep);
const kind =
"files" in metadata
metadata.files !== undefined
? "directory"
: "link" in metadata
: metadata.link !== undefined
? "symlink"
: "file";
const entry: ArtifactEntry = {
path,
kind,
declaredSize: "size" in metadata ? metadata.size : null,
declaredSize: metadata.size ?? null,
compressedSize: null,
executable: "executable" in metadata && metadata.executable,
executable: metadata.executable === true,
encrypted: false,
byteOffset: null,
declaredSha256:
"integrity" in metadata &&
metadata.integrity !== undefined &&
metadata.integrity.algorithm === "SHA256" &&
/^[a-f0-9]{64}$/u.test(metadata.integrity.hash)
? metadata.integrity.hash
@@ -603,7 +599,7 @@ export class AsarArtifactReader implements ArtifactReader {
}
}
type AsarFileMetadata = Extract<ReturnType<typeof statFile>, { size: number }>;
type AsarFileMetadata = AsarMetadata & { readonly size: number };
type AsarEntryState = {
readonly metadata: AsarFileMetadata;
readonly entry: ArtifactEntry;
@@ -652,12 +648,11 @@ const asarUnpackedEntryFailure = (
};
const isAsarFileMetadata = (
metadata: ReturnType<typeof statFile>,
metadata: AsarMetadata,
): metadata is AsarFileMetadata =>
"size" in metadata &&
typeof metadata.size === "number" &&
!("files" in metadata) &&
!("link" in metadata);
metadata.files === undefined &&
metadata.link === undefined;
const parseArchiveOffset = (value: string): number | undefined => {
if (!/^(?:0|[1-9][0-9]*)$/u.test(value)) return undefined;
@@ -699,33 +694,6 @@ const waitForOperation = async (
});
};
interface AsarListedPath {
readonly listed: string;
readonly path: string;
}
/**
* Pair each host-spelled listing with its portable archive path, ordered by
* the portable path so Windows and POSIX hosts agree.
*
* @electron/asar returns paths assembled with the host path module. Keep that
* spelling for its API calls, but expose archive paths with portable
* separators. On POSIX, backslashes can be literal filename characters and
* must remain untouched.
*/
export const orderAsarListing = (
listed: readonly string[],
separator: string = sep,
): AsarListedPath[] =>
listed
.map((entry) => ({ listed: entry, path: toArtifactPath(entry, separator) }))
.sort((left, right) => compareUnicodeCodePoints(left.path, right.path));
const toArtifactPath = (listed: string, separator: string): string => {
const portable = separator === "\\" ? listed.replaceAll("\\", "/") : listed;
return portable.replace(/^\/+|\/+$/gu, "");
};
const asarFailure = (
path: string,
operation: string,
+110
View File
@@ -0,0 +1,110 @@
import { setImmediate } from "node:timers/promises";
import { z } from "zod";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/** Capacity for expanded paths and listing records, independent of packed bytes. */
const MAX_LISTING_BYTES = 64 * 1024 * 1024;
const nodeSchema = z.looseObject({
files: z
.custom<Record<string, unknown>>(
(value) =>
value !== null && typeof value === "object" && !Array.isArray(value),
)
.optional(),
link: z.string().optional(),
size: z.number().nonnegative().safe().optional(),
offset: z.string().optional(),
unpacked: z.boolean().optional(),
executable: z.boolean().optional(),
integrity: z
.looseObject({ algorithm: z.string(), hash: z.string() })
.optional(),
});
export type AsarMetadata = z.infer<typeof nodeSchema>;
export interface AsarListedEntry {
readonly path: string;
readonly metadata: AsarMetadata;
}
function* ownChildren(files: Record<string, unknown>) {
for (const name in files)
if (Object.hasOwn(files, name)) yield [name, files[name]] as const;
}
/** Decode each node once; admit expanded paths before concatenation and retain no recursive lookup. */
export const readAsarListing = async (
header: unknown,
signal?: AbortSignal,
): Promise<AsarListedEntry[]> => {
const root = nodeSchema.parse(header);
if (root.files === undefined)
throw new ArtifactReaderFailure("format", "ASAR root has no files table");
const entries: AsarListedEntry[] = [];
const pending = [{ parent: "", children: ownChildren(root.files) }];
let retainedBytes = 0;
let examined = 0;
while (pending.length > 0) {
if (examined++ % 128 === 0) {
await setImmediate();
if (signal?.aborted)
throw new ArtifactReaderFailure(
"cancelled",
"ASAR operation cancelled",
);
}
const frame = pending.at(-1);
if (frame === undefined) break;
const next = frame.children.next();
if (next.done) {
pending.pop();
continue;
}
const [name, raw] = next.value;
// A header member is one component, not a host path to normalize. POSIX
// backslashes remain literal; Windows cannot represent them as components.
if (
name.length === 0 ||
name === "." ||
name === ".." ||
name.includes("/") ||
name.includes("\0") ||
(process.platform === "win32" && name.includes("\\"))
)
throw new ArtifactReaderFailure(
"path",
"ASAR header has an unsafe path component",
);
const units =
frame.parent.length + name.length + (frame.parent.length === 0 ? 0 : 1);
// UTF-16 storage, plus records and traversal bookkeeping. Charge every
// occurrence even when the engine can share a string prefix.
retainedBytes += units * 2 + 256;
if (retainedBytes > MAX_LISTING_BYTES)
throw new ArtifactReaderFailure(
"limit",
"ASAR expanded listing exceeds its 64 MiB representation budget",
);
const path = frame.parent.length === 0 ? name : `${frame.parent}/${name}`;
const metadata = nodeSchema.parse(raw);
if (
metadata.files === undefined &&
metadata.link === undefined &&
metadata.size === undefined
)
throw new ArtifactReaderFailure(
"format",
"ASAR entry has no directory, link or file metadata",
);
entries.push({ path, metadata });
if (metadata.files !== undefined)
pending.push({
parent: path,
children: ownChildren(metadata.files),
});
}
return entries.sort((left, right) =>
compareUnicodeCodePoints(left.path, right.path),
);
};
+84
View File
@@ -0,0 +1,84 @@
import { expect, it } from "vitest";
import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
import { captureStorage } from "./CdpCaptureStorage.js";
import { CdpCommandRejection } from "./CdpCommandRejection.js";
import type { CdpConnection } from "./CdpConnection.js";
const NO_CACHE_COMMAND = Symbol("unsupported");
const captureWithCacheResult = async (
cacheResult: unknown,
): Promise<Awaited<ReturnType<typeof captureStorage>>["value"]> => {
const connection = {
send(method: string): Promise<unknown> {
switch (method) {
case "Storage.getUsageAndQuota":
return Promise.resolve({ usage: 1, quota: 10 });
case "DOMStorage.getDOMStorageItems":
return Promise.resolve({ entries: [] });
case "IndexedDB.requestDatabaseNames":
return Promise.resolve({ databaseNames: [] });
case "Network.getCookies":
return Promise.resolve({ cookies: [] });
case "CacheStorage.requestCacheNames":
return cacheResult === NO_CACHE_COMMAND
? Promise.reject(
new CdpCommandRejection(
"inspect_web_page",
method,
-32601,
"Method not found",
),
)
: Promise.resolve(cacheResult);
case "CacheStorage.requestEntries":
return Promise.resolve({ cacheDataEntries: [], returnCount: 0 });
default:
return Promise.reject(new Error(`Unexpected command: ${method}`));
}
},
} as unknown as CdpConnection;
const { value } = await captureStorage(
{
connection,
sessionId: undefined,
input: inspectWebPageInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "fixture-page",
include_storage_keys: true,
include_storage_fingerprints: true,
}),
},
"https://example.test/",
[],
);
return value;
};
it.each([
["an observed empty cache list", { caches: [] }, true],
["a response without a cache list", {}, false],
["a non-array cache list", { caches: "nope" }, false],
["a cache list with an unusable entry", { caches: [5] }, false],
["an unsupported cache command", NO_CACHE_COMMAND, false],
] as const)(
"reports fingerprint completeness for %s",
async (_label, cacheResult, complete) => {
const value = await captureWithCacheResult(cacheResult);
expect(value.cache_names).toEqual([]);
expect(value.fingerprints_complete).toBe(complete);
},
);
it.each([false, true])(
"preserves valid cache evidence beside an unusable entry: %s",
async (mixed) => {
const cache = { cacheName: "fixture-cache", cacheId: "fixture-cache-id" };
const value = await captureWithCacheResult({
caches: mixed ? [cache, 5] : [cache],
});
expect(value.cache_names).toEqual(["fixture-cache"]);
expect(value.fingerprints_complete).toBe(!mixed);
},
);
+6 -4
View File
@@ -60,8 +60,8 @@ export const captureStorage = async (
limitations,
)
: undefined;
const cacheValues = recordsValue(recordValue(cacheRaw)?.caches);
const caches = capturedCaches(cacheValues);
const cacheField = recordValue(cacheRaw)?.caches;
const caches = capturedCaches(recordsValue(cacheField));
const fingerprints = context.input.include_storage_fingerprints
? await captureStorageFingerprints({
context,
@@ -78,8 +78,10 @@ export const captureStorage = async (
indexedRaw !== undefined &&
Array.isArray(indexedValues) &&
indexed.length === indexedValues.length &&
cacheRaw !== undefined &&
caches.length === cacheValues.length;
// Like IndexedDB names, a missing, non-array or partly unusable cache
// list is an incomplete enumeration rather than an empty one.
Array.isArray(cacheField) &&
caches.length === cacheField.length;
return {
value: {
origin,
+3 -17
View File
@@ -8,6 +8,8 @@ import {
FIELD_RECORD_BUDGET,
} from "./parseFieldDiscovery.js";
import {
BOUNDED_PRODUCER_LIMITS as LIMITS,
prlimitArgumentVector,
readLinuxResourceLimits,
type LinuxResourceLimits,
} from "../process/LinuxResourceLimits.js";
@@ -60,15 +62,6 @@ export const TSHARK_PROVIDER_IDENTITY = {
name: "REA TShark capture adapter",
version: "tshark@4",
} as const;
// Bound the resident input copy and retained text before allocation/collection.
const LIMITS = {
input_bytes: 32 * 1024 * 1024,
output_bytes: 4 * 1024 * 1024,
command_timeout_ms: 30_000,
address_space_bytes: 1024 * 1024 * 1024,
file_bytes: 64 * 1024 * 1024,
cpu_seconds: 30,
} as const;
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
/** Inspect selected capture files only, retaining cleanup ownership across failures. */
@@ -165,14 +158,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
options?.signal,
);
effectiveLimits = await this.#resources.readLimits(limits);
const limitArguments = [
`--as=${effectiveLimits.address_space_bytes}:${effectiveLimits.address_space_bytes}`,
`--fsize=${effectiveLimits.file_bytes}:${effectiveLimits.file_bytes}`,
`--cpu=${effectiveLimits.cpu_seconds}:${effectiveLimits.cpu_seconds}`,
"--core=0:0",
"--",
command,
];
const limitArguments = prlimitArgumentVector(effectiveLimits, command);
phase = "workspace";
root = await this.createRuntime();
this.#resources.retain(root, undefined);
+14 -14
View File
@@ -6,7 +6,10 @@ import { createApktoolResourceAnalysisProvider } from "../composition/apktool.js
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { ApktoolOperation } from "../domain/apktool/apktoolResourceAnalysis.js";
import {
apktoolInputSchemas,
type ApktoolOperation,
} from "../domain/apktool/apktoolResourceAnalysis.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
@@ -49,22 +52,19 @@ export const registerApktoolCommands = (
args: z.object({
path: z.string().min(1).describe("Local APK file to decode"),
}),
// The locale grammar and the string-projection default belong to the
// apktool input owner. Read them from that schema rather than restating a
// narrower locale pattern, which refused the owner's own advertised
// `b+zh+Hans+CN` form at the CLI boundary.
options: z.object({
locale: z
.string()
.min(2)
.max(16)
.regex(
/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/u,
"Locale must look like de or pt-BR",
)
.optional()
.describe(
"Project strings from res/values-<locale> instead of the default",
),
locale: apktoolInputSchemas.decode_android_resources.shape.locale,
strings: z
.boolean()
.default(true)
.default(
apktoolInputSchemas.decode_android_resources.shape.include_strings.parse(
undefined,
),
)
.describe(
"Include string resources; use --no-strings to skip projecting them",
),
+1 -1
View File
@@ -225,7 +225,7 @@ const registerInspectionCommand = (
description:
"Inspect one artifact and return all available observations and next probes",
args: z.object({
path: z.string().describe("Application or package path"),
path: z.string().min(1).describe("Application or package path"),
}),
options: z.object({
integrityPolicy: z
+4 -1
View File
@@ -48,7 +48,10 @@ const registerOverviewCommands = (
cli.command(CLI_COMMANDS.analyze, {
description: "Get an overview of an app",
args: z.object({
path: z.string().describe("App, program, or analysis database path"),
path: z
.string()
.min(1)
.describe("App, program, or analysis database path"),
}),
options: overviewOptions.extend({
integrityPolicy: javascriptApplicationOptions.shape.integrityPolicy,
+40
View File
@@ -17,6 +17,46 @@ export const registerCoreNativeCommands = (
runDirectAnalysis: DirectAnalysis["runDirectAnalysis"],
): void => {
registerAnnotationCommand(cli, logger, runDirectAnalysis);
cli.command(CLI_COMMANDS.searchBytes, {
description: "Find masked byte patterns in initialized provider memory",
args: z.object({
path: z.string().describe("Local executable path"),
pattern: z.string().describe("Hexadecimal byte pairs with ?? wildcards"),
}),
options: z.object({
mask: z.string().optional().describe("Equal-length hexadecimal bit mask"),
start: z.string().optional().describe("Inclusive start address"),
end: z.string().optional().describe("Inclusive end address"),
cursor: z
.string()
.optional()
.describe("Continuation from the same query's next_cursor"),
limit: z
.number()
.int()
.min(1)
.max(1000)
.default(100)
.describe("Maximum matches on this page"),
...nativeOpenOptionFields,
}),
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.searchBytes, () =>
runDirectAnalysis(
args.path,
"search_bytes",
{
pattern: args.pattern,
limit: options.limit,
...(options.mask === undefined ? {} : { mask: options.mask }),
...(options.start === undefined ? {} : { start: options.start }),
...(options.end === undefined ? {} : { end: options.end }),
...(options.cursor === undefined ? {} : { cursor: options.cursor }),
},
directAnalysisOptionsFromCli(logger, options),
),
),
});
cli.command(CLI_COMMANDS.inspectNativeLoadImage, {
description:
"Verify loaded native bytes, source mappings, relocations and entry",
+26
View File
@@ -1,3 +1,6 @@
import { compareWasmInterfaces } from "../application/wasm/WasmInterfaceComparisonService.js";
import { parseCliJsonInput } from "../cliJsonInput.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { z } from "incur";
import { resolve } from "node:path";
import { wasmArtifactModule } from "../composition/wasm.js";
@@ -13,6 +16,29 @@ export const registerWasmCommands = (
logger: Logger,
environment: Readonly<NodeJS.ProcessEnv>,
): void => {
cli.command(CLI_COMMANDS.compareWasmInterfaces, {
description:
"Compare core WASM interfaces from two exact inspection Evidence records",
args: z.object({
input: z
.string()
.describe(
"Inline JSON or input file containing left/right complete Evidence and required scope",
),
}),
run: ({ args }) =>
withCommandCancellation(async (signal) =>
logCliCommand(logger, CLI_COMMANDS.compareWasmInterfaces, async () => {
const input = await parseCliJsonInput(
args.input,
"compare_wasm_interfaces",
);
if (!input.ok) return input.error;
const result = await compareWasmInterfaces(input.value, { signal });
return result.ok ? result.value : projectAnalysisError(result.error);
}),
),
});
const service = wasmArtifactModule.create(environment);
cli.command(wasmArtifactModule.cliCommand, {
description: "Inspect an explicit local WASM artifact with WABT",
+2
View File
@@ -4,6 +4,7 @@ export const CLI_COMMANDS = Object.freeze({
inspectPacketCapture: "inspect-packet-capture",
inspectSignalDecoders: "inspect-signal-decoders",
decodeSignalRecording: "decode-signal-recording",
compareWasmInterfaces: "compare-wasm-interfaces",
inspectWasmArtifact: "inspect-wasm-artifact",
inspectSqliteDatabase: "inspect-sqlite-database",
inspectEvmInterface: "inspect-evm-interface",
@@ -39,6 +40,7 @@ export const CLI_COMMANDS = Object.freeze({
inspectNativeDataType: "inspect-native-data-type",
inspectNativeLoadImage: "inspect-native-load-image",
readBytes: "read-bytes",
searchBytes: "search-bytes",
addressToFileOffset: "address-to-file-offset",
traceNativeValues: "trace-native-values",
inspectNativeInstruction: "inspect-native-instruction",
+19
View File
@@ -1,8 +1,27 @@
import { z } from "zod";
import { address, document } from "./toolContractHelpers.js";
import {
bytePatternFields,
validateBytePattern,
} from "../domain/native/bytePattern.js";
/** Hopper memory and file-mapping contracts. */
export const HOPPER_MEMORY_TOOL_DEFINITIONS = [
{
name: "search_bytes",
description:
"Find masked byte signatures in initialized analyzed memory. Hex byte pairs and ?? wildcards are supported; an optional equal-length hex mask selects bits. Bounds are inclusive. Matches are ordered by provider address and never span blocks. Coverage describes this page; reuse the same query with next_cursor to continue. Uninitialized blocks are listed separately. Ghidra only; Hopper is unavailable.",
inputSchema: z
.strictObject({
...bytePatternFields,
document,
start: address.optional(),
end: address.optional(),
limit: z.number().int().min(1).max(1000).default(100),
cursor: z.string().min(1).optional(),
})
.superRefine(validateBytePattern),
},
{
name: "read_bytes",
description:
+74
View File
@@ -30,6 +30,7 @@ const resolveReference = (
root: Readonly<Record<string, unknown>>,
reference: string,
): unknown => {
if (reference === "#") return root;
if (!reference.startsWith("#/")) return undefined;
let value: unknown = root;
for (const token of reference.slice(2).split("/")) {
@@ -229,3 +230,76 @@ export const presentInputJsonSchema = (
const described = describeSchema(flattened, flattened, describeProperty);
return isObject(described) ? described : flattened;
};
/**
* Clients that render advertised inputs into SDK declarations expand
* schema-local references with a shared per-input budget: Pi 1.1.0 code-mode
* allows 32 expansions and degrades every later reference to `unknown`
* (morluto/rea#1632), hiding the fields those references describe. The budget
* counts conservatively — every resolvable, non-cyclic reference occurrence
* in every schema position — so any reference-resolving client stays within
* its measured limit.
*/
export const advertisedReferenceExpansionBudget = 32;
const definitionKeys = new Set(["$defs", "definitions"]);
const countReferenceExpansions = (
node: unknown,
root: Readonly<Record<string, unknown>>,
active: ReadonlySet<string>,
count: { value: number },
): void => {
if (Array.isArray(node)) {
node.forEach((child) =>
countReferenceExpansions(child, root, active, count),
);
return;
}
if (!isObject(node)) return;
if (typeof node.$ref === "string" && !active.has(node.$ref)) {
const target = resolveReference(root, node.$ref);
if (target !== undefined) {
count.value += 1;
countReferenceExpansions(
target,
root,
new Set([...active, node.$ref]),
count,
);
return;
}
}
for (const [key, value] of Object.entries(node)) {
if (definitionKeys.has(key)) continue;
if (schemaMaps.has(key) && isObject(value)) {
for (const child of Object.values(value))
countReferenceExpansions(child, root, active, count);
} else if (schemaArrays.has(key) || schemaChildren.has(key)) {
countReferenceExpansions(value, root, active, count);
}
}
};
/** Conservative client expansion count over every schema position. */
export const countLocalReferenceExpansions = (
schema: Record<string, unknown>,
): number => {
const count = { value: 0 };
countReferenceExpansions(schema, schema, new Set(), count);
return count.value;
};
/**
* Keep the shared-definition form of an advertised input while clients can
* still resolve it. Once rendering would exhaust the reference budget, fall
* back to the inline projection, which carries no shared definitions for the
* nonrecursive schemas this repository advertises, so every field renders
* with complete structure in every reference-resolving client.
*/
export const inputSchemaWithinReferenceExpansionBudget = (
shared: Record<string, unknown>,
inline: () => Record<string, unknown>,
budget: number,
): Record<string, unknown> =>
countLocalReferenceExpansions(shared) <= budget ? shared : inline();
@@ -67,7 +67,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [
...toolContractMetadata("inspect_recorded_crash"),
kind: "native-provider",
description:
"Inspect a supplied Linux ELF64 amd64 little-endian core without launching its target or attaching to any live PID. Returns all recorded segments, raw note owners/descriptors and source ranges, every Linux CORE PRSTATUS thread/register and SIGINFO fields inline with SHA-256 Evidence. Historical PID is recorded metadata; current process/file identity, note coverage and signal-thread associations stay unknown. Optionally add derived core-only GDB/pwndbg mapping candidates through explicit BYO configuration; zero map flags mean unknown permissions. Uses the same stable snapshot for both stages, bounded complete output and owned cleanup. Initial Linux x64 profile: unchanged pwntools 4.15.0/pyelftools 0.33/Unicorn 2.1.2; optional unchanged pwndbg 2026.09.15. No implicit executable/library pairing, GDB command language, host configuration changes or dependency installation.",
"Inspect a supplied Linux ELF64 amd64 or AArch64 little-endian core without launching its target or attaching to any live PID. Returns all recorded segments, raw note owners/descriptors and source ranges, every Linux CORE PRSTATUS thread/register and SIGINFO fields inline with SHA-256 Evidence. Historical PID is recorded metadata; current process/file identity, note coverage and signal-thread associations stay unknown. Optionally add derived core-only GDB/pwndbg mapping candidates through explicit BYO configuration; zero map flags mean unknown permissions. Uses the same stable snapshot for both stages, bounded complete output and owned cleanup. Linux x64 host profile: unchanged pwntools 4.15.0/pyelftools 0.33/Unicorn 2.1.2; optional unchanged pwndbg 2026.09.15. No implicit executable/library pairing, GDB command language, host configuration changes or dependency installation.",
inputSchema: inspectRecordedCrashInputSchema,
outputSchema: evidenceResultOf(recordedCrashSchema),
examples: [
+1
View File
@@ -26,6 +26,7 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
resolve_native_call_targets: { address: "0x1000" },
read_function_instructions: { procedure: "main" },
read_bytes: { address: "0x1000", length: 16 },
search_bytes: { pattern: "48 8B ?? ?? 89" },
address_to_file_offset: { address: "0x1000" },
procedure_references: { procedure: "main" },
procedure_pseudo_code: { procedure: "main" },
+2
View File
@@ -28,6 +28,8 @@ const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
inspect_macho: "runs host Mach-O inspection tools, not the target",
inspect_evm_interface:
"decodes bytecode in REA's bundled worker without executing it",
compare_wasm_interfaces:
"compares retained inspection Evidence without executing modules",
inspect_wasm_artifact:
"WABT validates and decompiles the module without executing it",
identify_flutter_build:
+2
View File
@@ -438,6 +438,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
inspect_native_data_type: evidence,
resolve_native_call_targets: evidence,
read_bytes: evidence,
search_bytes: evidence,
address_to_file_offset: evidence,
procedure_references: evidence,
procedure_pseudo_code: evidence,
@@ -622,6 +623,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
}),
compare_process_captures: sessionEvidence,
compare_artifacts: sessionEvidence,
compare_wasm_interfaces: sessionEvidence,
compare_functions: sessionEvidence,
compare_bundles: effects({ mutatesSession: true }),
find_changed_behavior: sessionEvidence,
+105 -1
View File
@@ -3,7 +3,12 @@ import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { presentInputJsonSchema } from "./inputSchemaPresentation.js";
import {
advertisedReferenceExpansionBudget,
countLocalReferenceExpansions,
inputSchemaWithinReferenceExpansionBudget,
presentInputJsonSchema,
} from "./inputSchemaPresentation.js";
import { toolContract } from "./toolContracts.js";
import { toolInputSchemaWithMetadata } from "./toolSchemaMetadata.js";
import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "./javascript/javascriptRuntimeReconciliationExample.js";
@@ -166,6 +171,105 @@ describe("advertised input references", () => {
);
});
describe("advertised reference expansion budget", () => {
it("counts references in keyword-named fields, excluding literals", () => {
const fields = ["default", "enum", "examples", "const", "$defs"];
const schema = {
type: "object",
properties: Object.fromEntries(
fields.map((name) => [name, { $ref: "#/$defs/value" }]),
),
$defs: { value: { type: "string" } },
default: { $ref: "#/$defs/value" },
examples: [{ $ref: "#/$defs/value" }],
};
expect(countLocalReferenceExpansions(schema)).toBe(fields.length);
});
const reusedComponent = z
.object({ kind: z.literal("rec"), value: z.string() })
.strict();
const inputWithReusedFields = (count: number) =>
z.strictObject(
Object.fromEntries(
Array.from({ length: count }, (_, index) => [
`field_${String(index).padStart(2, "0")}`,
reusedComponent,
]),
),
);
const advertisedInput = (
canonical: z.ZodType<Readonly<Record<string, unknown>>>,
) =>
toolInputSchemaWithMetadata({
...toolContract("open_binary"),
inputSchema: canonical,
})["~standard"].jsonSchema.input({ target: "draft-2020-12" });
it("keeps shared definitions while every client can resolve them", () => {
const advertised = advertisedInput(inputWithReusedFields(8));
expect(advertised.$defs).toBeDefined();
expect(countLocalReferenceExpansions(advertised)).toBe(8);
});
it("keeps shared definitions exactly at the budget", () => {
const advertised = advertisedInput(
inputWithReusedFields(advertisedReferenceExpansionBudget),
);
expect(advertised.$defs).toBeDefined();
expect(countLocalReferenceExpansions(advertised)).toBe(
advertisedReferenceExpansionBudget,
);
});
it("re-projects without shared definitions once the budget is exceeded", () => {
const advertised = advertisedInput(
inputWithReusedFields(advertisedReferenceExpansionBudget + 1),
);
expect(advertised.$defs).toBeUndefined();
expect(countLocalReferenceExpansions(advertised)).toBe(0);
const properties = advertised.properties as Record<string, unknown>;
expect(properties.field_00).toMatchObject({
type: "object",
properties: { kind: { const: "rec" }, value: { type: "string" } },
required: ["kind", "value"],
});
});
it("keeps the shared form untouched when it fits and swaps it when not", () => {
const shared = {
type: "object",
properties: { value: { $ref: "#/$defs/shared" } },
$defs: { shared: { type: "string" } },
};
const inlined = {
type: "object",
properties: { value: { type: "string" } },
};
expect(
inputSchemaWithinReferenceExpansionBudget(
shared,
() => inlined,
advertisedReferenceExpansionBudget,
),
).toBe(shared);
expect(
inputSchemaWithinReferenceExpansionBudget(
{
...shared,
properties: Object.fromEntries(
Array.from({ length: 33 }, (_, index) => [
`field_${index}`,
{ $ref: "#/$defs/shared" },
]),
),
},
() => inlined,
advertisedReferenceExpansionBudget,
),
).toBe(inlined);
});
});
describe("root input presentation", () => {
it("preserves prototype-named properties in object-root presentation", () => {
const fields = Object.fromEntries([
+2
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { byteSearchResultSchema } from "../domain/native/bytePattern.js";
import {
artifactInventorySummaryViewResultSchema,
machoSummaryViewResultSchema,
@@ -108,6 +109,7 @@ const bookmarkFacetSchema = z.discriminatedUnion("state", [
/** Exact structured-content schemas shared by direct analysis providers. */
export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
search_bytes: evidenceResultOf(byteSearchResultSchema),
annotate_native_function: evidenceResultOf(nativeFunctionAnnotationsSchema),
inspect_native_load_image: evidenceResultOf(nativeLoadImageSchema),
inspect_native_data_type: evidenceResultOf(nativeDataTypeSchema),
+24 -2
View File
@@ -2,7 +2,11 @@ import { z } from "zod";
import type { ToolContract } from "./toolContractTypes.js";
import { advertisedInputExamples } from "./advertisedInputExamples.js";
import { presentInputJsonSchema } from "./inputSchemaPresentation.js";
import {
advertisedReferenceExpansionBudget,
inputSchemaWithinReferenceExpansionBudget,
presentInputJsonSchema,
} from "./inputSchemaPresentation.js";
import { digestCanonicalValue } from "../domain/canonicalDigest.js";
const PROPERTY_DESCRIPTIONS: Readonly<Record<string, string>> = {
@@ -66,7 +70,25 @@ export const toolInputSchemaWithMetadata = <Contract extends ToolContract>(
});
const examples = advertisedInputExamples(contract);
return {
...presentInputJsonSchema(shared, fallbackPropertyDescription),
// Sharing definitions only helps clients that resolve them. A client
// rendering declarations from a shared expansion budget degrades
// every reference past it to `unknown`, so an input whose shared form
// exceeds the budget is re-projected without shared definitions.
...inputSchemaWithinReferenceExpansionBudget(
presentInputJsonSchema(shared, fallbackPropertyDescription),
() =>
presentInputJsonSchema(
project({
...options,
libraryOptions: {
...options.libraryOptions,
reused: "inline",
},
}),
fallbackPropertyDescription,
),
advertisedReferenceExpansionBudget,
),
...(examples.length === 0 ? {} : { examples }),
};
},
@@ -0,0 +1,63 @@
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
import { z } from "zod";
import { evidenceInputSchema } from "../evidenceInputContracts.js";
import { wasmInterfaceSchema } from "../../domain/wasm/wasmInterface.js";
import { toolContractMetadata } from "../toolEffects.js";
import type { ToolContract } from "../toolContractTypes.js";
export const compareWasmInterfacesInputSchema = z.strictObject({
left: evidenceInputSchema.describe(
"Exact complete inspect_wasm_artifact Evidence or retained session reference",
),
right: evidenceInputSchema.describe(
"Exact complete inspect_wasm_artifact Evidence or retained session reference",
),
scope: z
.enum(["imports", "exports", "both"])
.describe(
"Explicit interface selection; static equality does not establish runtime compatibility",
),
});
const identity = z.object({
evidence_id: z.string(),
artifact: z.object({
path: z.string(),
sha256: z.string(),
bytes: z.number().int().nonnegative(),
}),
});
export const wasmInterfaceComparisonSchema = z.object({
left: identity,
right: identity,
scope: z.enum(["imports", "exports", "both"]),
coverage: z.enum(["complete-within-inputs", "partial", "unknown"]),
changes: z.array(
z.object({
direction: z.enum(["import", "export"]),
module: z.string().nullable(),
name: z.string(),
state: z.enum(["added", "removed", "changed", "unchanged", "unknown"]),
left: wasmInterfaceSchema.shape.entries,
right: wasmInterfaceSchema.shape.entries,
reason: z.string().nullable(),
}),
),
summary: z.object({
added: z.number(),
removed: z.number(),
changed: z.number(),
unchanged: z.number(),
unknown: z.number(),
}),
limitations: z.array(z.string()),
});
export const COMPARE_WASM_INTERFACES_CONTRACT = {
name: "compare_wasm_interfaces",
...toolContractMetadata("compare_wasm_interfaces"),
kind: "application",
description:
"Compare typed core WASM import/export names, kinds and exact signatures from two authenticated inspect_wasm_artifact Evidence records. Select imports, exports or both explicitly. Retained references resolve only in the current session; CLI accepts portable inline Evidence. Duplicate names, unsupported types and missing historical interface facets remain unknown. Preserve original module digests and every occurrence; no source acquisition, module execution or runtime-compatibility inference.",
inputSchema: compareWasmInterfacesInputSchema,
outputSchema: evidenceResultOf(wasmInterfaceComparisonSchema),
examples: [],
} as const satisfies ToolContract;
+5 -1
View File
@@ -1,3 +1,4 @@
import { COMPARE_WASM_INTERFACES_CONTRACT } from "./wasmComparisonContracts.js";
import {
inspectWasmArtifactInputSchema,
wasmArtifactSchema,
@@ -40,4 +41,7 @@ export const INSPECT_WASM_ARTIFACT_CONTRACT = {
} as const satisfies ToolContract;
/** Keep the public catalog in its existing order, using its named contract. */
export const WASM_TOOL_CONTRACTS = [INSPECT_WASM_ARTIFACT_CONTRACT] as const;
export const WASM_TOOL_CONTRACTS = [
INSPECT_WASM_ARTIFACT_CONTRACT,
COMPARE_WASM_INTERFACES_CONTRACT,
] as const;
+28
View File
@@ -417,6 +417,34 @@ describe("Apple bundle layouts and containers", () => {
});
});
describe("Apple IPA components", () => {
it("excludes AppleDouble sidecars from IPA components", () => {
const result = project(
inventoryEvidence("ipa", "Fixture.ipa", [
{ path: "Payload/Fixture.app/Info.plist" },
macho("Payload/Fixture.app/Fixture"),
{ path: "Payload/Fixture.app/Contents/Resources/._libfoo.dylib" },
{ path: "Payload/Fixture.app/Frameworks/Foo.framework/._Foo" },
{ path: "__MACOSX/Payload/Fixture.app/libghost.dylib" },
macho("Payload/Fixture.app/Contents/Resources/libreal.dylib"),
macho("SwiftSupport/iphoneos/libswiftCore.dylib"),
]),
);
expect(result.components.native_libraries.map(({ path }) => path)).toEqual([
"Payload/Fixture.app/Contents/Resources/libreal.dylib",
"SwiftSupport/iphoneos/libswiftCore.dylib",
]);
expect(result.components.frameworks).toEqual([]);
expect(result.components.executables.map(({ path }) => path)).toEqual([
"Payload/Fixture.app/Contents/Resources/libreal.dylib",
"Payload/Fixture.app/Fixture",
]);
expect(result.limitations).toContainEqual(
expect.stringContaining("AppleDouble sidecar entries"),
);
});
});
describe("macOS application scope", () => {
it("attributes only components inside the application roots", () => {
const result = project(
+4 -3
View File
@@ -218,8 +218,9 @@ export const appleProjectionId = (projection: unknown): string =>
`aap_${digest(projection)}`;
/**
* IPA projection keeps every archive component, as before. Directory, ZIP,
* and DMG inventories can hold installers and other siblings, so only
* AppleDouble sidecars describe neighbouring files and are never components.
* IPA projection keeps every other archive component, as before. Directory,
* ZIP, and DMG inventories can hold installers and other siblings, so only
* components inside an application root are attributed to it.
*/
const attributeComponents = (
@@ -227,8 +228,8 @@ const attributeComponents = (
roots: readonly string[],
rootFormat: RootFormat,
): { readonly all: Component[]; readonly unattributed: number } => {
if (rootFormat === "ipa") return { all: [...inventoried], unattributed: 0 };
const visible = inventoried.filter(({ path }) => !isSidecar(path));
if (rootFormat === "ipa") return { all: visible, unattributed: 0 };
const all = visible.filter(({ path }) =>
roots.some((root) => isWithin(path, root)),
);
+5 -14
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { addressCoordinate } from "./native/addressCoordinate.js";
import type { JsonValue } from "./jsonValue.js";
@@ -38,16 +39,6 @@ export const addressDistance = (start: string, end: string): number => {
);
};
const addressCoordinate = (
value: string,
): { readonly space: string; readonly offset: bigint } | null => {
const separator = value.lastIndexOf(":0x");
const space = separator < 0 ? "default" : value.slice(0, separator);
const offset = separator < 0 ? value : value.slice(separator + 1);
if (!/^0x[0-9a-f]+$/u.test(offset)) return null;
return { space, offset: BigInt(offset) };
};
const procedureMapSchema = z.record(z.string(), z.string());
const addressedNamesSchema = z.array(
z.object({ address: z.string(), name: z.string() }),
@@ -128,9 +119,9 @@ export const functionBodySchema = z.discriminatedUnion("available", [
})
.superRefine((body, context) => {
let total = 0n;
const bounds = new Map<string, { start: bigint; end: bigint }>();
const closedSpaces = new Set<string>();
let previousSpace: string | null = null;
const bounds = new Map<string | null, { start: bigint; end: bigint }>();
const closedSpaces = new Set<string | null>();
let previousSpace: string | null | undefined;
for (const range of body.ranges) {
const start = addressCoordinate(range.start);
const end = addressCoordinate(range.end);
@@ -146,7 +137,7 @@ export const functionBodySchema = z.discriminatedUnion("available", [
});
return;
}
if (previousSpace !== null && previousSpace !== start.space)
if (previousSpace !== undefined && previousSpace !== start.space)
closedSpaces.add(previousSpace);
const previous = bounds.get(start.space);
if (
@@ -339,7 +339,10 @@ const spawnOptions = (candidate: SpawnCandidate): t.ObjectExpression | null => {
const spawnArgvCount = (candidate: SpawnCandidate): number | null => {
if (candidate.method === "exec") return null;
const args = candidate.node.arguments[1];
return t.isArrayExpression(args) ? args.elements.length : null;
return t.isArrayExpression(args) &&
!args.elements.some((element) => t.isSpreadElement(element))
? args.elements.length
: null;
};
const objectHasProperty = (
@@ -275,12 +275,3 @@ export const dataEffectMemberCallee = (
t.isMemberExpression(node.callee) || t.isOptionalMemberExpression(node.callee)
? node.callee
: null;
/** Read a parent member's object when present. */
export const dataEffectMemberObject = (
node: t.Node | null,
): t.Expression | t.Super | null =>
node !== null &&
(t.isMemberExpression(node) || t.isOptionalMemberExpression(node))
? node.object
: null;
@@ -24,7 +24,6 @@ import {
dataEffectArgumentBindingId as argumentBindingId,
dataEffectLiteralString as literalString,
dataEffectMemberCallee as memberCallee,
dataEffectMemberObject as memberObject,
dataEffectPrimitive as primitiveValue,
isSemanticProcessObject as isProcessObject,
outerDataEffectBinding as outerAssignedBinding,
@@ -83,8 +82,8 @@ const collectConfigurations = (
context: TraversalContext,
): ConfigurationCandidate[] => {
const output: ConfigurationCandidate[] = [];
traverseWithContext(program, context, (node, parent) => {
const details = configurationDetails(node, parent, context);
traverseWithContext(program, context, (node) => {
const details = configurationDetails(node, context);
if (details === null) return;
const operation: JavaScriptSemanticConfigurationOperation = {
configId: `config:${details.kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`,
@@ -104,17 +103,13 @@ const collectConfigurations = (
const configurationDetails = (
node: t.Node,
parent: t.Node | null,
context: TraversalContext,
): {
readonly kind: "environment" | "argv" | "file";
readonly key: string | null;
readonly resolution: "complete" | "partial";
} | null => {
if (
(t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) &&
!(memberObject(parent) === node)
) {
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
const processMember = processConfigurationMember(node, context.state);
if (processMember !== null) return processMember;
}
@@ -429,7 +429,12 @@ export const addSourceMapDirectives = (
end === null
)
continue;
const commentSource = source.slice(start, end);
// The parser owns comment boundaries. Exclude only the closing block
// delimiter; an asterisk elsewhere remains part of the declared URL.
const commentSource = source.slice(
start,
comment.type === "CommentBlock" ? end - 2 : end,
);
if (
!(commentSource.startsWith("//") || commentSource.startsWith("/*")) ||
!(commentSource[2] === "#" || commentSource[2] === "@")
@@ -449,9 +454,7 @@ export const addSourceMapDirectives = (
const urlOffset = commentSource.slice(equalsStart + 1).search(/\S/u);
if (urlOffset === -1) continue;
const declaredStart = equalsStart + 1 + urlOffset;
const terminator = commentSource
.slice(declaredStart)
.search(commentSource.startsWith("//") ? /\s/u : /[\s*]/u);
const terminator = commentSource.slice(declaredStart).search(/\s/u);
const declaredEnd =
terminator === -1 ? commentSource.length : declaredStart + terminator;
if (declaredEnd === declaredStart) continue;
@@ -72,10 +72,10 @@ describe("source map directives", () => {
it("preserves Unicode whitespace and URL terminator boundaries", () => {
const source =
"ğ/*@\u00a0sourceMappingURL\u2003=\ufeffapp.js.map* ignored */";
const declaredEnd = source.indexOf("* ignored");
const declaredEnd = source.indexOf(" ignored");
expect(analyzeJavaScriptStaticSource(source).source_map_urls).toEqual([
{
declared_url: "app.js.map",
declared_url: "app.js.map*",
location: {
start: { line: 1, column: 1 },
end: { line: 1, column: declaredEnd },
@@ -84,6 +84,29 @@ describe("source map directives", () => {
]);
});
it.each([
["/*#", "app*part.js.map", " */"],
["/*@", "*part.js.map", "*/"],
["/*#", "app.js.map*", "*/"],
["/*#", "**part.js.map", " */"],
["/*#", "app.js.map", "*/"],
["//#", "app*part.js.map", ""],
])("preserves the URL and range in %s %s%s", (marker, url, suffix) => {
const directive = marker + " sourceMappingURL=" + url;
const result = analyzeJavaScriptStaticSource(
"export const value = 1;\n" + directive + suffix,
);
expect(result.source_map_urls).toEqual([
{
declared_url: url,
location: {
start: { line: 2, column: 0 },
end: { line: 2, column: directive.length },
},
},
]);
});
it("reports nothing when no directive is present", () => {
expect(sourceMapUrls("const value = 1;")).toEqual([]);
});
+11
View File
@@ -0,0 +1,11 @@
/** Parse canonical native offsets without discarding their address space. */
export const addressCoordinate = (
value: string,
): { readonly space: string | null; readonly offset: bigint } | null => {
const separator = value.lastIndexOf(":0x");
if (separator === 0) return null;
const space = separator < 0 ? null : value.slice(0, separator);
const offset = separator < 0 ? value : value.slice(separator + 1);
if (!/^0x[0-9a-f]+$/u.test(offset)) return null;
return { space, offset: BigInt(offset) };
};
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { parseBytePattern } from "./bytePattern.js";
describe("masked byte patterns", () => {
it("preserves whole-byte wildcards and combines explicit bit masks", () => {
const parsed = parseBytePattern("48 8b\t??89", "ff f0 ff 0f");
if (!parsed.ok) throw parsed.error;
expect(parsed.value).toEqual({
bytes: [0x48, 0x8b, 0, 0x89],
masks: [255, 240, 0, 15],
});
const exact = parseBytePattern("Aa\u00a000");
if (!exact.ok) throw exact.error;
expect(exact.value).toEqual({ bytes: [170, 0], masks: [255, 255] });
});
it.each([
["", undefined, "pattern"],
["4", undefined, "pattern"],
["4?", undefined, "pattern"],
["gg", undefined, "pattern"],
["?? ??", undefined, "pattern"],
["ff", "00", "pattern"],
["ffff", "ff", "mask"],
["ff", "??", "mask"],
])("rejects invalid pattern %s with typed issues", (pattern, mask, field) => {
const parsed = parseBytePattern(pattern, mask);
if (parsed.ok) throw new Error("Expected a rejected pattern");
expect(parsed.error.issues).toMatchObject([
{ path: [field], reason: "invalid_value" },
]);
});
});
+125
View File
@@ -0,0 +1,125 @@
import { z } from "zod";
import { addressCoordinate } from "./addressCoordinate.js";
import { AnalysisInputError } from "../analysisErrorCore.js";
import { err, ok, type Result } from "../result.js";
/** Byte pairs, with whole-byte wildcards; explicit masks can select individual bits. */
export const bytePatternFields = {
pattern: z
.string()
.regex(/^([0-9a-fA-F]{2}|\?\?)(\s*([0-9a-fA-F]{2}|\?\?))*$/u),
mask: z
.string()
.regex(/^[0-9a-fA-F]{2}(\s*[0-9a-fA-F]{2})*$/u)
.optional(),
};
/** Parse once at the input boundary, retaining typed correction issues. */
export const parseBytePattern = (
pattern: string,
mask?: string,
): Result<{ bytes: number[]; masks: number[] }, AnalysisInputError> => {
const invalid = (field: string, message: string) =>
err(
new AnalysisInputError("search_bytes", undefined, [
{ path: [field], reason: "invalid_value", message },
]),
);
if (!bytePatternFields.pattern.safeParse(pattern).success)
return invalid("pattern", "Use hexadecimal byte pairs or ?? wildcards");
if (mask !== undefined && !bytePatternFields.mask.safeParse(mask).success)
return invalid("mask", "Use hexadecimal mask byte pairs");
const pairs = pattern.replace(/\s/gu, "").match(/../gu) ?? [];
const maskPairs = mask?.replace(/\s/gu, "").match(/../gu);
if (maskPairs && maskPairs.length !== pairs.length)
return invalid("mask", "Mask length must equal pattern length");
const bytes = pairs.map((pair) =>
pair === "??" ? 0 : Number.parseInt(pair, 16),
);
const masks = pairs.map((pair, index) =>
pair === "??" ? 0 : Number.parseInt(maskPairs?.[index] ?? "ff", 16),
);
if (!masks.some((value) => value !== 0))
return invalid("pattern", "Pattern must constrain at least one bit");
return ok({ bytes, masks });
};
/** Shared semantic validation for public and provider inputs. */
export const validateBytePattern = (
value: { pattern: string; mask?: string | undefined },
context: z.RefinementCtx,
): void => {
const parsed = parseBytePattern(value.pattern, value.mask);
if (!parsed.ok)
for (const issue of parsed.error.issues)
context.addIssue({
code: "custom",
path: [...issue.path],
message: issue.message ?? "Invalid byte pattern",
});
};
const coverageBlock = z
.strictObject({
segment: z.string(),
start: z.string(),
end: z.string(),
bytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
})
.superRefine((value, context) => {
const start = addressCoordinate(value.start);
const end = addressCoordinate(value.end);
if (
start === null ||
end === null ||
start.space !== end.space ||
start.offset > end.offset ||
end.offset - start.offset + 1n !== BigInt(value.bytes)
)
context.addIssue({
code: "custom",
message:
"Byte coverage must equal its inclusive address range in one space",
});
});
/** Inclusive page coverage; matches never span memory blocks. */
export const byteSearchResultSchema = z
.strictObject({
matches: z
.array(
z.strictObject({
address: z.string(),
segment: z.string(),
file_offset: z
.number()
.int()
.nonnegative()
.max(Number.MAX_SAFE_INTEGER)
.nullable(),
procedure: z
.strictObject({ address: z.string(), name: z.string() })
.nullable(),
}),
)
.max(1000),
searched: z.strictObject({
blocks: z.array(coverageBlock),
bytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
skipped_uninitialized: z.array(coverageBlock),
skipped_not_loaded: z.array(coverageBlock),
}),
complete: z.boolean(),
next_cursor: z.string().min(1).nullable(),
})
.superRefine((value, context) => {
if (
value.complete !== (value.next_cursor === null) ||
value.searched.bytes !==
value.searched.blocks.reduce((sum, block) => sum + block.bytes, 0)
)
context.addIssue({
code: "custom",
message: "Byte search coverage and continuation disagree",
});
});
+2
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { providerSchema } from "../evidence.js";
import {
compareUnicodeCodePoints,
@@ -115,6 +116,7 @@ export const nativeMetadataEvidenceSchema = z.strictObject({
"decompiler",
]),
description: z.string().min(1),
provider: providerSchema.optional(),
location: nativeMetadataLocationSchema,
artifact_path: z.string().min(1).nullable().default(null),
artifact_sha256: z
+94 -1
View File
@@ -1,7 +1,8 @@
import { expect, it } from "vitest";
import { describe, expect, it } from "vitest";
import {
inspectRecordedCrashInputSchema,
recordedCrashSchema,
type RecordedCrash,
} from "./recordedCrash.js";
import {
recordedCrashFixture,
@@ -282,3 +283,95 @@ it("keeps absent map flags unknown and validates reported permission bits", () =
}).success,
).toBe(false);
});
describe("recorded AArch64 core profile", () => {
it("accepts the complete AArch64 register window in ABI order", () => {
const value = recordedCrashSchema.parse(
recordedCrashFixture("/selected/aarch64.core", "aarch64-little-endian"),
);
expect(value.architecture).toBe("aarch64-little-endian");
const registers = value.threads[0]?.registers ?? [];
expect(registers.map(({ name }) => name)).toEqual([
...Array.from({ length: 31 }, (_, index) => `x${String(index)}`),
"sp",
"pc",
"pstate",
]);
expect(registers[14]?.value).toBe("0x1122334455667788");
expect(registers.every(({ location }) => location.bytes === "0x8")).toBe(
true,
);
});
it("keeps the AArch64 note ranges inside their recorded segment", () => {
const value = recordedCrashSchema.parse(
recordedCrashSignalFixture(undefined, "aarch64-little-endian"),
);
const note = value.notes[0];
const segment = value.segments[0];
if (note === undefined || segment === undefined)
throw new Error("Expected recorded notes");
expect(
BigInt(note.location.offset) + BigInt(note.location.bytes),
).toBeLessThanOrEqual(BigInt(segment.offset) + BigInt(segment.file_size));
expect(value.signals[0]?.fault_address).toBe("0x1122334455667788");
});
it.each([
[
"an amd64 register name inside an AArch64 window",
(v: RecordedCrash) => ({
...v,
threads: v.threads.map((thread) => ({
...thread,
registers: thread.registers.map((register, index) =>
index === 0 ? { ...register, name: "rax" } : register,
),
})),
}),
],
[
"the amd64 register count",
(v: RecordedCrash) => ({
...v,
threads: v.threads.map((thread) => ({
...thread,
registers: thread.registers.slice(0, 27),
})),
}),
],
[
"a 4-byte AArch64 register source",
(v: RecordedCrash) => ({
...v,
threads: v.threads.map((thread) => ({
...thread,
registers: thread.registers.map((register, index) =>
index === 0
? {
...register,
location: { ...register.location, bytes: "0x4" },
}
: register,
),
})),
}),
],
] as const)("rejects %s", (_name, change) => {
const value = recordedCrashFixture(
"/selected/aarch64.core",
"aarch64-little-endian",
);
expect(recordedCrashSchema.safeParse(change(value)).success).toBe(false);
});
it("rejects an architecture outside the interpreted profiles", () => {
const value = recordedCrashFixture();
expect(
recordedCrashSchema.safeParse({
...value,
architecture: "arm-little-endian",
}).success,
).toBe(false);
});
});
+97 -6
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import type { BinaryArchitecture } from "../binaryTargetTypes.js";
import { localPathStringSchema } from "../localPath.js";
import { CANONICAL_BASE64_PATTERN } from "../stringPatterns.js";
import { recordedNoteCoverageIssues } from "./recordedCrashNoteCoverage.js";
@@ -18,7 +19,7 @@ const diagnostics = z.strictObject({
const LINUX_CORE_OWNER_BASE64 = "Q09SRQA=";
/** Complete register identities in the supported Linux amd64 PRSTATUS ABI order. */
export const RECORDED_LINUX_AMD64_REGISTERS: readonly string[] = [
const RECORDED_LINUX_AMD64_REGISTERS: readonly string[] = [
"r15",
"r14",
"r13",
@@ -47,7 +48,95 @@ export const RECORDED_LINUX_AMD64_REGISTERS: readonly string[] = [
"fs",
"gs",
];
const supportedRegisters = new Set(RECORDED_LINUX_AMD64_REGISTERS);
const RECORDED_LINUX_AARCH64_REGISTERS: readonly string[] = [
"x0",
"x1",
"x2",
"x3",
"x4",
"x5",
"x6",
"x7",
"x8",
"x9",
"x10",
"x11",
"x12",
"x13",
"x14",
"x15",
"x16",
"x17",
"x18",
"x19",
"x20",
"x21",
"x22",
"x23",
"x24",
"x25",
"x26",
"x27",
"x28",
"x29",
"x30",
"sp",
"pc",
"pstate",
];
/** Recorded-core architectures whose Linux note ABI is interpreted. */
export const RECORDED_LINUX_CORE_ARCHITECTURES = [
"x86_64-little-endian",
"aarch64-little-endian",
] as const;
export type RecordedCrashArchitecture =
(typeof RECORDED_LINUX_CORE_ARCHITECTURES)[number];
/**
* ABI facts for one recorded-core architecture, measured from unchanged pwntools
* 4.15.0 `elf_prstatus_*` and `user_regs_struct_*` structures and mirrored by
* `bridge/pwntools/recorded_crash_impl.py`. Both profiles place `pr_cursig` at
* 12, `pr_pid` at 32 and the register window at 112; the ELF machine, the window
* contents and the Evidence CPU family differ per profile.
*/
export const RECORDED_LINUX_CORE_PROFILES: Record<
RecordedCrashArchitecture,
{
readonly machine: number;
readonly evidenceArchitecture: BinaryArchitecture;
readonly registers: readonly string[];
readonly registerBytes: number;
readonly registerOffset: number;
readonly prstatusBytes: number;
}
> = {
"x86_64-little-endian": {
machine: 62,
evidenceArchitecture: "x86_64",
registers: RECORDED_LINUX_AMD64_REGISTERS,
registerBytes: 8,
registerOffset: 112,
prstatusBytes: 336,
},
"aarch64-little-endian": {
machine: 183,
evidenceArchitecture: "arm64",
registers: RECORDED_LINUX_AARCH64_REGISTERS,
registerBytes: 8,
registerOffset: 112,
prstatusBytes: 392,
},
};
const recordedCoreRegisterSets: Record<
RecordedCrashArchitecture,
ReadonlySet<string>
> = {
"x86_64-little-endian": new Set(RECORDED_LINUX_AMD64_REGISTERS),
"aarch64-little-endian": new Set(RECORDED_LINUX_AARCH64_REGISTERS),
};
/** Select an explicit recording and optionally request debugger-derived mapping context. */
export const inspectRecordedCrashInputSchema = z.strictObject({
@@ -108,7 +197,7 @@ const recordedCrashObjectSchema = z.strictObject({
bytes: index,
}),
format: z.literal("elf-core"),
architecture: z.literal("x86_64-little-endian"),
architecture: z.enum(RECORDED_LINUX_CORE_ARCHITECTURES),
target_execution: z.literal("not-performed"),
live_process_identity: z.literal("unknown"),
segments: z.array(
@@ -284,6 +373,8 @@ export const recordedCrashSchema = recordedCrashObjectSchema.superRefine(
"Each supported raw note requires exactly one corresponding interpretation.",
);
}
const profile = RECORDED_LINUX_CORE_PROFILES[value.architecture];
const profileRegisters = recordedCoreRegisterSets[value.architecture];
for (const thread of value.threads) {
const note = value.notes[thread.note_index];
if (
@@ -295,8 +386,8 @@ export const recordedCrashSchema = recordedCrashObjectSchema.superRefine(
continue;
}
if (
thread.registers.length !== RECORDED_LINUX_AMD64_REGISTERS.length ||
!thread.registers.every(({ name }) => supportedRegisters.has(name)) ||
thread.registers.length !== profile.registers.length ||
!thread.registers.every(({ name }) => profileRegisters.has(name)) ||
new Set(thread.registers.map(({ name }) => name)).size !==
thread.registers.length
)
@@ -305,7 +396,7 @@ export const recordedCrashSchema = recordedCrashObjectSchema.superRefine(
);
for (const register of thread.registers)
if (
BigInt(register.location.bytes) !== 8n ||
BigInt(register.location.bytes) !== BigInt(profile.registerBytes) ||
!within(
register.location,
BigInt(note.descriptor_location.offset),
@@ -143,3 +143,13 @@ export const completeReconstructionCoverageData = () => {
],
});
};
/** Complete workspace with its first verifier result and boundary narrowed once. */
export const completeReconstructionCoverageFixture = () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
const boundary = workspace.boundaries[0];
if (result === undefined || boundary === undefined)
throw new Error("Expected complete reconstruction coverage fixture");
return { workspace, result, boundary };
};
+28 -64
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
completeReconstructionCoverageData,
completeReconstructionCoverageFixture,
RECONSTRUCTION_COVERAGE_NOW,
reconstructionCoverageEvidenceId,
} from "./reconstructionCoverage.fixture.js";
@@ -288,11 +289,8 @@ describe("reconstruction coverage verifier selection", () => {
describe("reconstruction coverage conflicting latest verifier observations", () => {
it("keeps conflicting tied assessments unknown regardless of input order", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
const boundary = workspace.boundaries[0];
if (result === undefined || boundary === undefined)
throw new Error("Expected complete reconstruction coverage fixture");
const { workspace, result, boundary } =
completeReconstructionCoverageFixture();
const failed = {
...result,
status: "fail" as const,
@@ -338,11 +336,8 @@ describe("reconstruction coverage conflicting latest verifier observations", ()
describe("reconstruction coverage equivalent latest verifier observations", () => {
it("coalesces equivalent equal-instant observations and retains all evidence", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
const boundary = workspace.boundaries[0];
if (result === undefined || boundary === undefined)
throw new Error("Expected complete reconstruction coverage fixture");
const { workspace, result, boundary } =
completeReconstructionCoverageFixture();
const first = {
...result,
observed_at: "2026-07-16T11:00:00.123456789012345678900Z",
@@ -388,11 +383,8 @@ describe("reconstruction coverage equivalent latest verifier observations", () =
describe("reconstruction coverage verifier timestamp selection", () => {
it("lets a later unambiguous observation supersede an older tie", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
const boundary = workspace.boundaries[0];
if (result === undefined || boundary === undefined)
throw new Error("Expected complete reconstruction coverage fixture");
const { workspace, result, boundary } =
completeReconstructionCoverageFixture();
const failed = { ...result, status: "fail" as const };
const latestPass = {
...result,
@@ -412,50 +404,14 @@ describe("reconstruction coverage verifier timestamp selection", () => {
).toMatchObject({ status: "ready", reasons: [] });
});
it("orders offset-bearing verifier timestamps chronologically", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
if (result === undefined)
throw new Error("Expected fixture verifier result");
const semantic = workspace;
const changed = createReconstructionCoverageData({
...semantic,
verifier_results: [
{ ...result, observed_at: "2026-07-16T08:00:00.000Z" },
{
...result,
observed_at: "2026-07-16T04:00:00.000-05:00",
status: "fail",
},
],
});
expect(
evaluateReconstructionClosure(
changed,
"replacement.cli",
RECONSTRUCTION_COVERAGE_NOW,
),
).toMatchObject({
status: "failed",
reasons: [expect.objectContaining({ code: "verifier-failed" })],
});
});
it("selects the later result when timestamps differ below millisecond precision", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
if (result === undefined)
throw new Error("Expected fixture verifier result");
/** Evaluate a workspace whose newest verifier observation fails the closure. */
const expectNewestObservationFails = (passedAt: string, failedAt: string) => {
const { workspace, result } = completeReconstructionCoverageFixture();
const changed = createReconstructionCoverageData({
...workspace,
verifier_results: [
{ ...result, observed_at: "2026-07-16T11:00:00.1231Z" },
{
...result,
observed_at: "2026-07-16T11:00:00.1239Z",
status: "fail",
},
{ ...result, observed_at: passedAt },
{ ...result, observed_at: failedAt, status: "fail" },
],
});
@@ -469,15 +425,26 @@ describe("reconstruction coverage verifier timestamp selection", () => {
status: "failed",
reasons: [expect.objectContaining({ code: "verifier-failed" })],
});
};
it("orders offset-bearing verifier timestamps chronologically", () => {
expectNewestObservationFails(
"2026-07-16T08:00:00.000Z",
"2026-07-16T04:00:00.000-05:00",
);
});
it("selects the later result when timestamps differ below millisecond precision", () => {
expectNewestObservationFails(
"2026-07-16T11:00:00.1231Z",
"2026-07-16T11:00:00.1239Z",
);
});
});
describe("reconstruction coverage verifier future timestamps", () => {
it("treats an observation beyond millisecond-precision now as future", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
if (result === undefined)
throw new Error("Expected fixture verifier result");
const { workspace, result } = completeReconstructionCoverageFixture();
const changed = createReconstructionCoverageData({
...workspace,
verifier_results: [
@@ -505,10 +472,7 @@ describe("reconstruction coverage verifier future timestamps", () => {
});
it("rejects verifier observations from the future", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
if (result === undefined)
throw new Error("Expected fixture verifier result");
const { workspace, result } = completeReconstructionCoverageFixture();
const semantic = workspace;
const changed = createReconstructionCoverageData({
...semantic,
@@ -53,6 +53,7 @@ const source = (
digit: string,
observation: Partial<EvidenceObservation> = {},
hasSubject = true,
hasCoverage = true,
): Evidence =>
createEvidence(
hasSubject
@@ -69,7 +70,9 @@ const source = (
result: dossier,
confidence: "derived",
authority: "shipped-artifact",
relationshipCoverage: { status: "complete" },
...(hasCoverage
? { relationshipCoverage: { status: "complete" as const } }
: {}),
...observation,
},
);
@@ -197,6 +200,118 @@ describe("function reconstruction source parameters", () => {
});
});
describe("historical calls-only reconstruction changes", () => {
it.each(["missing", "unknown", "partial", "unresolved"] as const)(
"keeps historical calls-only changes unknown with %s call coverage",
(coverage) => {
const changedDossier = functionDossierSchema.parse({
...functionDossierSchema.parse(dossier),
callees: [
{
address: "0x2000",
name: "puts",
classification: null,
body: { available: false, reason: "External function." },
},
],
});
const complete = source("8", {
result: jsonValueSchema.parse(changedDossier),
});
const incomplete = source(
"9",
{
result: jsonValueSchema.parse({
...changedDossier,
...(coverage === "unresolved"
? {
unresolved_calls: [
{
address: "0x1004",
reason: "Computed target unresolved.",
},
],
}
: {}),
}),
...(coverage === "missing"
? {}
: {
relationshipCoverage:
coverage === "unknown"
? { status: "unknown", reason: "Call graph unavailable." }
: coverage === "partial"
? {
status: "partial",
limitations: ["Additional edges omitted."],
}
: { status: "complete" },
}),
},
true,
coverage !== "missing",
);
const historicalResult = compareFunctions(left, complete);
expect(historicalResult).toMatchObject({
status: "changed",
summary: { changed: 1 },
});
expect(historicalResult.changes).toMatchObject([
{ dimension: "calls", status: "changed" },
]);
const completeComparison = comparison(
{
left_evidence_id: left.evidence_id,
right_evidence_id: complete.evidence_id,
},
{},
[left, complete],
{},
historicalResult,
);
expect(
admittedVerification(completeComparison, [left, complete], "overall")()
.status,
).toBe("fail");
const evidence = comparison(
{
left_evidence_id: left.evidence_id,
right_evidence_id: incomplete.evidence_id,
},
{},
[left, incomplete],
{},
historicalResult,
);
const before = JSON.stringify(evidence);
for (const dimension of ["calls", "overall"] as const) {
expect(
admittedVerification(evidence, [left, incomplete], dimension)(),
).toMatchObject({
status: "unknown",
summary: { total: 1, passed: 0, failed: 0, unknown: 1 },
claims: {
items: [
expect.objectContaining({
status: "unknown",
observed_status: "changed",
limitations: expect.arrayContaining([
expect.stringContaining(`Source ${incomplete.evidence_id}:`),
]),
}),
],
},
});
}
expect(
admittedVerification(evidence, [left, incomplete], "pseudocode")()
.status,
).toBe("pass");
expect(JSON.stringify(evidence)).toBe(before);
},
);
});
describe("function reconstruction call coverage", () => {
it("rechecks old unchanged comparisons without affecting unrelated finite dimensions", () => {
const incomplete = source("7", {
+35 -11
View File
@@ -144,10 +144,15 @@ const evaluateClaim = (
return source;
});
const functionSourceFacts = readValidatedSourceFacts(claim, sources);
const observed = observedStatus(claim, comparison);
const observation = comparisonObservation(claim, comparison);
const observed = observation.status;
const limitations = [
...authorityLimitations(claim, sources, sides),
...sourceCallCoverageLimitations(claim, functionSourceFacts, observed),
...sourceCallCoverageLimitations(
claim,
functionSourceFacts,
observation.hasIndependentFunctionChange === true,
),
];
const relatedUnknowns = reconstructionClaimUnknowns(
heads,
@@ -235,21 +240,40 @@ const validateComparisonIdentity = (claim: Claim, evidence: Evidence): void => {
throw new TypeError("Comparison Evidence identity or authority disagrees");
};
const observedStatus = (claim: Claim, evidence: Evidence): ObservedStatus => {
const comparisonObservation = (
claim: Claim,
evidence: Evidence,
): {
readonly status: ObservedStatus;
readonly hasIndependentFunctionChange?: boolean;
} => {
if (claim.kind === "behavioral") {
const result = processCaptureComparisonSchema.parse(
evidence.normalized_result,
);
validateProcessStatus(result);
return claim.dimension === "overall"
? result.status
: result[claim.dimension];
return {
status:
claim.dimension === "overall" ? result.status : result[claim.dimension],
};
}
if (claim.kind === "structural-function") {
const result = functionComparisonResultSchema.parse(
evidence.normalized_result,
);
if (claim.dimension === "overall") return result.status;
if (claim.dimension === "overall")
return {
status: result.status,
// Historical overall changes may come solely from incomplete call sets.
hasIndependentFunctionChange:
result.function_match.status === "mismatched" ||
(result.function_match.status === "matched" &&
result.dimensions.some(
(dimension) =>
dimension.dimension !== "calls" &&
dimension.status === "changed",
)),
};
const dimension = result.dimensions.find(
(item) => item.dimension === claim.dimension,
);
@@ -263,7 +287,7 @@ const observedStatus = (claim: Claim, evidence: Evidence): ObservedStatus => {
throw new TypeError(
"Function dimension cites Evidence outside comparison closure",
);
return dimension.status;
return { status: dimension.status };
}
const result = artifactComparisonResultSchema.parse(
evidence.normalized_result,
@@ -276,7 +300,7 @@ const observedStatus = (claim: Claim, evidence: Evidence): ObservedStatus => {
throw new TypeError(
"Artifact change cites Evidence outside comparison closure",
);
return result.status;
return { status: result.status };
};
const validateProcessStatus = (
@@ -340,12 +364,12 @@ const authorityLimitations = (
const sourceCallCoverageLimitations = (
claim: Claim,
functionSources: readonly FunctionSourceFacts[],
observed: ObservedStatus,
hasIndependentFunctionChange: boolean,
): string[] => {
if (
claim.kind !== "structural-function" ||
(claim.dimension !== "calls" &&
!(claim.dimension === "overall" && observed !== "changed"))
!(claim.dimension === "overall" && !hasIndependentFunctionChange))
)
return [];
return functionSources.flatMap(({ evidence_id, callCoverageLimitations }) =>
+14 -6
View File
@@ -2,10 +2,18 @@ import { expect, it } from "vitest";
import { hasValidSourceMapContents } from "./sourceMapContents.js";
it("accepts absent map-level source contents and aligned nullable slots", () => {
expect(hasValidSourceMapContents(2, undefined)).toBe(true);
expect(hasValidSourceMapContents(2, null)).toBe(true);
expect(hasValidSourceMapContents(2, [null, "retained source"])).toBe(true);
expect(hasValidSourceMapContents(2, ["retained source"])).toBe(false);
expect(hasValidSourceMapContents(2, [null, 42])).toBe(false);
it("accepts absent map-level source contents and nullable string slots", () => {
expect(hasValidSourceMapContents(undefined)).toBe(true);
expect(hasValidSourceMapContents(null)).toBe(true);
expect(hasValidSourceMapContents([null, "retained source"])).toBe(true);
expect(hasValidSourceMapContents([null, 42])).toBe(false);
expect(hasValidSourceMapContents("retained source")).toBe(false);
});
it("leaves sourcesContent length to source decoding (ECMA-426 DecodeSourceMapSources)", () => {
expect(hasValidSourceMapContents([])).toBe(true);
expect(hasValidSourceMapContents(["retained source"])).toBe(true);
expect(
hasValidSourceMapContents(["a", null, "unused trailing content"]),
).toBe(true);
});
+9 -6
View File
@@ -1,12 +1,15 @@
/** Validate optional source-map content against its source inventory. */
export const hasValidSourceMapContents = (
sourceCount: number,
contents: unknown,
): boolean =>
/**
* Validate optional source-map content against its source inventory.
*
* ECMA-426 DecodeSourceMapSources reads a content slot only while its index is
* within `sourcesContent`, so a shorter array leaves trailing sources without
* content and a longer array contributes no extra sources. Only the entry types
* are checked here.
*/
export const hasValidSourceMapContents = (contents: unknown): boolean =>
contents === undefined ||
contents === null ||
(Array.isArray(contents) &&
contents.length === sourceCount &&
contents.every(
(content: unknown) => content === null || typeof content === "string",
));
+2
View File
@@ -1,3 +1,4 @@
import { wasmInterfaceSchema } from "./wasmInterface.js";
import { z } from "zod";
import { createHash } from "node:crypto";
import type { EvidenceSubjectTarget } from "../evidence.js";
@@ -32,6 +33,7 @@ export const wasmArtifactSchema = z
description: z.string(),
}),
),
interface: wasmInterfaceSchema.exactOptional(),
imports: z.array(z.string()),
exports: z.array(z.string()),
headers: z.string(),
+109
View File
@@ -0,0 +1,109 @@
import { z } from "zod";
const kind = z.enum(["func", "table", "memory", "global", "tag", "unknown"]);
const valueType = z.enum([
"i32",
"i64",
"f32",
"f64",
"v128",
"funcref",
"externref",
]);
const limit = z.string().regex(/^(?:0|[1-9][0-9]*)$/u);
const signature = z.discriminatedUnion("kind", [
z.object({
kind: z.literal("func"),
params: z.array(valueType),
results: z.array(valueType),
}),
z.object({
kind: z.literal("tag"),
params: z.array(valueType),
results: z.array(valueType),
}),
z.object({
kind: z.literal("table"),
element: z.enum(["funcref", "externref"]),
address_type: z.enum(["i32", "i64"]),
minimum: limit,
maximum: limit.nullable(),
shared: z.boolean(),
}),
z.object({
kind: z.literal("memory"),
page_size: limit,
address_type: z.enum(["i32", "i64"]),
minimum: limit,
maximum: limit.nullable(),
shared: z.boolean(),
}),
z.object({
kind: z.literal("global"),
value_type: valueType,
mutable: z.boolean(),
}),
]);
/** Typed observations decoded once at the WABT producer boundary. */
export const wasmInterfaceSchema = z.object({
state: z.enum(["complete", "partial"]),
entries: z.array(
z
.object({
direction: z.enum(["import", "export"]),
module: z.string().nullable(),
name: z.string(),
kind,
index: z.number().int().nonnegative().max(0xffff_ffff).nullable(),
signature: signature.nullable(),
wat_form: z.string(),
issue: z.string().nullable(),
})
.superRefine((entry, context) => {
if (
(entry.direction === "export" && entry.module !== null) ||
(entry.direction === "import" && entry.module === null)
)
context.addIssue({
code: "custom",
message: "Interface direction does not match module-name presence",
});
if (entry.signature !== null && entry.signature.kind !== entry.kind)
context.addIssue({
code: "custom",
message: "Interface kind does not match its typed signature",
});
}),
),
issues: z.array(z.string()),
});
export type WasmInterface = z.infer<typeof wasmInterfaceSchema>;
export type WasmInterfaceEntry = WasmInterface["entries"][number];
export type WasmInterfaceSignature = NonNullable<
WasmInterfaceEntry["signature"]
>;
export type WasmInterfaceValueType = z.infer<typeof valueType>;
/** Bound eager typed output and repeated signature expansion independently of WAT bytes. */
export const WASM_INTERFACE_REPRESENTATION_BYTES = 32 * 1024 * 1024;
/** Conservative JSON/retention charge; shared arrays still expand at every occurrence. */
export const wasmInterfaceEntryRepresentationBytes = (
entry: WasmInterfaceEntry,
): number => {
let bytes =
1024 +
[entry.module, entry.name, entry.wat_form, entry.issue].reduce<number>(
(sum, value) => sum + (value?.length ?? 0) * 6,
0,
);
const signature = entry.signature;
if (signature?.kind === "func" || signature?.kind === "tag")
bytes += (signature.params.length + signature.results.length) * 16;
else if (signature !== null)
for (const value of Object.values(signature))
if (typeof value === "string") bytes += value.length * 6;
return bytes;
};
+93
View File
@@ -8,6 +8,48 @@ import { createWebTextArtifact } from "./webContentArtifact.js";
const origin = "https://app.example.test";
it.each([
{
kind: "recovered",
source: "function legacy(a, a) { return a; } fetch('/partial');",
parsed: 2,
failures: 0,
reason: "recovered",
endpoints: ["/partial", "/complete"],
},
{
kind: "failed",
source: "function broken( {",
parsed: 1,
failures: 1,
reason: "could not be parsed",
endpoints: ["/complete"],
},
])(
"attributes $kind parse uncertainty only to its affected source",
({ source, parsed, failures, reason, endpoints }) => {
const captured = inspection(source);
const good = inspection("fetch('/complete');").scripts.items[0];
if (good === undefined) throw new Error("Missing valid script fixture");
captured.scripts.items.push({ ...good, script_key: "valid-script" });
captured.scripts.total += 1;
const result = analyzeCapturedWebBundle(captured);
expect(result.completeness).toMatchObject({
status: "partial",
parsed_scripts: parsed,
parse_failures: failures,
});
expect(result.unknowns).toContainEqual({
dimension: "javascript_ast",
reason: expect.stringContaining(reason),
affected_script_keys: [captured.scripts.items[0]?.script_key],
});
expect(result.observations.endpoints.map(({ value }) => value)).toEqual(
endpoints,
);
},
);
describe("web bundle analyzer", () => {
it("extracts graph, route, endpoint, vendor, and WebMCP evidence", () => {
const source = `
@@ -714,3 +756,54 @@ it("keeps RPC lexical identity and bundled factory recognition in captured scrip
]);
expect(result.completeness.status).toBe("complete");
});
it("retains distinct WebMCP descriptions and names while deduplicating equivalent properties", () => {
const result = analyzeCapturedWebBundle(
inspection(`
document.modelContext.registerTool({ name: "lookup", description: "first", inputSchema: { properties: { alpha: {} } } });
document.modelContext.registerTool({ name: "lookup", description: "second", inputSchema: { properties: { alpha: {} } } });
document.modelContext.registerTool({ name: "equivalent", inputSchema: { properties: { alpha: {}, beta: {} } } });
document.modelContext.registerTool({ name: "equivalent", inputSchema: { properties: { beta: {}, alpha: {}, alpha: {} } } });
document.modelContext.registerTool({ description: "unnamed" });
document.modelContext.registerTool({ name: "", description: "unnamed" });
`),
);
expect(
result.observations.webmcp_declarations.map(
({ name, description, schema_property_names }) => ({
name,
description,
schema_property_names,
}),
),
).toEqual([
{
name: "lookup",
description: "first",
schema_property_names: ["alpha"],
},
{
name: "lookup",
description: "second",
schema_property_names: ["alpha"],
},
{
name: "equivalent",
description: null,
schema_property_names: ["alpha", "beta"],
},
{ name: null, description: "unnamed", schema_property_names: [] },
{ name: "", description: "unnamed", schema_property_names: [] },
]);
expect(result.observations.webmcp_declarations[2]?.location).toEqual({
script_key: `scr_${"1".repeat(64)}`,
line: 4,
column: 6,
});
expect(
result.observations.webmcp_declarations.every(
({ trust }) => trust === "page-declared-untrusted",
),
).toBe(true);
});
+15 -12
View File
@@ -50,7 +50,8 @@ export interface AnalysisAccumulator {
readonly seen: Set<string>;
visitedNodes: number;
parsedScripts: number;
parseFailures: number;
readonly failedScripts: string[];
readonly recoveredScripts: string[];
}
export const analyzeScript = (
@@ -67,10 +68,12 @@ export const analyzeScript = (
} catch (cause: unknown) {
// Unparseable scripts are counted; the failure needs no extra detail.
void cause;
accumulator.parseFailures += 1;
accumulator.failedScripts.push(script.script_key);
return;
}
accumulator.parsedScripts += 1;
if ((file.errors?.length ?? 0) > 0)
accumulator.recoveredScripts.push(script.script_key);
detectVendorFingerprints(script, accumulator);
const openReceiverFacts = classifyParsedJavaScriptOpenReceivers(file);
const rpc = createJavaScriptRpcScan(
@@ -293,19 +296,18 @@ const addWebMcpDeclaration = (
: [],
)
: [];
const metadata = {
name: name ?? null,
description: description ?? null,
schema_property_names: [...new Set(schemaPropertyNames)].sort(),
};
// Deduplicate the metadata we return, preserving omission and descriptions.
// Property names are a variable-length source-derived list: NUL-joins
// would collapse ["a\0b"] with ["a", "b"] and drop a declaration.
const key = compositeKey([
"webmcp",
script.script_key,
name ?? "",
schemaPropertyNames,
]);
const key = compositeKey(["webmcp", script.script_key, metadata]);
addUnique(accumulator, key, () =>
accumulator.webMcp.push({
name: name ?? null,
description: description ?? null,
schema_property_names: [...new Set(schemaPropertyNames)].sort(),
...metadata,
trust: "page-declared-untrusted",
location: location(script.script_key, node),
}),
@@ -387,7 +389,8 @@ export const emptyAccumulator = (): AnalysisAccumulator => ({
seen: new Set(),
visitedNodes: 0,
parsedScripts: 0,
parseFailures: 0,
failedScripts: [],
recoveredScripts: [],
});
export const isIncludedScript = (
+19 -10
View File
@@ -25,7 +25,8 @@ export const buildWebBundleAnalysis = (
const sourceMapIncomplete =
sourceMaps.status === "partial" || sourceMaps.status === "unavailable";
const partial =
accumulator.parseFailures > 0 ||
accumulator.failedScripts.length > 0 ||
accumulator.recoveredScripts.length > 0 ||
unavailable.length > 0 ||
sourceMapIncomplete ||
omittedScripts !== undefined ||
@@ -44,9 +45,9 @@ export const buildWebBundleAnalysis = (
},
inferences: accumulator.inferences,
unknowns: buildUnknowns({
sourceScripts,
unavailable,
parseFailures: accumulator.parseFailures,
failedScripts: accumulator.failedScripts,
recoveredScripts: accumulator.recoveredScripts,
sourceMaps,
omittedScripts,
omittedSourceMaps,
@@ -54,7 +55,7 @@ export const buildWebBundleAnalysis = (
completeness: buildCompleteness({
partial,
parsedScripts: accumulator.parsedScripts,
parseFailures: accumulator.parseFailures,
parseFailures: accumulator.failedScripts.length,
visitedNodes: accumulator.visitedNodes,
}),
limitations: bundleLimitations(),
@@ -88,9 +89,9 @@ const chunkNode = (script: IncludedScript) => {
};
interface UnknownsInput {
readonly sourceScripts: IncludedScript[];
readonly unavailable: string[];
readonly parseFailures: number;
readonly failedScripts: readonly string[];
readonly recoveredScripts: readonly string[];
readonly sourceMaps: WebBundleAnalysis["observations"]["source_maps"];
readonly omittedScripts: number | null | undefined;
readonly omittedSourceMaps: number | null | undefined;
@@ -115,15 +116,23 @@ const buildUnknowns = (input: UnknownsInput): WebBundleAnalysis["unknowns"] => [
affected_script_keys: input.unavailable,
},
]),
...(input.parseFailures === 0
...(input.failedScripts.length === 0
? []
: [
{
dimension: "javascript_ast" as const,
reason: "One or more source artifacts could not be parsed",
affected_script_keys: input.sourceScripts.map(
({ script_key }) => script_key,
),
affected_script_keys: [...input.failedScripts],
},
]),
...(input.recoveredScripts.length === 0
? []
: [
{
dimension: "javascript_ast" as const,
reason:
"The parser recovered from errors in one or more source artifacts; findings may be incomplete",
affected_script_keys: [...input.recoveredScripts],
},
]),
...(input.omittedSourceMaps === undefined
+120 -1
View File
@@ -8,7 +8,19 @@ import type { JsonValue } from "../domain/jsonValue.js";
import { javascriptApplicationAnalysisResultSchema } from "../domain/javascript/javascriptApplicationAnalysis.js";
import type { ApplicationNode } from "../domain/javascript/javascriptApplicationGraphSchemas.js";
import { javaScriptExportShapeComparisonResultSchema } from "../domain/javascript/javascriptExportShapeComparisonSchemas.js";
import type { FixtureClaimExpectation } from "./KnownAnswerEvaluation.js";
import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
} from "../domain/managed/managedArtifact.js";
import {
managedTokenScopesMatch,
parseManagedInspectionEvidence,
} from "../domain/managed/managedInspectionEvidence.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import type {
FixtureClaimContext,
FixtureClaimExpectation,
} from "./KnownAnswerEvaluation.js";
/** Source-owned artifact paths used by the configured known-answer benchmarks. */
export interface AgentEvaluationFixtureTargets {
@@ -16,6 +28,8 @@ export interface AgentEvaluationFixtureTargets {
readonly javascriptSha256: string;
readonly javascriptShapeLeft: string;
readonly javascriptShapeRight: string;
readonly managed?: string;
readonly managedSha256?: string;
}
const desktopFixtureFiles = {
@@ -277,17 +291,122 @@ const parserClaims = (
];
};
const managedMembers = ({ evidence }: FixtureClaimContext) => {
const { result } = parseManagedInspectionEvidence(
evidence,
"inspect_managed_members",
managedMemberInspectionSchema,
);
if (
result.coverage.state !== "complete" ||
result.metadata.status !== "complete" ||
!managedTokenScopesMatch(
result.identity_scope.requires_mvid,
result.module?.mvid ?? null,
)
)
return undefined;
return result;
};
const managedClaims = (
targets: AgentEvaluationFixtureTargets,
): readonly FixtureClaimExpectation[] => {
if (targets.managed === undefined || targets.managedSha256 === undefined)
throw new TypeError(
"Managed fixture grading requires the built DLL path and SHA-256",
);
const source = {
operation: "inspect_managed_members",
authority: "shipped-artifact",
confidence: "observed",
subject: { path: targets.managed, sha256: targets.managedSha256 },
} satisfies Omit<FixtureClaimExpectation["source"], "select">;
return [
{
id: "public_types",
expectedValue: ["AgentEval.Profile", "AgentEval.Program"],
source: {
...source,
select: (_value, context) => {
const members = managedMembers(context);
if (
members === undefined ||
members.selection !== null ||
Object.hasOwn(context.evidence.parameters, "type_names")
)
return undefined;
return members.types
.filter((type) => (type.flags & 7) === 1)
.map((type) => type.full_name)
.sort(compareUnicodeCodePoints);
},
},
},
{
id: "entry_point",
expectedValue: { declaring_type: "AgentEval.Program", name: "Main" },
source: {
...source,
select: (_value, context) => {
const members = managedMembers(context);
if (members === undefined) return undefined;
const artifacts = context.deliveredEvidence.filter(
(evidence) =>
evidence.operation === "inspect_managed_artifact" &&
evidence.authority === source.authority &&
evidence.confidence === source.confidence &&
evidence.subject?.local_path === source.subject.path &&
evidence.subject.digest.sha256 === source.subject.sha256,
);
if (artifacts.length !== 1) return undefined;
const { result: artifact } = parseManagedInspectionEvidence(
artifacts[0],
"inspect_managed_artifact",
managedArtifactInspectionSchema,
);
if (
artifact.coverage.state !== "complete" ||
artifact.metadata.status !== "complete" ||
!managedTokenScopesMatch(
artifact.module?.mvid ?? null,
members.module?.mvid ?? null,
) ||
artifact.pe.cli?.entry_point.kind !== "metadata-token"
)
return undefined;
const methods = members.methods.filter(
(method) => method.token === artifact.pe.cli?.entry_point.value,
);
const method = methods.length === 1 ? methods[0] : undefined;
return method === undefined
? undefined
: {
declaring_type: method.declaring_type,
name: method.name,
};
},
},
},
];
};
/** Return the closed known-answer rubric, or undefined for routing-only scenarios. */
export const agentFixtureClaims = (
scenarioId: string,
targets: AgentEvaluationFixtureTargets,
): readonly FixtureClaimExpectation[] | undefined => {
if (scenarioId === "asar") return asarClaims(targets);
if (scenarioId === "managed") return managedClaims(targets);
if (scenarioId === "javascript-export-shape") return parserClaims(targets);
return undefined;
};
const answerValueDescriptions: Readonly<Record<string, readonly string[]>> = {
managed: [
"public_types: string[], listing the exact public top-level type full names in Unicode code-point order from unfiltered member Evidence (omit type_names).",
'entry_point: {"declaring_type": string, "name": string}, resolving the CLI metadata entry-point token against the member inventory from the same artifact SHA-256 and module MVID. Cite member Evidence; both artifact and member Evidence must be delivered.',
],
asar: [
'renderer_api: {"key": string, "members": string[], "world": string, "source": string}, describing the exposed bridge API, its members, world, and source file.',
'renderer_ipc: {"channel": string, "operation": string, "source": string}, describing the renderer-side IPC operation and its source file.',
+16 -2
View File
@@ -5,6 +5,12 @@ import { parseEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { canonicalJson } from "../domain/comparisonSemantics.js";
/** Only authenticated, successful, non-conflicting transcript deliveries. */
export interface FixtureClaimContext {
readonly evidence: Evidence;
readonly deliveredEvidence: readonly Evidence[];
}
/** One closed fixture assertion and the producer facts that must support it. */
export interface FixtureClaimExpectation {
readonly id: string;
@@ -20,7 +26,10 @@ export interface FixtureClaimExpectation {
readonly path: string;
readonly sha256?: string;
}[];
readonly select: (normalizedResult: JsonValue) => JsonValue | undefined;
readonly select: (
normalizedResult: JsonValue,
context: FixtureClaimContext,
) => JsonValue | undefined;
};
}
@@ -430,7 +439,12 @@ const assessClaim = (
try {
if (
!sameJson(
expected.source.select(evidence.normalized_result),
expected.source.select(evidence.normalized_result, {
evidence,
deliveredEvidence: [...delivered.records.values()].filter(
(record) => !delivered.conflicts.has(record.evidence_id),
),
}),
expected.expectedValue,
)
)
+1 -1
View File
@@ -61,7 +61,7 @@ const doctorHost = (
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
hopperSetupSupported: true,
}),
validTarget: () => Promise.resolve(true),
executable: (path) =>
+34
View File
@@ -1,4 +1,9 @@
import { z } from "zod";
import {
bytePatternFields,
validateBytePattern,
byteSearchResultSchema,
} from "../domain/native/bytePattern.js";
import { nativeLoadImageObservationSchema } from "../domain/native/nativeLoadImage.js";
import {
@@ -20,6 +25,7 @@ import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"
export const GHIDRA_INVENTORY_OPERATIONS = [
"inspect_native_load_image",
"read_bytes",
"search_bytes",
"address_to_file_offset",
"address_name",
"list_documents",
@@ -72,6 +78,16 @@ const searchInput = {
};
const inputSchemas = {
search_bytes: z
.strictObject({
...bytePatternFields,
document,
start: explicitAddress.optional(),
end: explicitAddress.optional(),
limit: z.number().int().min(1).max(1000).default(100),
cursor: z.string().min(1).optional(),
})
.superRefine(validateBytePattern),
inspect_native_load_image: z.strictObject({}),
read_bytes: z.strictObject({
document,
@@ -271,6 +287,24 @@ const containingProcedure = z.discriminatedUnion("found", [
]);
const resultSchemas = {
search_bytes: byteSearchResultSchema.superRefine((value, context) => {
const addresses = [
...value.matches.flatMap((match) => [
match.address,
...(match.procedure === null ? [] : [match.procedure.address]),
]),
...[
...value.searched.blocks,
...value.searched.skipped_uninitialized,
...value.searched.skipped_not_loaded,
].flatMap((block) => [block.start, block.end]),
];
if (addresses.some((value) => !canonicalAddress.safeParse(value).success))
context.addIssue({
code: "custom",
message: "Byte search addresses must be canonical",
});
}),
inspect_native_load_image: nativeLoadImageObservationSchema,
read_bytes: z
.strictObject({
+5
View File
@@ -90,6 +90,11 @@ export const limitationsFor = (operation: string): readonly string[] => {
...common,
"Bytes reflect Ghidra's initialized memory, including loader fixups. Reads stop at an unmapped or uninitialized byte and report completeness explicitly.",
];
case "search_bytes":
return [
...common,
"Searches initialized loader-adjusted memory independently per block, in provider address order. Bounds and page coverage ends are inclusive. Uninitialized blocks are listed separately. Overlapping matches are included; patterns never cross block boundaries. A cursor resumes the same target, profile and query. Cancellation discards the active search and returns no successful partial page.",
];
case "address_to_file_offset":
return [
...common,
+7 -3
View File
@@ -62,12 +62,16 @@ const MUTATING_OPERATIONS = new Set<string>([
/** Source-owned capabilities without acquiring or probing a Hopper session. */
export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
HOPPER_OPERATIONS.map((operation) =>
[...HOPPER_OPERATIONS, "search_bytes" as const].map((operation) =>
Object.freeze({
provider: HOPPER_PROVIDER_IDENTITY,
operation,
available: true,
reason: null,
...(operation === "search_bytes"
? {
available: false as const,
reason: "Masked byte search has not been verified for Hopper.",
}
: { available: true as const, reason: null }),
effects: Object.freeze({
mutatesArtifact: MUTATING_OPERATIONS.has(operation),
launchesProcess: true,
+5
View File
@@ -279,6 +279,11 @@ describe("native IDA provider observations", () => {
);
if (!result.ok) throw result.error;
expect(result.value.provider.name).toBe("IDA MCP adapter");
if (operation === "xrefs")
expect(
result.value.referencesTruncated,
"the native producer's explicit cap flag is forwarded",
).toBe(false);
if (operation === "procedure_assembly")
expect(result.value.result).toBe("0x1000: ret");
if (operation === "procedure_pseudo_code") {
@@ -1,6 +1,5 @@
import { z } from "zod";
import { WEB_SOURCE_MAP_LIMITS } from "../../domain/webSourceLocation.js";
import { hasValidSourceMapContents } from "../../domain/sourceMapContents.js";
import { sourceMapJsonText } from "../../domain/sourceMapEnvelope.js";
import type { EncodedSourceMapXInput } from "@jridgewell/trace-mapping";
@@ -267,18 +266,6 @@ const inspectLeaf = (
consumeRecords(budget, Array.isArray(rawNames) ? rawNames.length : 0);
consumeRecords(budget, Array.isArray(rawContents) ? rawContents.length : 0);
options.check?.();
if (
options.profile === "browser-collection" &&
!hasValidSourceMapContents(
Array.isArray(rawSources) ? rawSources.length : 0,
rawContents,
)
)
throw new SourceMapFormatFailure(
"format",
"Source-map sourcesContent must align with its source declarations.",
);
options.check?.();
const leaf = leafSchema.parse(node.value);
const layout = inspectMappingLayout(leaf.mappings, options.check);
consumeRecords(budget, layout.segments + layout.lines);
+2
View File
@@ -7,6 +7,8 @@
*/
export const MCP_STARTUP_POLICY = {
codexStartupTimeoutSeconds: 30,
kimiStartupTimeoutMs: 30_000,
kimiToolTimeoutMs: 120_000,
initializeBudgetMs: 15_000,
toolsListBudgetMs: 5_000,
firstCatalogBudgetMs: 20_000,
+31 -95
View File
@@ -35,6 +35,28 @@ const validPng = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
"base64",
);
/** Screenshot payload as the native helper reports one PNG buffer. */
const screenshotOf = (bytes: Buffer) => ({
mime_type: "image/png",
base64: bytes.toString("base64"),
sha256: createHash("sha256").update(bytes).digest("hex"),
width: bytes.readUInt32BE(16),
height: bytes.readUInt32BE(20),
});
/** Observe the fixture snapshot carrying one screenshot payload. */
const observeWithScreenshot = (screenshot: Record<string, unknown>) =>
observeNativeUi(
target,
"observe_native_ui",
{ ...scope, screenshot: true },
{
environment: {},
invoke: async () => ({ ok: true, result: { ...snapshot, screenshot } }),
},
);
it.each([
{ offset: 8, value: 12 },
{ offset: 16, value: 0x8000_0000 },
@@ -44,49 +66,16 @@ it.each([
async ({ offset, value }) => {
const bytes = Buffer.from(validPng);
bytes.writeUInt32BE(value, offset);
const screenshot = {
mime_type: "image/png",
base64: bytes.toString("base64"),
sha256: createHash("sha256").update(bytes).digest("hex"),
width: bytes.readUInt32BE(16),
height: bytes.readUInt32BE(20),
};
const result = await observeNativeUi(
target,
"observe_native_ui",
{ ...scope, screenshot: true },
{
environment: {},
invoke: async () => ({
ok: true,
result: { ...snapshot, screenshot },
}),
},
);
const result = await observeWithScreenshot(screenshotOf(bytes));
expect(result.ok).toBe(false);
},
);
describe("native UI screenshot validation", () => {
it("rejects malformed or mismatched screenshot bytes from the helper", async () => {
const screenshot = {
mime_type: "image/png",
base64: validPng.toString("base64"),
const result = await observeWithScreenshot({
...screenshotOf(validPng),
sha256: "0".repeat(64),
width: 1,
height: 1,
};
const result = await observeNativeUi(
target,
"observe_native_ui",
{ ...scope, screenshot: true },
{
environment: {},
invoke: async () => ({
ok: true,
result: { ...snapshot, screenshot },
}),
},
);
});
expect(result.ok).toBe(false);
});
@@ -97,26 +86,10 @@ describe("native UI screenshot validation", () => {
])(
"rejects invalid screenshot field variants from the helper",
async (change) => {
const screenshot = {
mime_type: "image/png",
base64: validPng.toString("base64"),
sha256: createHash("sha256").update(validPng).digest("hex"),
width: 1,
height: 1,
const result = await observeWithScreenshot({
...screenshotOf(validPng),
...change,
};
const result = await observeNativeUi(
target,
"observe_native_ui",
{ ...scope, screenshot: true },
{
environment: {},
invoke: async () => ({
ok: true,
result: { ...snapshot, screenshot },
}),
},
);
});
expect(result.ok).toBe(false);
},
);
@@ -126,49 +99,12 @@ describe("native UI screenshot validation", () => {
const type = bytes.subarray(12, 16);
type[0] = (type[0] ?? 0) | 0x80;
expect(type.toString("ascii")).toBe("IHDR");
const screenshot = {
mime_type: "image/png",
base64: bytes.toString("base64"),
sha256: createHash("sha256").update(bytes).digest("hex"),
width: 1,
height: 1,
};
const result = await observeNativeUi(
target,
"observe_native_ui",
{ ...scope, screenshot: true },
{
environment: {},
invoke: async () => ({
ok: true,
result: { ...snapshot, screenshot },
}),
},
);
const result = await observeWithScreenshot(screenshotOf(bytes));
expect(result.ok).toBe(false);
});
it("accepts a self-consistent PNG screenshot from the helper", async () => {
const bytes = validPng;
const screenshot = {
mime_type: "image/png",
base64: bytes.toString("base64"),
sha256: createHash("sha256").update(bytes).digest("hex"),
width: 1,
height: 1,
};
const result = await observeNativeUi(
target,
"observe_native_ui",
{ ...scope, screenshot: true },
{
environment: {},
invoke: async () => ({
ok: true,
result: { ...snapshot, screenshot },
}),
},
);
const result = await observeWithScreenshot(screenshotOf(validPng));
expect(result.ok).toBe(true);
});
+55 -2
View File
@@ -63,6 +63,56 @@ const DYLIB_FIELDS = [
const DYLIB_ENCODING_FIELDS = ["time stamp", "options"];
const EMPTY_VALUE_FIELDS = new Set(["options", "segname", "sectname"]);
/**
* Non-verbose otool prints LC_BUILD_VERSION platform and tool codes as
* numbers. Name the codes declared in the SDK's <mach-o/loader.h>, without
* the PLATFORM_/TOOL_ prefix, so build metadata uses the same symbolic style
* as LC_VERSION_MIN_* platforms. Unknown codes keep their printed value.
*/
const BUILD_PLATFORM_NAMES: ReadonlyMap<string, string> = new Map([
["1", "MACOS"],
["2", "IOS"],
["3", "TVOS"],
["4", "WATCHOS"],
["5", "BRIDGEOS"],
["6", "MACCATALYST"],
["7", "IOSSIMULATOR"],
["8", "TVOSSIMULATOR"],
["9", "WATCHOSSIMULATOR"],
["10", "DRIVERKIT"],
["11", "VISIONOS"],
["12", "VISIONOSSIMULATOR"],
["13", "FIRMWARE"],
["14", "SEPOS"],
["15", "MACOS_EXCLAVECORE"],
["16", "MACOS_EXCLAVEKIT"],
["17", "IOS_EXCLAVECORE"],
["18", "IOS_EXCLAVEKIT"],
["19", "TVOS_EXCLAVECORE"],
["20", "TVOS_EXCLAVEKIT"],
["21", "WATCHOS_EXCLAVECORE"],
["22", "WATCHOS_EXCLAVEKIT"],
["23", "VISIONOS_EXCLAVECORE"],
["24", "VISIONOS_EXCLAVEKIT"],
]);
const BUILD_TOOL_NAMES: ReadonlyMap<string, string> = new Map([
["1", "CLANG"],
["2", "SWIFT"],
["3", "LD"],
["4", "LLD"],
["1024", "METAL"],
["1025", "AIRLLD"],
["1026", "AIRNT"],
["1027", "AIRNT_PLUGIN"],
["1028", "AIRPACK"],
["1031", "GPUARCHIVER"],
["1032", "METAL_FRAMEWORK"],
]);
const buildCodeName = (
names: ReadonlyMap<string, string>,
value: string | null,
): string | null => (value === null ? null : (names.get(value) ?? value));
/**
* otool emits LF, but a capture replayed from another host or toolchain can
* carry CRLF. The section/command boundaries below match a bare `\n`, so a
@@ -295,7 +345,10 @@ const collectBuild = (
if (numberField(fields, "ntools") !== tools.length)
throw new TypeError("otool build-tool count does not match ntools");
state.builds.push({
platform: stringField(fields, "platform"),
platform: buildCodeName(
BUILD_PLATFORM_NAMES,
stringField(fields, "platform"),
),
minimum_os: stringField(fields, "minos"),
sdk: stringField(fields, "sdk"),
tools,
@@ -434,7 +487,7 @@ const parseBuildTools = (
const tool = /^tool\s+(.+)$/u.exec(lines[index] ?? "")?.[1];
const version = /^version\s+(.+)$/u.exec(lines[index + 1] ?? "")?.[1];
if (tool !== undefined && version !== undefined)
tools.push({ name: tool, version });
tools.push({ name: BUILD_TOOL_NAMES.get(tool) ?? tool, version });
}
return tools;
};
@@ -0,0 +1,135 @@
import { describe, expect, it } from "vitest";
import {
RECORDED_LINUX_CORE_ARCHITECTURES,
RECORDED_LINUX_CORE_PROFILES,
} from "../../domain/native/recordedCrash.js";
import {
recordedCrashFixture,
recordedCrashFixtureBytes,
} from "../../../tests/fixtures/binaryDiagnostics/recordedCrash.js";
import { validateRecordedCrashSources } from "./RecordedCrashSourceBindings.js";
const diagnostics = { stdout: "", stderr: "", truncated: false } as const;
const bind = (
architecture?: "x86_64-little-endian" | "aarch64-little-endian",
) => {
const report = recordedCrashFixture("/selected.core", architecture);
return { report, bytes: recordedCrashFixtureBytes(report) };
};
describe("recorded core source bindings", () => {
it.each(RECORDED_LINUX_CORE_ARCHITECTURES)(
"binds each %s register to its own source bytes",
(architecture) => {
const { report, bytes } = bind(architecture);
expect(() =>
validateRecordedCrashSources(report, bytes, diagnostics),
).not.toThrow();
},
);
it("measures the AArch64 register window one slot wide per name", () => {
const profile = RECORDED_LINUX_CORE_PROFILES["aarch64-little-endian"];
expect(profile.registers.length).toBe(34);
expect(profile.prstatusBytes).toBe(392);
expect(profile.machine).toBe(183);
// The fixtures and the bindings both read these numbers, so they are pinned
// here against the ABI record rather than only used consistently.
expect(profile.registerOffset).toBe(112);
expect(profile.registerBytes).toBe(8);
const amd64 = RECORDED_LINUX_CORE_PROFILES["x86_64-little-endian"];
expect(amd64.registers.length).toBe(27);
expect(amd64.prstatusBytes).toBe(336);
expect(amd64.machine).toBe(62);
expect(amd64.registerOffset).toBe(112);
expect(amd64.registerBytes).toBe(8);
});
it("stamps each crafted core with the machine its profile declares", () => {
for (const architecture of RECORDED_LINUX_CORE_ARCHITECTURES) {
const bytes = bind(architecture).bytes;
expect(bytes.readUInt16LE(18)).toBe(
RECORDED_LINUX_CORE_PROFILES[architecture].machine,
);
}
});
it("rejects an AArch64 register bound to another slot", () => {
const { report, bytes } = bind("aarch64-little-endian");
const shifted = {
...report,
threads: report.threads.map((thread) => ({
...thread,
registers: thread.registers.map((register, index) =>
index === 3
? {
...register,
location: {
...register.location,
offset: `0x${(BigInt(register.location.offset) + 8n).toString(
16,
)}`,
},
}
: register,
),
})),
};
expect(() =>
validateRecordedCrashSources(shifted, bytes, diagnostics),
).toThrow(/aarch64-little-endian register identity/);
});
it("rejects an AArch64 note shorter than the profile descriptor", () => {
const { report, bytes } = bind("aarch64-little-endian");
const shortened = {
...report,
notes: report.notes.map((note, index) =>
index === 0
? {
...note,
descriptor_location: {
...note.descriptor_location,
bytes: "0x150",
},
}
: note,
),
};
expect(() =>
validateRecordedCrashSources(shortened, bytes, diagnostics),
).toThrow(/aarch64-little-endian source bytes/);
});
it("rejects an amd64 register name reported for AArch64", () => {
const { report, bytes } = bind("aarch64-little-endian");
const renamed = {
...report,
threads: report.threads.map((thread) => ({
...thread,
registers: thread.registers.map((register, index) =>
index === 0 ? { ...register, name: "rax" } : register,
),
})),
};
expect(() =>
validateRecordedCrashSources(renamed, bytes, diagnostics),
).toThrow(/aarch64-little-endian register identity/);
});
it("rejects a reported PID that differs from the recorded source bytes", () => {
const { report, bytes } = bind("aarch64-little-endian");
const wrongPid = {
...report,
threads: report.threads.map((thread) => ({
...thread,
historical_pid: thread.historical_pid + 1,
})),
};
expect(() =>
validateRecordedCrashSources(wrongPid, bytes, diagnostics),
).toThrow(/aarch64-little-endian source bytes/);
});
});
@@ -1,23 +1,26 @@
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import {
RECORDED_LINUX_AMD64_REGISTERS,
RECORDED_LINUX_CORE_PROFILES,
type RecordedCrash,
} from "../../domain/native/recordedCrash.js";
const registerOffsets = new Map<string, number>(
RECORDED_LINUX_AMD64_REGISTERS.map((name, index) => [name, 112 + index * 8]),
);
/** Bind interpreted values and register identities to Linux amd64 source bytes. */
/** Bind interpreted values and register identities to recorded source bytes. */
export function validateRecordedCrashSources(
report: RecordedCrash,
snapshot: Buffer,
diagnostics: RecordedCrash["decoder_diagnostics"],
): void {
const profile = RECORDED_LINUX_CORE_PROFILES[report.architecture];
const registerOffsets = new Map<string, number>(
profile.registers.map((name, index) => [
name,
profile.registerOffset + index * profile.registerBytes,
]),
);
const fail = () => {
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported PID or signal value differs from its recorded Linux amd64 source bytes.",
`Reported PID or signal value differs from its recorded ${report.architecture} source bytes.`,
{ capturedOutput: diagnostics },
);
};
@@ -29,10 +32,10 @@ export function validateRecordedCrashSources(
if (length < minimumBytes) return fail();
return snapshot.subarray(start, start + length);
};
// Fixed offsets independently checked against unchanged pwntools 4.15.0
// elf_prstatus_amd64 / elf_siginfo_64; this is the sole supported note ABI.
// Offsets come from unchanged pwntools 4.15.0 elf_prstatus_amd64 /
// elf_prstatus_aarch64 and elf_siginfo_64 through the shared domain profile.
for (const thread of report.threads) {
const bytes = descriptor(thread.note_index, 336);
const bytes = descriptor(thread.note_index, profile.prstatusBytes);
if (
thread.historical_pid !== bytes.readInt32LE(32) ||
thread.recorded_current_signal !== bytes.readInt16LE(12)
@@ -49,7 +52,7 @@ export function validateRecordedCrashSources(
)
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported register source does not match its Linux amd64 register identity.",
`Reported register source does not match its ${report.architecture} register identity.`,
{ capturedOutput: diagnostics },
);
}
@@ -1,5 +1,8 @@
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import type { RecordedCrash } from "../../domain/native/recordedCrash.js";
import {
RECORDED_LINUX_CORE_PROFILES,
type RecordedCrash,
} from "../../domain/native/recordedCrash.js";
// Exact amd64/core enum projections in the pinned pyelftools 0.33 profile.
const segmentKinds = new Map([
@@ -81,6 +84,8 @@ export function validateRecordedCrashStructure(
return snapshot.subarray(Number(offset), Number(offset) + bytes);
};
const header = bytesAt(0n, 64);
const expectedMachine =
RECORDED_LINUX_CORE_PROFILES[report.architecture].machine;
if (
!header
.subarray(0, 6)
@@ -90,7 +95,7 @@ export function validateRecordedCrashStructure(
![0, 3].includes(header[7] ?? -1) ||
header[8] !== 0 ||
header.readUInt16LE(16) !== 4 ||
header.readUInt16LE(18) !== 62
header.readUInt16LE(18) !== expectedMachine
)
fail();
const table = header.readBigUInt64LE(32);

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