feat(native): add inspection primitives, dispatch traces and approved UI observation (#500)

* fix(hopper): normalize string-backed addresses and update verification

* feat(native): add inspection primitives, dispatch traces and approved UI observation

* test: prioritize real artifact E2E and captured golden regressions

* fix(process): queue observed output before reactive rendering actions

* test: prune redundant cases and strengthen boundary assertions

* fix(cli): route native value tracing through shared workflows

* test: replace synthetic success with real workflows and captured data

* fix(catalog): separate portable metadata from native host availability
This commit is contained in:
morluto
2026-10-04 16:02:36 +08:00
committed by GitHub
parent 0356f7677f
commit 4fbc501121
205 changed files with 8136 additions and 1816 deletions
@@ -87,7 +87,8 @@ describe("analysis context queries: navigation", () => {
await expect(
getNavigationContext(analysis, { document: "fixture" }),
).resolves.toEqual(err(failure));
expect(calls).toEqual(["current_address", "resolve_containing_procedure"]);
expect(calls).not.toContain("current_document");
expect(calls).toContain("resolve_containing_procedure");
});
});
@@ -103,7 +103,9 @@ describe("analysis provider registry: discovery and selection", () => {
const selected = await registry.select(DATABASE_TARGET);
expect(selected.ok).toBe(true);
if (!selected.ok || selected.value.binding === null) return;
if (!selected.ok) throw new Error("provider selection failed");
if (selected.value.binding === null)
throw new Error("expected a bound provider");
expect(bindingProjection(selected.value.binding)).toEqual({
id: "alpha",
source: "auto-single-candidate",
@@ -198,6 +200,9 @@ describe("analysis provider registry: binding failures and cancellation", () =>
candidate("alpha", { available: false }).provider,
]).select(ARTIFACT_TARGET, "alpha");
expect(unsupported.ok).toBe(false);
if (unsupported.ok)
throw new Error("expected unsupported target rejection");
expect(unsupported.error).toBeInstanceOf(ProviderSelectionError);
if (
!unsupported.ok &&
unsupported.error instanceof ProviderSelectionError
@@ -237,7 +242,9 @@ describe("analysis provider registry: binding failures and cancellation", () =>
}
const explicit = await automatic.select(ARTIFACT_TARGET, "alpha");
expect(explicit.ok).toBe(false);
if (!explicit.ok && explicit.error instanceof ProviderSelectionError)
if (explicit.ok) throw new Error("expected provider selection rejection");
expect(explicit.error).toBeInstanceOf(ProviderSelectionError);
if (explicit.error instanceof ProviderSelectionError)
expect(explicit.error.reason).toBe("target_unsupported");
});
@@ -267,7 +274,9 @@ describe("analysis provider registry: binding failures and cancellation", () =>
failed.provider,
]).select(DATABASE_TARGET, "failed");
expect(explicit.ok).toBe(false);
if (!explicit.ok && explicit.error instanceof ProviderSelectionError)
if (explicit.ok) throw new Error("expected provider selection rejection");
expect(explicit.error).toBeInstanceOf(ProviderSelectionError);
if (explicit.error instanceof ProviderSelectionError)
expect(explicit.error.rejections).toMatchObject([
{
providerId: "failed",
@@ -31,16 +31,15 @@ describe("analysis snapshot cache partitioning", () => {
createEvidenceBundle([]),
);
expect(exported.ok).toBe(true);
if (!exported.ok) return;
if (!exported.ok) throw new Error("snapshot export failed");
const entry = exported.value.entries[0];
if (entry !== undefined) {
Reflect.set(entry.execution, "provider", {
id: "forged",
name: "Forged",
version: "9",
});
entry.execution.limitations.push("forged");
}
if (entry === undefined) throw new Error("exported snapshot entry missing");
Reflect.set(entry.execution, "provider", {
id: "forged",
name: "Forged",
version: "9",
});
entry.execution.limitations.push("forged");
expect(
cache.lookup(
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import { collectInterfaceBuilderResourceKeys } from "./AppleAssetCatalogAnalysis.js";
describe("Apple asset catalog application workflow", () => {
it("joins only explicit resource-key fields with archive provenance", () => {
expect(
collectInterfaceBuilderResourceKeys([
{
id: "ib:Main.nib:object:2",
kind: "resource",
name: "Decorative image",
attributes: {
imageName: "Toolbar",
title: "not-an-asset-key",
image: 42,
},
evidence: [
{
artifact_path: "Contents/Resources/Main.nib",
artifact_sha256: "d".repeat(64),
},
],
},
{
id: "ib:Main.nib:object:3",
kind: "control",
name: "Toolbar",
attributes: { title: "not-an-asset-key" },
evidence: [],
},
]),
).toEqual([
{
sourceNodeId: "ib:Main.nib:object:2",
sourcePath: "Contents/Resources/Main.nib",
sourceArchiveSha256: "d".repeat(64),
field: "imageName",
key: "Toolbar",
},
]);
});
});
@@ -0,0 +1,267 @@
import { createHash } from "node:crypto";
import { lstat } from "node:fs/promises";
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
import {
appleAssetCatalogInputSchema,
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "../domain/appleAssetCatalog.js";
import { execFileOutput } from "../process/ExecFileOutput.js";
const ASSETUTIL = "/usr/bin/assetutil";
const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
const MAX_TOTAL_METADATA_BYTES = 64 * 1024 * 1024;
const RESOURCE_KEY_FIELDS = new Set([
"image",
"imageName",
"image_name",
"resourceName",
"resource_name",
"assetName",
"asset_name",
"UIImageName",
"NSImageName",
]);
/** Inspect compiled asset catalog metadata without extracting rendition bytes. */
export const analyzeAppleAssetCatalogs = async (input: {
readonly bundlePath: string;
readonly targetSha256: string;
readonly page?: unknown;
readonly signal?: AbortSignal;
readonly runAssetUtil?: (
path: string,
signal?: AbortSignal,
) => Promise<string>;
}) => {
if (process.platform !== "darwin" && input.runAssetUtil === undefined)
throw new ArtifactReaderFailure(
"unavailable",
"Apple asset catalog inspection requires macOS assetutil",
);
const page = appleAssetCatalogInputSchema.parse(input.page ?? {});
const reader = new DirectoryArtifactReader(input.bundlePath);
const catalogs: {
path: string;
sha256: string;
records: ReturnType<typeof parseAppleAssetCatalogRecords>;
}[] = [];
let totalMetadataBytes = 0;
try {
for await (const entry of reader.entries(input.signal)) {
if (entry.kind !== "file" || !entry.path.endsWith("Assets.car")) continue;
const inspected = await inspectAssetCatalogEntry({
reader,
entry,
runAssetUtil: input.runAssetUtil ?? runAssetUtil,
...(input.signal === undefined ? {} : { signal: input.signal }),
});
totalMetadataBytes += inspected.metadataBytes;
if (totalMetadataBytes > MAX_TOTAL_METADATA_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Combined asset catalog metadata exceeds ${MAX_TOTAL_METADATA_BYTES} bytes`,
);
catalogs.push(inspected.catalog);
}
} finally {
await reader.close();
}
if (catalogs.length === 0)
throw new ArtifactReaderFailure(
"unavailable",
"No compiled Assets.car catalogs were found in the app bundle",
);
const interfaceBuilder = await analyzeInterfaceBuilderBundle({
bundlePath: input.bundlePath,
targetSha256: input.targetSha256,
...(input.signal === undefined ? {} : { signal: input.signal }),
});
const resourceReferences = collectInterfaceBuilderResourceKeys(
interfaceBuilder.graph.nodes,
);
const result = projectAppleAssetCatalogPage({
targetSha256: input.targetSha256,
catalogs,
offset: page.offset,
limit: page.limit,
resourceReferences,
});
return {
...result,
limitations: [
...result.limitations,
"Exact resource-key joins use only recognized image or asset key fields on decoded Interface Builder resource objects; other archive resource references are not inferred.",
...(interfaceBuilder.graph.truncated
? [
"Interface Builder resource-key joins may be incomplete because the decoded UI graph was truncated.",
]
: []),
],
};
};
const inspectAssetCatalogEntry = async (input: {
readonly reader: DirectoryArtifactReader;
readonly entry: import("../artifacts/ArtifactReader.js").ArtifactEntry;
readonly runAssetUtil: (
path: string,
signal?: AbortSignal,
) => Promise<string>;
readonly signal?: AbortSignal;
}) => {
const { entry, reader, signal } = input;
const sha256 = await digestBounded(reader, entry, signal);
const before = await lstat(entry.adapterKey);
if (
entry.sourceIdentity === undefined ||
before.dev !== entry.sourceIdentity.device ||
before.ino !== entry.sourceIdentity.inode
)
throw new ArtifactReaderFailure(
"integrity",
`Asset catalog changed before inspection: ${entry.path}`,
);
const output = await input.runAssetUtil(entry.adapterKey, signal);
const after = await lstat(entry.adapterKey);
if (
before.dev !== after.dev ||
before.ino !== after.ino ||
before.size !== after.size ||
(await digestBounded(reader, entry, signal)) !== sha256
)
throw new ArtifactReaderFailure(
"integrity",
`Asset catalog changed during inspection: ${entry.path}`,
);
let parsed: unknown;
try {
parsed = JSON.parse(output);
} catch (cause: unknown) {
throw new ArtifactReaderFailure(
"format",
`assetutil returned invalid JSON for ${entry.path}`,
{ cause },
);
}
try {
return {
catalog: {
path: entry.path,
sha256,
records: parseAppleAssetCatalogRecords(parsed),
},
metadataBytes: Buffer.byteLength(output, "utf8"),
};
} catch (cause: unknown) {
throw new ArtifactReaderFailure(
"format",
`assetutil returned an unsupported record for ${entry.path}`,
{ cause },
);
}
};
/** Return only explicit image or asset fields from decoded resource objects. */
export const collectInterfaceBuilderResourceKeys = (
nodes: readonly {
readonly id: string;
readonly kind: string;
readonly name?: string;
readonly attributes: Readonly<Record<string, unknown>>;
readonly evidence: readonly {
readonly artifact_path: string | null;
readonly artifact_sha256: string | null;
}[];
}[],
) =>
nodes.flatMap((node) => {
const source = node.evidence.find(
(item) => item.artifact_path !== null && item.artifact_sha256 !== null,
);
const sourcePath = source?.artifact_path;
const sourceArchiveSha256 = source?.artifact_sha256;
if (sourcePath == null || sourceArchiveSha256 == null) return [];
return Object.entries(node.attributes).flatMap(([field, value]) =>
RESOURCE_KEY_FIELDS.has(field) &&
typeof value === "string" &&
value.length > 0
? [
{
sourceNodeId: node.id,
sourcePath,
sourceArchiveSha256,
field,
key: value,
},
]
: [],
);
});
const runAssetUtil = async (
path: string,
signal?: AbortSignal,
): Promise<string> => {
try {
return (
await execFileOutput(ASSETUTIL, ["--info", path], {
timeout: 60_000,
maxBuffer: MAX_CATALOG_BYTES,
...(signal === undefined ? {} : { signal }),
})
).stdout;
} catch (cause: unknown) {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Asset catalog inspection cancelled",
);
const code =
typeof cause === "object" && cause !== null && "code" in cause
? cause.code
: undefined;
throw new ArtifactReaderFailure(
code === "ENOENT"
? "unavailable"
: code === "ETIMEDOUT" || code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"
? "limit"
: "io",
`assetutil failed${code === undefined ? "" : ` (${String(code)})`}`,
{ cause },
);
}
};
const digestBounded = async (
reader: DirectoryArtifactReader,
entry: import("../artifacts/ArtifactReader.js").ArtifactEntry,
signal?: AbortSignal,
): Promise<string> => {
if (entry.declaredSize === null || entry.declaredSize > MAX_CATALOG_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Asset catalog exceeds ${MAX_CATALOG_BYTES} bytes: ${entry.path}`,
);
const stream = await reader.open(entry, signal);
const hash = createHash("sha256");
let length = 0;
for await (const chunk of stream) {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Asset catalog inspection cancelled",
);
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
length += bytes.length;
if (length > MAX_CATALOG_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Asset catalog exceeds byte limit: ${entry.path}`,
);
hash.update(bytes);
}
return hash.digest("hex");
};
@@ -18,12 +18,6 @@ describe("artifact inventory policy resolution", () => {
});
});
it("projects strict integrity without dormant continuation state", () => {
expect(resolveArtifactIntegrityPolicy({ mode: "fail" }, true)).toEqual({
mode: "fail",
});
});
it("admits parsed continuation intent only under operator policy", () => {
expect(() =>
resolveArtifactIntegrityPolicy({ mode: "record-and-continue" }, false),
+6 -2
View File
@@ -303,7 +303,9 @@ export class BinarySession
unboundOperationError: (operation, route) =>
this.#providerRouter.unboundOperationError(operation, route),
lookupSnapshot: (target, profile, operation, parameters) =>
operation === "decode_interface_builder"
operation === "decode_interface_builder" ||
operation === "inspect_asset_catalog" ||
operation === "inspect_keyed_archive"
? undefined
: this.lookupSnapshot(target, profile, operation, parameters),
});
@@ -324,7 +326,9 @@ export class BinarySession
profiled.ok &&
cacheable &&
profile !== undefined &&
name !== "decode_interface_builder"
name !== "decode_interface_builder" &&
name !== "inspect_asset_catalog" &&
name !== "inspect_keyed_archive"
)
this.recordSnapshot({
target: active.target,
@@ -1,35 +0,0 @@
import { describe, expect, it } from "vitest";
import type {
AnalysisClient,
AnalysisProvider,
ProviderIdentity,
} from "./AnalysisProvider.js";
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
import { composeBinarySession } from "./BinarySessionComposition.js";
const auxiliaryProvider = (identity: ProviderIdentity): AnalysisProvider => ({
identity: () => identity,
capabilities: () => [],
createClient: (): AnalysisClient => {
throw new Error("The composition check must not create provider clients");
},
});
describe("composeBinarySession", () => {
it("exposes the complete configured provider set without starting clients", () => {
const session = composeBinarySession(new AnalysisProviderRegistry([]), [
auxiliaryProvider({
id: "test-auxiliary",
name: "Test auxiliary provider",
version: "1.0.0",
}),
]);
expect(session.providerIdentity()).toEqual({
id: "composite:test-auxiliary",
name: "REA composite analysis provider",
version: null,
});
});
});
+1
View File
@@ -71,6 +71,7 @@ type AvailabilityContext = {
};
const ENHANCED_REQUIREMENTS: Readonly<Record<string, readonly string[]>> = {
trace_native_values: ["analyze_function", "resolve_native_call_targets"],
trace_native_ui_action: [
"decode_interface_builder",
"list_names",
@@ -1,37 +0,0 @@
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);
});
});
+8 -1
View File
@@ -47,6 +47,9 @@ type DirectAnalysisTool =
| "binary_overview"
| "procedure_pseudo_code"
| "read_function_instructions"
| "inspect_native_instruction"
| "inspect_native_data_type"
| "resolve_native_call_targets"
| "analyze_function"
| "inspect_native_api"
| "inspect_native_dispatch_metadata"
@@ -54,7 +57,8 @@ type DirectAnalysisTool =
| "search_procedures"
| "xrefs"
| "trace_feature"
| "trace_native_ui_action";
| "trace_native_ui_action"
| "trace_native_values";
/**
* Open one binary, execute one tool, and always release provider resources.
@@ -285,6 +289,7 @@ const executeAnalysisTool = async (input: {
tool === "inspect_native_api" ||
tool === "inspect_native_dispatch_metadata" ||
tool === "trace_feature" ||
tool === "trace_native_values" ||
tool === "trace_native_ui_action"
) {
const result = await new EnhancedTools(session).execute(
@@ -407,7 +412,9 @@ const isWorkflowEvidenceTool = (
): boolean =>
tool === "binary_overview" ||
tool === "inspect_native_api" ||
tool === "inspect_native_dispatch_metadata" ||
tool === "trace_feature" ||
tool === "trace_native_values" ||
tool === "trace_native_ui_action";
const fileExists = async (path: string): Promise<boolean> => {
+11 -16
View File
@@ -4,11 +4,9 @@ import { ok } from "../domain/result.js";
import { traceLiteralFeature } from "./EnhancedLiteralTracing.js";
describe("literal feature tracing", () => {
it("searches procedure and string names before following references", async () => {
const calls: string[] = [];
it("returns matched procedure and string facts with references", async () => {
const result = await traceLiteralFeature(
async (name) => {
calls.push(name);
if (name === "search_strings")
return ok([{ address: "0x1000", value: "launch feature" }]);
if (name === "search_procedures")
@@ -31,21 +29,11 @@ describe("literal feature tracing", () => {
references: [],
},
});
expect(calls).toEqual([
"search_strings",
"search_procedures",
"search_strings",
"search_procedures",
"xrefs",
"xrefs",
]);
});
it("keeps string-code tracing scoped to string labels", async () => {
const calls: string[] = [];
await traceLiteralFeature(
const result = await traceLiteralFeature(
async (name) => {
calls.push(name);
if (name === "search_strings")
return ok([{ address: "0x1000", value: "launch feature" }]);
if (name === "xrefs") return ok([]);
@@ -54,7 +42,14 @@ describe("literal feature tracing", () => {
{ query: "launch", case_sensitive: false },
"string",
);
expect(calls).toEqual(["search_strings", "xrefs"]);
expect(result).toMatchObject({
ok: true,
value: {
matches: [
{ type: "string", address: "0x1000", value: "launch feature" },
],
references: [],
},
});
});
});
@@ -14,7 +14,10 @@ import {
} from "../domain/nativeInvestigationGraph.js";
import { err, ok } from "../domain/result.js";
import type { Result } from "../domain/result.js";
import { AnalysisCancelledError } from "../domain/errors.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
} from "../domain/errors.js";
const target = "a".repeat(64);
const provider = { id: "fixture", name: "Fixture", version: "1" };
@@ -138,6 +141,30 @@ const testAnalysis = (
const override = overrides[operation];
if (override !== undefined) return override(parameters);
switch (operation) {
case "procedure_address":
return err(
new AnalysisCapabilityUnavailableError(
"fixture",
operation,
"Seed not available",
),
);
case "procedure_references":
return err(
new AnalysisCapabilityUnavailableError(
"fixture",
operation,
"No typed reference reader in fixture",
),
);
case "inspect_native_dispatch_metadata":
return err(
new AnalysisCapabilityUnavailableError(
"fixture",
operation,
"No binary metadata reader in fixture",
),
);
case "decode_interface_builder":
return execution(operation, {
target_sha256: target,
@@ -170,6 +197,22 @@ const testAnalysis = (
});
describe("native UI action trace", () => {
it("accepts an explicit native seed without an authored UI connection", async () => {
const result = await new EnhancedTools(
testAnalysis({
procedure_address: () => execution("procedure_address", "0x1000"),
}),
).execute("trace_native_ui_action", { action: "0x1000" });
expect(result).toMatchObject({
ok: true,
value: {
start: "native:function:0x1000",
nodes: expect.arrayContaining([
expect.objectContaining({ id: "native:function:0x2000" }),
]),
},
});
});
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", {
@@ -189,7 +232,7 @@ describe("native UI action trace", () => {
);
expect(trace.edges).toContainEqual(
expect.objectContaining({
relation: "direct_call",
relation: "provider_call",
to: "native:function:0x2000",
}),
);
@@ -416,7 +459,7 @@ describe("native UI query outcomes", () => {
expect(result.value).toMatchObject({
coverage: expect.arrayContaining([
expect.objectContaining({
facet: "direct_native_calls",
facet: "static_native_calls",
status: "partial",
omitted: 1,
}),
+12 -41
View File
@@ -27,10 +27,8 @@ import {
discoverObjcClasses,
discoverObjcProtocols,
} from "../domain/symbolAnalysis.js";
import {
inspectNativeDispatchMetadata,
nativeDispatchMetadataResultSchema,
} from "../domain/objcSwiftMetadata.js";
import { inspectNativeDispatch } from "./NativeDispatchMetadataInspection.js";
import { traceNativeValues } from "./NativeValueTrace.js";
import { traceNativeUiAction } from "./NativeUiActionTrace.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
@@ -64,6 +62,12 @@ export class EnhancedTools {
name === "trace_call_path"
)
return this.#executeTracing(name, input, signal);
if (name === "trace_native_values") {
const parsed = enhancedInputSchemas.trace_native_values.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidEnhancedInput(name, parsed.error);
}
if (name === "trace_native_ui_action") {
const parsed =
enhancedInputSchemas.trace_native_ui_action.safeParse(input);
@@ -177,6 +181,8 @@ export class EnhancedTools {
call.input,
signal,
);
case "trace_native_values":
return traceNativeValues(this.analysis, call.input, signal);
case "trace_native_ui_action": {
return traceNativeUiAction(this.analysis, call.input, signal);
}
@@ -246,46 +252,11 @@ export class EnhancedTools {
return names.ok ? ok(discoverObjcClasses(names.value, pattern)) : names;
}
async #inspectNativeDispatchMetadata(
#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,
),
}),
);
return inspectNativeDispatch(this.analysis, maxRecords, signal);
}
async #objcProtocols(signal?: AbortSignal): EnhancedResult {
@@ -110,9 +110,6 @@ describe("residual unknown registry reads and identity", () => {
});
it("derives stable IDs, filters heads, and rejects duplicate creation", () => {
expect(recordUnknownInputSchema.parse(input("Is branch live?"))).toEqual(
input("Is branch live?"),
);
const store = ledger();
const first = store.recordUnknown(
input(" Is branch live? "),
@@ -306,11 +303,5 @@ describe("residual unknown registry resolution and history", () => {
const before = serializeEvidenceBundle(base.export());
expect(base.import(branch.export()).ok).toBe(false);
expect(serializeEvidenceBundle(base.export())).toBe(before);
const unbounded = new EvidenceLedger();
expect(
unbounded.recordUnknown(input("No quota"), mutation("unbounded")).ok,
).toBe(true);
expect(unbounded.export().unknowns).toHaveLength(1);
});
});
+18 -51
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { createEvidence, evidenceSchema } from "../domain/evidence.js";
import { createEvidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { recordUnknownInputSchema } from "../domain/residualUnknown.js";
import { EvidenceLedger } from "./EvidenceLedger.js";
@@ -41,27 +41,29 @@ describe("evidence ledger recording", () => {
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
});
expect(ledger.export().records).toEqual([evidence]);
ledger.clear();
expect(ledger.export().records).toEqual([]);
});
it("treats canonical JSON key order as semantically irrelevant", () => {
const evidence = createEvidence(TARGET, PROVIDER, {
const ordered = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: { alpha: 1, beta: 2 },
result: { alpha: 1, beta: 2 },
});
const reordered = evidenceSchema.parse({
...evidence,
parameters: { beta: 2, alpha: 1 },
normalized_result: { beta: 2, alpha: 1 },
});
const ledger = new EvidenceLedger();
expect(ledger.record(evidence)).toEqual({ ok: true, value: "added" });
expect(ledger.record(reordered)).toEqual({
expect(ledger.record(ordered)).toMatchObject({ ok: true, value: "added" });
const reorderedBundle: unknown = JSON.parse(
JSON.stringify(
createEvidenceBundle([
{
...ordered,
parameters: { beta: 2, alpha: 1 },
normalized_result: { beta: 2, alpha: 1 },
},
]),
),
);
expect(ledger.import(reorderedBundle)).toEqual({
ok: true,
value: "duplicate",
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
});
ledger.clear();
expect(ledger.export().records).toEqual([]);
});
it("retains more than ten thousand inline evidence records", () => {
@@ -87,41 +89,6 @@ describe("evidence ledger recording", () => {
expect(ledger.record(record)).toEqual({ ok: true, value: "added" });
expect(ledger.get(record.evidence_id)).toEqual(record);
});
it("retains Evidence alongside unknown revisions without a record quota", () => {
const ledger = new EvidenceLedger();
const mutation = createEvidence(undefined, PROVIDER, {
predicateType: "rea.residual-unknown-mutation",
operation: "record_unknown",
parameters: {},
result: { action: "record" },
});
const unknown = recordUnknownInputSchema.parse({
approved: true,
question: "What remains unresolved?",
severity: "high",
domain: "record-limit-test",
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
});
expect(ledger.recordUnknown(unknown, mutation).ok).toBe(true);
const direct = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: true,
});
expect(ledger.record(direct)).toEqual({ ok: true, value: "added" });
expect(ledger.export()).toMatchObject({
records: expect.arrayContaining([mutation, direct]),
unknowns: [expect.objectContaining({ domain: "record-limit-test" })],
});
});
});
describe("evidence bundle imports", () => {
@@ -18,7 +18,7 @@ afterEach(async () => {
});
describe("compiled Interface Builder bundle reader", () => {
it("reads nib plist archives without following symlinks and reports provenance", async () => {
it("reads nib plist archives and reports provenance", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-ib-test-"));
roots.push(root);
const bundle = join(root, "Example.app");
@@ -27,7 +27,6 @@ it("projects closure and direct interprocedural flow without execution", () => {
"returns-to-call",
] as const)
expect(relations.has(expected)).toBe(true);
expect(graph.coverage.families).toHaveLength(12);
expect(graph.limitations).toContain(
"The semantic graph contains static syntax observations and conservative relationship candidates; it does not claim runtime execution.",
);
@@ -244,7 +244,6 @@ it("uses unavailable evidence when no source produced semantic IR", () => {
applicationGraph: { graph_id: GRAPH_ID, nodes: [] },
analysis: emptyAnalysis(),
});
expect(graph.nodes).toHaveLength(1);
expect(graph.nodes[0]?.evidence).toMatchObject({
authority: "unknown",
state: "unavailable",
+1 -6
View File
@@ -6,7 +6,7 @@ import { nativeApiBoundarySchema } from "../domain/nativeApiBoundary.js";
import { projectNativeApiInspection } from "./NativeApiInspection.js";
describe("native API inspection", () => {
it("projects structured boundary evidence through inspectable substeps", () => {
it("preserves structured type and jump-table boundary evidence", () => {
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
expect(projectNativeApiInspection(dossier)).toMatchObject({
@@ -26,11 +26,6 @@ describe("native API inspection", () => {
},
],
},
substeps: [
{ operation: "analyze_function", status: "completed" },
{ operation: "project_native_api_boundary", status: "completed" },
{ operation: "preserve_residual_unknowns", status: "completed" },
],
unsupported_branches: [],
residual_unknowns: [],
});
+104
View File
@@ -0,0 +1,104 @@
import { describe, expect, it } from "vitest";
import { readNativeCallRoutes } from "./NativeCallRoutes.js";
import { createAnalysisExecution } from "./AnalysisProvider.js";
import { ghidraReferenceEdge } from "../domain/hopperValues.fixture.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok } from "../domain/result.js";
import { AnalysisCancelledError } from "../domain/errors.js";
const provider = { id: "fixture", name: "Fixture", version: "1" };
describe("typed native call routes", () => {
it("preserves computed targets, ambiguity and targetless call sites", async () => {
const reference = jsonValueSchema.parse(ghidraReferenceEdge());
if (
reference === null ||
typeof reference !== "object" ||
Array.isArray(reference)
)
throw new TypeError("Invalid reference fixture");
const result = await readNativeCallRoutes(
{
execute: async () =>
ok(
createAnalysisExecution(
{
reference_kinds_available: true,
references: ["0x2000", "0x3000"].map((address) => ({
...reference,
source_address: "0x1004",
target_address: address,
target_procedure: { address },
kind: {
available: true,
provenance: "fixture-reference",
type: "COMPUTED_CALL",
flow: true,
call: true,
jump: false,
data: false,
read: false,
write: false,
indirect: true,
computed: true,
external: false,
conditional: false,
terminal: false,
primary: true,
operand_index: 0,
},
})),
unresolved_calls: [
{ address: "0x1008", reason: "No static target" },
],
},
provider,
),
),
},
"0x1000",
);
expect(result).toMatchObject({
ok: true,
value: {
routes: [
{
address: "0x2000",
relation: "indirect_call",
resolution: "ambiguous",
},
{
address: "0x3000",
relation: "indirect_call",
resolution: "ambiguous",
},
],
unknowns: [{ address: "0x1008" }],
},
});
});
it("does not fall back on cancellation or invalid typed output", async () => {
let calls = 0;
const cancelled = await readNativeCallRoutes(
{
execute: async () => {
calls++;
return err(new AnalysisCancelledError("procedure_references"));
},
},
"0x1000",
);
expect(cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(calls).toBe(1);
const malformed = await readNativeCallRoutes(
{ execute: async () => ok(createAnalysisExecution({}, provider)) },
"0x1000",
);
expect(malformed).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
});
});
+101
View File
@@ -0,0 +1,101 @@
import { z } from "zod";
import type { AnalysisOperationPort } from "./AnalysisProvider.js";
import {
parseRelatedAddresses,
referenceKindSchema,
} from "../domain/hopperValues.js";
import { err, ok } from "../domain/result.js";
import { AnalysisOutputError } from "../domain/errors.js";
const referencesSchema = z.object({
reference_kinds_available: z.boolean().optional(),
references: z.array(
z.object({
source_address: z.string(),
target_address: z.string(),
target_procedure: z.object({ address: z.string() }).nullable(),
kind: referenceKindSchema,
}),
),
unresolved_calls: z
.array(z.object({ address: z.string(), reason: z.string() }))
.default([]),
});
/** Prefer typed static call references, preserving computed targets and targetless sites. */
export const readNativeCallRoutes = async (
analysis: AnalysisOperationPort,
procedure: string,
signal?: AbortSignal,
) => {
const options = signal === undefined ? {} : { signal };
const execution = await analysis.execute(
"procedure_references",
{ procedure, direction: "outgoing" },
options,
);
if (execution.ok) {
const parsed = referencesSchema.safeParse(execution.value.result);
if (!parsed.success)
return err(
new AnalysisOutputError(
"procedure_references",
"Invalid typed call references",
),
);
const references = parsed.data.references;
if (
parsed.data.reference_kinds_available === true ||
(references.length > 0 && references.every(({ kind }) => kind.available))
) {
const calls = references.filter(
({ kind }) => kind.available && kind.call,
);
const countBySite = new Map<string, Set<string>>();
for (const call of calls) {
const targets =
countBySite.get(call.source_address) ?? new Set<string>();
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,
});
}
} else if (execution.error._tag !== "AnalysisCapabilityUnavailableError")
return err(execution.error);
const callees = await analysis.execute(
"procedure_callees",
{ procedure },
options,
);
if (!callees.ok) return callees;
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;
};
@@ -0,0 +1,68 @@
import { z } from "zod";
import {
nativeDispatchMetadataResultSchema,
inspectNativeDispatchMetadata,
} from "../domain/objcSwiftMetadata.js";
import { AnalysisOutputError } from "../domain/errors.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok } from "../domain/result.js";
import type { AnalysisOperationPort } from "./AnalysisProvider.js";
import type { EnhancedResult } from "./EnhancedToolTypes.js";
/** Prefer validated binary metadata, otherwise preserve the bound provider's symbol-only coverage. */
export const inspectNativeDispatch = async (
analysis: AnalysisOperationPort,
maxRecords: number,
signal?: AbortSignal,
): EnhancedResult => {
const binaryMetadata = await analysis.execute(
"inspect_native_dispatch_metadata",
{ max_records: maxRecords },
signal === undefined ? {} : { signal },
);
if (binaryMetadata.ok)
return ok(
jsonValueSchema.parse(
nativeDispatchMetadataResultSchema.parse(binaryMetadata.value.result),
),
);
if (binaryMetadata.error._tag !== "AnalysisCapabilityUnavailableError")
return err(binaryMetadata.error);
const execution = await 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(
jsonValueSchema.parse(
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,
),
}),
),
);
};
+88 -73
View File
@@ -10,34 +10,21 @@ import {
traceNativeInvestigationGraph,
joinInterfaceBuilderDispatch,
} from "../domain/nativeInvestigationGraph.js";
import {
inspectNativeDispatchMetadata,
nativeDispatchMetadataResultSchema,
} from "../domain/objcSwiftMetadata.js";
import { nativeDispatchMetadataResultSchema } from "../domain/objcSwiftMetadata.js";
import { inspectNativeDispatch } from "./NativeDispatchMetadataInspection.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { parseRelatedAddresses } from "../domain/hopperValues.js";
import { readNativeCallRoutes } from "./NativeCallRoutes.js";
import { err, ok } from "../domain/result.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
projectAnalysisError,
} from "../domain/errors.js";
import { 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([
const [uiExecution, metadataExecution] = await Promise.all([
analysis.execute(
"decode_interface_builder",
{
@@ -47,44 +34,24 @@ export const traceNativeUiAction = async (
},
signal === undefined ? {} : { signal },
),
analysis.execute("list_names", {}, signal === undefined ? {} : { signal }),
inspectNativeDispatch(analysis, 20_000, 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(uiExecution.error);
if (!metadataExecution.ok) return err(metadataExecution.error);
const metadata = nativeDispatchMetadataResultSchema.parse(
metadataExecution.value,
);
const targetSha256 = metadata.target_sha256;
if (targetSha256 === null)
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",
"inspect_native_dispatch_metadata",
"Dispatch metadata lacks target identity",
),
);
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);
let graph = emptyGraph(targetSha256, metadata.provider);
const coverage = [];
if (uiExecution.ok) {
const decoded = interfaceBuilderAnalysisSchema.safeParse(
@@ -136,7 +103,44 @@ export const traceNativeUiAction = async (
});
}
const selected = resolveUiAction(graph, input.action);
let selected = resolveUiAction(graph, input.action);
if (selected.nodeId === null && selected.candidates.length === 0) {
const native = await analysis.execute(
"procedure_address",
{ procedure: input.action },
signal === undefined ? {} : { signal },
);
if (!native.ok && native.error._tag === "AnalysisCancelledError")
return err(native.error);
if (native.ok) {
const address = z.string().safeParse(native.value.result);
if (!address.success || native.value.subject?.sha256 !== targetSha256)
return err(
new AnalysisOutputError(
"procedure_address",
"Native seed lacks a validated address or matching target identity",
),
);
const id = `native:function:${address.data}`;
graph.nodes.push({
id,
kind: "function",
name: input.action,
location: { address: address.data, file_offset: null },
attributes: { resolved_by: native.value.provider.id },
evidence: [
{
kind: "reference",
description: `Provider resolved the explicit native seed ${input.action}`,
location: { address: address.data, file_offset: null },
artifact_path: null,
artifact_sha256: targetSha256,
},
],
});
selected = { nodeId: id, candidates: [], reason: null };
}
}
if (selected.nodeId === null) {
coverage.push(...graph.coverage);
const trace = {
@@ -152,7 +156,7 @@ export const traceNativeUiAction = async (
reason: selected.reason,
coverage,
limitations: [
"The query did not identify one unique authored UI action; no handler path was inferred.",
"The query did not identify one unique authored UI action or native function; no handler path was inferred.",
],
};
return ok(
@@ -179,9 +183,10 @@ export const traceNativeUiAction = async (
});
if (expanded.error !== undefined) return err(expanded.error);
coverage.push({
facet: "direct_native_calls",
facet: "static_native_calls",
status: "partial",
reason: "resolved_direct_calls_do_not_cover_all_indirect_dispatch",
reason:
"typed_direct_and_indirect_references_do_not_cover_all_runtime_dispatch; untyped_provider_callees_remain_inferred",
examined: expanded.examined,
omitted: expanded.omitted,
});
@@ -390,10 +395,10 @@ const addDirectCallees = async (input: {
omitted += queue.length - queueIndex + 1;
break;
}
const execution = await input.analysis.execute(
"procedure_callees",
{ procedure: current.address },
input.signal === undefined ? {} : { signal: input.signal },
const execution = await readNativeCallRoutes(
input.analysis,
current.address,
input.signal,
);
examined += 1;
if (!execution.ok) {
@@ -414,35 +419,45 @@ const addDirectCallees = async (input: {
});
continue;
}
const related = parseRelatedAddresses(execution.value.result, "callees");
if (!related.ok) {
const id = `unknown-callees:${current.address}`;
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: "direct_call",
relation: "indirect_call",
resolution: "unresolved",
reason: "provider_returned_unreadable_callee_relationships",
evidence: [],
limitations: [
"The provider result could not be normalized into callee addresses.",
reason: unknown.reason,
evidence: [
{
kind: "reference",
description: unknown.reason,
location: { address: unknown.address, file_offset: null },
artifact_path: null,
artifact_sha256: input.targetSha256,
},
],
limitations: [],
});
continue;
}
for (const [index, address] of related.value.entries()) {
for (const [index, route] of execution.value.routes.entries()) {
const address = route.address;
if (edges.size >= input.input.max_edges) {
truncated = true;
omitted += related.value.length - index;
omitted += execution.value.routes.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 },
description: `${execution.value.provider.name} reported ${route.relation} from ${current.address} to ${address}`,
location: { address: route.site, file_offset: null },
artifact_path: null,
artifact_sha256: input.targetSha256,
},
@@ -476,13 +491,13 @@ const addDirectCallees = async (input: {
nodes.set(targetId, node);
queue.push({ node, address, depth: current.depth + 1 });
}
const edgeId = `call:${current.address}:${address}`;
const edgeId = `call:${current.address}:${route.site}:${address}`;
edges.set(edgeId, {
id: edgeId,
from: current.node.id,
to: targetId,
relation: "direct_call",
resolution: "observed",
relation: route.relation,
resolution: route.resolution,
evidence,
limitations: [
"A resolved static call edge does not establish runtime reachability.",
+194
View File
@@ -0,0 +1,194 @@
import { describe, expect, it } from "vitest";
import { traceNativeValues } from "./NativeValueTrace.js";
import {
createAnalysisExecution,
type AnalysisOperationPort,
} from "./AnalysisProvider.js";
import { ghidraFunctionDossier } from "../domain/hopperValues.fixture.js";
import { functionDossierSchema } from "../domain/hopperValues.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { AnalysisCancelledError } from "../domain/errors.js";
import { ok, err } from "../domain/result.js";
const subject = {
path: "/fixture",
sha256: "a".repeat(64),
format: "mach-o" as const,
architecture: "arm64" as const,
};
const provider = { id: "fixture", name: "Fixture", version: "1" };
const scalar = {
kind: "constant",
size_bytes: 4,
location: null,
constant_hex: "3",
};
const node = (id: string, address: string, opcode: string) => ({
id,
address,
sequence: 0,
opcode,
is_dead: true,
block_membership: "member",
inputs: [scalar, scalar],
output: scalar,
});
const analysis: AnalysisOperationPort = {
execute: async (operation, parameters) => {
if (operation === "resolve_native_call_targets")
return ok(
createAnalysisExecution(
{
call_site: "0x1000",
procedure: "0x1000",
status: "direct",
mechanism: "direct",
targets: [
{
address: "0x2000",
procedure: "0x2000",
status: "direct",
basis: "provider-reference",
references: [],
},
],
limitations: [],
},
provider,
{ subject },
),
);
const callee = parameters.procedure === "0x2000";
return ok(
createAnalysisExecution(
jsonValueSchema.parse({
...functionDossierSchema.parse(ghidraFunctionDossier()),
procedure: {
address: callee ? "0x2000" : "0x1000",
name: callee ? "callee" : "caller",
classification: null,
signature: null,
locals: [],
},
native_value_flow: {
available: true,
provenance: "ghidra-high-pcode",
operations: callee
? [node("return", "0x2000", "RETURN")]
: [node("call", "0x1000", "CALL")],
def_use: [],
effects: [],
parameters: callee
? [{ ordinal: 0, name: "value", data_type: "/int" }]
: [],
parameter_uses: callee
? [{ ordinal: 0, use: "return", input_index: 1 }]
: [],
truncated: false,
omitted_operations_lower_bound: 0,
known_omitted_inputs: 0,
known_omitted_edges: 0,
limitations: [],
},
}),
provider,
{ subject },
),
);
},
};
describe("bounded native value dependency composition", () => {
it("reports work truncation and stable pagination without traversing ambiguous calls", async () => {
const bounded = await traceNativeValues(analysis, {
procedure: "0x1000",
max_functions: 1,
});
expect(bounded.ok).toBe(true);
if (bounded.ok)
expect(bounded.value).toMatchObject({
truncated: true,
decompilations: 1,
});
const page = await traceNativeValues(analysis, {
procedure: "0x1000",
limit: 1,
});
expect(page.ok).toBe(true);
if (page.ok)
expect(page.value).toMatchObject({ total_nodes: 3, next_offset: 1 });
const ambiguous = await traceNativeValues(
{
execute: async (operation, parameters, options) => {
if (operation !== "resolve_native_call_targets")
return analysis.execute(operation, parameters, options);
return ok(
createAnalysisExecution(
{
call_site: "0x1000",
procedure: "0x1000",
status: "ambiguous",
mechanism: "computed",
targets: [
{
address: "0x2000",
procedure: "0x2000",
status: "candidate",
basis: "provider-reference",
references: [],
},
],
limitations: [],
},
provider,
{ subject },
),
);
},
},
{ procedure: "0x1000" },
);
expect(ambiguous.ok).toBe(true);
if (ambiguous.ok)
expect(ambiguous.value).toMatchObject({
decompilations: 1,
edges: [expect.objectContaining({ status: "candidate" })],
});
});
it("propagates cancellation and rejects cross-target dependencies", async () => {
const controller = new AbortController();
controller.abort();
expect(
await traceNativeValues(
analysis,
{ procedure: "0x1000" },
controller.signal,
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
const cancelled = await traceNativeValues(
{
execute: async () =>
err(new AnalysisCancelledError("analyze_function")),
},
{ procedure: "0x1000" },
);
expect(cancelled.ok).toBe(false);
const mismatch = await traceNativeValues(
{
execute: async (operation, parameters, options) => {
const value = await analysis.execute(operation, parameters, options);
return value.ok && parameters.procedure === "0x2000"
? ok({
...value.value,
subject: { ...subject, sha256: "b".repeat(64) },
})
: value;
},
},
{ procedure: "0x1000" },
);
expect(mismatch).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
});
});
+389
View File
@@ -0,0 +1,389 @@
import { functionDossierSchema } from "../domain/hopperValues.js";
import { nativeCallTargetsSchema } from "../domain/nativeInstruction.js";
import {
nativeValueTraceInputSchema,
nativeValueTraceSchema,
} from "../domain/nativeValueTrace.js";
import { createEvidence } from "../domain/evidence.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../domain/errors.js";
import { err, ok } from "../domain/result.js";
import type { AnalysisOperationPort } from "./AnalysisProvider.js";
import type { EnhancedResult } from "./EnhancedToolTypes.js";
/** Compose bounded high-p-code def-use graphs across exactly referenced call destinations. */
export const traceNativeValues = async (
analysis: AnalysisOperationPort,
parameters: unknown,
signal?: AbortSignal,
): EnhancedResult => {
const input = nativeValueTraceInputSchema.parse(parameters);
const nodes: typeof nativeValueTraceSchema._output.nodes = [];
const edges: typeof nativeValueTraceSchema._output.edges = [];
const procedures: typeof nativeValueTraceSchema._output.procedures = [];
const unknowns: typeof nativeValueTraceSchema._output.unknowns = [];
const callBindings: {
caller: string;
callee: string;
call: string;
argument_count: number;
output: boolean;
evidence_id: string;
}[] = [];
const pending = [{ procedure: input.procedure, depth: 0 }];
const visited = new Set<string>();
let targetSha256: string | undefined;
let truncated = false;
let decompilations = 0;
let callSites = 0;
let bytes = 0;
while (pending.length > 0) {
if (signal?.aborted)
return err(new AnalysisCancelledError("trace_native_values"));
const next = pending.shift();
if (next === undefined || visited.has(next.procedure)) continue;
if (decompilations >= input.max_functions) {
truncated = true;
unknowns.push({
procedure: next.procedure,
address: null,
reason: "decompilation budget reached",
});
break;
}
const execution = await analysis.execute(
"analyze_function",
{ procedure: next.procedure },
signal === undefined ? {} : { signal },
);
decompilations++;
if (!execution.ok) {
if (execution.error._tag === "AnalysisCancelledError")
return err(execution.error);
unknowns.push({
procedure: next.procedure,
address: null,
reason: execution.error.message,
});
continue;
}
const parsed = functionDossierSchema.safeParse(execution.value.result);
if (!parsed.success || execution.value.subject === null)
return err(
new AnalysisOutputError(
"trace_native_values",
"Function dossier lacks validated facts or artifact identity",
),
);
const dossier = parsed.data;
const address = dossier.procedure.address;
if (visited.has(address)) continue;
visited.add(next.procedure);
visited.add(address);
targetSha256 ??= execution.value.subject.sha256;
if (execution.value.subject.sha256 !== targetSha256)
return err(
new AnalysisOutputError(
"trace_native_values",
"Cross-function target digest mismatch",
),
);
const evidence = createEvidence(
execution.value.subject,
execution.value.provider,
{
operation: "analyze_function",
parameters: { procedure: next.procedure },
result: execution.value.result,
rawResult: execution.value.rawResult,
limitations: execution.value.limitations,
locations: execution.value.locations,
...(execution.value.analysisProfile === undefined
? {}
: { analysisProfile: execution.value.analysisProfile }),
},
);
const evidenceId = evidence.evidence_id;
procedures.push({
address,
depth: next.depth,
evidence_id: evidenceId,
provider: execution.value.provider.id,
analysis_profile_digest: execution.value.analysisProfile?.digest ?? null,
});
const flow = dossier.native_value_flow;
if (flow === null || !flow.available) {
unknowns.push({
procedure: address,
address: null,
reason: flow?.reason ?? "Provider has no native def-use model",
});
continue;
}
if (flow.truncated) {
truncated = true;
unknowns.push({
procedure: address,
address: null,
reason: "Provider p-code was truncated",
});
}
const ids = new Set<string>();
const qualified = (id: string) => `${address}/${id}`;
for (const operation of flow.operations) {
if (
operation.block_membership === "detached" ||
(operation.block_membership === "unavailable" && operation.is_dead)
)
continue;
const node = {
id: qualified(operation.id),
procedure: address,
evidence_id: evidenceId,
operation,
kind: "operation" as const,
parameter: null,
};
const size = Buffer.byteLength(JSON.stringify(node));
if (nodes.length >= input.max_nodes || bytes + size > 8 * 1024 * 1024) {
truncated = true;
break;
}
bytes += size;
ids.add(operation.id);
nodes.push(node);
}
for (const parameter of flow.parameters) {
if (nodes.length >= input.max_nodes) {
truncated = true;
break;
}
nodes.push({
id: `${address}/parameter:${parameter.ordinal}`,
procedure: address,
evidence_id: evidenceId,
kind: "parameter",
operation: null,
parameter,
});
}
for (const use of flow.parameter_uses) {
if (
!ids.has(use.use) ||
!nodes.some((node) => node.id === `${address}/parameter:${use.ordinal}`)
)
continue;
if (edges.length >= input.max_edges) {
truncated = true;
break;
}
edges.push({
source: `${address}/parameter:${use.ordinal}`,
target: qualified(use.use),
input_index: use.input_index,
kind: "parameter-use",
status: "derived",
evidence_id: evidenceId,
});
}
for (const edge of flow.def_use) {
if (!ids.has(edge.definition) || !ids.has(edge.use)) continue;
if (edges.length >= input.max_edges) {
truncated = true;
break;
}
edges.push({
source: qualified(edge.definition),
target: qualified(edge.use),
input_index: edge.input_index,
kind: "def-use",
status: "derived",
evidence_id: evidenceId,
});
}
for (const operation of flow.operations) {
if (
!ids.has(operation.id) ||
!["CALL", "CALLIND"].includes(operation.opcode)
)
continue;
if (callSites >= input.max_call_sites) {
truncated = true;
unknowns.push({
procedure: address,
address: operation.address,
reason: "Call-site resolution budget reached",
});
break;
}
callSites++;
const resolved = await analysis.execute(
"resolve_native_call_targets",
{ address: operation.address },
signal === undefined ? {} : { signal },
);
if (!resolved.ok) {
if (resolved.error._tag === "AnalysisCancelledError")
return err(resolved.error);
unknowns.push({
procedure: address,
address: operation.address,
reason: resolved.error.message,
});
continue;
}
const targets = nativeCallTargetsSchema.safeParse(resolved.value.result);
if (!targets.success)
return err(
new AnalysisOutputError(
"resolve_native_call_targets",
"Invalid static call resolution",
),
);
if (targets.data.targets.length === 0)
unknowns.push({
procedure: address,
address: operation.address,
reason: `Call target ${targets.data.status}`,
});
for (const target of targets.data.targets) {
if (edges.length >= input.max_edges) {
truncated = true;
break;
}
const destination = target.procedure ?? target.address;
edges.push({
source: qualified(operation.id),
target: destination,
input_index: null,
kind: "call",
status: target.status,
evidence_id: evidenceId,
});
if (target.status !== "candidate")
callBindings.push({
caller: address,
callee: destination,
call: qualified(operation.id),
argument_count: Math.max(0, operation.inputs.length - 1),
output: operation.output !== null,
evidence_id: evidenceId,
});
if (next.depth < input.max_depth && target.status !== "candidate")
pending.push({ procedure: destination, depth: next.depth + 1 });
else if (!visited.has(destination)) {
truncated = true;
unknowns.push({
procedure: address,
address: operation.address,
reason:
target.status === "candidate"
? "Ambiguous call candidates were not traversed"
: "Call depth budget reached",
});
}
}
}
if (
truncated &&
(nodes.length >= input.max_nodes ||
edges.length >= input.max_edges ||
bytes >= 8 * 1024 * 1024)
)
break;
}
if (targetSha256 === undefined)
return err(
new AnalysisOutputError(
"trace_native_values",
"No seed function could be analyzed",
),
);
for (const binding of callBindings) {
const parameters = nodes.filter(
(node) => node.procedure === binding.callee && node.kind === "parameter",
);
if (parameters.length === 0)
unknowns.push({
procedure: binding.caller,
address: null,
reason: `Parameter bindings for ${binding.callee} are unavailable or omitted`,
});
for (const node of parameters) {
const ordinal = node.parameter?.ordinal;
if (ordinal === undefined || ordinal >= binding.argument_count) {
unknowns.push({
procedure: binding.caller,
address: null,
reason: `Argument ${ordinal ?? "unknown"} for ${binding.callee} was not recovered`,
});
continue;
}
if (edges.length >= input.max_edges) {
truncated = true;
break;
}
edges.push({
source: binding.call,
target: node.id,
input_index: ordinal + 1,
kind: "argument-binding",
status: "derived",
evidence_id: binding.evidence_id,
});
}
if (binding.output)
for (const node of nodes.filter(
(node) =>
node.procedure === binding.callee &&
node.operation?.opcode === "RETURN" &&
node.operation.inputs.length > 1,
)) {
if (edges.length >= input.max_edges) {
truncated = true;
break;
}
edges.push({
source: node.id,
target: binding.call,
input_index: 1,
kind: "return-binding",
status: "derived",
evidence_id: node.evidence_id,
});
}
}
const page = nodes.slice(input.offset, input.offset + input.limit);
const pageIds = new Set(page.map(({ id }) => id));
const result = nativeValueTraceSchema.parse({
seed: input.procedure,
target_sha256: targetSha256,
nodes: page,
edges: edges.filter(({ source }) => pageIds.has(source)),
procedures,
unknowns,
total_nodes: nodes.length,
total_edges: edges.length,
decompilations,
next_offset:
input.offset + page.length < nodes.length
? input.offset + page.length
: null,
truncated: truncated || page.length !== nodes.length,
limitations: [
"Static decompiler def-use graphs cover recovered block members; when membership is unavailable they exclude operations marked dead. Logical CALL argument positions bind to recovered HighParam ordinals and RETURN values bind to recovered CALL outputs; these are decompiler-derived dependencies, not original source or runtime observations. Missing parameters, variadic arguments and alias dependencies remain unknown.",
"LOAD and STORE are memory operations; object fields, persistent state and RNG semantics are not inferred from names or pseudocode.",
"Traversal caps depth, decompilations, call-site resolutions, nodes, edges and node payloads (8 MiB). Complete serialized output is bounded to 32 MiB. Pagination reruns analysis and returns edges whose source is on the node page; endpoints outside the page retain stable identities.",
],
});
if (Buffer.byteLength(JSON.stringify(result)) > 32 * 1024 * 1024)
return err(
new AnalysisOutputError(
"trace_native_values",
"Graph output exceeds 32 MiB; lower max_nodes, max_edges or page limit",
),
);
return ok(result);
};
+3 -1
View File
@@ -394,8 +394,10 @@ export const captureTerminalFrames = (options: {
at_ms: atMs,
data: normalized,
});
options.recordEvent("frames", sequence);
// Queue the observed output before publishing it: reactive subscribers may
// synchronously resize the terminal in response to this journal entry.
options.renderer.write(data, atMs);
options.recordEvent("frames", sequence);
options.checkpoints.observeTerminal(normalized);
});
return () => truncated;
@@ -43,8 +43,13 @@ it("returns detached terminal and filesystem checkpoint observations", async ()
expect(frames).toHaveLength(22);
expect(frames.slice(0, 2).map(({ at_ms }) => at_ms)).toEqual([20, 10]);
expect(observed).toHaveLength(22);
if (frames[0] !== undefined) Reflect.set(frames[0], "cursor_x", 999);
expect((await renderer.frames())[0]?.cursor_x).not.toBe(999);
const frame = frames[0];
if (frame === undefined) throw new Error("expected observed frame");
const originalCursor = frame.cursor_x;
Reflect.set(frame, "cursor_x", 999);
const reread = await renderer.frames();
expect(reread).toHaveLength(frames.length);
expect(reread[0]?.cursor_x).toBe(originalCursor);
await renderer.dispose();
const scenario = parseProcessScenario(base);
@@ -55,7 +60,9 @@ it("returns detached terminal and filesystem checkpoint observations", async ()
{ signal: undefined },
);
const first = await checkpoints.finish({ files: [], truncated: false });
if (first[0] !== undefined) Reflect.set(first[0], "name", "tampered");
const checkpoint = first[0];
if (checkpoint === undefined) throw new Error("expected checkpoint");
Reflect.set(checkpoint, "name", "tampered");
const second = await checkpoints.finish({ files: [], truncated: false });
expect(second[0]?.name).toBe("before");
await checkpoints.dispose();
@@ -276,7 +283,7 @@ it("cancels filesystem snapshots before traversing declared roots", async () =>
});
it("parses bounded scenarios and rejects unordered events", () => {
expect(parseProcessScenario(base).timeout_ms).toBe(30_000);
const timeoutMs = parseProcessScenario(base).timeout_ms;
expect(() =>
parseProcessScenario({
...base,
@@ -295,7 +302,7 @@ it("parses bounded scenarios and rejects unordered events", () => {
expect(() =>
parseProcessScenario({
...base,
events: [{ type: "input", at_ms: 31_000, data: "late" }],
events: [{ type: "input", at_ms: timeoutMs + 1, data: "late" }],
}),
).toThrow(/after the scenario timeout/);
});
@@ -1,16 +0,0 @@
import { describe, expect, it } from "vitest";
import { completeReconstructionCoverageData } from "../domain/reconstructionCoverage.fixture.js";
import { reconstructionCoverageEvaluationInputSchema } from "./ReconstructionCoverageService.js";
describe("reconstruction coverage service input", () => {
it("accepts caller boundary identifiers longer than the former schema ceiling", () => {
const boundaryId = "b".repeat(1_000);
const parsed = reconstructionCoverageEvaluationInputSchema.parse({
coverage: completeReconstructionCoverageData(),
boundary_id: boundaryId,
});
expect(parsed.boundary_id).toBe(boundaryId);
});
});
@@ -12,7 +12,6 @@ import { jsonValueSchema } from "../domain/jsonValue.js";
import { processCaptureSchema } from "../domain/processCapture.js";
import {
reconstructionObligationLedgerSchema,
serializeReconstructionObligationLedger,
type ReconstructionObligationLedgerInput,
type ReconstructionObligationLedger,
type ReviewedReconstructionObligation,
@@ -153,13 +152,8 @@ describe("reconstruction obligation ledger", () => {
);
expect(first.obligations).toHaveLength(2);
expect(first).toEqual(second);
expect(second.ledger_id).toBe(first.ledger_id);
expect(second.closure_digest).toBe(first.closure_digest);
expect(first.obligations[0]?.source_state).toBe("reviewed");
expect(first.status).toBe("open");
expect(serializeReconstructionObligationLedger(first)).toBe(
serializeReconstructionObligationLedger(second),
);
});
it("does not let green unit evidence close a packaged-process obligation", () => {
-1
View File
@@ -92,7 +92,6 @@ describe("setup workflow", () => {
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(result.appliedActions).toEqual(["installed_skill"]);
expect(result.remediation).toContain("--install-hopper");
expect(result.remediation).toBe(
"Hopper is optional for non-Hopper providers. Rerun with --yes --install-hopper for deep native analysis.",
);
+1 -2
View File
@@ -26,7 +26,6 @@ describe("setup installer failure projection", () => {
] as const)("maps %s to %s", (reason, code) => {
const result = setupInstallFailure(reason as HopperInstallFailureReason);
expect(result).toMatchObject({ status: "failed", code });
if (result.status === "failed")
expect(result.remediation.length).toBeGreaterThan(20);
expect(result).toMatchObject({ remediation: expect.stringMatching(/\S/u) });
});
});
+6 -1
View File
@@ -6,6 +6,7 @@ import { silentLogger, type Logger } from "../logger.js";
import { GENERATED_AUXILIARY_PROVIDERS } from "../generatedMcpToolCatalog.js";
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
import { composeBinarySession } from "./BinarySessionComposition.js";
import { nativeHostCapabilities } from "../native/NativeHostCapabilities.js";
import { LazyAnalysisProvider } from "./LazyAnalysisProvider.js";
/**
@@ -32,7 +33,11 @@ export const createBinarySession = (
const generated = auxiliary.get(id);
if (generated === undefined)
throw new TypeError(`Missing generated provider metadata for ${id}`);
return new LazyAnalysisProvider({ ...generated, load });
return new LazyAnalysisProvider({
...generated,
capabilities: nativeHostCapabilities(generated.capabilities),
load,
});
};
return composeBinarySession(
new AnalysisProviderRegistry([hopper, ghidra], config.analysisProvider),
+118 -24
View File
@@ -7,9 +7,12 @@ import {
type ProviderIdentity,
type ExecutionOptions,
} from "../application/AnalysisProvider.js";
import { inspectBundleKeyedArchive } from "./KeyedArchiveReader.js";
import { basename, dirname } from "node:path";
import { inventoryArtifact } from "../application/ArtifactInventory.js";
import { extractArtifact } from "../application/ArtifactExtraction.js";
import { analyzeInterfaceBuilderBundle } from "../application/InterfaceBuilderAnalysis.js";
import { analyzeAppleAssetCatalogs } from "../application/AppleAssetCatalogAnalysis.js";
import {
ARTIFACT_ANALYSIS_OPERATIONS,
artifactInventoryInputSchema,
@@ -38,34 +41,47 @@ const IDENTITY: ProviderIdentity = Object.freeze(ARTIFACT_GRAPH_PROVIDER);
/** Read-only inventory and exclusively owned extraction provider. */
export class ArtifactProvider implements AnalysisProvider {
readonly #capabilities: readonly CapabilityDescriptor[];
constructor(
private readonly nativeMountEnabled = false,
private readonly integrityContinueEnabled = false,
) {}
readonly #capabilities: readonly CapabilityDescriptor[] = Object.freeze(
ARTIFACT_ANALYSIS_OPERATIONS.map((operation) =>
Object.freeze({
provider: IDENTITY,
operation,
available: true as const,
reason: null,
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess: operation !== "decode_interface_builder",
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: operation === "extract_artifact",
changesPermissions: false,
requiresRoot: false,
}),
limitations: Object.freeze([
"DMG child inventory is macOS-only and requires per-call approval plus operator policy; PKG remains root-hash-only.",
"ASAR files discovered in filesystem-backed inventories are expanded without bulk extraction; other nested containers remain recorded only.",
]),
platform: NodeJS.Platform = process.platform,
) {
this.#capabilities = Object.freeze(
ARTIFACT_ANALYSIS_OPERATIONS.map((operation) => {
const common = {
provider: IDENTITY,
operation,
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess:
operation !== "decode_interface_builder" &&
operation !== "inspect_keyed_archive",
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: operation === "extract_artifact",
changesPermissions: false,
requiresRoot: false,
}),
limitations: Object.freeze([
"DMG child inventory is macOS-only and requires per-call approval plus operator policy; PKG remains root-hash-only.",
"ASAR files discovered in filesystem-backed inventories are expanded without bulk extraction; other nested containers remain recorded only.",
]),
};
return Object.freeze(
operation === "inspect_asset_catalog" && platform !== "darwin"
? {
...common,
available: false as const,
availabilityCode: "unsupported_host" as const,
reason: "Apple asset catalogs require macOS assetutil.",
}
: { ...common, available: true as const, reason: null },
);
}),
),
);
);
}
identity(): ProviderIdentity {
return IDENTITY;
@@ -138,6 +154,53 @@ class ArtifactClient implements AnalysisClient {
}),
);
}
if (operation === "inspect_keyed_archive") {
const standalone =
this.target.kind === "artifact" && this.target.format === "plist";
if (
standalone &&
parameters.path !== undefined &&
parameters.path !== "." &&
parameters.path !== basename(this.target.path)
)
throw new ArtifactReaderFailure(
"path",
"For an active plist, path must select that archive (omit path or use its basename)",
);
const bundlePath = standalone
? dirname(this.target.path)
: this.target.sourcePath;
if (
bundlePath === undefined ||
(!standalone && !bundlePath.toLowerCase().endsWith(".app"))
)
throw new ArtifactReaderFailure(
"unavailable",
"inspect_keyed_archive requires an active plist or .app bundle",
);
const result = await inspectBundleKeyedArchive({
bundlePath,
targetSha256: this.target.sha256,
parameters: standalone
? { ...parameters, path: basename(this.target.path) }
: parameters,
...(options?.signal === undefined ? {} : { signal: options.signal }),
});
if (standalone && result.archive_sha256 !== this.target.sha256)
throw new ArtifactReaderFailure(
"integrity",
`Active archive digest changed: expected ${this.target.sha256}, observed ${result.archive_sha256}`,
);
return ok(
createAnalysisExecution(result, IDENTITY, {
limitations: result.limitations,
locations: [{ kind: "artifact-path", path: result.archive_path }],
}),
);
}
if (operation === "inspect_asset_catalog") {
return await this.inspectAssetCatalog(parameters, options);
}
if (operation === "extract_artifact") {
const parsed = artifactExtractionExecutionSchema.parse(parameters);
const result = await extractArtifact(
@@ -188,6 +251,37 @@ class ArtifactClient implements AnalysisClient {
return Promise.resolve();
}
private async inspectAssetCatalog(
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
) {
const bundlePath = this.target.sourcePath;
if (
this.target.kind !== "executable" ||
bundlePath === undefined ||
!bundlePath.toLowerCase().endsWith(".app")
)
throw new ArtifactReaderFailure(
"unavailable",
"inspect_asset_catalog requires an active .app bundle target",
);
const result = await analyzeAppleAssetCatalogs({
bundlePath,
targetSha256: this.target.sha256,
page: parameters,
...(options?.signal === undefined ? {} : { signal: options.signal }),
});
return ok(
createAnalysisExecution(result, IDENTITY, {
limitations: result.limitations,
locations: result.catalogs.map(({ path }) => ({
kind: "artifact-path" as const,
path,
})),
}),
);
}
private async inspectArtifact(
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
+2
View File
@@ -38,6 +38,8 @@ export class ArtifactReaderFailure extends Error {
| "cancelled"
| "format"
| "integrity"
| "io"
| "limit"
| "path"
| "policy"
| "unavailable",
+81
View File
@@ -0,0 +1,81 @@
import { describe, expect, it } from "vitest";
import { build, buildBinary } from "plist";
import { decodeKeyedArchiveBytes } from "./KeyedArchiveReader.js";
const archive = {
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: [
"$null",
{
$class: { UID: 4 },
child: { UID: 2 },
shared: { UID: 2 },
self: { UID: 1 },
conditional: { UID: 0 },
broken: { UID: 90 },
},
{ "NS.objects": [{ UID: 1 }, { UID: 3 }] },
"value",
{ $classname: "UnknownModel", $classes: ["UnknownModel", "NSObject"] },
],
$top: { root: { UID: 1 }, other: { UID: 2 } },
};
describe("inert keyed archive decoding", () => {
it("preserves CF$UID, malformed references and original pagination identities", () => {
const bytes = Buffer.from(
build({
...archive,
$objects: [
"$null",
{ bad: { CF$UID: -1 }, valid: { CF$UID: 2 }, broken: { CF$UID: 90 } },
"value",
],
}),
);
const graph = decodeKeyedArchiveBytes(bytes, {
root: "root",
offset: 1,
limit: 1,
});
expect(graph.roots).toEqual({ root: { UID: 1 } });
expect(graph.objects.map(({ id }) => id)).toEqual([1]);
expect(graph.next_offset).toBe(2);
expect(graph.references).toContainEqual(
expect.objectContaining({ source: 1, target: 90, status: "unresolved" }),
);
expect(graph.references).toContainEqual(
expect.objectContaining({ source: 1, target: null, status: "malformed" }),
);
expect(graph.references).toContainEqual(
expect.objectContaining({ source: 1, target: 2, status: "resolved" }),
);
});
it("rejects missing roots, malformed plist, and non-keyed archives", () => {
expect(() =>
decodeKeyedArchiveBytes(Buffer.from("bplist00bad"), {
offset: 0,
limit: 1,
}),
).toThrow();
expect(() =>
decodeKeyedArchiveBytes(Buffer.from(build({ ...archive, $top: {} })), {
offset: 0,
limit: 1,
}),
).toThrow("roots");
expect(() =>
decodeKeyedArchiveBytes(Buffer.from(build({ plain: true })), {
offset: 0,
limit: 1,
}),
).toThrow("NSKeyedArchiver");
expect(() =>
decodeKeyedArchiveBytes(Buffer.from(buildBinary(archive)), {
root: "missing",
offset: 0,
limit: 1,
}),
).toThrow("does not exist");
});
});
+132
View File
@@ -0,0 +1,132 @@
import { createHash } from "node:crypto";
import { parse, parseBinary } from "plist";
import { z } from "zod";
import type { JsonValue } from "../domain/jsonValue.js";
import {
keyedArchiveInputSchema,
keyedArchiveResultSchema,
projectKeyedArchive,
} from "../domain/keyedArchive.js";
import { DirectoryArtifactReader } from "./DirectoryArtifactReader.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
const MAX_BYTES = 64 * 1024 * 1024;
/** Parse inert plist bytes, preserving data and dates with explicit typed values. */
export const decodeKeyedArchiveBytes = (
bytes: Buffer,
selection: { root?: string | undefined; offset: number; limit: number },
) => {
if (bytes.length > MAX_BYTES)
throw new RangeError("Keyed archive exceeds 64 MiB");
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
const parsed: unknown = binary
? parseBinary(bytes)
: parse(bytes.toString("utf8"));
return {
archive_format: binary ? ("binary-plist" as const) : ("xml-plist" as const),
...projectKeyedArchive(normalizePlist(parsed), selection),
};
};
const normalizePlist = (value: unknown, depth = 0): JsonValue => {
if (depth > 128) throw new RangeError("Plist exceeds 128 nesting levels");
if (value instanceof Uint8Array)
return {
$plist_type: "data",
base64: Buffer.from(value).toString("base64"),
};
if (value instanceof Date)
return { $plist_type: "date", iso8601: value.toISOString() };
if (Array.isArray(value))
return value.map((item: unknown) => normalizePlist(item, depth + 1));
if (value !== null && typeof value === "object")
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [
key,
normalizePlist(item, depth + 1),
]),
);
return z
.union([z.string(), z.number().finite(), z.boolean(), z.null()])
.parse(value);
};
/** Read exactly one regular, contained bundle entry without following symlinks. */
export const inspectBundleKeyedArchive = async (input: {
bundlePath: string;
targetSha256: string;
parameters: unknown;
signal?: AbortSignal;
}) => {
const selected = keyedArchiveInputSchema.parse(input.parameters);
if (
selected.path.startsWith("/") ||
selected.path
.split("/")
.some((part) => part === ".." || part === "." || part.length === 0)
)
throw new ArtifactReaderFailure(
"path",
"Archive path must be a canonical relative bundle path",
);
const reader = new DirectoryArtifactReader(input.bundlePath);
try {
for await (const entry of reader.entries(input.signal)) {
if (entry.path !== selected.path) continue;
if (entry.kind !== "file")
throw new ArtifactReaderFailure(
"path",
"Archive must be a regular file, not a symlink or directory",
);
if ((entry.declaredSize ?? 0) > MAX_BYTES)
throw new ArtifactReaderFailure(
"limit",
"Keyed archive exceeds 64 MiB",
);
const stream = await reader.open(entry, input.signal);
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of stream) {
if (input.signal?.aborted) {
stream.destroy();
throw new ArtifactReaderFailure(
"cancelled",
"Archive inspection cancelled",
);
}
const bytes = z.instanceof(Buffer).parse(chunk);
size += bytes.length;
if (size > MAX_BYTES) {
stream.destroy();
throw new ArtifactReaderFailure(
"limit",
"Keyed archive exceeds 64 MiB",
);
}
chunks.push(bytes);
}
const bytes = Buffer.concat(chunks, size);
try {
return keyedArchiveResultSchema.parse({
target_sha256: input.targetSha256,
archive_path: entry.path,
archive_sha256: createHash("sha256").update(bytes).digest("hex"),
...decodeKeyedArchiveBytes(bytes, selected),
});
} catch (cause) {
throw new ArtifactReaderFailure(
cause instanceof RangeError ? "limit" : "format",
"Cannot decode selected Foundation keyed archive",
{ cause },
);
}
}
throw new ArtifactReaderFailure(
"path",
`Archive not found in bundle: ${selected.path}`,
);
} finally {
await reader.close();
}
};
@@ -189,28 +189,6 @@ class FakeSession implements BrowserScenarioSessionPort {
}
describe("PlaywrightBrowserScenarioProvider", () => {
it("captures initial and action steps and closes its launched session", async () => {
const session = new FakeSession("launch");
const provider = new PlaywrightBrowserScenarioProvider({
open: () => Promise.resolve(session),
});
const result = await provider.captureScenario(scenario());
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.steps.map(({ step_index }) => step_index)).toEqual([
0, 1,
]);
expect(result.value.browser).toMatchObject({
process_ownership: "provider-owned",
cleanup: "terminated-owned-process",
});
expect(result.value.completeness).toMatchObject({
status: "complete",
equality_eligible: true,
});
expect(session.closeCalls).toBe(1);
});
it("returns an initial state and every step beyond the former action ceiling", async () => {
const session = new FakeSession("launch");
const provider = new PlaywrightBrowserScenarioProvider({
@@ -39,31 +39,3 @@ it("returns a complete requested text artifact beyond the former inline ceiling"
value: { bytes: 16 * 1_024 * 1_024 + 1 },
});
});
it("wraps URL, history, and storage snapshots in the capture state contract", async () => {
const page = {
url: () => "https://app.example.test/path?token=secret",
evaluate: async (expression: string) =>
expression.includes("window.history.length")
? {
length: 2,
navigation_entries: [
{ type: "navigate", name: "https://app.example.test/path" },
],
}
: { local_storage: [], session_storage: [] },
} as unknown as Page;
const context = { cookies: async () => [] } as unknown as BrowserContext;
const result = await capturePlaywrightStepArtifacts({
context,
page,
scenario,
secrets,
requested: new Set(["url", "history", "storage"]),
});
expect(result.url.state).toBe("captured");
expect(result.history.state).toBe("captured");
expect(result.storage.state).toBe("captured");
});
+5 -1
View File
@@ -1,4 +1,4 @@
import { deflateSync } from "node:zlib";
import { crc32, deflateSync } from "node:zlib";
import { describe, expect, it } from "vitest";
@@ -111,5 +111,9 @@ const chunk = (type: string, data: Buffer): Buffer => {
result.writeUInt32BE(data.byteLength, 0);
result.write(type, 4, 4, "ascii");
data.copy(result, 8);
result.writeUInt32BE(
crc32(result.subarray(4, 8 + data.byteLength)),
8 + data.byteLength,
);
return result;
};
+77
View File
@@ -14,6 +14,83 @@ export const registerArtifactCommands = (
registerInspectionCommand(cli, logger);
registerExtractionCommand(cli, logger);
registerInterfaceBuilderCommand(cli, logger);
registerAssetCatalogCommand(cli, logger);
cli.command(CLI_COMMANDS.inspectKeyedArchive, {
description:
"Inspect a Foundation keyed archive as an object-reference graph",
args: z.object({
path: z.string().describe("Foundation plist archive or Apple app bundle"),
archive: z
.string()
.default(".")
.describe("Relative archive path when the target is a bundle"),
}),
options: z.object({
root: z.string().optional().describe("Named $top archive root"),
offset: z
.number()
.int()
.min(0)
.default(0)
.describe("First original object-table index"),
limit: z
.number()
.int()
.min(1)
.max(20000)
.default(20000)
.describe("Maximum object-table entries to return"),
}),
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.inspectKeyedArchive, () =>
runProviderAnalysis(
args.path,
"inspect_keyed_archive",
{
path: args.archive,
offset: options.offset,
limit: options.limit,
...(options.root === undefined ? {} : { root: options.root }),
},
logger,
),
),
});
};
const registerAssetCatalogCommand = (
cli: CliInstance,
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.inspectAssetCatalog, {
description: "Inspect compiled Apple asset catalog metadata",
args: z.object({ path: z.string().describe("Apple .app bundle path") }),
options: z.object({
offset: z
.number()
.int()
.min(0)
.default(0)
.describe("First metadata record"),
limit: z
.number()
.int()
.min(1)
.max(10_000)
.default(1_000)
.describe("Maximum records to return"),
}),
alias: {},
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.inspectAssetCatalog, () =>
runProviderAnalysis(
args.path,
"inspect_asset_catalog",
{ offset: options.offset, limit: options.limit },
logger,
),
),
});
};
const registerInterfaceBuilderCommand = (
+135
View File
@@ -15,6 +15,141 @@ export const registerCoreAnalysisCommands = (
logger: Logger,
): void => {
registerCoreCommands(cli, logger);
cli.command(CLI_COMMANDS.traceNativeValues, {
description: "Trace bounded native def-use and call dependencies",
args: z.object({
path: z.string().describe("Local native executable or app path"),
procedure: z
.string()
.describe("Explicit native procedure symbol or address"),
}),
options: z.object({
maxDepth: z
.number()
.int()
.min(0)
.max(16)
.default(3)
.describe("Maximum call traversal depth"),
maxFunctions: z
.number()
.int()
.min(1)
.max(64)
.default(16)
.describe("Maximum function decompilations"),
maxCallSites: z
.number()
.int()
.min(1)
.max(4096)
.default(256)
.describe("Maximum static call-site resolutions"),
maxNodes: z
.number()
.int()
.min(1)
.max(20000)
.default(5000)
.describe("Maximum retained graph nodes"),
maxEdges: z
.number()
.int()
.min(1)
.max(40000)
.default(10000)
.describe("Maximum retained graph edges"),
offset: z
.number()
.int()
.min(0)
.default(0)
.describe("First graph node index"),
limit: z
.number()
.int()
.min(1)
.max(5000)
.default(1000)
.describe("Maximum nodes on this page"),
provider: providerSelectionOption,
}),
alias: {
maxDepth: "max-depth",
maxFunctions: "max-functions",
maxCallSites: "max-call-sites",
maxNodes: "max-nodes",
maxEdges: "max-edges",
},
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.traceNativeValues, () =>
runDirectAnalysis(
args.path,
"trace_native_values",
{
procedure: args.procedure,
max_depth: options.maxDepth,
max_functions: options.maxFunctions,
max_call_sites: options.maxCallSites,
max_nodes: options.maxNodes,
max_edges: options.maxEdges,
offset: options.offset,
limit: options.limit,
},
directAnalysisOptions(logger, undefined, options.provider),
),
),
});
cli.command(CLI_COMMANDS.inspectNativeDataType, {
description: "Inspect one recovered database type or typed data object",
args: z.object({
path: z.string().describe("Local native executable or app path"),
}),
options: z.object({
type: z.string().optional().describe("Exact database type category path"),
address: z.string().describe("Exact native address").optional(),
provider: providerSelectionOption,
}),
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.inspectNativeDataType, () =>
runDirectAnalysis(
args.path,
"inspect_native_data_type",
{
...(options.type === undefined ? {} : { type: options.type }),
...(options.address === undefined
? {}
: { address: options.address }),
},
directAnalysisOptions(logger, undefined, options.provider),
),
),
});
for (const [command, operation] of [
[CLI_COMMANDS.inspectNativeInstruction, "inspect_native_instruction"],
[CLI_COMMANDS.resolveNativeCallTargets, "resolve_native_call_targets"],
] as const) {
cli.command(command, {
description:
operation === "inspect_native_instruction"
? "Inspect one native instruction with decoded operand facts"
: "Resolve one static native call site",
args: z.object({
path: z.string().describe("Local native executable or app path"),
address: z.string().describe("Exact native address"),
}),
options: z.object({ provider: providerSelectionOption }),
run: ({ args, options }) =>
logCliCommand(logger, command, () =>
runDirectAnalysis(
args.path,
operation,
{ address: args.address },
directAnalysisOptions(logger, undefined, options.provider),
),
),
});
}
registerFunctionCommand(cli, logger);
registerNativeApiCommand(cli, logger);
registerInstructionsCommand(cli, logger);
+90
View File
@@ -1,4 +1,5 @@
import { z } from "incur";
import { jsonValueSchema } from "../domain/jsonValue.js";
import {
runCapabilityStatus,
@@ -21,6 +22,95 @@ export const registerUtilityCommands = (
): void => {
registerCapabilityCommands(cli, logger);
registerNativeCommands(cli, logger);
for (const [command, operation] of [
[CLI_COMMANDS.observeNativeUi, "observe_native_ui"],
[CLI_COMMANDS.captureNativeUiScenario, "capture_native_ui_scenario"],
] as const) {
cli.command(command, {
description:
"Observe or run an approved scenario in one exact native application window",
args: z.object({
path: z.string().describe("Local native executable or app path"),
}),
options: z.object({
pid: z
.number()
.int()
.positive()
.describe("Approved existing application PID"),
windowId: z
.number()
.int()
.positive()
.describe("Exact selected application window ID"),
observationApproved: z
.boolean()
.default(false)
.describe("Approve passive observation of this PID/window"),
actionsApproved: z
.boolean()
.default(false)
.describe("Independently approve scenario actions"),
restore: z
.enum(["leave-as-is"])
.optional()
.describe("Explicit choice to leave application state as-is"),
steps: z
.string()
.optional()
.describe("JSON array of approved declarative AX actions or waits"),
screenshot: z
.boolean()
.default(true)
.describe("Capture only the selected window"),
accessibility: z
.boolean()
.default(true)
.describe("Read the selected window accessibility tree"),
maxNodes: z
.number()
.int()
.min(1)
.max(2000)
.default(500)
.describe("Maximum accessibility nodes per capture"),
}),
alias: {
windowId: "window-id",
observationApproved: "observation-approved",
actionsApproved: "actions-approved",
maxNodes: "max-nodes",
},
run: ({ args, options }) =>
logCliCommand(logger, command, () =>
runProviderAnalysis(
args.path,
operation,
{
pid: options.pid,
window_id: options.windowId,
observation_approved: options.observationApproved,
screenshot: options.screenshot,
accessibility: options.accessibility,
max_nodes: options.maxNodes,
...(operation === "capture_native_ui_scenario"
? {
actions_approved: options.actionsApproved,
...(options.restore === undefined
? {}
: { restore: options.restore }),
steps:
options.steps === undefined
? []
: jsonValueSchema.parse(JSON.parse(options.steps)),
}
: {}),
},
logger,
),
),
});
}
registerReferenceSourceCommand(cli, logger);
};
+8
View File
@@ -21,6 +21,12 @@ export const CLI_COMMANDS = Object.freeze({
inspectArtifact: "inspect-artifact",
extractArtifact: "extract-artifact",
decodeInterfaceBuilder: "decode-interface-builder",
inspectKeyedArchive: "inspect-keyed-archive",
inspectNativeDataType: "inspect-native-data-type",
traceNativeValues: "trace-native-values",
inspectNativeInstruction: "inspect-native-instruction",
resolveNativeCallTargets: "resolve-native-call-targets",
inspectAssetCatalog: "inspect-asset-catalog",
inspectManagedArtifact: "inspect-managed-artifact",
inspectManagedMembers: "inspect-managed-members",
inspectManagedNativeBoundaries: "inspect-managed-native-boundaries",
@@ -29,6 +35,8 @@ export const CLI_COMMANDS = Object.freeze({
importManagedReconstruction: "import-managed-reconstruction",
planManagedRuntimeCorrelation: "plan-managed-runtime-correlation",
projectManagedApplicationGraph: "project-managed-application-graph",
observeNativeUi: "observe-native-ui",
captureNativeUiScenario: "capture-native-ui-scenario",
inspectMacho: "inspect-macho",
inspectSignature: "inspect-signature",
listArchitectures: "list-architectures",
+13 -12
View File
@@ -4,17 +4,18 @@ import { parseConfig } from "./config.js";
describe("capability flags", () => {
it("rejects values outside the exact true/false boundary", () => {
const result = parseConfig({
REA_PROCESS_CAPTURE_ENABLED: "typo",
REA_BROWSER_OBSERVE_ENABLED: "typo",
REA_BROWSER_SCENARIO_ENABLED: "typo",
REA_ELECTRON_OBSERVE_ENABLED: "typo",
REA_ELECTRON_AUTOMATE_ENABLED: "typo",
REA_V8_INSPECTOR_OBSERVE_ENABLED: "typo",
REA_JAVASCRIPT_REPLAY_ENABLED: "typo",
REA_MANAGED_RUNTIME_ENABLED: "typo",
});
expect(result.ok).toBe(false);
for (const key of [
"REA_PROCESS_CAPTURE_ENABLED",
"REA_BROWSER_OBSERVE_ENABLED",
"REA_BROWSER_SCENARIO_ENABLED",
"REA_ELECTRON_OBSERVE_ENABLED",
"REA_ELECTRON_AUTOMATE_ENABLED",
"REA_V8_INSPECTOR_OBSERVE_ENABLED",
"REA_JAVASCRIPT_REPLAY_ENABLED",
"REA_MANAGED_RUNTIME_ENABLED",
]) {
const result = parseConfig({ [key]: "typo" });
expect(result.ok, key).toBe(false);
}
});
});
-86
View File
@@ -1,86 +0,0 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "./config.js";
describe("configuration parsing integration", () => {
it("returns defaults when no environment variables are set", () => {
const result = parseConfig({});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperLauncherPath).toBe(
process.platform === "linux"
? "/opt/hopper/bin/Hopper"
: "/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
);
expect(result.value.hopperTargetPath).toBeUndefined();
expect(result.value.hopperTargetKind).toBe("executable");
expect(result.value.hopperLoaderArgs).toEqual([]);
expect(result.value.analysisProvider).toBe("auto");
});
it("parses a complete target-bound configuration", () => {
const result = parseConfig({
HOPPER_TARGET_PATH: "/usr/bin/true",
HOPPER_TARGET_KIND: "executable",
HOPPER_LOADER_ARGS_JSON: '["-l","Mach-O","--aarch64"]',
REA_ANALYSIS_PROVIDER: "hopper",
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperTargetPath).toBe("/usr/bin/true");
expect(result.value.hopperTargetKind).toBe("executable");
expect(result.value.analysisProvider).toBe("hopper");
expect(result.value.hopperLoaderArgs).toEqual([
"-l",
"Mach-O",
"--aarch64",
]);
});
it("rejects target kind values outside the enum", () => {
const result = parseConfig({
HOPPER_TARGET_KIND: "archive",
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("unreachable");
expect(result.error.message).toContain("Invalid REA environment");
});
it("rejects invalid JSON in loader arguments", () => {
const result = parseConfig({
HOPPER_LOADER_ARGS_JSON: "not json",
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("unreachable");
expect(result.error.message).toContain("valid JSON");
});
it("rejects non-array types in loader arguments JSON", () => {
const result = parseConfig({
HOPPER_LOADER_ARGS_JSON: '"just a string"',
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("unreachable");
expect(result.error.message).toContain("array of strings");
});
it("allows overriding the launcher path while keeping other defaults", () => {
const result = parseConfig({
HOPPER_LAUNCHER_PATH: "/custom/hopper",
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperLauncherPath).toBe("/custom/hopper");
expect(result.value.hopperTargetPath).toBeUndefined();
});
it("parses database target kind correctly", () => {
const result = parseConfig({
HOPPER_TARGET_PATH: "/path/to/file.hop",
HOPPER_TARGET_KIND: "database",
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperTargetKind).toBe("database");
});
});
+22 -11
View File
@@ -302,6 +302,13 @@ describe("runtime permission configuration", () => {
});
describe("runtime target configuration", () => {
it("rejects invalid target kinds with actionable environment diagnostics", () => {
const result = parseConfig({ HOPPER_TARGET_KIND: "archive" });
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected invalid target kind");
expect(result.error.message).toContain("Invalid REA environment");
});
it("builds a no-network managed runtime ceiling only when enabled", () => {
const result = parseConfig({
REA_MANAGED_RUNTIME_ENABLED: "true",
@@ -361,6 +368,8 @@ describe("runtime target configuration", () => {
it("parses database kind and loader arguments", () => {
expect(
parseConfig({
HOPPER_LAUNCHER_PATH: "/custom/hopper",
REA_ANALYSIS_PROVIDER: "hopper",
HOPPER_TARGET_PATH: "/fixture/sample.hop",
HOPPER_TARGET_KIND: "database",
HOPPER_LOADER_ARGS_JSON: '["-l","FAT","--aarch64","-l","Mach-O"]',
@@ -368,10 +377,8 @@ describe("runtime target configuration", () => {
).toMatchObject({
ok: true,
value: {
hopperLauncherPath:
process.platform === "linux"
? "/opt/hopper/bin/Hopper"
: "/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
hopperLauncherPath: "/custom/hopper",
analysisProvider: "hopper",
hopperTargetPath: "/fixture/sample.hop",
hopperTargetKind: "database",
hopperLoaderArgs: ["-l", "FAT", "--aarch64", "-l", "Mach-O"],
@@ -389,15 +396,19 @@ describe("runtime target configuration", () => {
});
describe("runtime collection configuration", () => {
it.each(["not-json", "{}", '["ok",1]'])(
it.each(["not-json", "{}", '"just a string"', '["ok",1]'])(
"rejects invalid loader args: %s",
(encoded) => {
expect(
parseConfig({
HOPPER_TARGET_PATH: "/tmp/a",
HOPPER_LOADER_ARGS_JSON: encoded,
}).ok,
).toBe(false);
const result = parseConfig({
HOPPER_TARGET_PATH: "/tmp/a",
HOPPER_LOADER_ARGS_JSON: encoded,
});
expect(result.ok).toBe(false);
if (result.ok)
throw new Error("expected malformed loader arguments to fail");
expect(result.error.message).toContain(
encoded === "not-json" ? "valid JSON" : "array of strings",
);
},
);
+14
View File
@@ -5,6 +5,8 @@ import { artifactOutputSchemas } from "./toolOutputSchemas.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { toolContractMetadata } from "./toolEffects.js";
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
import { appleAssetCatalogInputSchema } from "../domain/appleAssetCatalog.js";
import { keyedArchiveInputSchema } from "../domain/keyedArchive.js";
const integrityInput = {
fail: {
integrity_policy: z.literal("fail").default("fail"),
@@ -39,6 +41,8 @@ const examples: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
inspect_artifact: {},
extract_artifact: {},
decode_interface_builder: {},
inspect_asset_catalog: { offset: 0, limit: 1000 },
inspect_keyed_archive: { path: "Contents/Resources/Model.plist" },
};
const artifact = <
@@ -87,6 +91,16 @@ export const ARTIFACT_TOOL_CONTRACTS = [
max_connections: z.number().int().min(1).max(40_000).default(40_000),
}),
),
artifact(
"inspect_keyed_archive",
"Inspect one Foundation NSKeyedArchiver plist in the active app bundle as original object-table nodes, class descriptors, named roots, and UID edges. Preserves shared and cyclic references without instantiating classes. The path is relative to the bundle; root selection and object pagination preserve original identities.",
keyedArchiveInputSchema,
),
artifact(
"inspect_asset_catalog",
"Inspect compiled Assets.car metadata in an active Apple app bundle. Returns stable paginated catalog and rendition records with raw assetutil metadata and catalog digests; rendition bytes are not extracted.",
appleAssetCatalogInputSchema,
),
] as const satisfies readonly ToolContract[];
/** Provider operations; inventory remains an internal primitive of inspection. */
+3 -97
View File
@@ -5,7 +5,6 @@ import {
ENHANCED_TOOL_CONTRACTS,
OFFICIAL_TOOL_CONTRACTS,
SESSION_TOOL_CONTRACTS,
TOOL_CONTRACTS,
} from "./toolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
@@ -16,47 +15,10 @@ import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "./browserScenarioToolContracts.
import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascriptRuntimeObservationToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
import {
enhancedOutputSchemas,
managedOutputSchemas,
managedWorkflowOutputSchemas,
officialOutputSchemas,
sessionOutputSchemas,
} from "./toolOutputSchemas.js";
import { annotationsFromEffects, TOOL_EFFECTS } from "./toolEffects.js";
import { TOOL_EFFECTS } from "./toolEffects.js";
const convertContractJsonSchema = (schema: z.ZodType) =>
z.toJSONSchema(schema, {
target: "draft-07",
unrepresentable: "any",
});
const jsonSchemaCache = new WeakMap<
z.ZodType,
ReturnType<typeof convertContractJsonSchema>
>();
const contractJsonSchema = (schema: z.ZodType) => {
const cached = jsonSchemaCache.get(schema);
if (cached !== undefined) return cached;
const converted = convertContractJsonSchema(schema);
jsonSchemaCache.set(schema, converted);
return converted;
};
const describesObject = (schema: ReturnType<typeof contractJsonSchema>) =>
schema.type === "object" ||
[schema.oneOf, schema.anyOf].some(
(variants) =>
Array.isArray(variants) &&
variants.every(
(variant) =>
typeof variant === "object" &&
variant !== null &&
"type" in variant &&
variant.type === "object",
),
);
const contractJsonSchema = (schema: z.ZodType) =>
z.toJSONSchema(schema, { target: "draft-07", unrepresentable: "any" });
describe("tool contract surface", () => {
it("advertises capture comparison alternatives on an object root", () => {
@@ -98,32 +60,6 @@ describe("tool contract surface", () => {
expect(contract.inputSchema.safeParse(incomplete).success).toBe(false);
});
it("advertises complete typed schemas and annotations for every public tool", () => {
const contracts = TOOL_CONTRACTS;
for (const contract of contracts) {
const inputSchema = contractJsonSchema(contract.inputSchema);
const outputSchema = contractJsonSchema(contract.outputSchema);
expect(describesObject(inputSchema), contract.name).toBe(true);
expect(describesObject(outputSchema)).toBe(true);
expect(contract.title.length).toBeGreaterThan(2);
expect(contract.annotations).toEqual(
annotationsFromEffects(contract.effects),
);
expect(typeof contract.annotations.idempotentHint).toBe("boolean");
expect(typeof contract.annotations.openWorldHint).toBe("boolean");
expect(typeof contract.annotations.readOnlyHint).toBe("boolean");
expect(typeof contract.annotations.destructiveHint).toBe("boolean");
expect(contract.examples.length).toBeGreaterThan(0);
for (const example of contract.examples) {
expect(example.title.trim().length).toBeGreaterThan(0);
expect(
contract.inputSchema.safeParse(example.input).success,
`${contract.name}: ${example.title}`,
).toBe(true);
}
}
});
it("audits every tool effect explicitly with no heuristic fallback", () => {
const names = [
...OFFICIAL_TOOL_CONTRACTS,
@@ -166,34 +102,4 @@ describe("tool contract surface", () => {
destructiveHint: false,
});
});
it("publishes a dedicated output schema and agent guidance for every tool", () => {
expect(Object.keys(officialOutputSchemas).sort()).toEqual(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
expect(Object.keys(enhancedOutputSchemas).sort()).toEqual(
ENHANCED_TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
expect(Object.keys(sessionOutputSchemas).sort()).toEqual(
SESSION_TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
expect(Object.keys(managedOutputSchemas).sort()).toEqual(
MANAGED_TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
expect(Object.keys(managedWorkflowOutputSchemas).sort()).toEqual(
MANAGED_WORKFLOW_TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
for (const contract of [
...OFFICIAL_TOOL_CONTRACTS,
...ENHANCED_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...MANAGED_WORKFLOW_TOOL_CONTRACTS,
...SESSION_TOOL_CONTRACTS,
]) {
const schema = contractJsonSchema(contract.outputSchema);
expect(JSON.stringify(schema)).not.toContain('"result":{}');
expect(contract.description.trim().length).toBeGreaterThan(0);
}
});
});
+5 -1
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { nativeValueTraceInputSchema } from "../domain/nativeValueTrace.js";
const traceLiteralInputSchema = z.strictObject({
query: z.string().min(1),
case_sensitive: z.boolean().default(false),
@@ -6,6 +7,7 @@ const traceLiteralInputSchema = z.strictObject({
/** Input schemas shared by MCP registration and enhanced application dispatch. */
export const enhancedInputSchemas = {
trace_native_values: nativeValueTraceInputSchema,
inspect_native_dispatch_metadata: z.strictObject({
max_records: z.number().int().min(1).max(20_000).default(5_000),
}),
@@ -54,7 +56,9 @@ export const enhancedInputSchemas = {
action: z
.string()
.min(1)
.describe("A unique compiled UI action selector or interface object ID"),
.describe(
"A unique compiled UI action selector, interface object ID, native symbol or exact function address",
),
max_depth: z.number().int().min(0).max(32).default(8),
max_nodes: z.number().int().min(1).max(2_000).default(250),
max_edges: z.number().int().min(1).max(5_000).default(500),
+23
View File
@@ -1,4 +1,8 @@
import { z } from "zod";
import {
nativeUiObservationInputSchema,
nativeUiScenarioInputSchema,
} from "../domain/nativeUiObservation.js";
import type { ToolContract } from "./toolContracts.js";
import { nativeOutputSchemas } from "./toolOutputSchemas.js";
@@ -11,6 +15,15 @@ const examples: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
inspect_signature: {},
inspect_plist: { path: "/Applications/Example.app/Contents/Info.plist" },
list_architectures: {},
observe_native_ui: { pid: 123, window_id: 456, observation_approved: true },
capture_native_ui_scenario: {
pid: 123,
window_id: 456,
observation_approved: true,
actions_approved: true,
restore: "leave-as-is",
steps: [{ kind: "wait", milliseconds: 100 }],
},
demangle_swift: { symbols: ["$s4Test3fooyyF"] },
};
@@ -40,6 +53,16 @@ const native = <Name extends string, Schema extends z.ZodObject>(
/** Provider-neutral semantic operations backed initially by macOS utilities. */
export const NATIVE_TOOL_CONTRACTS = [
native(
"observe_native_ui",
"Passively observe one explicitly approved already-running native app PID and window ID bound to the active Mach-O target. Captures a bounded accessibility tree and selected-window screenshot; OS permission denial fails without broad capture or target launch.",
nativeUiObservationInputSchema,
),
native(
"capture_native_ui_scenario",
"Run separately approved selected-element press, increment/decrement scroll, AXValue text entry and bounded wait steps in one exact native app window. Returns ordered before/after captures and action/capture failures. Actions can change app data, network activity and persistent state. The caller must choose leave-as-is; automatic restoration is unsupported.",
nativeUiScenarioInputSchema,
),
native(
"inspect_macho",
"Inspect Mach-O slices, load commands, imports, exports, dependencies, build metadata, segments, sections, permissions, and exact command provenance without launching Hopper.",
+13 -7
View File
@@ -53,7 +53,7 @@ describe("guided prompt contracts", () => {
});
// Assert the properties an analyst depends on rather than thirteen
// incidental fragments, so a copy edit is a reviewable diff instead of a
// wall of failures. The wording is still pinned by the last assertion.
// wall of failures.
// Untrusted caller input must be framed as data, never as instruction.
expect(rendered).toMatch(/not instructions/i);
expect(rendered).toContain(
@@ -67,12 +67,6 @@ describe("guided prompt contracts", () => {
expect(rendered).toContain(section);
// Tools are never a grant of authority.
expect(rendered).toMatch(/never as authorization/i);
expect(rendered.indexOf("`list_documents`")).toBeLessThan(
rendered.indexOf("`search_strings`"),
);
expect(rendered.indexOf("`search_strings`")).toBeLessThan(
rendered.indexOf("`analyze_function`"),
);
});
it("orders mutation and execution after inspection and preparation", () => {
@@ -82,6 +76,12 @@ describe("guided prompt contracts", () => {
renderGuidedPrompt(prompt, {}),
]),
);
expect(rendered.get("audit_residual_unknowns")).toContain(
"`list_unknowns`",
);
expect(rendered.get("audit_residual_unknowns")).toContain(
"`update_unknown`",
);
expect(
rendered.get("audit_residual_unknowns")?.indexOf("`list_unknowns`"),
).toBeLessThan(
@@ -95,6 +95,12 @@ describe("guided prompt contracts", () => {
.get("prepare_bounded_process_capture")
?.indexOf("`capture_process_scenario`"),
).toBeGreaterThanOrEqual(0);
expect(rendered.get("compare_application_versions")).toContain(
"`inspect_artifact`",
);
expect(rendered.get("compare_application_versions")).toContain(
"`compare_artifacts`",
);
expect(
rendered
.get("compare_application_versions")
+4
View File
@@ -21,6 +21,10 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
procedure_callees: { procedure: "main" },
procedure_callers: { procedure: "main" },
procedure_info: { procedure: "main" },
trace_native_values: { procedure: "0x1000" },
inspect_native_data_type: { type: "/MyStruct" },
inspect_native_instruction: { address: "0x1000" },
resolve_native_call_targets: { address: "0x1000" },
read_function_instructions: { procedure: "main" },
read_bytes: { address: "0x1000", length: 16 },
address_to_file_offset: { address: "0x1000" },
+1
View File
@@ -91,6 +91,7 @@ const PUBLISHED_TOOL_NAME_FLOOR = [
"inline_comment",
"inspect_address_context",
"inspect_artifact",
"inspect_asset_catalog",
"inspect_electron_page",
"inspect_macho",
"inspect_managed_artifact",
+23 -1
View File
@@ -46,6 +46,8 @@ import {
} from "./toolContractHelpers.js";
import type { ToolContract } from "./toolContractTypes.js";
import { toolContractMetadata } from "./toolEffects.js";
import { nativeDataTypeInputSchema } from "../domain/nativeDataType.js";
import { nativeInstructionInputSchema } from "../domain/nativeInstruction.js";
import { functionInstructionInputSchema } from "./functionInstructionContract.js";
import { HOPPER_MEMORY_TOOL_DEFINITIONS } from "./hopperMemoryContracts.js";
import { analysisSearchInput } from "./analysisSearchContract.js";
@@ -111,6 +113,21 @@ const session = <Name extends string, Schema extends z.ZodObject>(
/** Bridge operations exposed without additional application composition. */
export const OFFICIAL_TOOL_CONTRACTS = [
official(
"inspect_native_data_type",
"Inspect one recovered type by exact database category path or defined typed data address. Returns observed size, alignment, packing, fields, bitfields, enum values, and child type identities; source-level authority and flexible-tail semantics remain unknown unless substantiated.",
nativeDataTypeInputSchema,
),
official(
"inspect_native_instruction",
"Inspect one exact instruction address: decoded bytes, mnemonic, ordered operand tokens, flow and typed references. Memory addressing decomposition is unavailable when the provider supplies only tokens. Data, interior instruction addresses and undecodable bytes are distinct outcomes.",
nativeInstructionInputSchema,
),
official(
"resolve_native_call_targets",
"Resolve one explicit static call site using typed provider call references. Preserves ambiguous targets as candidates and unresolved computed calls as unknown; does not execute code or traverse a call graph.",
nativeInstructionInputSchema,
),
official(
"address_name",
"Resolve the primary analyzed name at a code or data address. Headless providers require an explicit address; GUI providers may default to their current cursor. Null means the provider has no primary name at that address.",
@@ -353,9 +370,14 @@ export const ENHANCED_TOOL_CONTRACTS = [
),
enhanced(
"trace_native_ui_action",
"Trace one unique compiled Interface Builder action selector or object ID through its authored UI connections to symbolized Objective-C handlers and bounded direct callees. REA decodes the active app bundle and reads the selected provider's symbol inventory itself. Authored connections, statically matched handlers, resolved direct calls, and unresolved dynamic dispatch remain distinct; runtime reachability and cross-function value flow are not claimed.",
"Trace one unique compiled UI action, object ID, native symbol or exact function address through authored connections, encoded or symbolized Objective-C handlers, and bounded static call references. Typed direct and resolved indirect calls, ambiguous candidates, inferred untyped provider callees, and targetless sites remain distinct. Runtime reachability is unknown; use trace_native_values for recovered value dependencies.",
enhancedInputSchemas.trace_native_ui_action,
),
enhanced(
"trace_native_values",
"Trace a bounded static dependency graph from one explicit native procedure. Includes high-p-code def-use, constants, operators, memory and branch operations, resolved call edges, and derived argument/parameter and return/output bindings. Missing bindings, alias semantics, persistent state and RNG roles remain unknown. Budgets bound depth, decompilations, graph size and payloads; nodes are paginated.",
enhancedInputSchemas.trace_native_values,
),
] as const satisfies readonly ToolContract[];
/** Session-owned Evidence bundle export options. */
+21
View File
@@ -42,6 +42,7 @@ const sessionEvidence = effects({ mutatesSession: true });
export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
inspect_native_dispatch_metadata: evidence,
trace_native_ui_action: evidence,
trace_native_values: evidence,
address_name: evidence,
comment: evidence,
current_address: evidence,
@@ -63,6 +64,9 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
procedure_callers: evidence,
procedure_info: evidence,
read_function_instructions: evidence,
inspect_native_instruction: evidence,
inspect_native_data_type: evidence,
resolve_native_call_targets: evidence,
read_bytes: evidence,
address_to_file_offset: evidence,
procedure_references: evidence,
@@ -94,6 +98,21 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
trace_feature: effects({ mutatesSession: true, idempotent: false }),
find_code_for_string: effects({ mutatesSession: true, idempotent: false }),
trace_call_path: effects({ mutatesSession: true, idempotent: false }),
observe_native_ui: effects({
mutatesSession: true,
launchesProcess: true,
writesFilesystem: true,
}),
capture_native_ui_scenario: effects({
writesFilesystem: true,
mutatesTarget: true,
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
changesUiState: true,
mayDiscardData: true,
idempotent: false,
}),
inspect_macho: nativeEvidence,
inspect_signature: nativeEvidence,
inspect_plist: nativeEvidence,
@@ -102,6 +121,8 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
inspect_artifact: evidence,
extract_artifact: effects({ mutatesSession: true, writesFilesystem: true }),
decode_interface_builder: evidence,
inspect_asset_catalog: nativeEvidence,
inspect_keyed_archive: evidence,
inspect_managed_artifact: evidence,
inspect_managed_members: evidence,
inspect_managed_native_boundaries: evidence,
+21
View File
@@ -1,4 +1,11 @@
import { z } from "zod";
import { nativeUiResultSchema } from "../domain/nativeUiObservation.js";
import { nativeValueTraceSchema } from "../domain/nativeValueTrace.js";
import { nativeDataTypeSchema } from "../domain/nativeDataType.js";
import {
nativeInstructionSchema,
nativeCallTargetsSchema,
} from "../domain/nativeInstruction.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { residualUnknownSchema } from "../domain/residualUnknown.js";
import { evidenceBundleSchema } from "../domain/evidenceBundle.js";
@@ -22,6 +29,8 @@ import {
import { artifactExtractionResultSchema } from "../domain/artifactGraph.js";
import { artifactInspectionResultSchema } from "../domain/artifactInspection.js";
import { interfaceBuilderAnalysisSchema } from "../domain/interfaceBuilderGraph.js";
import { keyedArchiveResultSchema } from "../domain/keyedArchive.js";
import { appleAssetCatalogResultSchema } from "../domain/appleAssetCatalog.js";
import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
@@ -93,6 +102,9 @@ const addressedString = z.object({
/** Exact structured-content schemas shared by direct analysis providers. */
export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
inspect_native_data_type: resultOf(nativeDataTypeSchema),
inspect_native_instruction: resultOf(nativeInstructionSchema),
resolve_native_call_targets: resultOf(nativeCallTargetsSchema),
address_name: resultOf(nullableText),
comment: resultOf(nullableText),
current_address: resultOf(z.string()),
@@ -133,6 +145,10 @@ export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
z.object({
procedure: procedureIdentity,
direction: z.enum(["incoming", "outgoing"]),
reference_kinds_available: z.boolean().optional(),
unresolved_calls: z
.array(z.object({ address: z.string(), reason: z.string() }))
.default([]),
references: z.array(
z.object({
source_address: z.string(),
@@ -225,6 +241,7 @@ export const enhancedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
inspect_native_dispatch_metadata: resultOf(
nativeDispatchMetadataResultSchema,
),
trace_native_values: resultOf(nativeValueTraceSchema),
trace_native_ui_action: resultOf(nativeInvestigationTraceSchema),
get_objc_classes: symbolDiscoveryOutput("classes"),
get_objc_protocols: symbolDiscoveryOutput("protocols"),
@@ -302,6 +319,8 @@ export const enhancedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
/** Exact Evidence schemas for provider-neutral native inspection. */
export const nativeOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
observe_native_ui: resultOf(nativeUiResultSchema),
capture_native_ui_scenario: resultOf(nativeUiResultSchema),
inspect_macho: resultOf(inspectMachoSchema),
inspect_signature: resultOf(inspectSignatureSchema),
inspect_plist: resultOf(inspectPlistSchema),
@@ -314,6 +333,8 @@ export const artifactOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
inspect_artifact: resultOf(artifactInspectionResultSchema),
extract_artifact: resultOf(artifactExtractionResultSchema),
decode_interface_builder: resultOf(interfaceBuilderAnalysisSchema),
inspect_keyed_archive: resultOf(keyedArchiveResultSchema),
inspect_asset_catalog: resultOf(appleAssetCatalogResultSchema),
};
/** Exact Evidence schema for execution-free managed static analysis. */
+1 -1
View File
@@ -124,7 +124,7 @@ describe("analysis error projection: provider failures", () => {
code: "provider_unavailable",
details: { failure_code: code, exit_code: exitCode },
});
expect(projected.message.length).toBeGreaterThan(20);
expect(projected.message).toMatch(/\S/u);
expect(JSON.stringify(projected)).not.toContain("/proc/");
}
});
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, it } from "vitest";
import {
appleAssetCatalogInputSchema,
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "./appleAssetCatalog.js";
describe("compiled Apple asset catalog projection", () => {
it("preserves metadata and paginates across catalog boundaries", () => {
const catalogs = [
{
path: "Resources/A/Assets.car",
sha256: "a".repeat(64),
records: parseAppleAssetCatalogRecords([
{ AssetStorageVersion: 1, Platform: "ios" },
{
Name: "Toolbar",
RenditionName: "toolbar@2x.png",
Scale: 2,
Idiom: "iphone",
Locale: "en",
Appearance: "dark",
},
]),
},
{
path: "Resources/B/Assets.car",
sha256: "b".repeat(64),
records: parseAppleAssetCatalogRecords([
{
Name: "Toolbar",
RenditionName: "toolbar~ipad.png",
PixelWidth: 64,
},
]),
},
];
const first = projectAppleAssetCatalogPage({
targetSha256: "c".repeat(64),
catalogs,
offset: 0,
limit: 2,
resourceReferences: [
{
sourceNodeId: "ib:Main.nib:object:1",
sourcePath: "Main.nib",
sourceArchiveSha256: "d".repeat(64),
field: "imageName",
key: "Toolbar",
},
{
sourceNodeId: "ib:Main.nib:object:2",
sourcePath: "Main.nib",
sourceArchiveSha256: "d".repeat(64),
field: "imageName",
key: "Missing",
},
],
});
expect(first.records.map(({ kind }) => kind)).toEqual([
"catalog",
"rendition",
]);
expect(first.records[1]?.metadata.Scale).toBe(2);
expect(first.records[1]?.metadata.Idiom).toBe("iphone");
expect(first.records[1]?.metadata.Locale).toBe("en");
expect(first.records[1]?.metadata.Appearance).toBe("dark");
expect(first.resource_key_matches).toEqual([
expect.objectContaining({ status: "ambiguous", key: "Toolbar" }),
expect.objectContaining({ status: "unmatched", key: "Missing" }),
]);
expect(first.next_offset).toBe(2);
expect(first.truncated).toBe(true);
const second = projectAppleAssetCatalogPage({
targetSha256: "c".repeat(64),
catalogs,
offset: 2,
limit: 2,
});
expect(second.records[0]?.catalog_path).toBe("Resources/B/Assets.car");
expect(second.next_offset).toBeNull();
expect(second.total_records).toBe(3);
});
it("rejects malformed pages and invalid utility data", () => {
expect(appleAssetCatalogInputSchema.safeParse({ offset: -1 }).success).toBe(
false,
);
expect(() =>
parseAppleAssetCatalogRecords({ Name: "not an array" }),
).toThrow(/JSON array/u);
expect(() => parseAppleAssetCatalogRecords([null])).toThrow(/record 0/u);
});
});
+168
View File
@@ -0,0 +1,168 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
/** Caller-controlled page bounds for compiled Apple asset metadata. */
export const appleAssetCatalogInputSchema = z.strictObject({
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(10_000).default(1_000),
});
const catalogSchema = z.strictObject({
path: z.string().min(1),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
record_count: z.number().int().nonnegative(),
});
const recordSchema = z.strictObject({
catalog_path: z.string().min(1),
catalog_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
index: z.number().int().nonnegative(),
kind: z.enum(["catalog", "rendition"]),
asset_name: z.string().nullable(),
rendition_name: z.string().nullable(),
metadata: z.record(z.string(), jsonValueSchema),
});
const resourceKeyMatchSchema = z.strictObject({
source_node_id: z.string().min(1),
source_path: z.string().min(1),
source_archive_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
field: z.string().min(1),
key: z.string().min(1),
status: z.enum(["matched", "ambiguous", "unmatched"]),
renditions: z.array(
z.strictObject({
catalog_path: z.string().min(1),
catalog_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
record_index: z.number().int().nonnegative(),
rendition_name: z.string().nullable(),
}),
),
});
/** Normalized result returned by asset catalog inspection. */
export const appleAssetCatalogResultSchema = z.strictObject({
target_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
catalogs: z.array(catalogSchema),
total_records: z.number().int().nonnegative(),
offset: z.number().int().nonnegative(),
limit: z.number().int().positive(),
records: z.array(recordSchema),
resource_key_matches: z.array(resourceKeyMatchSchema),
next_offset: z.number().int().nonnegative().nullable(),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
export type AppleAssetCatalogRecord = z.infer<typeof recordSchema>;
/** Parse assetutil JSON records without discarding format-specific metadata. */
export const parseAppleAssetCatalogRecords = (
value: unknown,
): readonly Readonly<
Record<string, ReturnType<typeof jsonValueSchema.parse>>
>[] => {
if (!Array.isArray(value))
throw new Error("assetutil output must be a JSON array");
return value.map((record, index) => {
const parsed = z.record(z.string(), jsonValueSchema).safeParse(record);
if (!parsed.success)
throw new Error(`assetutil record ${index} is not a JSON object`);
return parsed.data;
});
};
/** Project catalog records and apply stable global pagination. */
export const projectAppleAssetCatalogPage = (input: {
readonly targetSha256: string;
readonly catalogs: readonly {
readonly path: string;
readonly sha256: string;
readonly records: readonly Readonly<
Record<string, ReturnType<typeof jsonValueSchema.parse>>
>[];
}[];
readonly offset: number;
readonly limit: number;
readonly resourceReferences?: readonly {
readonly sourceNodeId: string;
readonly sourcePath: string;
readonly sourceArchiveSha256: string;
readonly field: string;
readonly key: string;
}[];
}) => {
const all = input.catalogs.flatMap((catalog) =>
catalog.records.map(
(metadata, index): AppleAssetCatalogRecord => ({
catalog_path: catalog.path,
catalog_sha256: catalog.sha256,
index,
kind:
typeof metadata.RenditionName === "string" ||
typeof metadata.Name === "string"
? "rendition"
: "catalog",
asset_name: typeof metadata.Name === "string" ? metadata.Name : null,
rendition_name:
typeof metadata.RenditionName === "string"
? metadata.RenditionName
: null,
metadata,
}),
),
);
const records = all.slice(input.offset, input.offset + input.limit);
const next = input.offset + records.length;
const recordsByAssetName = new Map<string, typeof all>();
for (const record of all) {
if (record.kind !== "rendition" || record.asset_name === null) continue;
const matches = recordsByAssetName.get(record.asset_name) ?? [];
matches.push(record);
recordsByAssetName.set(record.asset_name, matches);
}
const resourceKeyMatches = (input.resourceReferences ?? []).map((source) => {
const matches = recordsByAssetName.get(source.key) ?? [];
return {
source_node_id: source.sourceNodeId,
source_path: source.sourcePath,
source_archive_sha256: source.sourceArchiveSha256,
field: source.field,
key: source.key,
status:
matches.length === 0
? ("unmatched" as const)
: matches.length === 1
? ("matched" as const)
: ("ambiguous" as const),
renditions: matches.map((record) => ({
catalog_path: record.catalog_path,
catalog_sha256: record.catalog_sha256,
record_index: record.index,
rendition_name: record.rendition_name,
})),
};
});
return appleAssetCatalogResultSchema.parse({
target_sha256: input.targetSha256,
catalogs: input.catalogs.map(
({ path, sha256, records: catalogRecords }) => ({
path,
sha256,
record_count: catalogRecords.length,
}),
),
total_records: all.length,
offset: input.offset,
limit: input.limit,
records,
resource_key_matches: resourceKeyMatches,
next_offset: next < all.length ? next : null,
truncated: input.offset > 0 || next < all.length,
limitations: [
"Rendition metadata is reported as emitted by the installed assetutil version; private fields and platform-specific interpretations are not normalized.",
"Asset catalog inspection does not decode or extract rendition image bytes.",
],
});
};
+1 -1
View File
@@ -244,7 +244,7 @@ describe("browser scenario comparison validation", () => {
});
});
it("rejects ambiguous input pairs and duplicate normalization rule IDs", () => {
it("rejects duplicate normalization rule IDs", () => {
const capture = scenarioCapture({});
expect(
compareBrowserScenariosInputSchema.safeParse({
+2
View File
@@ -276,6 +276,8 @@ export class ArtifactOperationError extends AnalysisError {
| "inspect_artifact"
| "extract_artifact"
| "decode_interface_builder"
| "inspect_asset_catalog"
| "inspect_keyed_archive"
| "analyze_javascript_application",
readonly reason:
| "cancelled"
@@ -132,7 +132,7 @@ describe("JavaScript semantic analysis: calls 1", () => {
({ method }) => method === "all",
);
expect(aggregate?.sourcePromiseIds).toHaveLength(2);
expect(aggregate?.returnSiteId).not.toBeNull();
expect(aggregate?.returnSiteId).toBeTypeOf("string");
});
});
+200
View File
@@ -0,0 +1,200 @@
import { z } from "zod";
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
/** Select one archive within the active bundle and optionally one named root. */
export const keyedArchiveInputSchema = z.strictObject({
path: z.string().min(1).default("."),
root: z.string().optional(),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(20_000).default(20_000),
});
const linkSchema = z.strictObject({
source: z.number().int().nonnegative().nullable(),
path: z.array(z.union([z.string(), z.number().int().nonnegative()])),
target: z.number().int().nonnegative().nullable(),
status: z.enum(["resolved", "nil", "unresolved", "malformed"]),
raw: jsonValueSchema,
});
/** Archive object identity is its original $objects index, never a recursive copy. */
export const keyedArchiveResultSchema = z.strictObject({
target_sha256: z.string(),
archive_path: z.string(),
archive_sha256: z.string(),
archive_format: z.enum(["binary-plist", "xml-plist"]),
roots: z.record(z.string(), jsonValueSchema),
objects: z.array(
z.strictObject({
id: z.number().int().nonnegative(),
kind: z.enum([
"nil",
"scalar",
"array",
"dictionary",
"class-descriptor",
"archived-object",
]),
class_id: z.number().int().nonnegative().nullable(),
class_name: z.string().nullable(),
status: z.enum(["observed", "unknown-class", "unresolved-class", "nil"]),
value: jsonValueSchema,
}),
),
references: z.array(linkSchema),
total_objects: z.number().int().nonnegative(),
total_references: z.number().int().nonnegative(),
offset: z.number().int().nonnegative(),
next_offset: z.number().int().nonnegative().nullable(),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
const record = (
value: JsonValue | undefined,
): Record<string, JsonValue> | undefined =>
value !== null && typeof value === "object" && !Array.isArray(value)
? value
: undefined;
const uid = (value: JsonValue | undefined): JsonValue | undefined => {
const object = record(value);
if (object === undefined || Object.keys(object).length !== 1)
return undefined;
return Object.hasOwn(object, "UID") ? object.UID : object["CF$UID"];
};
/** Interpret serialized Foundation references without instantiating archive classes. */
export const projectKeyedArchive = (
value: unknown,
selection: { root?: string | undefined; offset: number; limit: number },
) => {
const archive = record(jsonValueSchema.parse(value));
if (
archive?.$archiver !== "NSKeyedArchiver" ||
!Array.isArray(archive.$objects)
)
throw new TypeError("Expected NSKeyedArchiver with an $objects array");
const table = archive.$objects;
if (table.length > 200_000)
throw new RangeError("Archive exceeds 200000 object-table entries");
const top = record(archive.$top);
if (top === undefined || Object.keys(top).length === 0)
throw new TypeError("Keyed archive has no $top roots");
if (selection.root !== undefined && !Object.hasOwn(top, selection.root))
throw new TypeError(`Archive root does not exist: ${selection.root}`);
const roots =
selection.root === undefined
? top
: { [selection.root]: top[selection.root] ?? null };
const references: z.infer<typeof linkSchema>[] = [];
const scan = (source: number | null, initial: JsonValue) => {
const pending: { value: JsonValue; path: (string | number)[] }[] = [
{ value: initial, path: [] },
];
let visited = 0;
while (pending.length > 0) {
const item = pending.pop();
if (item === undefined) break;
if (++visited > 200_000 || item.path.length > 128)
throw new RangeError(
"Archive exceeds 200000 values per object or 128 nesting levels",
);
const target = uid(item.value);
if (target !== undefined) {
const valid =
typeof target === "number" &&
Number.isSafeInteger(target) &&
target >= 0;
const index = valid ? target : null;
references.push({
source,
path: item.path,
target: index,
raw: item.value,
status:
index === null
? "malformed"
: index >= table.length
? "unresolved"
: index === 0 && table[0] === "$null"
? "nil"
: "resolved",
});
} else if (Array.isArray(item.value)) {
for (let index = item.value.length - 1; index >= 0; index--) {
const child = item.value[index];
if (child !== undefined)
pending.push({ value: child, path: [...item.path, index] });
}
} else {
const fields = record(item.value);
if (fields !== undefined)
for (const key of Object.keys(fields).sort().reverse()) {
const child = fields[key];
if (child !== undefined)
pending.push({ value: child, path: [...item.path, key] });
}
}
if (references.length > 200_000)
throw new RangeError("Archive exceeds 200000 reference edges");
}
};
scan(null, roots);
const objects = table.map((value, id) => {
scan(id, value);
const fields = record(value);
const classUid = uid(fields?.$class);
const classId =
typeof classUid === "number" &&
Number.isSafeInteger(classUid) &&
classUid >= 0
? classUid
: null;
const descriptor = classId === null ? undefined : record(table[classId]);
const className =
typeof descriptor?.$classname === "string" ? descriptor.$classname : null;
const isNil = id === 0 && value === "$null";
return {
id,
kind: isNil
? ("nil" as const)
: Array.isArray(value)
? ("array" as const)
: fields === undefined
? ("scalar" as const)
: typeof fields.$classname === "string"
? ("class-descriptor" as const)
: Object.hasOwn(fields, "$class")
? ("archived-object" as const)
: ("dictionary" as const),
class_id: classId,
class_name: className,
status: isNil
? ("nil" as const)
: fields !== undefined && Object.hasOwn(fields, "$class")
? className === null
? ("unresolved-class" as const)
: ("unknown-class" as const)
: ("observed" as const),
value,
};
});
const end = Math.min(objects.length, selection.offset + selection.limit);
const page = objects.slice(selection.offset, end);
const ids = new Set(page.map(({ id }) => id));
return {
roots,
objects: page,
references: references.filter(
({ source }) => source === null || ids.has(source),
),
total_objects: objects.length,
total_references: references.length,
offset: selection.offset,
next_offset: end < objects.length ? end : null,
truncated: page.length !== objects.length,
limitations: [
"Archive classes are never instantiated. Class names and serialized fields are observed; class-specific semantics are unknown.",
"Conditional references serialized as UID 0 cannot be distinguished from ordinary nil references. Missing fields remain absent in the raw serialized value.",
"Root selection selects the named $top entry; object pagination retains original indices and does not recursively expand references.",
],
};
};
+1
View File
@@ -53,6 +53,7 @@ const jumpTableDataSourceSchema = z
"ghidra-decompiler-load-table",
"ghidra-dispatch-block-data-reference",
"ghidra-aarch64-byte-table",
"ghidra-aarch64-halfword-table",
]),
entry_size_bytes: z.number().int().min(1).nullable(),
entry_count: z.number().int().min(0).nullable(),
+57
View File
@@ -0,0 +1,57 @@
import { z } from "zod";
/** Select a database type by exact category path or a defined typed data address. */
export const nativeDataTypeInputSchema = z
.strictObject({
type: z.string().min(1).optional(),
address: z.string().min(1).optional(),
document: z.string().optional(),
})
.refine(
(value) => (value.type === undefined) !== (value.address === undefined),
"Supply exactly one of type or address",
);
/** Types remain analysis database observations; child identities can be inspected separately. */
export const nativeDataTypeSchema = z.strictObject({
status: z.enum(["available", "unavailable"]),
reason: z.string().nullable(),
id: z.string().nullable(),
name: z.string().nullable(),
kind: z.enum([
"struct",
"union",
"enum",
"pointer",
"array",
"typedef",
"scalar",
"unsupported",
"unavailable",
]),
source: z.literal("analysis-database"),
source_archive: z.string().nullable(),
address: z.string().nullable(),
size_bytes: z.number().int().nonnegative().nullable(),
alignment_bytes: z.number().int().positive().nullable(),
packing_enabled: z.boolean().nullable(),
referenced_type: z.string().nullable(),
array_count: z.number().int().nonnegative().nullable(),
array_stride_bytes: z.number().int().nonnegative().nullable(),
fields: z.array(
z.strictObject({
ordinal: z.number().int().nonnegative(),
name: z.string().nullable(),
offset_bytes: z.number().int().nonnegative(),
size_bytes: z.number().int().nonnegative().nullable(),
type_id: z.string(),
bit_size: z.number().int().nonnegative().nullable(),
bit_offset: z.number().int().nonnegative().nullable(),
status: z.enum(["observed", "unsupported"]),
flexible_tail: z.literal("unknown"),
}),
),
members: z.array(z.strictObject({ name: z.string(), value: z.string() })),
total_fields: z.number().int().nonnegative(),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
+90
View File
@@ -0,0 +1,90 @@
import { z } from "zod";
/** Exact instruction location within the active analysis program. */
export const nativeInstructionInputSchema = z.strictObject({
address: z.string().min(1),
document: z.string().optional(),
});
const reference = z.strictObject({
target_address: z.string(),
type: z.string(),
call: z.boolean(),
jump: z.boolean(),
indirect: z.boolean(),
computed: z.boolean(),
operand_index: z.number().int(),
});
/** Provider-decoded facts for one instruction; operand tokens preserve their native ordering. */
export const nativeInstructionSchema = z.strictObject({
address: z.string(),
status: z.enum([
"decoded",
"not-instruction-boundary",
"data",
"undecodable",
"outside-memory",
]),
procedure: z.string().nullable(),
architecture: z.string(),
mode: z.string(),
bytes: z.string().nullable(),
length: z.number().int().positive().nullable(),
mnemonic: z.string().nullable(),
raw_disassembly: z.string().nullable(),
operands: z.array(
z.strictObject({
index: z.number().int().nonnegative(),
raw: z.string(),
provider_type: z.number().int(),
components: z.array(
z.strictObject({
kind: z.enum(["register", "immediate", "address", "unknown"]),
text: z.string(),
value: z.string().nullable(),
bit_width: z.number().int().nonnegative().nullable(),
}),
),
memory_addressing: z.literal("unavailable"),
}),
),
flow: z.strictObject({
kind: z.enum([
"call",
"jump",
"return",
"fallthrough",
"terminal",
"unavailable",
]),
conditional: z.boolean(),
computed: z.boolean(),
direct_destinations: z.array(z.string()),
}),
references: z.array(reference),
limitations: z.array(z.string()),
});
/** Static target resolution preserves provider references as evidence, never runtime certainty. */
export const nativeCallTargetsSchema = z.strictObject({
call_site: z.string(),
procedure: z.string().nullable(),
status: z.enum([
"direct",
"resolved-indirect",
"ambiguous",
"unresolved",
"not-call",
"unavailable",
]),
mechanism: z.enum(["direct", "computed", "indirect", "unavailable"]),
targets: z.array(
z.strictObject({
address: z.string(),
procedure: z.string().nullable(),
status: z.enum(["direct", "resolved-indirect", "candidate"]),
basis: z.literal("provider-reference"),
references: z.array(reference),
}),
),
limitations: z.array(z.string()),
});
+5 -2
View File
@@ -168,6 +168,7 @@ describe("Interface Builder dispatch joins", () => {
objc_protocols: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
objc_dispatch_implementations: [
{
class_name: "BuildViewController",
@@ -189,7 +190,7 @@ describe("Interface Builder dispatch joins", () => {
expect(joined.edges).toContainEqual(
expect.objectContaining({
relation: "objc_dispatch",
resolution: "inferred",
resolution: "resolved",
to: "native:function:0x1000",
}),
);
@@ -228,6 +229,7 @@ describe("Interface Builder dispatch joins", () => {
objc_protocols: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
objc_dispatch_implementations: [
{
class_name: "BuildViewController",
@@ -260,7 +262,7 @@ describe("Interface Builder dispatch joins", () => {
expect(joined.edges).toContainEqual(
expect.objectContaining({
relation: "objc_dispatch",
resolution: "inferred",
resolution: "resolved",
to: "native:function:0x1000",
}),
);
@@ -304,6 +306,7 @@ describe("placeholder dispatch joins", () => {
objc_protocols: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
objc_dispatch_implementations: [
{
class_name: "BuildViewController",
+10 -5
View File
@@ -64,6 +64,8 @@ export const nativeInvestigationRelationSchema = z.enum([
"swift_vtable_dispatch",
"thunk_to",
"direct_call",
"indirect_call",
"provider_call",
"reads",
"writes",
"flows_to",
@@ -83,7 +85,7 @@ export const nativeInvestigationEdgeSchema = z.discriminatedUnion(
from: z.string().min(1),
to: z.string().min(1),
relation: nativeInvestigationRelationSchema,
resolution: z.enum(["observed", "inferred"]),
resolution: z.enum(["observed", "inferred", "resolved", "ambiguous"]),
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
limitations: z.array(z.string()),
}),
@@ -344,7 +346,7 @@ export const joinInterfaceBuilderDispatch = (
reason:
candidates.length > 1
? "selector_has_multiple_candidate_implementations"
: "implementation_not_resolved_from_provider_symbols",
: "implementation_not_resolved_from_binary_metadata_or_provider_symbols",
evidence: [
...action.evidence,
...candidates.flatMap(({ evidence }) => evidence),
@@ -378,15 +380,18 @@ export const joinInterfaceBuilderDispatch = (
from: selectorNodeId,
to: functionId,
relation: "objc_dispatch",
resolution: "inferred",
resolution:
className !== null && implementation.decode.status === "decoded"
? "resolved"
: "inferred",
evidence: [...action.evidence, ...implementation.evidence],
limitations:
className === null
? [
"The selector uniquely matches a symbolized method, but the Interface Builder receiver is an unresolved placeholder; runtime dispatch was not observed.",
"The selector uniquely matches a encoded or symbolized method, but the Interface Builder receiver is an unresolved placeholder; runtime dispatch was not observed.",
]
: [
"The Interface Builder target and symbolized method agree on class and selector; runtime dispatch and dynamically supplied targets were not observed.",
"The Interface Builder target and encoded or symbolized method agree on class and selector; runtime dispatch and dynamically supplied targets were not observed.",
],
});
resolved += 1;
+90
View File
@@ -0,0 +1,90 @@
import { z } from "zod";
const scope = {
pid: z.number().int().positive(),
window_id: z.number().int().positive(),
observation_approved: z.literal(true),
screenshot: z.boolean().default(true),
accessibility: z.boolean().default(true),
max_nodes: z.number().int().min(1).max(2_000).default(500),
};
/** Opt-in passive observation binds one already-running process and window. */
export const nativeUiObservationInputSchema = z.strictObject(scope);
/** Active scenarios require independent action approval and an explicit restore choice. */
export const nativeUiScenarioInputSchema = z.strictObject({
...scope,
actions_approved: z.literal(true),
restore: z.literal("leave-as-is"),
steps: z
.array(
z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("click"),
path: z.array(z.number().int().nonnegative()).max(32),
}),
z.strictObject({
kind: z.literal("scroll"),
path: z.array(z.number().int().nonnegative()).max(32),
direction: z.enum(["increment", "decrement"]),
}),
z.strictObject({
kind: z.literal("key-entry"),
path: z.array(z.number().int().nonnegative()).max(32),
text: z.string().max(4_096),
}),
z.strictObject({
kind: z.literal("wait"),
milliseconds: z.number().int().min(0).max(10_000),
}),
]),
)
.min(1)
.max(16),
});
/** Ordered captures and failures distinguish missing observation from a failed action. */
export const nativeUiSnapshotSchema = z.strictObject({
window: z.strictObject({
pid: z.number().int().positive(),
window_id: z.number().int().positive(),
executable: z.string(),
launch_time: z.number(),
title: z.string(),
}),
nodes: z.array(
z.strictObject({
path: z.array(z.number().int().nonnegative()),
role: z.string().nullable(),
title: z.string().nullable(),
value: z.string().nullable(),
actions: z.array(z.string()),
children_count: z.number().int().nonnegative(),
}),
),
truncated: z.boolean(),
screenshot: z
.strictObject({
mime_type: z.literal("image/png"),
base64: z.string(),
sha256: z.string(),
width: z.number().int().positive(),
height: z.number().int().positive(),
})
.nullable(),
gaps: z.array(z.string()),
});
export const nativeUiResultSchema = z.strictObject({
target_sha256: z.string(),
initial: nativeUiSnapshotSchema,
steps: z.array(
z.strictObject({
index: z.number().int().nonnegative(),
kind: z.string(),
before: nativeUiSnapshotSchema,
after: nativeUiSnapshotSchema.nullable(),
outcome: z.enum(["completed", "failed", "cancelled"]),
reason: z.string().nullable(),
}),
),
restore: z.literal("leave-as-is"),
limitations: z.array(z.string()),
});
+21
View File
@@ -18,6 +18,9 @@ export const nativePcodeOperationSchema = z.strictObject({
sequence: z.number().int().nonnegative(),
opcode: z.string().min(1),
is_dead: z.boolean(),
block_membership: z
.enum(["member", "detached", "unavailable"])
.default("unavailable"),
inputs: z.array(nativeVarnodeSchema),
output: nativeVarnodeSchema.nullable(),
});
@@ -52,6 +55,24 @@ export const nativeValueFlowSchema = z.discriminatedUnion("available", [
operations: z.array(nativePcodeOperationSchema),
def_use: z.array(nativePcodeDefUseSchema),
effects: z.array(nativePcodeEffectSchema),
parameters: z
.array(
z.strictObject({
ordinal: z.number().int().nonnegative(),
name: z.string(),
data_type: z.string(),
}),
)
.default([]),
parameter_uses: z
.array(
z.strictObject({
ordinal: z.number().int().nonnegative(),
use: z.string(),
input_index: z.number().int().nonnegative(),
}),
)
.default([]),
truncated: z.boolean(),
omitted_operations_lower_bound: z.number().int().nonnegative(),
known_omitted_inputs: z.number().int().nonnegative(),
+73
View File
@@ -0,0 +1,73 @@
import { z } from "zod";
import { nativePcodeOperationSchema } from "./nativeValueFlow.js";
/** Work and output budgets for a static procedure-seeded dependency graph. */
export const nativeValueTraceInputSchema = z.strictObject({
procedure: z.string().min(1),
max_depth: z.number().int().min(0).max(16).default(3),
max_functions: z.number().int().min(1).max(64).default(16),
max_call_sites: z.number().int().min(1).max(4096).default(256),
max_nodes: z.number().int().min(1).max(20_000).default(5_000),
max_edges: z.number().int().min(1).max(40_000).default(10_000),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(5_000).default(1_000),
});
/** Def-use observations and call relationships retain separate authority. */
export const nativeValueTraceSchema = z.strictObject({
seed: z.string(),
target_sha256: z.string(),
nodes: z.array(
z.strictObject({
id: z.string(),
procedure: z.string(),
evidence_id: z.string(),
kind: z.enum(["operation", "parameter"]),
operation: nativePcodeOperationSchema.nullable(),
parameter: z
.strictObject({
ordinal: z.number().int().nonnegative(),
name: z.string(),
data_type: z.string(),
})
.nullable(),
}),
),
edges: z.array(
z.strictObject({
source: z.string(),
target: z.string(),
input_index: z.number().int().nonnegative().nullable(),
kind: z.enum([
"def-use",
"call",
"parameter-use",
"argument-binding",
"return-binding",
]),
status: z.enum(["derived", "direct", "resolved-indirect", "candidate"]),
evidence_id: z.string(),
}),
),
procedures: z.array(
z.strictObject({
address: z.string(),
depth: z.number().int().nonnegative(),
evidence_id: z.string(),
provider: z.string(),
analysis_profile_digest: z.string().nullable(),
}),
),
unknowns: z.array(
z.strictObject({
procedure: z.string(),
address: z.string().nullable(),
reason: z.string(),
}),
),
total_nodes: z.number().int().nonnegative(),
total_edges: z.number().int().nonnegative(),
decompilations: z.number().int().nonnegative(),
next_offset: z.number().int().nonnegative().nullable(),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
+42
View File
@@ -61,6 +61,34 @@ export const objcClassSchema = z.strictObject({
protocols: z.array(z.string()).default([]),
ivar_count: z.number().int().nonnegative().default(0),
instance_size: z.number().int().nonnegative().nullable(),
location: z
.object({
address: z.string().nullable(),
file_offset: z.number().int().nonnegative().nullable(),
})
.optional(),
superclass_address: z.string().nullable().optional(),
metaclass_address: z.string().nullable().optional(),
decode: z
.object({
status: z.enum(["decoded", "partial", "unsupported", "invalid"]),
reason: z.string().nullable(),
})
.optional(),
evidence: z
.array(
z.object({
kind: z.literal("binary_metadata"),
description: z.string(),
location: z.object({
address: z.string().nullable(),
file_offset: z.number().int().nonnegative().nullable(),
}),
artifact_path: z.string(),
artifact_sha256: z.string(),
}),
)
.optional(),
});
export type ObjcClass = z.infer<typeof objcClassSchema>;
@@ -108,12 +136,25 @@ export const objcIvarSchema = z.strictObject({
name: z.string().min(1),
type_encoding: z.string().nullable(),
offset: z.number().int().nonnegative().nullable(),
size: z.number().int().nonnegative().nullable().default(null),
alignment: z.number().int().positive().nullable().default(null),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type ObjcIvar = z.infer<typeof objcIvarSchema>;
/** Encoded Objective-C protocol declaration with required and optional method facts. */
export const objcProtocolRecordSchema = z.strictObject({
name: z.string(),
adopted_protocols: z.array(z.string()),
methods: z.array(objcMethodSchema),
optional_methods: z.array(objcMethodSchema),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
/** Selector implementation resolved from a class or metaclass method list. */
export const objcDispatchImplementationSchema = z.strictObject({
class_name: z.string().min(1),
@@ -254,6 +295,7 @@ export const objcSwiftMetadataSchema = z.strictObject({
objc_protocols: z.array(objcProtocolSchema).default([]),
swift_decls: z.array(swiftDeclSchema).default([]),
objc_ivars: z.array(objcIvarSchema).default([]),
objc_protocol_records: z.array(objcProtocolRecordSchema).default([]),
objc_dispatch_implementations: z
.array(objcDispatchImplementationSchema)
.default([]),
@@ -129,7 +129,6 @@ describe("process reactive scenario schema", () => {
expect(processReactiveScenarioSchema.parse(baseScenario())).toMatchObject({
initial_state: "starting",
});
expect(PROCESS_REACTIVE_LIMITS.triggerDepth).toBe(256);
});
it("accepts caller-defined scenario sizes without count ceilings", () => {
+30 -11
View File
@@ -1,3 +1,4 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import {
@@ -79,18 +80,36 @@ describe("protocol capture", () => {
});
describe("JSON-RPC decoding", () => {
it("decodes a simple JSON-RPC request", () => {
const payload = new TextEncoder().encode(
JSON.stringify({
jsonrpc: "2.0",
method: "add",
params: [1, 2],
id: 1,
}),
it("decodes the captured MCP SDK initialize request with exact field values", async () => {
const payload = await readFile(
new URL(
"../../tests/fixtures/golden/mcp-initialize.json",
import.meta.url,
),
);
const result = decodeJsonRpc(payload);
expect(result.decoded_fields.length).toBe(4);
expect(result.truncated).toBe(false);
expect(decodeJsonRpc(payload)).toEqual({
decoded_fields: [
{
path: "method",
wire_type: "json",
value: "initialize",
inferred: false,
},
{
path: "params",
wire_type: "json",
inferred: false,
value: {
protocolVersion: "2025-11-25",
capabilities: {},
clientInfo: { name: "rea-protocol-golden", version: "1" },
},
},
{ path: "jsonrpc", wire_type: "json", value: "2.0", inferred: false },
{ path: "id", wire_type: "json", value: 0, inferred: false },
],
truncated: false,
});
});
it("redacts credential-like fields", () => {
+1 -1
View File
@@ -134,7 +134,7 @@ describe("reconstruction coverage closure", () => {
);
});
it("never lets mock-strength or stale results satisfy stronger current claims", () => {
it("does not let stale verifier results satisfy current claims", () => {
const workspace = completeReconstructionCoverageData();
const semantic = workspace;
const stale = createReconstructionCoverageData({
@@ -1,4 +1,3 @@
import canonicalize from "canonicalize";
import { z } from "zod";
import { evidenceBundleSchema } from "./evidenceBundle.js";
@@ -298,16 +297,3 @@ export type ReviewedReconstructionObligation = z.infer<
export type ReconstructionObligationManifest = z.infer<
typeof reconstructionObligationManifestSchema
>;
/** Parse and canonically serialize one complete reconstruction obligation ledger. */
export const serializeReconstructionObligationLedger = (
input: unknown,
): string => {
const ledger = reconstructionObligationLedgerSchema.parse(input);
const encoded = canonicalize(ledger);
if (encoded === undefined)
throw new TypeError(
"Reconstruction obligation ledger is not canonical JSON",
);
return encoded;
};
+1 -1
View File
@@ -26,7 +26,7 @@ describe("reconstruction readiness report", () => {
expect(parsed.capabilities).toHaveLength(1_001);
});
it("passes the complete repository conformance journey deterministically", () => {
it("projects the complete conformance report deterministically", () => {
const first = createReconstructionReadinessReport(input());
const second = createReconstructionReadinessReport(input());
+1 -16
View File
@@ -90,6 +90,7 @@ describe("historical source to bundle comparison", () => {
expect(item(first, "src/merged-b.ts").status).toBe("merged");
expect(item(first, "src/duplicated.ts")).toMatchObject({
status: "duplicated",
candidates: [{}, {}],
confidence: "exact",
current_node_ids: [expect.any(String), expect.any(String)],
});
@@ -117,22 +118,6 @@ describe("historical source to bundle comparison", () => {
expect(result.coverage.status).toBe("partial");
});
it("retains every candidate without caller-selected caps", () => {
const result = compareSourceToBundle({
reference: historicalGraph("complete"),
application: {
evidenceId: EVIDENCE_ID,
rootArtifactSha256: HASH.artifact,
graph: applicationGraph("complete"),
},
});
expect(item(result, "src/duplicated.ts")).toMatchObject({
status: "duplicated",
candidates: [{}, {}],
});
});
it("evaluates all indexed candidates for each source file", () => {
const result = compareSourceToBundle({
reference: historicalGraph("complete", ["src/split.ts"]),
+13 -1
View File
@@ -48,7 +48,19 @@ describe("stable web inventory", () => {
};
it("excludes transient CDP and target identity from script keys", () => {
expect(stableWebScriptKey(script)).toBe(stableWebScriptKey({ ...script }));
const first = {
...script,
script_id: "session-one-script",
target_id: "tab-one",
capture_id: "capture-one",
};
const second = {
...script,
script_id: "session-two-script",
target_id: "tab-two",
capture_id: "capture-two",
};
expect(stableWebScriptKey(first)).toBe(stableWebScriptKey(second));
expect(stableWebScriptKey({ ...script, length: 1_025 })).not.toBe(
stableWebScriptKey(script),
);
-9
View File
@@ -4,18 +4,9 @@ import {
captureWebScreenshotInputSchema,
compareWebScreenshotsInputSchema,
createWebScreenshotArtifact,
webScreenshotArtifactSchema,
} from "./webScreenshot.js";
describe("inline web screenshots", () => {
it("accepts complete inline image artifacts above the former size ceiling", () => {
const artifact = createWebScreenshotArtifact(
Buffer.alloc(8 * 1_024 * 1_024 + 1),
);
expect(webScreenshotArtifactSchema.parse(artifact)).toEqual(artifact);
});
it("rejects removed screenshot size and pixel controls", () => {
expect(
captureWebScreenshotInputSchema.safeParse({
File diff suppressed because one or more lines are too long
-11
View File
@@ -3,8 +3,6 @@ import { describe, expect, it } from "vitest";
import type { JsonValue } from "../domain/jsonValue.js";
import { functionDossierSchema } from "../domain/hopperValues.js";
import {
GHIDRA_FUNCTION_OPERATIONS,
isGhidraFunctionOperation,
parseGhidraFunctionInput,
parseGhidraFunctionResult,
type GhidraFunctionOperation,
@@ -60,15 +58,6 @@ describe("Ghidra function-analysis boundary values", () => {
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
});
it("keeps the admitted operation set closed", () => {
expect(GHIDRA_FUNCTION_OPERATIONS).toHaveLength(9);
expect(isGhidraFunctionOperation("analyze_function")).toBe(true);
expect(isGhidraFunctionOperation("read_function_instructions")).toBe(true);
expect(isGhidraFunctionOperation("procedure_pseudo_code")).toBe(true);
expect(isGhidraFunctionOperation("list_procedures")).toBe(false);
expect(isGhidraFunctionOperation("set_comment")).toBe(false);
});
});
describe("Ghidra function-analysis result values", () => {
+47 -2
View File
@@ -1,4 +1,9 @@
import { z } from "zod";
import { nativeDataTypeSchema } from "../domain/nativeDataType.js";
import {
nativeInstructionSchema,
nativeCallTargetsSchema,
} from "../domain/nativeInstruction.js";
import { AnalysisInputError, AnalysisOutputError } from "../domain/errors.js";
import {
@@ -6,7 +11,7 @@ import {
functionDossierSchema,
type FunctionDossier,
} from "../domain/hopperValues.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
import { nativeApiBoundarySchema } from "../domain/nativeApiBoundary.js";
import { nativeValueFlowSchema } from "../domain/nativeValueFlow.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -17,6 +22,9 @@ import {
/** Read-only function operations admitted by the Ghidra adapter. */
export const GHIDRA_FUNCTION_OPERATIONS = [
"inspect_native_data_type",
"inspect_native_instruction",
"resolve_native_call_targets",
"analyze_function",
"procedure_assembly",
"procedure_callees",
@@ -44,6 +52,23 @@ const procedure = ghidraIdentifierSchema;
const directProcedure = { document, procedure };
const inputSchemas = {
inspect_native_data_type: z
.object({
document,
type: z.string().min(1).nullable().default(null),
address: ghidraCanonicalAddressSchema.nullable().default(null),
})
.strict()
.refine(
(value) => (value.type === null) !== (value.address === null),
"Supply exactly one of type or address",
),
inspect_native_instruction: z
.object({ document, address: ghidraCanonicalAddressSchema })
.strict(),
resolve_native_call_targets: z
.object({ document, address: ghidraCanonicalAddressSchema })
.strict(),
analyze_function: z.object({ procedure }).strict(),
procedure_assembly: z.object(directProcedure).strict(),
procedure_callees: z.object(directProcedure).strict(),
@@ -67,7 +92,15 @@ export const parseGhidraFunctionInput = (
): Result<Readonly<Record<string, JsonValue>>, AnalysisInputError> => {
const parsed = inputSchemas[operation].safeParse(value);
return parsed.success
? ok(parsed.data)
? ok(
jsonObjectSchema.parse(
Object.fromEntries(
Object.entries(parsed.data).filter(
([, value]) => value !== undefined,
),
),
),
)
: err(new AnalysisInputError(operation, { cause: parsed.error }));
};
@@ -126,6 +159,15 @@ const procedureReferences = z
procedure: procedureIdentity,
direction: z.enum(["incoming", "outgoing"]),
references: z.array(referenceEdge),
reference_kinds_available: z.boolean().default(true),
unresolved_calls: z
.array(
z.strictObject({
address: ghidraCanonicalAddressSchema,
reason: z.string(),
}),
)
.default([]),
})
.strict();
const procedureInfo = z
@@ -305,6 +347,9 @@ const resultSchemas = {
procedure_info: procedureInfo,
procedure_pseudo_code: z.string().nullable(),
read_function_instructions: ghidraFunctionInstructionWindow,
inspect_native_instruction: nativeInstructionSchema,
inspect_native_data_type: nativeDataTypeSchema,
resolve_native_call_targets: nativeCallTargetsSchema,
procedure_references: procedureReferences,
xrefs: z.array(ghidraCanonicalAddressSchema),
} satisfies Readonly<Record<GhidraFunctionOperation, z.ZodType>>;
+2 -2
View File
@@ -75,7 +75,7 @@ describe("Ghidra installation inspection", () => {
});
it.each(["x64", "arm64"] as const)(
"keeps Ghidra unavailable on unadmitted macOS %s hosts",
"accepts macOS %s with matching native tools",
(architecture) => {
const decompiler = `${INSTALL}/Ghidra/Features/Decompiler/os/${architecture === "arm64" ? "mac_arm_64" : "mac_x86_64"}/decompile`;
const macHost: GhidraInstallationHost = {
@@ -91,7 +91,7 @@ describe("Ghidra installation inspection", () => {
macHost,
),
).toMatchObject({
status: "unavailable",
status: "available",
platform: "darwin",
architecture,
nativeDecompilerPath: decompiler,
+9 -4
View File
@@ -297,18 +297,23 @@ const installationChecks = ({
}),
installationCheck({
name: "platform",
passed: platform === "linux" || platform === "win32",
passed:
platform === "linux" || platform === "win32" || platform === "darwin",
code: "unsupported_host",
detail: platform,
remediation: "Use REA's Ghidra adapter on Linux or Windows x64.",
remediation:
"Use Linux or Windows x64, or macOS x64/arm64 with matching native Ghidra tools.",
}),
installationCheck({
name: "architecture",
passed:
(platform === "linux" || platform === "win32") && architecture === "x64",
((platform === "linux" || platform === "win32") &&
architecture === "x64") ||
(platform === "darwin" &&
(architecture === "x64" || architecture === "arm64")),
code: "unsupported_host",
detail: architecture,
remediation: "Use x64 on Linux or Windows.",
remediation: "Use x64 on Linux or Windows, or x64/arm64 on macOS.",
}),
installationCheck({
name: "installation",
-2
View File
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vitest";
import {
GHIDRA_INVENTORY_OPERATIONS,
isGhidraInventoryOperation,
parseGhidraInventoryInput,
parseGhidraInventoryResult,
@@ -33,7 +32,6 @@ describe("Ghidra inventory boundary values", () => {
});
it("keeps the admitted operation set closed", () => {
expect(GHIDRA_INVENTORY_OPERATIONS).toHaveLength(10);
expect(isGhidraInventoryOperation("list_names")).toBe(true);
expect(isGhidraInventoryOperation("goto_address")).toBe(false);
expect(isGhidraInventoryOperation("set_comment")).toBe(false);
+12 -5
View File
@@ -60,7 +60,6 @@ describe("Ghidra provider", () => {
expect(ghidra.capabilities().map(({ operation }) => operation)).toEqual(
GHIDRA_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name),
);
expect(GHIDRA_PROVIDER_TOOL_CONTRACTS).toHaveLength(19);
expect(ghidra.capabilities()).toEqual(
expect.arrayContaining([
expect.objectContaining({
@@ -253,7 +252,9 @@ describe("Ghidra client projection", () => {
);
expect(resolved.ok).toBe(true);
if (!resolved.ok || resolved.value.profile === null) return;
if (!resolved.ok) throw resolved.error;
if (resolved.value.profile === null)
throw new Error("Expected a bound Ghidra profile");
expect(resolved.value.profile).toMatchObject({
provider: { id: "ghidra", name: "Ghidra", version: "12.1.4" },
parameters: {
@@ -310,7 +311,9 @@ describe("Ghidra result projection", () => {
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
if (!resolved.ok || resolved.value.profile === null) return;
if (!resolved.ok) throw resolved.error;
if (resolved.value.profile === null)
throw new Error("Expected a bound Ghidra profile");
await expect(
ghidra
@@ -348,7 +351,9 @@ describe("Ghidra result projection", () => {
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
if (!resolved.ok || resolved.value.profile === null) return;
if (!resolved.ok) throw resolved.error;
if (resolved.value.profile === null)
throw new Error("Expected a bound Ghidra profile");
await expect(
ghidra
@@ -382,7 +387,9 @@ describe("Ghidra result projection", () => {
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
if (!resolved.ok || resolved.value.profile === null) return;
if (!resolved.ok) throw resolved.error;
if (resolved.value.profile === null)
throw new Error("Expected a bound Ghidra profile");
const result = await ghidra
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
+8 -3
View File
@@ -2,17 +2,22 @@ import { describe, expect, it } from "vitest";
import { parseConfig } from "../config.js";
import { silentLogger } from "../logger.js";
import { HopperProvider } from "./HopperProvider.js";
import {
HopperProvider,
HOPPER_PROVIDER_TOOL_CONTRACTS,
} from "./HopperProvider.js";
describe("Hopper provider capabilities", () => {
it("publishes deterministic descriptors and resists caller mutation", () => {
const config = parseConfig({});
expect(config.ok).toBe(true);
if (!config.ok) return;
if (!config.ok) throw new Error("expected valid configuration");
const provider = new HopperProvider(config.value, silentLogger);
const capabilities = provider.capabilities();
const published = structuredClone(capabilities);
expect(capabilities).toHaveLength(37);
expect(capabilities.map(({ operation }) => operation)).toEqual(
HOPPER_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name),
);
expect(new Set(capabilities.map(({ operation }) => operation)).size).toBe(
capabilities.length,
);
+7 -1
View File
@@ -44,7 +44,13 @@ const MUTATING_OPERATIONS = new Set([
/** Tool contracts implemented directly by the Hopper adapter. */
export const HOPPER_PROVIDER_TOOL_CONTRACTS = Object.freeze([
...GENERATED_MCP_TOOL_CATALOG.filter(({ kind }) => kind === "official-proxy"),
...GENERATED_MCP_TOOL_CATALOG.filter(
({ kind, name }) =>
kind === "official-proxy" &&
name !== "inspect_native_data_type" &&
name !== "inspect_native_instruction" &&
name !== "resolve_native_call_targets",
),
...GENERATED_MCP_TOOL_CATALOG.filter(
({ name }) => name === "analyze_function",
),
@@ -44,20 +44,6 @@ describe("Hopper provider discovery", () => {
diagnostics: { target_kind: "archive", target_format: "asar" },
});
});
it("advertises byte reads as an available operation", () => {
const capabilities = provider(process.execPath).capabilities();
expect(
capabilities.find(({ operation }) => operation === "read_bytes"),
).toMatchObject({
available: true,
});
expect(
capabilities.find(
({ operation }) => operation === "address_to_file_offset",
),
).toMatchObject({ available: true });
});
});
const provider = (launcherPath: string): HopperProvider => {
+1 -1
View File
@@ -20,6 +20,6 @@ describe("Hopper response stream", () => {
stream.push(`${line}\n`);
expect(failures).toEqual([]);
expect(messages).toHaveLength(1);
expect(messages).toEqual([JSON.parse(line)]);
});
});
+119
View File
@@ -0,0 +1,119 @@
import { describe, expect, it } from "vitest";
import { decodeAppleDispatchMetadata } from "./AppleDispatchMetadata.js";
const base = 0x100000000n;
const fixture = (relative = false) => {
const bytes = Buffer.alloc(2048);
const u32 = (offset: number, value: number) =>
bytes.writeUInt32LE(value, offset);
const ptr = (offset: number, target: number) =>
bytes.writeBigUInt64LE(base + BigInt(target), offset);
u32(0, 0xfeedfacf);
u32(4, 0x0100000c);
u32(16, 1);
u32(20, 152);
u32(32, 0x19);
u32(36, 152);
bytes.write("__DATA", 40);
ptr(56, 0);
bytes.writeBigUInt64LE(2048n, 64);
bytes.writeBigUInt64LE(2048n, 80);
u32(92, 5);
u32(96, 1);
bytes.write("__objc_classlist", 104);
bytes.write("__DATA", 120);
ptr(136, 0x180);
bytes.writeBigUInt64LE(8n, 144);
u32(152, 0x180);
ptr(0x180, 0x200);
ptr(0x200, 0x280);
ptr(0x220, 0x300);
ptr(0x2a0, 0x380);
u32(0x308, 16);
ptr(0x318, 0x450);
ptr(0x320, 0x480);
ptr(0x330, 0x500);
u32(0x380, 1);
ptr(0x398, 0x450);
bytes.write("Fixture\0", 0x450);
bytes.write("performAction:\0", 0x460);
u32(0x480, relative ? 0xc000000c : 24);
u32(0x484, 1);
if (relative) {
bytes.writeInt32LE(0x460 - 0x488, 0x488);
bytes.writeInt32LE(0x5c0 - 0x48c, 0x48c);
bytes.writeInt32LE(0x700 - 0x490, 0x490);
} else {
ptr(0x488, 0x460);
ptr(0x490, 0x5c0);
ptr(0x498, 0x700);
}
u32(0x500, 32);
u32(0x504, 1);
ptr(0x508, 0x580);
ptr(0x510, 0x5a0);
ptr(0x518, 0x5c0);
u32(0x580, 8);
bytes.write("state\0", 0x5a0);
bytes.write("i\0", 0x5c0);
return bytes;
};
const provenance = { path: "/fixture/app", sha256: "a".repeat(64) };
describe("Apple dispatch binary metadata", () => {
it.each([false, true])(
"decodes stripped absolute/relative method lists (relative=%s) with exact offsets",
(relative) => {
const result = decodeAppleDispatchMetadata(
fixture(relative),
100,
provenance,
);
expect(result.objc_classes).toMatchObject([
{
name: "Fixture",
instance_size: 16,
location: { address: "0x100000200", file_offset: 512 },
},
{ name: "Fixture", is_meta_class: true },
]);
expect(result.objc_dispatch_implementations).toMatchObject([
{
selector: "performAction:",
implementation_address: "0x100000700",
location: { file_offset: 0x488 },
decode: { status: "decoded" },
},
]);
expect(result.objc_ivars).toMatchObject([
{
name: "state",
type_encoding: "i",
offset: 8,
location: { file_offset: 0x508 },
},
]);
},
);
it("keeps unsupported pointers and record truncation explicit", () => {
const bytes = fixture();
bytes.writeBigUInt64LE(0xffffffffffffffffn, 0x498);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_dispatch_implementations[0]).toMatchObject({
implementation_address: null,
decode: { status: "partial" },
});
expect(
decodeAppleDispatchMetadata(fixture(), 1, provenance).coverage[0]?.reason,
).toContain("max_records_reached");
});
it("rejects malformed command and section boundaries", () => {
const bytes = fixture();
bytes.writeUInt32LE(7, 36);
expect(() => decodeAppleDispatchMetadata(bytes, 100, provenance)).toThrow(
"command size",
);
expect(() =>
decodeAppleDispatchMetadata(Buffer.alloc(10), 100, provenance),
).toThrow("Truncated");
});
});
+674
View File
@@ -0,0 +1,674 @@
import { createHash } from "node:crypto";
import { open } from "node:fs/promises";
import { constants } from "node:fs";
import {
objcSwiftMetadataSchema,
nativeDispatchMetadataResultSchema,
type ObjcSwiftMetadata,
} from "../domain/objcSwiftMetadata.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { decodeSwiftClassVtables } from "./AppleSwiftVtables.js";
import { createObjcProtocolReader } from "./AppleObjcProtocols.js";
interface Segment {
address: bigint;
size: bigint;
offset: number;
executable: boolean;
}
interface Section {
name: string;
address: bigint;
size: number;
}
const hex = (value: bigint) => `0x${value.toString(16)}`;
const decoded = { status: "decoded" as const, reason: null };
/** Decode validated little-endian 64-bit Apple Objective-C metadata without loading target code. */
export const decodeAppleDispatchMetadata = (
bytes: Buffer,
maxRecords: number,
provenance: { path: string; sha256: string },
architecture = "arm64",
): ObjcSwiftMetadata => {
let slice = 0;
let sliceEnd = bytes.length;
if (bytes.length < 32) throw new RangeError("Truncated Mach-O header");
if (bytes.readUInt32BE(0) === 0xcafebabe) {
const count = bytes.readUInt32BE(4);
if (count > 128 || 8 + count * 20 > bytes.length)
throw new RangeError("Malformed FAT architecture table");
const cpu = architecture === "arm64" ? 0x0100000c : 0x01000007;
let selected: number | undefined;
for (let index = 0; index < count; index++) {
const offset = 8 + index * 20;
if (bytes.readUInt32BE(offset) === cpu) {
if (selected !== undefined)
throw new TypeError("Ambiguous FAT architecture slice");
selected = bytes.readUInt32BE(offset + 8);
sliceEnd = selected + bytes.readUInt32BE(offset + 12);
if (sliceEnd > bytes.length || selected < 8 + count * 20)
throw new RangeError("FAT slice exceeds file");
}
}
if (selected === undefined)
throw new TypeError("Requested FAT architecture is absent");
slice = selected;
}
if (slice + 32 > sliceEnd || bytes.readUInt32LE(slice) !== 0xfeedfacf)
throw new TypeError(
"Only little-endian 64-bit Mach-O metadata is supported",
);
const commands = bytes.readUInt32LE(slice + 16);
const commandEnd = slice + 32 + bytes.readUInt32LE(slice + 20);
if (commands > 4096 || commandEnd > sliceEnd)
throw new RangeError("Malformed Mach-O command bounds");
const segments: Segment[] = [];
const sections: Section[] = [];
let cursor = slice + 32;
for (let index = 0; index < commands; index++) {
if (cursor + 8 > commandEnd) throw new RangeError("Truncated load command");
const kind = bytes.readUInt32LE(cursor),
size = bytes.readUInt32LE(cursor + 4);
if (size < 8 || cursor + size > commandEnd)
throw new RangeError("Invalid load command size");
if (kind === 0x19) {
if (size < 72) throw new RangeError("Truncated segment command");
const address = bytes.readBigUInt64LE(cursor + 24),
fileSize = bytes.readBigUInt64LE(cursor + 48),
fileOffset = bytes.readBigUInt64LE(cursor + 40);
if (fileOffset + fileSize > BigInt(sliceEnd - slice))
throw new RangeError("Segment file range exceeds target bytes");
segments.push({
address,
size: fileSize,
offset: slice + Number(fileOffset),
executable: (bytes.readUInt32LE(cursor + 60) & 4) !== 0,
});
const count = bytes.readUInt32LE(cursor + 64);
if (72 + count * 80 > size)
throw new RangeError("Truncated section table");
for (let section = 0; section < count; section++) {
const position = cursor + 72 + section * 80;
const sectionSize = bytes.readBigUInt64LE(position + 40);
if (sectionSize > BigInt(Number.MAX_SAFE_INTEGER))
throw new RangeError("Section size exceeds exact numeric range");
sections.push({
name: bytes
.subarray(position, position + 16)
.toString("ascii")
.replace(/\0.*$/u, ""),
address: bytes.readBigUInt64LE(position + 32),
size: Number(sectionSize),
});
}
}
cursor += size;
}
const offset = (address: bigint, size = 1): number => {
const matches = segments.filter(
(segment) =>
address >= segment.address &&
address + BigInt(size) <= segment.address + segment.size,
);
if (matches.length !== 1)
throw new RangeError(
`Unmapped or ambiguous metadata pointer ${hex(address)}`,
);
const segment = matches[0];
if (segment === undefined) throw new RangeError("Missing metadata segment");
return segment.offset + Number(address - segment.address);
};
const u32 = (address: bigint) => bytes.readUInt32LE(offset(address, 4));
const pointer = (address: bigint) =>
bytes.readBigUInt64LE(offset(address, 8));
const location = (address: bigint) => ({
address: hex(address),
file_offset: offset(address),
});
const evidence = (address: bigint, description: string) => [
{
kind: "binary_metadata" as const,
description,
location: location(address),
artifact_path: provenance.path,
artifact_sha256: provenance.sha256,
},
];
const string = (address: bigint) => {
const start = offset(address);
let end = start;
while (end < bytes.length && end - start < 4096 && bytes[end] !== 0) end++;
if (end === bytes.length || end - start >= 4096)
throw new RangeError("Unterminated or oversized metadata string");
offset(address, end - start + 1);
return new TextDecoder("utf-8", { fatal: true }).decode(
bytes.subarray(start, end),
);
};
const result = objcSwiftMetadataSchema.parse({ db_save_result: null });
const failures: string[] = [];
let records = 0,
examined = 0,
truncated = false;
const admit = () => {
if (records >= maxRecords) {
truncated = true;
return false;
}
records++;
return true;
};
const methods = (
list: bigint,
className: string,
methodType: "instance" | "class",
) => {
if (list === 0n) return;
const flags = u32(list),
count = u32(list + 4n),
relative = (flags & 0x80000000) !== 0;
const stride = flags & 0xfffc;
if (stride !== (relative ? 12 : 24))
throw new TypeError(`Unsupported method stride/flags at ${hex(list)}`);
for (let index = 0; index < count; index++) {
if (!admit()) break;
const entry = list + 8n + BigInt(index * stride);
const rel = (field: bigint) => {
const displacement = bytes.readInt32LE(offset(field, 4));
const target = field + BigInt(displacement);
let fileOffset: number | null = null;
try {
fileOffset = offset(target);
} catch {
/* serialized target remains unresolved */
}
if (admit())
result.relative_pointers.push({
field: location(field),
target: { address: hex(target), file_offset: fileOffset },
displacement,
indirectable: false,
indirect: false,
decode:
fileOffset === null
? { status: "partial", reason: "relative_target_unmapped" }
: decoded,
evidence: evidence(
field,
"Signed-relative Objective-C method-list pointer",
),
});
return target;
};
let selectorAddress = relative ? rel(entry) : pointer(entry);
if (relative && (flags & 0x40000000) === 0)
selectorAddress = pointer(selectorAddress);
const implementation = relative ? rel(entry + 8n) : pointer(entry + 16n);
let implementationLocation: {
address: string;
file_offset: number;
} | null = null;
try {
if (
!segments.some(
(segment) =>
segment.executable &&
implementation >= segment.address &&
implementation < segment.address + segment.size,
)
)
throw new RangeError(
"Method implementation is not in an executable segment",
);
implementationLocation = location(implementation);
} catch {
/* external/chained pointers remain unresolved */
}
result.objc_dispatch_implementations.push({
class_name: className,
selector: string(selectorAddress),
method_type: methodType,
implementation_address: implementationLocation?.address ?? null,
location: location(entry),
decode:
implementationLocation === null
? {
status: "partial",
reason: "implementation_pointer_unmapped_or_encoded",
}
: decoded,
evidence: evidence(
entry,
relative
? "Encoded relative Objective-C method entry"
: "Encoded absolute Objective-C method entry",
),
});
}
};
const protocolReader = createObjcProtocolReader({
readers: {
u32,
pointer,
string,
location,
evidence,
admit,
i32: (address) => bytes.readInt32LE(offset(address, 4)),
},
result,
failures,
});
for (const section of sections.filter(
({ name }) => name === "__objc_protolist",
)) {
if (section.size % 8 !== 0)
throw new RangeError("Misaligned Objective-C protocol list");
for (let index = 0; index < section.size / 8; index++) {
if (records >= maxRecords) {
truncated = true;
break;
}
protocolReader.record(pointer(section.address + BigInt(index * 8)));
}
}
const visited = new Set<string>();
const readClass = (address: bigint, meta = false) => {
if (address === 0n || visited.has(hex(address)) || !admit()) return;
visited.add(hex(address));
const ro = pointer(address + 32n) & ~7n;
const name = string(pointer(ro + 24n));
const superclass = pointer(address + 8n);
const root = (u32(ro) & 2) !== 0;
let superclassName: string | null = null;
if (superclass !== 0n) {
try {
superclassName = string(
pointer((pointer(superclass + 32n) & ~7n) + 24n),
);
} catch {
failures.push(
`Superclass pointer ${hex(superclass)} of ${name} requires unsupported binding/fixup resolution`,
);
}
}
if (superclass === 0n && !root)
failures.push(
`Superclass of ${name} requires external binding resolution`,
);
const ivarList = pointer(ro + 48n);
let ivarCount = 0;
if (ivarList !== 0n && !meta) {
const stride = u32(ivarList),
count = u32(ivarList + 4n);
if (stride !== 32)
throw new TypeError("Unsupported Objective-C ivar entry size");
ivarCount = count;
for (let index = 0; index < count; index++) {
if (!admit()) break;
const entry = ivarList + 8n + BigInt(index * stride);
const encodedOffset = pointer(entry);
let value: number | null = null;
try {
value = u32(encodedOffset);
} catch {
failures.push(`Unresolved ivar offset pointer ${hex(encodedOffset)}`);
}
result.objc_ivars.push({
class_name: name,
name: string(pointer(entry + 8n)),
type_encoding: string(pointer(entry + 16n)),
offset: value,
size: u32(entry + 28n),
alignment: u32(entry + 24n) < 31 ? 2 ** u32(entry + 24n) : null,
location: location(entry),
decode:
value === null
? { status: "partial", reason: "ivar_offset_pointer_unresolved" }
: decoded,
evidence: evidence(
entry,
"Objective-C ivar entry and encoded offset storage",
),
});
}
}
methods(pointer(ro + 32n), name, meta ? "class" : "instance");
result.objc_classes.push({
name,
super_class: superclassName,
is_meta_class: meta,
is_root_class: root,
methods: result.objc_dispatch_implementations
.filter(
(item) =>
item.class_name === name &&
item.method_type === (meta ? "class" : "instance"),
)
.map((item) => ({
selector: item.selector,
method_type: item.method_type,
address:
item.implementation_address !== null &&
BigInt(item.implementation_address) <=
BigInt(Number.MAX_SAFE_INTEGER)
? Number(BigInt(item.implementation_address))
: null,
is_required: false,
is_optional: false,
})),
properties: [],
protocols: protocolReader.list(pointer(ro + 40n)),
ivar_count: ivarCount,
instance_size: u32(ro + 8n),
location: location(address),
superclass_address: superclass === 0n ? null : hex(superclass),
metaclass_address: meta ? null : hex(pointer(address)),
decode:
superclassName === null && !root
? { status: "partial", reason: "superclass_binding_unresolved" }
: decoded,
evidence: evidence(address, "Objective-C class and class_ro_t records"),
});
if (!meta) {
try {
readClass(pointer(address), true);
} catch (cause) {
failures.push(
`Metaclass of ${name}: ${cause instanceof Error ? cause.message : String(cause)}`,
);
}
}
};
for (const section of sections.filter(
({ name }) => name === "__objc_classlist",
)) {
if (section.size % 8 !== 0)
throw new RangeError("Misaligned Objective-C class-list size");
for (let index = 0; index < section.size / 8; index++) {
if (records >= maxRecords) {
truncated = true;
break;
}
examined++;
const field = section.address + BigInt(index * 8);
try {
readClass(pointer(field));
} catch (cause) {
failures.push(
`${hex(field)}: ${cause instanceof Error ? cause.message : String(cause)}`,
);
}
}
}
const swiftRelative = (field: bigint, indirectable = false): bigint => {
const displacement = bytes.readInt32LE(offset(field, 4));
const indirect = indirectable && (displacement & 1) !== 0;
let target =
displacement === 0
? 0n
: field + BigInt(indirectable ? displacement & ~1 : displacement);
let fileOffset: number | null = null;
let reason: string | null = null;
try {
if (indirect && target !== 0n) target = pointer(target);
if (target !== 0n) fileOffset = offset(target);
} catch (cause) {
reason = cause instanceof Error ? cause.message : String(cause);
}
if (admit())
result.relative_pointers.push({
field: location(field),
target: {
address: target === 0n ? null : hex(target),
file_offset: fileOffset,
},
displacement,
indirectable,
indirect,
decode: reason === null ? decoded : { status: "partial", reason },
evidence: evidence(field, "Swift ABI signed-relative metadata pointer"),
});
if (reason !== null) throw new RangeError(reason);
return target;
};
const swiftFailures: string[] = [];
let swiftExamined = 0;
for (const section of sections.filter(
({ name }) => name === "__swift5_proto",
)) {
if (section.size % 4 !== 0)
throw new RangeError("Misaligned Swift conformance section");
for (let index = 0; index < section.size / 4; index++) {
if (!admit()) break;
swiftExamined++;
const field = section.address + BigInt(index * 4);
try {
const descriptor = swiftRelative(field);
const flags = u32(descriptor + 12n);
const protocol = swiftRelative(descriptor, true);
if ((u32(protocol) & 31) !== 3)
throw new TypeError("Unsupported Swift protocol descriptor kind");
const protocolName = string(swiftRelative(protocol + 8n));
const typeKind = (flags >>> 3) & 7;
if (typeKind !== 0 && typeKind !== 1)
throw new TypeError(
"Unsupported Swift conformance type-reference kind",
);
let type = swiftRelative(descriptor + 4n);
if (typeKind === 1) type = pointer(type);
if (![16, 17, 18].includes(u32(type) & 31))
throw new TypeError("Unsupported Swift type descriptor kind");
const typeName = string(swiftRelative(type + 8n));
const witness = swiftRelative(descriptor + 8n);
const staticWitness =
witness !== 0n && (flags & ~0x38) === 0 && (u32(type) & 0x80) === 0;
let witnessReason: string | null = staticWitness
? null
: "Conditional, generic, resilient or missing static witness table is not decoded";
if (staticWitness && pointer(witness) !== descriptor)
witnessReason =
"Witness-table conformance header is unresolved or encoded";
result.swift_conformances.push({
type_name: typeName,
protocol_name: protocolName,
module: null,
witness_table:
witness === 0n
? { address: null, file_offset: null }
: location(witness),
location: location(descriptor),
decode:
witnessReason === null
? decoded
: {
status: "partial",
reason: witnessReason,
},
evidence: evidence(
descriptor,
"Swift protocol conformance descriptor and directly encoded type/protocol names",
),
});
if (witnessReason !== null) {
swiftFailures.push(`${typeName}: ${witnessReason}`);
continue;
}
const count = u32(protocol + 16n);
const signatureCount = u32(protocol + 12n);
if (count > 20_000 || signatureCount > 20_000)
throw new RangeError("Swift witness requirement count exceeds 20000");
for (let slot = 0; slot < count; slot++) {
if (!admit()) break;
const entry = witness + BigInt((slot + 1) * 8);
const implementation = pointer(entry);
const requirementFlags = u32(
protocol + 24n + BigInt(signatureCount * 12 + slot * 8),
);
const kind = requirementFlags & 15;
const synchronousFunction =
kind >= 1 && kind <= 4 && (requirementFlags & 0x20) === 0;
const executable =
synchronousFunction &&
segments.some(
(segment) =>
segment.executable &&
implementation >= segment.address &&
implementation < segment.address + segment.size,
);
result.swift_dispatch_slots.push({
owner: `${typeName}: ${protocolName}`,
table_kind: "witness_table",
slot_index: slot + 1,
requirement: null,
implementation: null,
implementation_address: executable ? hex(implementation) : null,
thunk_address: null,
location: location(entry),
decode: executable
? decoded
: {
status: "partial",
reason:
"Witness slot is non-function, async, nil, external, authenticated or encoded; implementation target is unresolved",
},
evidence: evidence(
entry,
"Static Swift witness slot, indexed after the conformance-descriptor header",
),
});
}
} catch (cause) {
swiftFailures.push(
`${hex(field)}: ${cause instanceof Error ? cause.message : String(cause)}`,
);
}
}
}
result.coverage.push({
facet: "swift_conformances_static_witness_slots",
status: swiftFailures.length > 0 || truncated ? "partial" : "complete",
reason:
[...swiftFailures, ...(truncated ? ["max_records_reached"] : [])].join(
"; ",
) || null,
examined: swiftExamined,
decoded: result.swift_conformances.length,
});
const typeEntries: bigint[] = [];
for (const section of sections.filter(
({ name }) => name === "__swift5_types",
)) {
if (section.size % 4 !== 0)
throw new RangeError("Misaligned Swift type section");
for (let index = 0; index < section.size / 4 && index < maxRecords; index++)
typeEntries.push(section.address + BigInt(index * 4));
if (section.size / 4 > maxRecords) truncated = true;
}
decodeSwiftClassVtables({
entries: typeEntries,
result,
readers: {
u32,
relative: swiftRelative,
string,
location,
evidence,
admit,
executable: (address) =>
segments.some(
(segment) =>
segment.executable &&
address >= segment.address &&
address < segment.address + segment.size,
),
},
});
result.coverage.push({
facet: "objc_class_method_ivar_metadata",
status: failures.length > 0 || truncated ? "partial" : "complete",
reason:
[...failures, ...(truncated ? ["max_records_reached"] : [])].join("; ") ||
null,
examined,
decoded: result.objc_classes.length,
});
result.coverage.push({
facet: "binary_relative_pointers",
status:
truncated ||
result.relative_pointers.some((item) => item.decode.status !== "decoded")
? "partial"
: "complete",
reason: truncated
? "max_records_reached"
: result.relative_pointers.some(
(item) => item.decode.status !== "decoded",
)
? "relative_pointer_targets_unresolved"
: null,
examined: result.relative_pointers.length,
decoded: result.relative_pointers.filter(
(item) => item.decode.status === "decoded",
).length,
});
for (const facet of [
"objc_properties_categories",
"swift_generic_resilient_witnesses_overrides_async_coroutines",
])
result.coverage.push({
facet,
status: "unsupported",
reason:
"This reader admits validated 64-bit Objective-C class/ivar/method lists and simple Swift conformance/static witness records; chained fixups, generic/resilient tables and other metadata families are not decoded",
examined: 0,
decoded: 0,
});
return objcSwiftMetadataSchema.parse(result);
};
/** Read digest-verified target bytes under a 64 MiB static metadata budget. */
export const inspectAppleDispatchMetadata = async (
target: BinaryTarget,
maxRecords: number,
signal?: AbortSignal,
) => {
if (target.kind !== "executable" || target.format !== "mach-o")
throw new TypeError("Apple dispatch metadata requires a Mach-O target");
const handle = await open(
target.path,
constants.O_RDONLY | constants.O_NOFOLLOW,
);
try {
const before = await handle.stat();
if (!before.isFile() || before.size > 64 * 1024 * 1024)
throw new RangeError(
"Apple metadata target must be a regular file no larger than 64 MiB",
);
if (signal?.aborted) throw new Error("cancelled");
const bytes = await handle.readFile({ signal });
const digest = createHash("sha256").update(bytes).digest("hex");
if (digest !== target.sha256)
throw new Error(
"Apple metadata target digest changed after session binding",
);
return nativeDispatchMetadataResultSchema.parse({
target_sha256: target.sha256,
provider: {
id: "native-macos",
name: "macOS native inspection utilities",
version: "apple-metadata-reader-1",
},
analysis_profile_digest: null,
result: decodeAppleDispatchMetadata(
bytes,
maxRecords,
{ path: target.path, sha256: digest },
target.architecture,
),
});
} finally {
await handle.close();
}
};
+98
View File
@@ -0,0 +1,98 @@
import type { ObjcSwiftMetadata } from "../domain/objcSwiftMetadata.js";
import type { SwiftMetadataReaders } from "./AppleSwiftVtables.js";
/** Read protocol lists and absolute protocol method declarations with cycle-safe identities. */
export const createObjcProtocolReader = (input: {
readers: Pick<
SwiftMetadataReaders,
"u32" | "string" | "location" | "evidence" | "admit"
> & { pointer(address: bigint): bigint; i32(address: bigint): number };
result: ObjcSwiftMetadata;
failures: string[];
}) => {
const { readers: read, result, failures } = input;
const visited = new Set<bigint>();
const name = (address: bigint) => read.string(read.pointer(address + 8n));
const list = (address: bigint): string[] => {
if (address === 0n) return [];
const count = read.pointer(address);
if (count > 20000n)
throw new RangeError("Protocol list exceeds 20000 entries");
const names: string[] = [];
for (let index = 0n; index < count; index++) {
if (!read.admit()) break;
const protocol = read.pointer(address + 8n + index * 8n);
names.push(name(protocol));
record(protocol);
}
return names;
};
const methods = (address: bigint, required: boolean, instance: boolean) => {
const output: ObjcSwiftMetadata["objc_protocols"][number]["methods"] = [];
if (address === 0n) return output;
const flags = read.u32(address),
count = read.u32(address + 4n);
const relative = (flags & 0x80000000) !== 0;
const stride = flags & 0xfffc;
if (stride !== (relative ? 12 : 24))
throw new TypeError("Unsupported Objective-C protocol method entry size");
for (let index = 0; index < count; index++) {
if (!read.admit()) break;
const entry = address + 8n + BigInt(index * stride);
let selector = relative
? entry + BigInt(read.i32(entry))
: read.pointer(entry);
if (relative && (flags & 0x40000000) === 0)
selector = read.pointer(selector);
output.push({
selector: read.string(selector),
method_type: instance ? "instance" : "class",
address: null,
is_required: required,
is_optional: !required,
});
}
return output;
};
const record = (address: bigint) => {
if (address === 0n || visited.has(address) || !read.admit()) return;
visited.add(address);
try {
if (read.u32(address + 64n) < 72)
throw new RangeError("Truncated Objective-C protocol declaration");
const protocolName = name(address);
const adopted = list(read.pointer(address + 16n));
const required = [
...methods(read.pointer(address + 24n), true, true),
...methods(read.pointer(address + 32n), true, false),
];
const optional = [
...methods(read.pointer(address + 40n), false, true),
...methods(read.pointer(address + 48n), false, false),
];
result.objc_protocols.push({
name: protocolName,
methods: required,
optional_methods: optional,
properties: [],
});
result.objc_protocol_records.push({
name: protocolName,
adopted_protocols: adopted,
methods: required,
optional_methods: optional,
location: read.location(address),
decode: { status: "decoded", reason: null },
evidence: read.evidence(
address,
"Objective-C protocol declaration and encoded method lists; IMP fields are not handler targets",
),
});
} catch (cause) {
failures.push(
`Protocol 0x${address.toString(16)}: ${cause instanceof Error ? cause.message : String(cause)}`,
);
}
};
return { list, record };
};
+122
View File
@@ -0,0 +1,122 @@
import type {
ObjcSwiftMetadata,
NativeMetadataEvidence,
NativeMetadataLocation,
} from "../domain/objcSwiftMetadata.js";
/** Byte readers shared with the validated Mach-O metadata boundary. */
export interface SwiftMetadataReaders {
u32(address: bigint): number;
relative(address: bigint): bigint;
string(address: bigint): string;
location(address: bigint): NativeMetadataLocation;
evidence(address: bigint, description: string): NativeMetadataEvidence[];
executable(address: bigint): boolean;
admit(): boolean;
}
/** Decode non-generic, non-resilient Swift class vtable descriptors without instantiating metadata. */
export const decodeSwiftClassVtables = (input: {
readers: SwiftMetadataReaders;
entries: readonly bigint[];
result: ObjcSwiftMetadata;
}) => {
const { readers: read, result } = input;
const failures: string[] = [];
let examined = 0;
for (const field of input.entries) {
if (!read.admit()) {
failures.push("max_records_reached");
break;
}
examined++;
try {
const descriptor = read.relative(field);
const flags = read.u32(descriptor);
if ((flags & 31) !== 16) continue;
const specific = flags >>> 16;
if ((flags & 0x80) !== 0 || (specific & 0x2000) !== 0)
throw new TypeError(
"Generic class or resilient superclass metadata is unsupported",
);
if ((specific & 0x8000) === 0) continue;
const initialization = specific & 3;
if (initialization === 3)
throw new TypeError("Unknown metadata initialization kind");
const header =
descriptor +
44n +
BigInt(initialization === 1 ? 12 : initialization === 2 ? 4 : 0);
const tableOffset = read.u32(header);
const count = read.u32(header + 4n);
const positiveWords = read.u32(descriptor + 28n);
if (count > 20000 || tableOffset + count > positiveWords)
throw new RangeError(
"Swift vtable count or offset exceeds declared metadata bounds",
);
const owner = read.string(read.relative(descriptor + 8n));
for (let index = 0; index < count; index++) {
if (!read.admit()) {
failures.push("max_records_reached");
break;
}
const entry = header + 8n + BigInt(index * 8);
const methodFlags = read.u32(entry);
// Async slots reference async descriptors; coroutine and future kinds need separate decoders.
const synchronous =
(methodFlags & 0x40) === 0 && (methodFlags & 15) <= 3;
const implementation = read.relative(entry + 4n);
const resolved = synchronous && read.executable(implementation);
result.swift_dispatch_slots.push({
owner,
table_kind: "class_vtable",
slot_index: tableOffset + index,
requirement: null,
implementation: null,
implementation_address: resolved
? `0x${implementation.toString(16)}`
: null,
thunk_address: null,
location: read.location(entry),
decode: resolved
? { status: "decoded", reason: null }
: {
status: "partial",
reason:
"Async, coroutine, external or unmapped vtable implementation is unresolved",
},
evidence: read.evidence(
entry,
"Swift class vtable method descriptor; slot index is a metadata word offset, not a source method ordinal",
),
});
}
if ((specific & 0x4000) !== 0)
failures.push(
`${owner}: inherited override descriptors are unsupported`,
);
} catch (cause) {
failures.push(
`0x${field.toString(16)}: ${cause instanceof Error ? cause.message : String(cause)}`,
);
}
}
const slots = result.swift_dispatch_slots.filter(
(slot) => slot.table_kind === "class_vtable",
);
result.coverage.push({
facet: "swift_class_vtable_descriptors",
examined,
decoded: slots.filter((slot) => slot.decode.status === "decoded").length,
status:
failures.length > 0 ||
slots.some((slot) => slot.decode.status !== "decoded")
? "partial"
: "complete",
reason:
failures.join("; ") ||
(slots.some((slot) => slot.decode.status !== "decoded")
? "vtable_implementations_unresolved"
: null),
});
};
+29
View File
@@ -0,0 +1,29 @@
import type { CapabilityDescriptor } from "../application/AnalysisProvider.js";
/** Apply native host restrictions to portable provider discovery metadata. */
export const nativeHostCapabilities = (
capabilities: readonly CapabilityDescriptor[],
platform: NodeJS.Platform = process.platform,
): readonly CapabilityDescriptor[] => {
if (platform === "darwin") return capabilities;
return capabilities.map((capability): CapabilityDescriptor => {
if (capability.provider.id === "native-macos")
return {
...capability,
available: false,
availabilityCode: "unsupported_host",
reason: "Native macOS utilities require macOS.",
};
if (
capability.provider.id === "rea-artifact-graph" &&
capability.operation === "inspect_asset_catalog"
)
return {
...capability,
available: false,
availabilityCode: "unsupported_host",
reason: "Apple asset catalogs require macOS assetutil.",
};
return capability;
});
};
+83 -5
View File
@@ -1,3 +1,5 @@
import { inspectAppleDispatchMetadata } from "./AppleDispatchMetadata.js";
import { observeNativeUi } from "./NativeUiObservation.js";
import { dirname, isAbsolute, resolve } from "node:path";
import { stat } from "node:fs/promises";
@@ -67,7 +69,10 @@ export class NativeMacOSProvider implements AnalysisProvider {
) {
const available = platform === "darwin";
this.#capabilities = Object.freeze(
NATIVE_TOOL_CONTRACTS.map((contract): CapabilityDescriptor => {
[
...NATIVE_TOOL_CONTRACTS,
{ name: "inspect_native_dispatch_metadata" as const },
].map((contract): CapabilityDescriptor => {
const availability = available
? ({ available: true, reason: null } as const)
: ({
@@ -81,10 +86,13 @@ export class NativeMacOSProvider implements AnalysisProvider {
...availability,
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess: true,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
launchesProcess:
contract.name !== "inspect_native_dispatch_metadata",
mayShowUi: contract.name === "capture_native_ui_scenario",
mayAccessNetwork: contract.name === "capture_native_ui_scenario",
mayWriteFilesystem:
contract.name === "capture_native_ui_scenario" ||
contract.name === "observe_native_ui",
changesPermissions: false,
requiresRoot: false,
}),
@@ -124,6 +132,50 @@ class NativeMacOSClient implements AnalysisClient {
return err(new AnalysisCancelledError(operation));
if (operation === "health")
return ok(createAnalysisExecution(null, IDENTITY));
if (operation === "inspect_native_dispatch_metadata") {
if (this.target.kind !== "executable" || this.target.format !== "mach-o")
return err(
new AnalysisCapabilityUnavailableError(
IDENTITY.id,
operation,
"Binary Apple metadata requires Mach-O; other providers can report symbol-only metadata",
),
);
try {
const maxRecords = z
.number()
.int()
.min(1)
.max(20000)
.parse(parameters.max_records ?? 5000);
const result = await inspectAppleDispatchMetadata(
this.target,
maxRecords,
options?.signal,
);
return ok(
createAnalysisExecution(result, result.provider, {
locations: [{ kind: "artifact-path", path: this.target.path }],
limitations: result.result.coverage.flatMap(({ reason }) =>
reason === null ? [] : [reason],
),
}),
);
} catch (cause) {
return err(
options?.signal?.aborted
? new AnalysisCancelledError(operation)
: new ProviderAdapterError(IDENTITY.id, operation, {
cause,
diagnostics: {
target_path: this.target.path,
reason:
cause instanceof Error ? cause.message : String(cause),
},
}),
);
}
}
if (!isNativeOperation(operation))
return err(
new AnalysisCapabilityUnavailableError(
@@ -132,6 +184,21 @@ class NativeMacOSClient implements AnalysisClient {
"Operation is not implemented by native macOS tools.",
),
);
if (
operation === "observe_native_ui" ||
operation === "capture_native_ui_scenario"
) {
const result = await observeNativeUi(this.target, operation, parameters, {
signal: options?.signal,
});
return result.ok
? ok(
createAnalysisExecution(result.value, IDENTITY, {
limitations: result.value.limitations,
}),
)
: result;
}
try {
const observation = await this.#dispatch(
operation,
@@ -166,6 +233,17 @@ class NativeMacOSClient implements AnalysisClient {
signal?: AbortSignal,
): Promise<Result<NativeObservation, AnalysisError>> {
switch (operation) {
case "observe_native_ui":
case "capture_native_ui_scenario":
return Promise.resolve(
err(
new AnalysisCapabilityUnavailableError(
IDENTITY.id,
operation,
"UI observation uses its explicit authority boundary",
),
),
);
case "inspect_macho":
return this.#inspectMacho(signal);
case "inspect_signature":
+53
View File
@@ -0,0 +1,53 @@
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { execFileOutput } from "../process/ExecFileOutput.js";
import type { NativeUiHelper } from "./NativeUiObservation.js";
/** Lazily compile one owned helper per observation/scenario and remove its compiler cache. */
export const createNativeUiHelperRuntime = () => {
let root: string | undefined;
let executable: string | undefined;
const invoke: NativeUiHelper = async (parameters, signal) => {
if (executable === undefined) {
root = await mkdtemp(join(tmpdir(), "rea-native-ui-"));
const output = join(root, "observer");
await execFileOutput(
"/usr/bin/xcrun",
[
"swiftc",
"-module-cache-path",
join(root, "modules"),
fileURLToPath(
new URL("../../bridge/native/ReaNativeUI.swift", import.meta.url),
),
"-o",
output,
],
{
timeout: 60_000,
maxBuffer: 1024 * 1024,
...(signal === undefined ? {} : { signal }),
},
);
executable = output;
}
const output = await execFileOutput(
executable,
[JSON.stringify(parameters)],
{
timeout: 30_000,
maxBuffer: 16 * 1024 * 1024,
...(signal === undefined ? {} : { signal }),
},
);
return JSON.parse(output.stdout) as unknown;
};
return {
invoke,
close: async () => {
if (root !== undefined) await rm(root, { recursive: true, force: true });
},
};
};
+153
View File
@@ -0,0 +1,153 @@
import { describe, expect, it } from "vitest";
import { observeNativeUi } from "./NativeUiObservation.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
const target: BinaryTarget = {
path: "/fixture/App",
sha256: "a".repeat(64),
kind: "executable",
format: "mach-o",
architecture: "arm64",
availableArchitectures: ["arm64"],
};
const scope = {
pid: 123,
window_id: 456,
observation_approved: true,
screenshot: false,
};
const snapshot = {
window: {
pid: 123,
window_id: 456,
executable: target.path,
launch_time: 1,
title: "Fixture",
},
nodes: [],
screenshot: null,
gaps: [],
truncated: false,
};
describe("native UI authority and lifecycle", () => {
it("requires observation and independent action approval before invoking a helper", async () => {
let calls = 0;
const invoke = async () => {
calls++;
return { ok: true, result: snapshot };
};
expect(
(
await observeNativeUi(
target,
"observe_native_ui",
{ ...scope, observation_approved: false },
{ invoke },
)
).ok,
).toBe(false);
expect(
(
await observeNativeUi(
target,
"capture_native_ui_scenario",
{
...scope,
restore: "leave-as-is",
steps: [{ kind: "click", path: [] }],
},
{ invoke },
)
).ok,
).toBe(false);
expect(calls).toBe(0);
});
it.each([
"accessibility-denied",
"screen-recording-denied",
"ambiguous-window",
])("preserves actionable %s without fallback", async (code) => {
const result = await observeNativeUi(target, "observe_native_ui", scope, {
invoke: async () => ({
ok: false,
code,
message: "Grant permission or select an unambiguous window",
}),
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.message).toContain(code);
});
it("stops on a failed action and returns ordered before/capture-gap evidence", async () => {
const calls: Readonly<Record<string, unknown>>[] = [];
const result = await observeNativeUi(
target,
"capture_native_ui_scenario",
{
...scope,
actions_approved: true,
restore: "leave-as-is",
steps: [
{ kind: "scroll", path: [1], direction: "increment" },
{ kind: "click", path: [2] },
],
},
{
invoke: async (parameters) => {
calls.push(parameters);
return calls.length === 1
? { ok: true, result: snapshot }
: {
ok: false,
code: "action-failed",
message: "AXIncrement unsupported",
};
},
},
);
expect(calls).toHaveLength(2);
expect(calls[1]).toMatchObject({
launch_time: 1,
action: { kind: "scroll", path: [1] },
});
expect(result.ok).toBe(true);
if (result.ok)
expect(result.value.steps).toMatchObject([
{ index: 0, outcome: "failed", before: snapshot, after: null },
]);
});
it("rejects target replacement and stops subsequent actions after cancellation", async () => {
const controller = new AbortController();
let calls = 0;
const result = await observeNativeUi(
target,
"capture_native_ui_scenario",
{
...scope,
actions_approved: true,
restore: "leave-as-is",
steps: [
{ kind: "wait", milliseconds: 1000 },
{ kind: "click", path: [] },
],
},
{
signal: controller.signal,
invoke: async () => {
calls++;
controller.abort();
return { ok: true, result: snapshot };
},
},
);
expect(calls).toBe(1);
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.steps[0]?.outcome).toBe("cancelled");
const replaced = await observeNativeUi(target, "observe_native_ui", scope, {
invoke: async () => ({
ok: true,
result: { ...snapshot, window: { ...snapshot.window, pid: 999 } },
}),
});
expect(replaced.ok).toBe(false);
});
});

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