feat(native): add investigation features (#486)

* feat(native): add UI and dispatch investigation workflows

* feat(ghidra): support macOS host validation

* docs: update native investigation capabilities

* feat(artifacts): decode compiled Interface Builder archives

* feat(ghidra): expose bounded p-code value flow

* test(ghidra): split host and cross-format verification

* fix(verify): follow complete result contracts

* refactor: remove unused authorization and schema helpers

* refactor: remove unused evidence result alias

* fix(ghidra): report jump-table evidence precisely

* fix(verify): align browser scenario fixture schema

* fix(setup): compare parsed client config structurally

* test(ghidra): verify AArch64 jump-table mappings

* fix(ghidra): recover AArch64 byte jump tables

* test(artifacts): verify compiled interface builder archives

* feat(native): trace UI actions through handlers

* fix(tests): update native trace and shutdown fixtures

* fix(verification): diagnose browser scenario failures

* fix(browser): wrap scenario snapshots in capture state

* fix(native): bind and bound investigation workflows

* fix(artifacts): preserve bounded interface builder evidence

* fix(ghidra): enforce admitted hosts and preflight tools

* fix(native): preserve trace cancellation and bounds

* test(application): expect bound analysis target evidence

* fix(native): preserve investigation bounds and cancellation

* fix(application): preserve bundle and unresolved trace evidence

* style(test): format artifact subject fixture
This commit is contained in:
morluto
2026-09-30 00:41:05 +08:00
committed by GitHub
parent fa26affc86
commit ed933d1893
87 changed files with 6771 additions and 375 deletions
+55 -3
View File
@@ -12,6 +12,7 @@ import {
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { EvidenceSubjectTarget } from "../domain/evidence.js";
import type {
AnalysisClient,
AnalysisExecution,
@@ -302,7 +303,9 @@ export class BinarySession
unboundOperationError: (operation, route) =>
this.#providerRouter.unboundOperationError(operation, route),
lookupSnapshot: (target, profile, operation, parameters) =>
this.lookupSnapshot(target, profile, operation, parameters),
operation === "decode_interface_builder"
? undefined
: this.lookupSnapshot(target, profile, operation, parameters),
});
if (!prepared.ok) return prepared;
const { active, capability, profile, cacheable, cached } = prepared.value;
@@ -311,9 +314,18 @@ export class BinarySession
this.#calls.add(call);
try {
const result = await call;
const profiled = commitExecutionProfile(name, result, profile);
const profiled = bindExecutionTarget(
commitExecutionProfile(name, result, profile),
name,
active.target,
);
this.#observeRuntimeAvailability(name, profiled);
if (profiled.ok && cacheable && profile !== undefined)
if (
profiled.ok &&
cacheable &&
profile !== undefined &&
name !== "decode_interface_builder"
)
this.recordSnapshot({
target: active.target,
profile,
@@ -500,3 +512,43 @@ const commitExecutionProfile = (
analysisProfile: structuredClone(profile),
});
};
const bindExecutionTarget = (
result: Result<AnalysisExecution, AnalysisError>,
operation: AnalysisOperation,
target: BinaryTarget,
): Result<AnalysisExecution, AnalysisError> => {
if (!result.ok) return result;
const subject: EvidenceSubjectTarget = {
path: target.path,
sha256: target.sha256,
format:
target.format === "analysis-database"
? "analysis-database"
: target.format,
...(target.architecture === undefined
? {}
: { architecture: target.architecture }),
};
if (
result.value.subject !== null &&
result.value.subject.sha256 !== target.sha256
) {
if (!isArtifactInventorySubject(operation, result.value.subject, target))
return err(
new ProviderAdapterError(
result.value.provider.id,
`${operation}:subject`,
),
);
}
return ok({ ...result.value, subject: result.value.subject ?? subject });
};
const isArtifactInventorySubject = (
operation: AnalysisOperation,
subject: EvidenceSubjectTarget,
target: BinaryTarget,
): boolean =>
(operation === "inventory_artifact" || operation === "inspect_artifact") &&
subject.path === (target.sourcePath ?? target.path);
+6
View File
@@ -71,6 +71,12 @@ type AvailabilityContext = {
};
const ENHANCED_REQUIREMENTS: Readonly<Record<string, readonly string[]>> = {
trace_native_ui_action: [
"decode_interface_builder",
"list_names",
"procedure_callees",
],
inspect_native_dispatch_metadata: ["list_names"],
get_objc_classes: ["list_names"],
get_objc_protocols: ["list_names"],
batch_decompile: ["procedure_pseudo_code"],
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import { clientConfigurationValuesEqual } from "./ClientConfigurationDocument.js";
describe("client configuration comparison", () => {
it("ignores TOML parser object prototypes and key order", () => {
const parsedEnvironment = {
HOPPER_LAUNCHER_PATH: "/opt/rea/node",
};
const parsedRegistration = {
env: parsedEnvironment,
startup_timeout_sec: 30,
args: ["mcp"],
command: "/opt/rea/bin/rea",
};
Object.setPrototypeOf(parsedEnvironment, null);
Object.setPrototypeOf(parsedRegistration, null);
expect(
clientConfigurationValuesEqual(parsedRegistration, {
command: "/opt/rea/bin/rea",
args: ["mcp"],
startup_timeout_sec: 30,
env: { HOPPER_LAUNCHER_PATH: "/opt/rea/node" },
}),
).toBe(true);
});
it("still detects configuration value changes", () => {
expect(
clientConfigurationValuesEqual(
{ startup_timeout_sec: 30 },
{ startup_timeout_sec: 15 },
),
).toBe(false);
});
});
@@ -1,4 +1,5 @@
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
import { isDeepStrictEqual } from "node:util";
import { z } from "zod";
import type { SetupClient } from "./SupportedClients.js";
@@ -12,6 +13,27 @@ export interface ClientConfigurationDocument {
const objectSchema = z.record(z.string(), z.unknown());
/** Compare parsed configuration values without depending on parser prototypes. */
export const clientConfigurationValuesEqual = (
left: unknown,
right: unknown,
): boolean =>
isDeepStrictEqual(
normalizeConfigurationValue(left),
normalizeConfigurationValue(right),
);
const normalizeConfigurationValue = (value: unknown): unknown => {
if (Array.isArray(value)) return value.map(normalizeConfigurationValue);
if (typeof value !== "object" || value === null || value instanceof Date)
return value;
return Object.fromEntries(
Object.entries(value)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, nested]) => [key, normalizeConfigurationValue(nested)]),
);
};
/** Parse the client format and reject malformed root or server-table values. */
export const parseClientConfiguration = (
text: string,
+14 -4
View File
@@ -49,10 +49,12 @@ type DirectAnalysisTool =
| "read_function_instructions"
| "analyze_function"
| "inspect_native_api"
| "inspect_native_dispatch_metadata"
| "search_strings"
| "search_procedures"
| "xrefs"
| "trace_feature";
| "trace_feature"
| "trace_native_ui_action";
/**
* Open one binary, execute one tool, and always release provider resources.
@@ -220,6 +222,7 @@ const runAnalysis = async (
const evidenceProfile = analysisProfileForEvidence(session, tool);
const bindingProfile = session.analysisProfile();
if (
tool !== "trace_native_ui_action" &&
snapshot !== undefined &&
evidenceProfile !== undefined &&
bindingProfile !== undefined
@@ -243,7 +246,11 @@ const runAnalysis = async (
evidenceProfile,
});
if (evidence !== undefined) session.recordEvidence(evidence);
if (snapshotPath !== undefined && evidence !== undefined) {
if (
tool !== "trace_native_ui_action" &&
snapshotPath !== undefined &&
evidence !== undefined
) {
const snapshot = session.exportAnalysisSnapshot();
if (!snapshot.ok) return cliError(snapshot.error);
const written = await writeAnalysisSnapshot(
@@ -276,7 +283,9 @@ const executeAnalysisTool = async (input: {
tool === "binary_overview" ||
tool === "analyze_function" ||
tool === "inspect_native_api" ||
tool === "trace_feature"
tool === "inspect_native_dispatch_metadata" ||
tool === "trace_feature" ||
tool === "trace_native_ui_action"
) {
const result = await new EnhancedTools(session).execute(
tool,
@@ -398,7 +407,8 @@ const isWorkflowEvidenceTool = (
): boolean =>
tool === "binary_overview" ||
tool === "inspect_native_api" ||
tool === "trace_feature";
tool === "trace_feature" ||
tool === "trace_native_ui_action";
const fileExists = async (path: string): Promise<boolean> => {
try {
@@ -0,0 +1,503 @@
import { describe, expect, it } from "vitest";
import { z } from "zod";
import {
createAnalysisExecution,
type AnalysisExecution,
type AnalysisOperation,
} from "./AnalysisProvider.js";
import type { AnalysisError } from "../domain/errors.js";
import { EnhancedTools } from "./EnhancedTools.js";
import {
nativeInvestigationGraphSchema,
nativeInvestigationTraceSchema,
} from "../domain/nativeInvestigationGraph.js";
import { err, ok } from "../domain/result.js";
import type { Result } from "../domain/result.js";
import { AnalysisCancelledError } from "../domain/errors.js";
const target = "a".repeat(64);
const provider = { id: "fixture", name: "Fixture", version: "1" };
const evidence = [
{
kind: "interface_builder_resource" as const,
description: "Fixture UI archive",
location: { address: null, file_offset: null },
artifact_path: null,
artifact_sha256: null,
},
];
const graph = {
target_sha256: target,
provider: {
id: provider.id,
version: provider.version,
tool_version: "fixture",
},
nodes: [
{
id: "button",
kind: "control" as const,
name: "Build",
location: null,
attributes: {
class_name: "UIButton",
interface_builder_object_id: "button",
},
evidence,
},
{
id: "action",
kind: "action" as const,
name: "buildTapped:",
location: null,
attributes: { selector: "buildTapped:" },
evidence,
},
{
id: "controller",
kind: "view_controller" as const,
name: "BuildViewController",
location: null,
attributes: { class_name: "BuildViewController" },
evidence,
},
{
id: "selector",
kind: "objc_selector" as const,
name: "buildTapped:",
location: null,
attributes: {},
evidence,
},
],
edges: [
{
id: "button-action",
from: "button",
to: "action",
relation: "target_action" as const,
resolution: "observed" as const,
evidence,
limitations: [],
},
{
id: "action-selector",
from: "action",
to: "selector",
relation: "target_action" as const,
resolution: "observed" as const,
evidence,
limitations: [],
},
{
id: "action-controller",
from: "action",
to: "controller",
relation: "target_action" as const,
resolution: "observed" as const,
evidence,
limitations: [],
},
],
coverage: [],
truncated: false,
};
const execution = (
operation: AnalysisOperation,
result: unknown,
sha256 = target,
) =>
ok(
createAnalysisExecution(result, provider, {
subject: {
sha256,
path: "/fixture.app",
format: "mach-o",
architecture: "arm64",
},
}),
);
const testAnalysis = (
overrides: Partial<
Record<
AnalysisOperation,
(
parameters: Readonly<Record<string, unknown>>,
) => Result<AnalysisExecution, AnalysisError>
>
> = {},
uiGraph: z.input<typeof nativeInvestigationGraphSchema> = graph,
) => ({
execute: async (
operation: AnalysisOperation,
parameters: Readonly<Record<string, unknown>>,
): Promise<Result<AnalysisExecution, AnalysisError>> => {
const override = overrides[operation];
if (override !== undefined) return override(parameters);
switch (operation) {
case "decode_interface_builder":
return execution(operation, {
target_sha256: target,
documents: [
{
relative_path: "Base.lproj/Main.nib",
archive_sha256: "b".repeat(64),
document_kind: "nib",
object_count: 4,
connection_count: 3,
hierarchy_complete: true,
},
],
graph: uiGraph,
limitations: [],
});
case "list_names":
return execution(operation, [
{ address: "0x1000", name: "-[BuildViewController buildTapped:]" },
]);
case "procedure_callees":
return execution(
operation,
parameters.procedure === "0x1000" ? ["0x2000"] : [],
);
default:
throw new Error(`Unexpected provider operation: ${operation}`);
}
},
});
describe("native UI action trace", () => {
it("builds the evidence path from the active app and native provider", async () => {
const tools = new EnhancedTools(testAnalysis());
const result = await tools.execute("trace_native_ui_action", {
action: "buildTapped:",
});
expect(result.ok).toBe(true);
if (!result.ok) return;
const trace = nativeInvestigationTraceSchema.parse(result.value);
expect(trace.start).toBe("action");
expect(trace.nodes.map(({ id }) => id)).toContain("native:function:0x1000");
expect(trace.nodes.map(({ id }) => id)).toContain("native:function:0x2000");
expect(trace.edges).toContainEqual(
expect.objectContaining({
relation: "objc_dispatch",
resolution: "inferred",
}),
);
expect(trace.edges).toContainEqual(
expect.objectContaining({
relation: "direct_call",
to: "native:function:0x2000",
}),
);
expect(trace.coverage).toContainEqual(
expect.objectContaining({
facet: "cross_function_value_flow",
status: "unsupported",
}),
);
});
});
describe("bounded native UI tracing", () => {
it("continues handler traversal from its own depth when another UI branch is deeper", async () => {
const deepGraph = {
...graph,
nodes: [
...graph.nodes,
{
id: "view",
kind: "view" as const,
name: "Container",
location: null,
attributes: {},
evidence,
},
{
id: "nested-view",
kind: "view" as const,
name: "Nested container",
location: null,
attributes: {},
evidence,
},
],
edges: [
...graph.edges,
{
id: "controller-view",
from: "controller",
to: "view",
relation: "contains" as const,
resolution: "observed" as const,
evidence,
limitations: [],
},
{
id: "view-nested-view",
from: "view",
to: "nested-view",
relation: "contains" as const,
resolution: "observed" as const,
evidence,
limitations: [],
},
],
};
const result = await new EnhancedTools(testAnalysis({}, deepGraph)).execute(
"trace_native_ui_action",
{ action: "buildTapped:", max_depth: 3 },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(
nativeInvestigationTraceSchema
.parse(result.value)
.nodes.map(({ id }) => id),
).toContain("native:function:0x2000");
});
it("returns a typed input error for malformed direct metadata requests", async () => {
const result = await new EnhancedTools(testAnalysis()).execute(
"inspect_native_dispatch_metadata",
{ max_records: 0 },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
});
it("binds dispatch metadata to the active target digest", async () => {
const result = await new EnhancedTools(testAnalysis()).execute(
"inspect_native_dispatch_metadata",
{ max_records: 10 },
);
expect(result).toMatchObject({
ok: true,
value: { target_sha256: target },
});
});
});
describe("native UI query outcomes", () => {
it("resolves a control object ID through its authored action edge", async () => {
const tools = new EnhancedTools(testAnalysis());
const result = await tools.execute("trace_native_ui_action", {
action: "button",
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value).toMatchObject({ start: "action" });
});
it("rejects UI and native observations with different target identities", async () => {
const tools = new EnhancedTools(
testAnalysis({
list_names: () => execution("list_names", [], "c".repeat(64)),
}),
);
const result = await tools.execute("trace_native_ui_action", {
action: "buildTapped:",
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
operation: "decode_interface_builder",
},
});
});
it("returns candidates and a reason for an ambiguous selector", async () => {
const duplicateGraph = {
...graph,
nodes: [
...graph.nodes,
{
...graph.nodes[1],
id: "second-action",
},
],
};
const tools = new EnhancedTools(
testAnalysis({
decode_interface_builder: () =>
execution("decode_interface_builder", {
target_sha256: target,
documents: [],
graph: duplicateGraph,
limitations: [],
}),
}),
);
const result = await tools.execute("trace_native_ui_action", {
action: "buildTapped:",
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value).toMatchObject({
reason: "action_selector_matches_multiple_ui_connections",
nodes: [{ id: "action" }, { id: "second-action" }],
});
});
it("retains decoder truncation coverage when the action is absent", async () => {
const boundedGraph = {
...graph,
coverage: [
{
facet: "objects:Main.nib",
status: "partial" as const,
reason: "object_limit_reached",
examined: 2,
omitted: 1,
},
],
truncated: true,
};
const result = await new EnhancedTools(
testAnalysis({}, boundedGraph),
).execute("trace_native_ui_action", { action: "missing-selector" });
expect(result).toMatchObject({ ok: true, value: { truncated: true } });
if (!result.ok) return;
expect(result.value).toHaveProperty("coverage");
expect(result.value).toMatchObject({
coverage: expect.arrayContaining([
expect.objectContaining({
facet: "objects:Main.nib",
status: "partial",
reason: "object_limit_reached",
}),
]),
});
});
it("returns cancellation instead of a successful trace during callee expansion", async () => {
const result = await new EnhancedTools(
testAnalysis({
procedure_callees: () =>
err(new AnalysisCancelledError("procedure_callees")),
}),
).execute("trace_native_ui_action", { action: "buildTapped:" });
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", operation: "procedure_callees" },
});
});
it("reports only callees left unprocessed by the edge limit", async () => {
const result = await new EnhancedTools(
testAnalysis({
procedure_callees: (parameters) =>
execution(
"procedure_callees",
parameters.procedure === "0x1000"
? ["0x2000", "0x2001", "0x2002"]
: [],
),
}),
).execute("trace_native_ui_action", {
action: "buildTapped:",
max_depth: 4,
max_edges: 5,
});
expect(result).toMatchObject({ ok: true });
if (!result.ok) return;
expect(result.value).toMatchObject({
coverage: expect.arrayContaining([
expect.objectContaining({
facet: "direct_native_calls",
status: "partial",
omitted: 1,
}),
]),
});
});
});
describe("native UI trace boundaries", () => {
it("retains unresolved dispatch evidence during callee expansion", async () => {
const result = await new EnhancedTools(
testAnalysis({ list_names: () => execution("list_names", []) }),
).execute("trace_native_ui_action", { action: "buildTapped:" });
expect(result).toMatchObject({ ok: true });
if (!result.ok) return;
expect(result.value).toMatchObject({
unresolved: [
expect.objectContaining({
relation: "objc_dispatch",
resolution: "unresolved",
}),
],
});
});
it("returns cancellation when archive decoding is cancelled", async () => {
const result = await new EnhancedTools(
testAnalysis({
decode_interface_builder: () =>
err(new AnalysisCancelledError("decode_interface_builder")),
}),
).execute("trace_native_ui_action", { action: "buildTapped:" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
operation: "decode_interface_builder",
},
});
});
it("matches handlers after the dispatch inventory's former default limit", async () => {
const names = Array.from({ length: 5_000 }, (_, index) => ({
address: `0x${(index + 1).toString(16)}`,
name: `unrelated_symbol_${index}`,
}));
names.push({
address: "0x2000",
name: "-[BuildViewController buildTapped:]",
});
const result = await new EnhancedTools(
testAnalysis({ list_names: () => execution("list_names", names) }),
).execute("trace_native_ui_action", { action: "buildTapped:" });
expect(result).toMatchObject({ ok: true });
if (!result.ok) return;
expect(result.value).toMatchObject({
nodes: expect.arrayContaining([
expect.objectContaining({ id: "native:function:0x2000" }),
]),
});
});
it("counts edges removed with nodes in bounded graph coverage", async () => {
const result = await new EnhancedTools(testAnalysis()).execute(
"trace_native_ui_action",
{ action: "missing-selector", max_nodes: 1 },
);
expect(result).toMatchObject({ ok: true });
if (!result.ok) return;
expect(result.value).toMatchObject({
coverage: expect.arrayContaining([
expect.objectContaining({
facet: "interface_builder_graph",
status: "partial",
omitted: 8,
}),
]),
});
});
});
+71
View File
@@ -27,6 +27,11 @@ import {
discoverObjcClasses,
discoverObjcProtocols,
} from "../domain/symbolAnalysis.js";
import {
inspectNativeDispatchMetadata,
nativeDispatchMetadataResultSchema,
} from "../domain/objcSwiftMetadata.js";
import { traceNativeUiAction } from "./NativeUiActionTrace.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import {
@@ -59,9 +64,25 @@ export class EnhancedTools {
name === "trace_call_path"
)
return this.#executeTracing(name, input, signal);
if (name === "trace_native_ui_action") {
const parsed =
enhancedInputSchemas.trace_native_ui_action.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidEnhancedInput(name, parsed.error);
}
if (name === "analyze_function" || name === "inspect_native_api")
return this.#executeFunctionAnalysis(name, input, signal);
switch (name) {
case "inspect_native_dispatch_metadata": {
const parsed =
enhancedInputSchemas.inspect_native_dispatch_metadata.safeParse(
input,
);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidEnhancedInput(name, parsed.error);
}
case "get_objc_classes": {
const parsed = enhancedInputSchemas.get_objc_classes.safeParse(input);
return parsed.success
@@ -110,6 +131,11 @@ export class EnhancedTools {
signal?: AbortSignal,
): EnhancedResult {
switch (call.name) {
case "inspect_native_dispatch_metadata":
return this.#inspectNativeDispatchMetadata(
call.input.max_records,
signal,
);
case "get_objc_classes":
return this.#objcClasses(call.input.pattern, signal);
case "get_objc_protocols":
@@ -151,6 +177,9 @@ export class EnhancedTools {
call.input,
signal,
);
case "trace_native_ui_action": {
return traceNativeUiAction(this.analysis, call.input, signal);
}
}
}
@@ -217,6 +246,48 @@ export class EnhancedTools {
return names.ok ? ok(discoverObjcClasses(names.value, pattern)) : names;
}
async #inspectNativeDispatchMetadata(
maxRecords: number,
signal?: AbortSignal,
): EnhancedResult {
const execution = await this.analysis.execute(
"list_names",
{},
signal === undefined ? {} : { signal },
);
if (!execution.ok) return err(execution.error);
const names = z
.array(
z.union([
z.strictObject({ address: z.string(), value: z.string() }),
z.strictObject({ address: z.string(), name: z.string() }),
]),
)
.safeParse(execution.value.result);
if (!names.success)
return err(
new AnalysisOutputError(
"list_names",
"provider returned an invalid inventory",
),
);
return ok(
nativeDispatchMetadataResultSchema.parse({
target_sha256: execution.value.subject?.sha256 ?? null,
provider: execution.value.provider,
analysis_profile_digest:
execution.value.analysisProfile?.digest ?? null,
result: inspectNativeDispatchMetadata(
names.data.map((entry) => ({
address: entry.address,
name: "value" in entry ? entry.value : entry.name,
})),
maxRecords,
),
}),
);
}
async #objcProtocols(signal?: AbortSignal): EnhancedResult {
const names = await this.#allAddressed("list_names", signal);
return names.ok ? ok(discoverObjcProtocols(names.value)) : names;
@@ -0,0 +1,189 @@
import { existsSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { buildBinary } from "plist";
import { afterEach, describe, expect, it } from "vitest";
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
describe("compiled Interface Builder bundle reader", () => {
it("reads nib plist archives without following symlinks and reports provenance", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-ib-test-"));
roots.push(root);
const bundle = join(root, "Example.app");
const nib = join(
bundle,
"Contents",
"Resources",
"Main.storyboardc",
"Main.nib",
);
await mkdir(nib, { recursive: true });
await writeFile(
join(nib, "objects.nib"),
buildBinary({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: [
"$null",
{ $class: { UID: 2 }, title: "Build" },
{
$classname: "UIButton",
$classes: ["UIButton", "UIControl", "UIView", "NSObject"],
},
],
$top: { root: { UID: 1 } },
}),
);
await writeFile(
join(bundle, "Contents", "Resources", "Main.storyboardc", "Info.plist"),
'<?xml version="1.0"?><plist><dict><key>notAnArchive</key><string>scene-index</string></dict></plist>',
);
await mkdir(join(bundle, "Contents", "Resources", "outside.nib"), {
recursive: true,
});
await writeFile(
join(bundle, "Contents", "Resources", "outside.nib", "not-nib.txt"),
"ignored",
);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "b".repeat(64),
});
expect(analysis.documents).toMatchObject([
{
relative_path:
"Contents/Resources/Main.storyboardc/Main.nib/objects.nib",
document_kind: "storyboard_scene",
object_count: 1,
},
]);
expect(analysis.documents).toHaveLength(1);
expect(analysis.graph.target_sha256).toBe("b".repeat(64));
expect(analysis.graph.nodes.some(({ name }) => name === "Build")).toBe(
true,
);
});
it("honors cancellation during directory traversal", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-ib-test-"));
roots.push(root);
const controller = new AbortController();
controller.abort();
await expect(
analyzeInterfaceBuilderBundle({
bundlePath: root,
targetSha256: "c".repeat(64),
signal: controller.signal,
}),
).rejects.toMatchObject({ reason: "cancelled" });
});
});
describe("bounded Interface Builder archive decoding", () => {
it("counts malformed archives against the document limit", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-ib-test-"));
roots.push(root);
const bundle = join(root, "Example.app");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
await writeFile(join(resources, "BadOne.nib"), Buffer.from("bplist00bad"));
await writeFile(join(resources, "BadTwo.nib"), Buffer.from("bplist00bad"));
const result = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "e".repeat(64),
limits: { max_documents: 1 },
});
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "archive_decode",
status: "partial",
examined: 1,
omitted: 1,
}),
);
expect(result.graph.truncated).toBe(true);
});
it.skipIf(process.platform !== "darwin" || !existsSync("/usr/bin/ibtool"))(
"decodes an Xcode-compiled storyboard NIB and recovers its UI routes",
async () => {
const root = await mkdtemp(join(tmpdir(), "rea-ib-compiled-test-"));
roots.push(root);
const bundle = join(root, "Example.app");
const resources = join(bundle, "Contents", "Resources");
const source = join(
process.cwd(),
"tests",
"fixtures",
"interface-builder",
"MacFixture.storyboard",
);
await mkdir(resources, { recursive: true });
execFileSync("/usr/bin/ibtool", [
"--compile",
join(resources, "MacFixture.storyboardc"),
source,
]);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "d".repeat(64),
});
const names = analysis.graph.nodes.map(({ name }) => name);
expect(names).toContain("BuildViewController");
expect(names).toContain("Button");
expect(names).toContain("buildTapped:");
expect(
analysis.graph.edges.some(
({ relation }) => relation === "target_action",
),
).toBe(true);
const action = analysis.graph.nodes.find(
({ kind, name }) => kind === "action" && name === "buildTapped:",
);
expect(action).toBeDefined();
const actionSource = analysis.graph.edges.find(
({ from, relation, to }) =>
relation === "target_action" &&
to === action?.id &&
analysis.graph.nodes.find(({ id }) => id === from)?.kind ===
"control",
);
expect(actionSource).toBeDefined();
expect(
analysis.graph.edges.some(
({ from, relation, to }) =>
from === action?.id &&
relation === "target_action" &&
to !== null &&
analysis.graph.nodes.find(({ id }) => id === to)?.kind ===
"placeholder",
),
).toBe(true);
expect(
analysis.graph.edges.some(({ relation }) => relation === "contains"),
).toBe(true);
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "archive_decode",
status: "complete",
}),
);
},
);
});
+306
View File
@@ -0,0 +1,306 @@
import { createHash } from "node:crypto";
import { parse, parseBinary } from "plist";
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import {
decodeNibArchive,
type NibArchiveDocument,
} from "../artifacts/NibArchive.js";
import type { ArtifactEntry } from "../artifacts/ArtifactReader.js";
import {
buildInterfaceBuilderAnalysis,
interfaceBuilderLimitsSchema,
type InterfaceBuilderDocumentInput,
} from "../domain/interfaceBuilderGraph.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
const MAX_DOCUMENT_BYTES = 64 * 1024 * 1024;
/** Decode compiled Interface Builder archives from a local app bundle. */
export const analyzeInterfaceBuilderBundle = async (input: {
readonly bundlePath: string;
readonly targetSha256: string;
readonly limits?: unknown;
readonly signal?: AbortSignal;
}) => {
const limits = interfaceBuilderLimitsSchema.parse(input.limits ?? {});
const reader = new DirectoryArtifactReader(input.bundlePath);
const documents: InterfaceBuilderDocumentInput[] = [];
const invalid: string[] = [];
let omitted = 0;
let attempted = 0;
try {
for await (const entry of reader.entries(input.signal)) {
if (entry.kind !== "file" || !isInterfaceBuilderArchive(entry.path))
continue;
if (attempted >= limits.max_documents) {
omitted += 1;
continue;
}
attempted += 1;
try {
const bytes = await readEntry(reader, entry, input.signal);
const raw =
bytes.subarray(0, 10).toString("ascii") === "NIBArchive"
? projectNibArchive(decodeNibArchive(bytes))
: decodePlist(bytes);
const documentHash = createHash("sha256").update(bytes).digest("hex");
documents.push({
relativePath: entry.path,
archiveSha256: documentHash,
documentKind: entry.path.includes(".storyboardc/")
? "storyboard_scene"
: "nib",
raw,
});
} catch (cause: unknown) {
if (input.signal?.aborted === true) throw cause;
invalid.push(
`${entry.path}: ${cause instanceof Error ? cause.message : "archive decode failed"}`,
);
}
}
} finally {
await reader.close();
}
const result = buildInterfaceBuilderAnalysis({
targetSha256: input.targetSha256,
toolVersion: "rea-interface-builder/1",
documents,
limits,
});
return {
...result,
graph: {
...result.graph,
coverage: [
...result.graph.coverage,
{
facet: "archive_decode",
status:
invalid.length > 0 ? ("partial" as const) : ("complete" as const),
reason: invalid.length > 0 ? "one_or_more_archives_invalid" : null,
examined: attempted,
omitted,
},
],
truncated: result.graph.truncated || omitted > 0 || invalid.length > 0,
},
limitations: [
...result.limitations,
"Compiled Interface Builder archives are private serialized object graphs. The decoder reports only recognized keyed-archive objects and connections; unrecognized object classes and fields remain unknown.",
...(invalid.length === 0
? []
: [
`Some Interface Builder archives could not be decoded: ${invalid.slice(0, 16).join("; ")}`,
]),
],
};
};
/** Project decoded NIB records into the same bounded graph input as ibtool. */
const projectNibArchive = (archive: NibArchiveDocument): JsonValue => {
const byId = new Map(archive.objects.map((object) => [object.id, object]));
const dereference = (value: JsonValue | undefined): JsonValue | undefined => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return value;
const ref = value.$nib_object_ref;
if (typeof ref !== "number") return value;
const target = byId.get(ref);
if (target === undefined) return undefined;
if (target.class_name.replace(/\0+$/u, "") === "NSString") {
const data = target.values["NS.bytes"];
if (typeof data === "object" && data !== null && !Array.isArray(data)) {
const encoded = data.$nib_data_base64;
if (typeof encoded === "string")
return Buffer.from(encoded, "base64").toString("utf8");
}
}
return { objectID: String(ref) };
};
const referencedString = (value: JsonValue | undefined): string | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
const ref = value.$nib_object_ref;
if (typeof ref !== "number") return null;
const target = byId.get(ref);
const data = target?.values["NS.bytes"];
if (target?.class_name.replace(/\0+$/u, "") !== "NSString") return null;
if (typeof data !== "object" || data === null || Array.isArray(data))
return null;
const encoded = data.$nib_data_base64;
return typeof encoded === "string"
? Buffer.from(encoded, "base64").toString("utf8")
: null;
};
const runtimeClass = (objectId: number): string | null => {
const object = byId.get(objectId);
if (object === undefined) return null;
const storedClass = object.class_name.replace(/\0+$/u, "");
return storedClass === "NSClassSwapper"
? (referencedString(object.values.NSClassName) ?? storedClass)
: storedClass;
};
const objects = Object.fromEntries(
archive.objects
.filter((object) => {
const name = runtimeClass(object.id) ?? "";
return !/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector)$/u.test(
name,
);
})
.map((object) => {
const className =
runtimeClass(object.id) ?? object.class_name.replace(/\0+$/u, "");
const strings = Object.entries(object.values).flatMap(
([key, value]) => {
const resolved = dereference(value);
return typeof resolved === "string" ? [[key, resolved]] : [];
},
);
const name =
strings.find(([key]) =>
/(?:title|label|identifier|accessibility|name|contents)/iu.test(
key ?? "",
),
)?.[1] ?? className;
return [
String(object.id),
{
customClass: className,
label: name,
objectID: String(object.id),
nibValues: Object.fromEntries(
Object.entries(object.values).map(([key, value]) => [
key,
dereference(value) ?? null,
]),
),
},
];
}),
);
const connections: Record<string, JsonValue[]> = {};
const hierarchy: JsonValue[] = [];
const reference = (value: JsonValue | undefined): number | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
return typeof value.$nib_object_ref === "number"
? value.$nib_object_ref
: null;
};
for (const object of archive.objects) {
const className = object.class_name.replace(/\0+$/u, "");
const source = reference(object.values.NSSource);
const destination = reference(object.values.NSDestination);
if (className.includes("Connector") && source !== null) {
const label = referencedString(object.values.NSLabel);
const type = className.includes("Outlet")
? "outlet"
: className.includes("Control")
? "action"
: className;
const controlAction = className.includes("Control");
const connectionSource = controlAction ? destination : source;
const connectionDestination = controlAction ? source : destination;
if (connectionSource === null) continue;
(connections[String(connectionSource)] ??= []).push({
type,
"destination-id":
connectionDestination === null ? null : String(connectionDestination),
label,
source_id: String(connectionSource),
archive_object_id: String(object.id),
});
}
}
const hierarchyFor = (
objectId: number,
seen: Set<number>,
depth: number,
): JsonValue | null => {
if (depth > 32 || seen.has(objectId)) return null;
const object = byId.get(objectId);
if (object === undefined) return null;
const nextSeen = new Set(seen).add(objectId);
const children: JsonValue[] = [];
for (const [key, value] of Object.entries(object.values)) {
if (!/(?:subviews|contentview|childviewcontrollers|view)$/iu.test(key))
continue;
const direct = reference(value);
if (direct === null) continue;
const target = byId.get(direct);
if (target === undefined) continue;
if (/array|set/iu.test(target.class_name)) {
for (const candidate of Object.values(target.values)) {
const child = reference(candidate);
const nested =
child === null ? null : hierarchyFor(child, nextSeen, depth + 1);
if (nested !== null) children.push(nested);
}
} else {
const nested = hierarchyFor(direct, nextSeen, depth + 1);
if (nested !== null) children.push(nested);
}
}
return { objectID: String(objectId), children };
};
const ibData = archive.objects.find(
({ class_name }) => class_name.replace(/\0+$/u, "") === "NSIBObjectData",
);
const rootId = reference(ibData?.values.NSRoot);
const hierarchyRoots = rootId === null ? [] : [rootId];
for (const hierarchyRoot of hierarchyRoots) {
const root = hierarchyFor(hierarchyRoot, new Set(), 0);
if (root !== null) hierarchy.push(root);
}
return jsonValueSchema.parse({
"com.apple.ibtool.document.objects": objects,
"com.apple.ibtool.document.connections": connections,
"com.apple.ibtool.document.hierarchy": hierarchy,
"com.apple.ibtool.document.classes": Object.fromEntries(
archive.classes.map((name) => [name.replace(/\0+$/u, ""), {}]),
),
});
};
const isInterfaceBuilderArchive = (path: string): boolean => {
const lower = path.toLowerCase();
return lower.endsWith(".nib") || lower.endsWith("/objects.nib");
};
const readEntry = async (
reader: DirectoryArtifactReader,
entry: ArtifactEntry,
signal?: AbortSignal,
): Promise<Buffer> => {
if (entry.declaredSize !== null && entry.declaredSize > MAX_DOCUMENT_BYTES)
throw new RangeError(
"archive exceeds the 64 MiB per-document decode limit",
);
const stream = await reader.open(entry, signal);
const chunks: Buffer[] = [];
let length = 0;
for await (const chunk of stream) {
const bytes = Buffer.isBuffer(chunk)
? chunk
: Buffer.from(chunk as Uint8Array);
length += bytes.length;
if (length > MAX_DOCUMENT_BYTES) {
stream.destroy();
throw new RangeError(
"archive exceeded the 64 MiB per-document decode limit",
);
}
chunks.push(bytes);
}
return Buffer.concat(chunks, length);
};
const decodePlist = (bytes: Buffer): JsonValue => {
const parsed =
bytes.subarray(0, 8).toString("ascii") === "bplist00"
? parseBinary(bytes)
: parse(bytes.toString("utf8"));
return jsonValueSchema.parse(parsed);
};
+22 -1
View File
@@ -21,7 +21,6 @@ describe("native API inspection", () => {
mappings: [
{
target_address: "0x401020",
data_addresses: ["0x403000"],
},
],
},
@@ -60,6 +59,28 @@ describe("native API inspection", () => {
});
});
it("reports missing jump-table targets as an explicit unknown", () => {
const value = ghidraFunctionDossier();
const dossier = functionDossierSchema.parse(value);
const boundary = dossier.native_api;
if (boundary?.available !== true)
throw new TypeError("Ghidra native API fixture is unavailable");
const table = boundary.jump_tables[0];
if (table === undefined)
throw new TypeError("Ghidra jump-table fixture is unavailable");
const incomplete = functionDossierSchema.parse({
...dossier,
native_api: {
...boundary,
jump_tables: [{ ...table, mappings: [] }],
},
});
expect(projectNativeApiInspection(incomplete).residual_unknowns).toContain(
"Which case values and targets belong to the dispatch at 0x401010?",
);
});
it("rejects boundary types placed in the wrong ABI role", () => {
const boundary = functionDossierSchema.parse(
ghidraFunctionDossier(),
+4
View File
@@ -72,6 +72,10 @@ const availableResidualUnknowns = (
): readonly string[] => {
const unknowns: string[] = [];
for (const table of boundary.jump_tables) {
if (table.mappings.length === 0)
unknowns.push(
`Which case values and targets belong to the dispatch at ${table.dispatch_address}?`,
);
if (table.data_sources.length === 0)
unknowns.push(
`What backing data address produced the jump table dispatched at ${table.dispatch_address}?`,
+532
View File
@@ -0,0 +1,532 @@
import { z } from "zod";
import type { AnalysisOperationPort } from "./AnalysisProvider.js";
import type { EnhancedResult } from "./EnhancedToolTypes.js";
import type { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import { interfaceBuilderAnalysisSchema } from "../domain/interfaceBuilderGraph.js";
import {
nativeInvestigationGraphSchema,
nativeInvestigationTraceSchema,
traceNativeInvestigationGraph,
joinInterfaceBuilderDispatch,
} from "../domain/nativeInvestigationGraph.js";
import {
inspectNativeDispatchMetadata,
nativeDispatchMetadataResultSchema,
} from "../domain/objcSwiftMetadata.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { parseRelatedAddresses } from "../domain/hopperValues.js";
import { err, ok } from "../domain/result.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
projectAnalysisError,
} from "../domain/errors.js";
type Input = z.output<typeof enhancedInputSchemas.trace_native_ui_action>;
const nativeNameSchema = z.array(
z.union([
z.strictObject({ address: z.string(), name: z.string() }),
z.strictObject({ address: z.string(), value: z.string() }),
]),
);
/** Build a UI-to-code trace from the active app and selected native provider. */
export const traceNativeUiAction = async (
analysis: AnalysisOperationPort,
input: Input,
signal?: AbortSignal,
): EnhancedResult => {
const [uiExecution, namesExecution] = await Promise.all([
analysis.execute(
"decode_interface_builder",
{
max_documents: 64,
max_objects: input.max_nodes,
max_connections: input.max_edges,
},
signal === undefined ? {} : { signal },
),
analysis.execute("list_names", {}, signal === undefined ? {} : { signal }),
]);
if (!uiExecution.ok && uiExecution.error._tag === "AnalysisCancelledError")
return err(new AnalysisCancelledError("decode_interface_builder"));
if (!namesExecution.ok) return err(namesExecution.error);
const parsedNames = nativeNameSchema.safeParse(namesExecution.value.result);
if (!parsedNames.success)
return err(
new AnalysisOutputError(
"list_names",
"provider returned an invalid name inventory",
),
);
const targetSha256 = namesExecution.value.subject?.sha256;
if (targetSha256 === undefined)
return err(
new AnalysisOutputError(
"list_names",
"provider did not bind the name inventory to a target SHA-256",
),
);
const metadata = nativeDispatchMetadataResultSchema.parse({
target_sha256: targetSha256,
provider: namesExecution.value.provider,
analysis_profile_digest:
namesExecution.value.analysisProfile?.digest ?? null,
result: inspectNativeDispatchMetadata(
parsedNames.data.map((entry) => ({
address: entry.address,
name: "name" in entry ? entry.name : entry.value,
})),
parsedNames.data.length,
),
});
let graph = emptyGraph(targetSha256, namesExecution.value.provider);
const coverage = [];
if (uiExecution.ok) {
const decoded = interfaceBuilderAnalysisSchema.safeParse(
uiExecution.value.result,
);
if (!decoded.success)
return err(
new AnalysisOutputError(
"decode_interface_builder",
"artifact provider returned an invalid interface graph",
),
);
if (decoded.data.target_sha256 !== targetSha256)
return err(
new AnalysisOutputError(
"decode_interface_builder",
"UI and native provider results refer to different target SHA-256 values",
),
);
graph = joinInterfaceBuilderDispatch(decoded.data.graph, metadata.result);
coverage.push({
facet: "interface_builder_archives",
status: decoded.data.documents.length > 0 ? "complete" : "unsupported",
reason:
decoded.data.documents.length > 0
? null
: "no_compiled_interface_builder_archives_found",
examined: decoded.data.documents.length,
omitted: 0,
});
const bounded = boundUiGraph(graph, input.max_nodes, input.max_edges);
graph = bounded.graph;
if (bounded.truncated)
coverage.push({
facet: "interface_builder_graph",
status: "partial",
reason: "native_trace_output_bounds_reached",
examined:
decoded.data.graph.nodes.length + decoded.data.graph.edges.length,
omitted: bounded.omitted,
});
} else {
coverage.push({
facet: "interface_builder_archives",
status: "unsupported",
reason: projectAnalysisError(uiExecution.error).message,
examined: 0,
omitted: 0,
});
}
const selected = resolveUiAction(graph, input.action);
if (selected.nodeId === null) {
coverage.push(...graph.coverage);
const trace = {
target_sha256: graph.target_sha256,
provider: graph.provider,
start: input.action,
direction: "forward" as const,
nodes: selected.candidates,
edges: [],
unresolved: [],
reached_depth: 0,
truncated: graph.truncated,
reason: selected.reason,
coverage,
limitations: [
"The query did not identify one unique authored UI action; no handler path was inferred.",
],
};
return ok(
jsonValueSchema.parse(nativeInvestigationTraceSchema.parse(trace)),
);
}
const initial = traceNativeInvestigationGraph(graph, {
start: selected.nodeId,
direction: "forward",
limits: {
max_depth: input.max_depth,
max_nodes: input.max_nodes,
max_edges: input.max_edges,
},
});
const expanded = await addDirectCallees({
analysis,
graph,
initial,
input,
targetSha256,
signal,
});
if (expanded.error !== undefined) return err(expanded.error);
coverage.push({
facet: "direct_native_calls",
status: "partial",
reason: "resolved_direct_calls_do_not_cover_all_indirect_dispatch",
examined: expanded.examined,
omitted: expanded.omitted,
});
coverage.push({
facet: "cross_function_value_flow",
status: "unsupported",
reason:
"call edges identify control-flow candidates but do not recover argument, return, or shared-memory value relationships",
examined: 0,
omitted: 0,
});
const finalGraph = nativeInvestigationGraphSchema.parse({
...graph,
nodes: expanded.nodes,
edges: expanded.edges,
coverage: [...graph.coverage, ...coverage],
truncated: graph.truncated || expanded.truncated,
});
const trace = traceNativeInvestigationGraph(finalGraph, {
start: selected.nodeId,
direction: "forward",
limits: {
max_depth: input.max_depth,
max_nodes: input.max_nodes,
max_edges: input.max_edges,
},
});
return ok(
jsonValueSchema.parse(
nativeInvestigationTraceSchema.parse({
...trace,
truncated: trace.truncated || expanded.truncated || graph.truncated,
reason:
expanded.truncated && trace.reason === null
? "native_call_traversal_bound_reached"
: graph.truncated && trace.reason === null
? "native_trace_output_bound_reached"
: trace.reason,
}),
),
);
};
const emptyGraph = (
targetSha256: string,
provider: {
readonly id: string;
readonly version: string | null;
},
) =>
nativeInvestigationGraphSchema.parse({
target_sha256: targetSha256,
provider: {
id: provider.id,
version: provider.version,
tool_version: "rea-native-ui-trace/1",
},
nodes: [],
edges: [],
coverage: [],
truncated: false,
});
const boundUiGraph = (
graph: z.infer<typeof nativeInvestigationGraphSchema>,
maxNodes: number,
maxEdges: number,
): {
readonly graph: z.infer<typeof nativeInvestigationGraphSchema>;
readonly truncated: boolean;
readonly omitted: number;
} => {
const nodes = graph.nodes.slice(0, maxNodes);
const nodeIds = new Set(nodes.map(({ id }) => id));
const eligibleEdges = graph.edges.filter(
(edge) =>
nodeIds.has(edge.from) && (edge.to === null || nodeIds.has(edge.to)),
);
const edges = eligibleEdges.slice(0, maxEdges);
const omitted =
graph.nodes.length - nodes.length + graph.edges.length - edges.length;
const truncated = omitted > 0;
return {
graph: nativeInvestigationGraphSchema.parse({
...graph,
nodes,
edges,
truncated: graph.truncated || truncated,
}),
truncated,
omitted,
};
};
const resolveUiAction = (
graph: z.infer<typeof nativeInvestigationGraphSchema>,
query: string,
): {
readonly nodeId: string | null;
readonly candidates: z.infer<typeof nativeInvestigationGraphSchema>["nodes"];
readonly reason: string | null;
} => {
const exactId = graph.nodes.find((node) => node.id === query);
if (exactId?.kind === "action")
return { nodeId: exactId.id, candidates: [], reason: null };
const actions = graph.nodes.filter(
(node) =>
node.kind === "action" &&
(node.name === query || node.attributes.selector === query),
);
if (actions.length === 1)
return { nodeId: actions[0]?.id ?? null, candidates: [], reason: null };
if (actions.length > 1)
return {
nodeId: null,
candidates: actions,
reason: "action_selector_matches_multiple_ui_connections",
};
const objectMatches = graph.nodes.filter(
(node) =>
["control", "view", "view_controller", "scene"].includes(node.kind) &&
(node.id === query ||
node.attributes.interface_builder_object_id === query ||
node.id.endsWith(`:object:${query}`)),
);
const actionIds = new Set(
graph.edges.flatMap((edge) =>
edge.resolution === "observed" &&
edge.relation === "target_action" &&
objectMatches.some(({ id }) => edge.from === id) &&
graph.nodes.some(({ id, kind }) => id === edge.to && kind === "action")
? [edge.to]
: [],
),
);
if (actionIds.size === 1)
return { nodeId: [...actionIds][0] ?? null, candidates: [], reason: null };
if (actionIds.size > 1)
return {
nodeId: null,
candidates: graph.nodes.filter(({ id }) => actionIds.has(id)),
reason: "interface_object_has_multiple_action_connections",
};
return {
nodeId: null,
candidates: [],
reason: "ui_action_or_object_not_found",
};
};
const addDirectCallees = async (input: {
readonly analysis: AnalysisOperationPort;
readonly graph: z.infer<typeof nativeInvestigationGraphSchema>;
readonly initial: z.infer<typeof nativeInvestigationTraceSchema>;
readonly input: Input;
readonly targetSha256: string;
readonly signal: AbortSignal | undefined;
}) => {
const nodes = new Map(input.initial.nodes.map((node) => [node.id, node]));
const edges = new Map(
[...input.initial.edges, ...input.initial.unresolved].map((edge) => [
edge.id,
edge,
]),
);
const addressNames = new Map<string, string>();
const depthByNode = graphNodeDepths(
input.initial.start,
input.initial.nodes,
input.initial.edges,
);
for (const node of nodes.values()) {
if (node.kind === "function" && node.location?.address !== null)
addressNames.set(node.location?.address ?? "", node.name);
}
const queue = input.initial.nodes.flatMap((node) =>
node.kind === "function" && node.location?.address != null
? [
{
node,
address: node.location.address,
depth: depthByNode.get(node.id) ?? input.initial.reached_depth,
},
]
: [],
);
const visited = new Set<string>();
let queueIndex = 0;
let examined = 0;
let omitted = 0;
let truncated = false;
while (queueIndex < queue.length) {
const current = queue[queueIndex++];
if (current === undefined || visited.has(current.address)) continue;
visited.add(current.address);
if (current.depth >= input.input.max_depth) {
truncated = true;
omitted += 1;
continue;
}
if (nodes.size >= input.input.max_nodes) {
truncated = true;
omitted += queue.length - queueIndex + 1;
break;
}
const execution = await input.analysis.execute(
"procedure_callees",
{ procedure: current.address },
input.signal === undefined ? {} : { signal: input.signal },
);
examined += 1;
if (!execution.ok) {
if (execution.error._tag === "AnalysisCancelledError")
return { error: execution.error };
const id = `unknown-callees:${current.address}`;
edges.set(id, {
id,
from: current.node.id,
to: null,
relation: "direct_call",
resolution: "unresolved",
reason: projectAnalysisError(execution.error).message,
evidence: [],
limitations: [
"The provider could not enumerate resolved direct callees.",
],
});
continue;
}
const related = parseRelatedAddresses(execution.value.result, "callees");
if (!related.ok) {
const id = `unknown-callees:${current.address}`;
edges.set(id, {
id,
from: current.node.id,
to: null,
relation: "direct_call",
resolution: "unresolved",
reason: "provider_returned_unreadable_callee_relationships",
evidence: [],
limitations: [
"The provider result could not be normalized into callee addresses.",
],
});
continue;
}
for (const [index, address] of related.value.entries()) {
if (edges.size >= input.input.max_edges) {
truncated = true;
omitted += related.value.length - index;
break;
}
const targetId = `native:function:${address}`;
const evidence = [
{
kind: "reference" as const,
description: `${execution.value.provider.name} resolved a direct callee from ${current.address} to ${address}`,
location: { address: current.address, file_offset: null },
artifact_path: null,
artifact_sha256: input.targetSha256,
},
];
if (!nodes.has(targetId)) {
if (nodes.size >= input.input.max_nodes) {
truncated = true;
omitted += 1;
const id = `unknown-node-bound:${current.address}:${address}`;
edges.set(id, {
id,
from: current.node.id,
to: null,
relation: "direct_call",
resolution: "unresolved",
reason: "native_trace_node_bound_reached",
evidence,
limitations: [],
});
continue;
}
const name = addressNames.get(address) ?? address;
const node = {
id: targetId,
kind: "function" as const,
name,
location: { address, file_offset: null },
attributes: { resolved_by: execution.value.provider.id },
evidence,
};
nodes.set(targetId, node);
queue.push({ node, address, depth: current.depth + 1 });
}
const edgeId = `call:${current.address}:${address}`;
edges.set(edgeId, {
id: edgeId,
from: current.node.id,
to: targetId,
relation: "direct_call",
resolution: "observed",
evidence,
limitations: [
"A resolved static call edge does not establish runtime reachability.",
],
});
}
}
return {
nodes: [...nodes.values()],
edges: [...edges.values()],
examined,
omitted,
truncated,
};
};
const graphNodeDepths = (
start: string,
nodes: readonly z.infer<
typeof nativeInvestigationGraphSchema
>["nodes"][number][],
edges: readonly z.infer<
typeof nativeInvestigationGraphSchema
>["edges"][number][],
): ReadonlyMap<string, number> => {
const known = new Set(nodes.map(({ id }) => id));
const depths = new Map([[start, 0]]);
const queue = [start];
for (let index = 0; index < queue.length; index += 1) {
const current = queue[index];
if (current === undefined) continue;
const depth = depths.get(current) ?? 0;
for (const edge of edges) {
if (
edge.resolution === "unresolved" ||
edge.from !== current ||
edge.to === null ||
!known.has(edge.to) ||
depths.has(edge.to)
)
continue;
depths.set(edge.to, depth + 1);
queue.push(edge.to);
}
}
return depths;
};
+18 -5
View File
@@ -1,4 +1,5 @@
import {
clientConfigurationValuesEqual,
parseClientConfiguration,
serializeClientConfiguration,
type ClientConfigurationDocument,
@@ -6,7 +7,6 @@ import {
import { constants as fsConstants } from "node:fs";
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { isDeepStrictEqual } from "node:util";
import writeFileAtomic from "write-file-atomic";
import { PRODUCT_IDENTITY } from "../identity.js";
@@ -70,7 +70,12 @@ const configureClientDocument = async (
}
const { document, servers, serversKey } = parsed;
const desired = clientConfigurationDesired(client, environment, command);
if (isDeepStrictEqual(servers[PRODUCT_IDENTITY.mcpServerKey], desired))
if (
clientConfigurationValuesEqual(
servers[PRODUCT_IDENTITY.mcpServerKey],
desired,
)
)
return { status: "unchanged" };
const backupPath =
original === undefined ? undefined : `${client.configPath}.rea.backup`;
@@ -102,7 +107,7 @@ const configureClientDocument = async (
format,
);
if (
!isDeepStrictEqual(
!clientConfigurationValuesEqual(
readback.servers[PRODUCT_IDENTITY.mcpServerKey],
desired,
)
@@ -134,7 +139,10 @@ export const clientConfigurationAligned = async (
try {
const original = await readFile(client.configPath, "utf8");
const { servers } = parseClientConfiguration(original, client.format);
return isDeepStrictEqual(servers[PRODUCT_IDENTITY.mcpServerKey], desired);
return clientConfigurationValuesEqual(
servers[PRODUCT_IDENTITY.mcpServerKey],
desired,
);
} catch {
return false;
}
@@ -174,7 +182,12 @@ export const inspectClientConfiguration = async (
);
try {
const { servers } = parseClientConfiguration(original, client.format);
if (isDeepStrictEqual(servers[PRODUCT_IDENTITY.mcpServerKey], desired))
if (
clientConfigurationValuesEqual(
servers[PRODUCT_IDENTITY.mcpServerKey],
desired,
)
)
return { status: "already_current" };
} catch {
return {