Merge remote-tracking branch 'origin/main' into fix/exact-empty-graph-identities

# Conflicts:
#	docs/product-catalog.json
#	docs/verification/managed-conformance-manifest.json
#	skills/reverse-engineer-anything/SKILL.md
#	src/generatedMcpToolCatalog.ts
This commit is contained in:
Iwakurakaoru0822
2026-10-06 21:36:34 -07:00
110 changed files with 2995 additions and 1275 deletions
+1 -1
View File
@@ -79,7 +79,7 @@ export class JadxSession {
);
const engine = {
name: "jadx-headless-mcp",
version: "0.7.1",
version: JADX_RELEASE.version,
artifact_sha256: jarHash,
source_revision:
jarHash === JADX_RELEASE.sha256 ? JADX_RELEASE.revision : null,
+10 -9
View File
@@ -18,12 +18,14 @@ import type {
ProviderIdentity,
} from "./AnalysisProvider.js";
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/officialToolContracts.js";
import { ENHANCED_TOOL_CONTRACTS } from "../contracts/enhancedToolContracts.js";
import type { BinarySessionPort } from "./BinarySessionPort.js";
import {
SessionProviderRouter,
type SessionProviderRoute,
} from "./SessionProviderRouter.js";
import { InvestigationRecords } from "./investigation/InvestigationRecords.js";
import { BinarySessionRecords } from "./BinarySessionRecords.js";
import { binarySessionStatus } from "./BinarySessionStatus.js";
import {
@@ -38,14 +40,10 @@ import {
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
export type { BinarySessionPort } from "./BinarySessionPort.js";
const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
GENERATED_MCP_TOOL_CATALOG.filter(
({ kind }) => kind === "official-proxy",
).map(({ name }) => name),
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
);
const ENHANCED_OPERATIONS: ReadonlySet<string> = new Set(
GENERATED_MCP_TOOL_CATALOG.filter(({ kind }) => kind === "enhanced").map(
({ name }) => name,
),
ENHANCED_TOOL_CONTRACTS.map(({ name }) => name),
);
/**
@@ -78,8 +76,11 @@ export class BinarySession
>();
readonly #availabilityListeners = new Set<() => void | Promise<void>>();
constructor(providerRouter: SessionProviderRouter) {
super();
constructor(
providerRouter: SessionProviderRouter,
records: InvestigationRecords = new InvestigationRecords(),
) {
super(records);
this.#providerRouter = providerRouter;
}
@@ -1,3 +1,4 @@
import { InvestigationRecords } from "./investigation/InvestigationRecords.js";
import type { AnalysisProvider } from "./AnalysisProvider.js";
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
import { BinarySession } from "./BinarySession.js";
@@ -15,4 +16,5 @@ export const composeBinarySession = (
registry instanceof SessionProviderRouter
? registry
: SessionProviderRouter.selectable(registry, auxiliaryProviders),
new InvestigationRecords(),
);
+4 -41
View File
@@ -1,21 +1,13 @@
import type { InvestigationRecordPort } from "./investigation/InvestigationRecordPort.js";
import type { ExecutableFormatHint } from "../domain/dosCom.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Evidence } from "../domain/evidence.js";
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import type { UnknownRegistryError } from "../domain/unknownRegistryError.js";
import type { Result } from "../domain/result.js";
import type {
RecordUnknownInput,
ResidualUnknown,
UnknownStatus,
UpdateUnknownInput,
} from "../domain/residualUnknown.js";
import type {
AnalysisOperation,
AnalysisOperationPort,
@@ -24,7 +16,8 @@ import type {
} from "./AnalysisProvider.js";
/** Target lifecycle used by CLI and MCP without exposing a concrete provider. */
export interface BinarySessionPort extends AnalysisOperationPort {
export interface BinarySessionPort
extends AnalysisOperationPort, InvestigationRecordPort {
open(
path: string,
options?: {
@@ -42,40 +35,10 @@ export interface BinarySessionPort extends AnalysisOperationPort {
): Promise<Result<null, AnalysisError>>;
status(): JsonValue;
activeTarget(): BinaryTarget | undefined;
recordEvidence(
evidence: Evidence,
): Result<"added" | "duplicate", EvidenceIntegrityError>;
hasEvidence(evidenceId: string): boolean;
evidenceById(evidenceId: string): Evidence | undefined;
exportEvidenceBundle(): EvidenceBundle;
importEvidenceBundle(bundle: unknown): Result<number, EvidenceIntegrityError>;
exportAnalysisSnapshot(): Result<AnalysisSnapshot, AnalysisError>;
importAnalysisSnapshot(
snapshot: AnalysisSnapshot,
): Result<number, AnalysisError>;
recordUnknown(
input: RecordUnknownInput,
): Result<ResidualUnknown, AnalysisError>;
recordEvidenceWithUnknown(
evidence: Evidence,
input: RecordUnknownInput,
): Result<ResidualUnknown | null, AnalysisError>;
updateUnknown(
input: UpdateUnknownInput,
): Result<ResidualUnknown, AnalysisError>;
listUnknowns(filters?: {
readonly status?: UnknownStatus;
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
}): ResidualUnknown[];
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
readonly truthVerified: boolean;
readonly unknown: ResidualUnknown;
},
UnknownRegistryError
>;
providerIdentity(operation?: AnalysisOperation): ProviderIdentity;
analysisProfile(
operation?: AnalysisOperation,
+25 -45
View File
@@ -1,7 +1,7 @@
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import type { Evidence } from "../domain/evidence.js";
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
import { evidenceBundleForTarget } from "../domain/evidenceBundle.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
@@ -19,25 +19,24 @@ import type {
AnalysisOperation,
} from "./AnalysisProvider.js";
import { AnalysisSnapshotCache } from "./AnalysisSnapshotCache.js";
import { EvidenceLedger } from "./EvidenceLedger.js";
import {
UNKNOWN_REGISTRY_PROVIDER,
unknownEvidenceLinks,
unknownMutationEvidence,
} from "./UnknownEvidence.js";
import { InvestigationRecords } from "./investigation/InvestigationRecords.js";
export interface ActiveAnalysisBinding {
readonly target: BinaryTarget;
readonly profile: AnalysisProfileCommitment | null;
}
/** Owns session evidence, snapshots, and residual unknowns. */
/** Binary snapshot owner and compatibility facade for composed investigation records. */
export abstract class BinarySessionRecords {
readonly #evidence = new EvidenceLedger();
readonly #records: InvestigationRecords;
readonly #snapshot = new AnalysisSnapshotCache();
#snapshotInvalidated = false;
readonly #snapshotListeners = new Set<() => void | Promise<void>>();
constructor(records: InvestigationRecords = new InvestigationRecords()) {
this.#records = records;
}
/** Observe changes to the mutable current analysis snapshot resource. */
onAnalysisSnapshotChanged(listener: () => void | Promise<void>): () => void {
this.#snapshotListeners.add(listener);
@@ -47,27 +46,27 @@ export abstract class BinarySessionRecords {
recordEvidence(
evidence: Evidence,
): Result<"added" | "duplicate", EvidenceIntegrityError> {
const recorded = this.#evidence.record(evidence);
const recorded = this.#records.recordEvidence(evidence);
if (recorded.ok && recorded.value === "added") this.#emitSnapshotChanged();
return recorded;
}
hasEvidence(evidenceId: string): boolean {
return this.#evidence.has(evidenceId);
return this.#records.hasEvidence(evidenceId);
}
evidenceById(evidenceId: string): Evidence | undefined {
return this.#evidence.get(evidenceId);
return this.#records.evidenceById(evidenceId);
}
exportEvidenceBundle(): EvidenceBundle {
return this.#evidence.export();
return this.#records.exportEvidenceBundle();
}
importEvidenceBundle(
bundle: unknown,
): Result<number, EvidenceIntegrityError> {
const imported = this.#evidence.import(bundle);
const imported = this.#records.mergeEvidenceBundle(bundle);
if (!imported.ok) return imported;
if (imported.value.changed) this.#emitSnapshotChanged();
return ok(imported.value.recordsAdded);
@@ -95,8 +94,11 @@ export abstract class BinarySessionRecords {
target,
profile,
target === undefined
? this.#evidence.export()
: evidenceBundleForTarget(this.#evidence.export(), target.sha256),
? this.#records.exportEvidenceBundle()
: evidenceBundleForTarget(
this.#records.exportEvidenceBundle(),
target.sha256,
),
);
}
@@ -116,7 +118,7 @@ export abstract class BinarySessionRecords {
? undefined
: { target: active.target, profile: active.profile },
(bundle) => {
const imported = this.#evidence.import(bundle);
const imported = this.#records.mergeEvidenceBundle(bundle);
return imported.ok ? ok(imported.value.recordsAdded) : imported;
},
);
@@ -175,7 +177,7 @@ export abstract class BinarySessionRecords {
}
protected clearSessionRecords(): void {
this.#evidence.clear();
this.#records.clear();
this.#snapshot.clear();
this.#snapshotInvalidated = false;
this.#emitSnapshotChanged();
@@ -202,10 +204,7 @@ export abstract class BinarySessionRecords {
input: RecordUnknownInput,
): Result<ResidualUnknown, AnalysisError> {
const target = this.activeAnalysisBinding()?.target;
const recorded = this.#evidence.recordUnknown(
input,
unknownMutationEvidence(target, input),
);
const recorded = this.#records.recordUnknown(input, target);
if (recorded.ok) this.#emitSnapshotChanged();
return recorded;
}
@@ -214,11 +213,7 @@ export abstract class BinarySessionRecords {
evidence: Evidence,
input: RecordUnknownInput,
): Result<ResidualUnknown | null, AnalysisError> {
const recorded = this.#evidence.recordWithUnknown(
evidence,
input,
unknownMutationEvidence(undefined, input),
);
const recorded = this.#records.recordEvidenceWithUnknown(evidence, input);
if (recorded.ok) this.#emitSnapshotChanged();
return recorded;
}
@@ -227,22 +222,7 @@ export abstract class BinarySessionRecords {
input: UpdateUnknownInput,
): Result<ResidualUnknown, AnalysisError> {
const target = this.activeAnalysisBinding()?.target;
const evidence = createEvidence(target, UNKNOWN_REGISTRY_PROVIDER, {
predicateType: "rea.residual-unknown-mutation",
operation: "update_unknown",
parameters: {
unknown_id: input.unknown_id,
expected_revision: input.expected_revision,
},
result: { action: "update", status: input.status },
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: unknownEvidenceLinks(input),
limitations: [
"Registry mutation evidence records analyst intent, not proof of the answer.",
],
});
const updated = this.#evidence.updateUnknown(input, evidence);
const updated = this.#records.updateUnknown(input, target);
if (updated.ok) this.#emitSnapshotChanged();
return updated;
}
@@ -254,7 +234,7 @@ export abstract class BinarySessionRecords {
readonly domain?: string;
} = {},
): ResidualUnknown[] {
return this.#evidence.listUnknowns(filters);
return this.#records.listUnknowns(filters);
}
verifyUnknownResolution(unknownId: string): Result<
@@ -265,6 +245,6 @@ export abstract class BinarySessionRecords {
},
UnknownRegistryError
> {
return this.#evidence.verifyUnknownResolution(unknownId);
return this.#records.verifyUnknownResolution(unknownId);
}
}
+3 -3
View File
@@ -14,7 +14,7 @@ import {
} from "../contracts/toolOutputSchemaPrimitives.js";
import type { ToolKind } from "../contracts/toolContractTypes.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
import { TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import {
clientRequirementsFor,
NO_CLIENT_FEATURES,
@@ -131,7 +131,7 @@ export const buildCapabilityInventory = (
const descriptors = new Map<string, ProviderDescriptor>(
status.capabilities.map((descriptor) => [descriptor.operation, descriptor]),
);
return GENERATED_MCP_TOOL_CATALOG.map((contract): ToolAvailability => {
return TOOL_CONTRACTS.map((contract): ToolAvailability => {
const availability = availabilityFor({
name: contract.name,
kind: contract.kind,
@@ -246,7 +246,7 @@ const workflowAvailabilityFor = ({
: {
reason: "provider_missing",
remediation:
"On Linux, provide an absolute REA_BINWALK_COMMAND (Binwalk 3.1.0) or REA_UNBLOB_COMMAND (Unblob 26.6.4) path and util-linux prlimit. Extraction also requires the selected format’s external extractor.",
"On Linux, provide an absolute REA_BINWALK_COMMAND (Binwalk 3.1.x, verified with 3.1.0) or REA_UNBLOB_COMMAND (Unblob 26.6.x, verified with 26.6.4) path and util-linux prlimit. Extraction also requires the selected format’s external extractor.",
};
}
if (kind === "android-provider")
@@ -1,189 +0,0 @@
import { existsSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { buildBinary } from "plist";
import { afterEach, describe, expect, it } from "vitest";
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
describe("compiled Interface Builder bundle reader", () => {
it("reads nib plist archives and reports provenance", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-ib-test-"));
roots.push(root);
const bundle = join(root, "Example.app");
const nib = join(
bundle,
"Contents",
"Resources",
"Main.storyboardc",
"Main.nib",
);
await mkdir(nib, { recursive: true });
await writeFile(
join(nib, "objects.nib"),
buildBinary({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: [
"$null",
{ $class: { UID: 2 }, title: "Build" },
{
$classname: "UIButton",
$classes: ["UIButton", "UIControl", "UIView", "NSObject"],
},
],
$top: { root: { UID: 1 } },
}),
);
await writeFile(
join(bundle, "Contents", "Resources", "Main.storyboardc", "Info.plist"),
'<?xml version="1.0"?><plist><dict><key>notAnArchive</key><string>scene-index</string></dict></plist>',
);
await mkdir(join(bundle, "Contents", "Resources", "outside.nib"), {
recursive: true,
});
await writeFile(
join(bundle, "Contents", "Resources", "outside.nib", "not-nib.txt"),
"ignored",
);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "b".repeat(64),
});
expect(analysis.documents).toMatchObject([
{
relative_path:
"Contents/Resources/Main.storyboardc/Main.nib/objects.nib",
document_kind: "storyboard_scene",
object_count: 1,
},
]);
expect(analysis.documents).toHaveLength(1);
expect(analysis.graph.target_sha256).toBe("b".repeat(64));
expect(analysis.graph.nodes.some(({ name }) => name === "Build")).toBe(
true,
);
});
it("honors cancellation during directory traversal", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-ib-test-"));
roots.push(root);
const controller = new AbortController();
controller.abort();
await expect(
analyzeInterfaceBuilderBundle({
bundlePath: root,
targetSha256: "c".repeat(64),
signal: controller.signal,
}),
).rejects.toMatchObject({ reason: "cancelled" });
});
});
describe("bounded Interface Builder archive decoding", () => {
it("counts malformed archives against the document limit", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-ib-test-"));
roots.push(root);
const bundle = join(root, "Example.app");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
await writeFile(join(resources, "BadOne.nib"), Buffer.from("bplist00bad"));
await writeFile(join(resources, "BadTwo.nib"), Buffer.from("bplist00bad"));
const result = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "e".repeat(64),
limits: { max_documents: 1 },
});
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "archive_decode",
status: "partial",
examined: 1,
omitted: 1,
}),
);
expect(result.graph.truncated).toBe(true);
});
it.skipIf(process.platform !== "darwin" || !existsSync("/usr/bin/ibtool"))(
"decodes an Xcode-compiled storyboard NIB and recovers its UI routes",
async () => {
const root = await mkdtemp(join(tmpdir(), "rea-ib-compiled-test-"));
roots.push(root);
const bundle = join(root, "Example.app");
const resources = join(bundle, "Contents", "Resources");
const source = join(
process.cwd(),
"tests",
"fixtures",
"interface-builder",
"MacFixture.storyboard",
);
await mkdir(resources, { recursive: true });
execFileSync("/usr/bin/ibtool", [
"--compile",
join(resources, "MacFixture.storyboardc"),
source,
]);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "d".repeat(64),
});
const names = analysis.graph.nodes.map(({ name }) => name);
expect(names).toContain("BuildViewController");
expect(names).toContain("Button");
expect(names).toContain("buildTapped:");
expect(
analysis.graph.edges.some(
({ relation }) => relation === "target_action",
),
).toBe(true);
const action = analysis.graph.nodes.find(
({ kind, name }) => kind === "action" && name === "buildTapped:",
);
expect(action).toBeDefined();
const actionSource = analysis.graph.edges.find(
({ from, relation, to }) =>
relation === "target_action" &&
to === action?.id &&
analysis.graph.nodes.find(({ id }) => id === from)?.kind ===
"control",
);
expect(actionSource).toBeDefined();
expect(
analysis.graph.edges.some(
({ from, relation, to }) =>
from === action?.id &&
relation === "target_action" &&
to !== null &&
analysis.graph.nodes.find(({ id }) => id === to)?.kind ===
"placeholder",
),
).toBe(true);
expect(
analysis.graph.edges.some(({ relation }) => relation === "contains"),
).toBe(true);
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "archive_decode",
status: "complete",
}),
);
},
);
});
@@ -75,7 +75,12 @@ export const analyzeJavaScriptApplicationValidated = async (
} catch (cause: unknown) {
if (cause instanceof ArtifactReaderFailure)
return err(
new ArtifactOperationError(OPERATION, cause.reason, cause.details),
new ArtifactOperationError(
OPERATION,
cause.reason,
cause.details,
cause.message,
),
);
if (cause instanceof z.ZodError)
return err(
+2 -2
View File
@@ -40,12 +40,12 @@ export class LazyAnalysisProvider implements AnalysisProvider {
this.#loadProvider = options.load;
}
/** Return generated provider identity without loading its implementation. */
/** Return source-declared provider identity without loading its implementation. */
identity(): ProviderIdentity {
return this.#providerIdentity;
}
/** Return generated capability metadata without loading its implementation. */
/** Return source-declared capability metadata without loading its implementation. */
capabilities(): readonly CapabilityDescriptor[] {
return this.#capabilityDescriptors;
}
-177
View File
@@ -1,177 +0,0 @@
import { execFileSync } from "node:child_process";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { decodeNibArchive } from "../artifacts/NibArchive.js";
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
const compileNestedViews = async (depth: number, withWindow = false) => {
const root = await createTestTempDirectory("rea-nib-hierarchy-");
const bundle = join(root, "Fixture.app");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
const source = await readFile(
"tests/conformance/interface-builder/Main.xib",
"utf8",
);
const nested =
Array.from(
{ length: depth },
(_, i) =>
`<view id="nested-${i}" customClass="NSView"><rect key="frame" x="0" y="0" width="100" height="100"/><subviews>`,
).join("") + "</subviews></view>".repeat(depth);
const xib = join(root, "Nested.xib");
let xibSource = source.replace("</subviews>", `${nested}</subviews>`);
if (withWindow)
xibSource = xibSource
.replace(
'<view id="view" customClass="NSView">',
'<window title="Example" id="window"><windowStyleMask key="styleMask" titled="YES" closable="YES"/><rect key="contentRect" x="0" y="0" width="480" height="320"/><view key="contentView" id="view" customClass="NSView">',
)
.replace("</view>\n </objects>", "</view></window>\n </objects>");
await writeFile(xib, xibSource);
const nib = join(resources, "Main.nib");
execFileSync("/usr/bin/xcrun", [
"ibtool",
"--errors",
"--warnings",
"--compile",
nib,
xib,
]);
return { bundle, archive: decodeNibArchive(await readFile(nib)) };
};
describe.skipIf(process.platform !== "darwin")(
"native compiled NIB view hierarchy",
() => {
it.each([4, 40])(
"recovers every serialized superview link for %i nested views",
async (depth) => {
const { bundle, archive } = await compileNestedViews(depth);
const result = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "a".repeat(64),
});
const parents = archive.objects.flatMap(({ id, values }) => {
const parent = values.NSSuperview;
return typeof parent === "object" &&
parent !== null &&
!Array.isArray(parent) &&
typeof parent.$nib_object_ref === "number"
? [{ child: String(id), parent: String(parent.$nib_object_ref) }]
: [];
});
expect(parents).toHaveLength(depth + 1);
for (const pair of parents) {
const child = result.graph.nodes.find(
({ attributes }) =>
attributes.interface_builder_object_id === pair.child,
);
const parent = result.graph.nodes.find(
({ attributes }) =>
attributes.interface_builder_object_id === pair.parent,
);
expect(child).toBeDefined();
expect(parent).toBeDefined();
expect(
result.graph.edges.some(
({ from, to, relation }) =>
from === parent?.id &&
to === child?.id &&
relation === "contains",
),
).toBe(true);
}
expect(result.documents[0]?.hierarchy_complete).toBe(true);
expect(result.graph.truncated).toBe(false);
},
);
it("retains the native window-to-content-view relation alongside superview links", async () => {
const { bundle, archive } = await compileNestedViews(4, true);
const result = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "c".repeat(64),
});
const window = archive.objects.find(
({ class_name }) => class_name === "NSWindowTemplate",
);
const content = window?.values.NSWindowView;
if (
window === undefined ||
typeof content !== "object" ||
content === null ||
Array.isArray(content)
)
throw new Error("native window content link missing");
const windowNode = result.graph.nodes.find(
({ attributes }) =>
attributes.interface_builder_object_id === String(window.id),
);
const viewNode = result.graph.nodes.find(
({ attributes }) =>
attributes.interface_builder_object_id ===
String(content.$nib_object_ref),
);
expect(windowNode).toBeDefined();
expect(viewNode).toBeDefined();
expect(
result.graph.edges.some(
({ from, to, relation }) =>
from === windowNode?.id &&
to === viewNode?.id &&
relation === "contains",
),
).toBe(true);
expect(result.documents[0]?.hierarchy_complete).toBe(true);
expect(result.graph.truncated).toBe(false);
});
it("reports partial coverage for a native hierarchy beyond the projection depth bound", async () => {
const { bundle } = await compileNestedViews(132);
const result = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "d".repeat(64),
});
expect(result.documents[0]?.hierarchy_complete).toBe(false);
expect(result.graph.truncated).toBe(true);
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "hierarchy:Contents/Resources/Main.nib",
status: "partial",
reason: "serialized_view_hierarchy_incomplete",
omitted: expect.any(Number),
}),
);
expect(
result.graph.coverage.find(
({ facet }) => facet === "hierarchy:Contents/Resources/Main.nib",
)?.omitted,
).toBeGreaterThan(0);
});
it.each([false, true])(
"reports partial hierarchy at the object budget (window=%s)",
async (withWindow) => {
const { bundle } = await compileNestedViews(4, withWindow);
const result = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "b".repeat(64),
limits: { max_objects: 2 },
});
expect(result.documents[0]?.hierarchy_complete).toBe(false);
expect(result.graph.truncated).toBe(true);
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "hierarchy:Contents/Resources/Main.nib",
status: "partial",
}),
);
},
);
},
);
@@ -0,0 +1,67 @@
import type { Evidence } from "../../domain/evidence.js";
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
import type {
RecordUnknownInput,
ResidualUnknown,
UnknownStatus,
UpdateUnknownInput,
} from "../../domain/residualUnknown.js";
import type { Result } from "../../domain/result.js";
/** Detached investigation Evidence reads without target execution or lifecycle authority. */
export interface EvidenceReader {
hasEvidence(evidenceId: string): boolean;
evidenceById(evidenceId: string): Evidence | undefined;
exportEvidenceBundle(): EvidenceBundle;
}
/** Idempotent investigation Evidence writes without target execution. */
export interface EvidenceWriter {
recordEvidence(
evidence: Evidence,
): Result<"added" | "duplicate", EvidenceIntegrityError>;
}
/** Atomic derived Evidence and linked Unknown writes. */
export interface EvidenceUnknownWriter {
recordEvidenceWithUnknown(
evidence: Evidence,
input: RecordUnknownInput,
): Result<ResidualUnknown | null, AnalysisError>;
}
/** Optimistic Unknown revisions and consistency verification. */
export interface UnknownRegistryPort {
recordUnknown(
input: RecordUnknownInput,
): Result<ResidualUnknown, AnalysisError>;
updateUnknown(
input: UpdateUnknownInput,
): Result<ResidualUnknown, AnalysisError>;
listUnknowns(filters?: {
readonly status?: UnknownStatus;
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
}): ResidualUnknown[];
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
readonly truthVerified: boolean;
readonly unknown: ResidualUnknown;
},
UnknownRegistryError
>;
}
/** Compatibility record surface; binary execution and snapshots remain separate. */
export interface InvestigationRecordPort
extends
EvidenceReader,
EvidenceWriter,
EvidenceUnknownWriter,
UnknownRegistryPort {
importEvidenceBundle(bundle: unknown): Result<number, EvidenceIntegrityError>;
}
@@ -0,0 +1,145 @@
import { describe, expect, it } from "vitest";
import {
ANALYSIS_SNAPSHOT_TARGET as target,
ANALYSIS_SNAPSHOT_PROVIDER as provider,
} from "../../domain/analysisSnapshot.fixture.js";
import { createEvidence } from "../../domain/evidence.js";
import { createEvidenceBundle } from "../../domain/evidenceBundle.js";
import {
recordUnknownInputSchema,
updateUnknownInputSchema,
} from "../../domain/residualUnknown.js";
import { unknownMutationEvidence } from "../UnknownEvidence.js";
import { InvestigationRecords } from "./InvestigationRecords.js";
const unknownInput = (question: string) =>
recordUnknownInputSchema.parse({
question,
severity: "medium",
domain: "investigation",
required_authority: "analyst-inference",
required_confidence: "derived",
required_environment: null,
recommended_probes: [],
relationships: [],
});
const evidence = createEvidence(undefined, provider, {
operation: "inspect-fixture",
parameters: {},
result: true,
confidence: "derived",
authority: "analyst-inference",
});
describe("investigation record ownership", () => {
it("keeps identity, detached reads and independent stores without a binary target", () => {
const records = new InvestigationRecords();
expect(records.recordEvidence(evidence)).toEqual({
ok: true,
value: "added",
});
expect(records.recordEvidence(evidence)).toEqual({
ok: true,
value: "duplicate",
});
const read = records.evidenceById(evidence.evidence_id);
if (read === undefined) throw new Error("Missing recorded Evidence");
Reflect.set(read, "operation", "forged");
expect(records.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(new InvestigationRecords().hasEvidence(evidence.evidence_id)).toBe(
false,
);
});
it("preserves explicit Unknown subjects and target-free atomic mutation subjects", () => {
const records = new InvestigationRecords();
const input = unknownInput("Which target supplies this observation?");
const bound = records.recordUnknown(input, target);
expect(bound).toMatchObject({
ok: true,
value: {
scope_digest: target.sha256,
mutation_evidence_ids: [
unknownMutationEvidence(target, input).evidence_id,
],
},
});
const independent = records.recordEvidenceWithUnknown(evidence, input);
expect(independent).toMatchObject({
ok: true,
value: {
scope_digest: null,
mutation_evidence_ids: [
unknownMutationEvidence(undefined, input).evidence_id,
],
},
});
const mutation = records.evidenceById(
unknownMutationEvidence(undefined, input).evidence_id,
);
expect(mutation?.subject).toBeNull();
expect(records.listUnknowns()).toHaveLength(2);
});
it("rolls back Evidence when the linked Unknown fails validation", () => {
const records = new InvestigationRecords();
const invalid = {
...unknownInput("Is the missing Evidence present?"),
supporting_evidence_ids: [`ev_${"f".repeat(64)}`],
};
expect(records.recordEvidenceWithUnknown(evidence, invalid).ok).toBe(false);
expect(records.hasEvidence(evidence.evidence_id)).toBe(false);
expect(records.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
});
it("preserves optimistic revisions and the explicit update subject", () => {
const records = new InvestigationRecords();
const created = records.recordUnknown(
unknownInput("Can this revision be updated?"),
target,
);
if (!created.ok) throw created.error;
const input = updateUnknownInputSchema.parse({
...created.value,
expected_revision: created.value.revision,
status: "investigating",
});
const updated = records.updateUnknown(input, target);
expect(updated).toMatchObject({
ok: true,
value: { revision: 2, scope_digest: target.sha256 },
});
const bundle = records.exportEvidenceBundle();
expect(
bundle.records.find(({ operation }) => operation === "update_unknown")
?.subject?.digest.sha256,
).toBe(target.sha256);
expect(records.updateUnknown(input, target).ok).toBe(false);
expect(records.exportEvidenceBundle()).toEqual(bundle);
});
it("reports Unknown-only bundle changes and clears the single record owner", () => {
const source = new InvestigationRecords();
expect(
source.recordUnknown(
unknownInput("Can imported Unknowns notify observers?"),
).ok,
).toBe(true);
const bundle = source.exportEvidenceBundle();
const records = new InvestigationRecords();
expect(
records.mergeEvidenceBundle(createEvidenceBundle(bundle.records)).ok,
).toBe(true);
expect(records.mergeEvidenceBundle(bundle)).toEqual({
ok: true,
value: { recordsAdded: 0, unknownsAdded: 1, changed: true },
});
expect(records.mergeEvidenceBundle(bundle)).toEqual({
ok: true,
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
});
records.clear();
expect(records.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
});
});
@@ -0,0 +1,142 @@
import type { BinaryTarget } from "../../domain/binaryTarget.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
import type {
RecordUnknownInput,
ResidualUnknown,
UnknownStatus,
UpdateUnknownInput,
} from "../../domain/residualUnknown.js";
import type { Result } from "../../domain/result.js";
import { EvidenceLedger, type EvidenceImportDelta } from "../EvidenceLedger.js";
import {
UNKNOWN_REGISTRY_PROVIDER,
unknownEvidenceLinks,
unknownMutationEvidence,
} from "../UnknownEvidence.js";
import type {
EvidenceReader,
EvidenceWriter,
EvidenceUnknownWriter,
UnknownRegistryPort,
} from "./InvestigationRecordPort.js";
/** One investigation's validated record owner, independent of binary execution. */
export class InvestigationRecords
implements
EvidenceReader,
EvidenceWriter,
EvidenceUnknownWriter,
UnknownRegistryPort
{
readonly #evidence = new EvidenceLedger();
/** Record immutable Evidence idempotently; reject conflicting content. */
recordEvidence(
evidence: Evidence,
): Result<"added" | "duplicate", EvidenceIntegrityError> {
return this.#evidence.record(evidence);
}
/** Check one semantic Evidence ID without exposing stored values. */
hasEvidence(evidenceId: string): boolean {
return this.#evidence.has(evidenceId);
}
/** Return a detached Evidence value for one semantic ID. */
evidenceById(evidenceId: string): Evidence | undefined {
return this.#evidence.get(evidenceId);
}
/** Export a detached deterministic bundle of Evidence and Unknown revisions. */
exportEvidenceBundle(): EvidenceBundle {
return this.#evidence.export();
}
/** Atomically merge a bundle and report changes for the owner's post-commit observers. */
mergeEvidenceBundle(
bundle: unknown,
): Result<EvidenceImportDelta, EvidenceIntegrityError> {
return this.#evidence.import(bundle);
}
/** Clear records when the owning runtime applies its existing lifecycle policy. */
clear(): void {
this.#evidence.clear();
}
/** Record an Unknown with an explicitly supplied Evidence subject, if any. */
recordUnknown(
input: RecordUnknownInput,
target?: BinaryTarget,
): Result<ResidualUnknown, AnalysisError> {
const recorded = this.#evidence.recordUnknown(
input,
unknownMutationEvidence(target, input),
);
return recorded;
}
/** Commit derived Evidence and its Unknown atomically without an implicit subject. */
recordEvidenceWithUnknown(
evidence: Evidence,
input: RecordUnknownInput,
): Result<ResidualUnknown | null, AnalysisError> {
const recorded = this.#evidence.recordWithUnknown(
evidence,
input,
unknownMutationEvidence(undefined, input),
);
return recorded;
}
/** Update an optimistic revision with an explicitly supplied Evidence subject. */
updateUnknown(
input: UpdateUnknownInput,
target?: BinaryTarget,
): Result<ResidualUnknown, AnalysisError> {
const evidence = createEvidence(target, UNKNOWN_REGISTRY_PROVIDER, {
predicateType: "rea.residual-unknown-mutation",
operation: "update_unknown",
parameters: {
unknown_id: input.unknown_id,
expected_revision: input.expected_revision,
},
result: { action: "update", status: input.status },
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: unknownEvidenceLinks(input),
limitations: [
"Registry mutation evidence records analyst intent, not proof of the answer.",
],
});
const updated = this.#evidence.updateUnknown(input, evidence);
return updated;
}
/** Return detached current Unknown revisions matching the selected filters. */
listUnknowns(
filters: {
readonly status?: UnknownStatus;
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
} = {},
): ResidualUnknown[] {
return this.#evidence.listUnknowns(filters);
}
/** Verify registry consistency without asserting the answer is true. */
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
readonly truthVerified: boolean;
readonly unknown: ResidualUnknown;
},
UnknownRegistryError
> {
return this.#evidence.verifyUnknownResolution(unknownId);
}
}
+4 -38
View File
@@ -4,10 +4,9 @@ import { HopperProvider } from "../hopper/HopperProvider.js";
import { GhidraProvider } from "../ghidra/GhidraProvider.js";
import { IdaProvider } from "../ida/IdaProvider.js";
import { silentLogger, type Logger } from "../logger.js";
import { GENERATED_AUXILIARY_PROVIDERS } from "../generatedMcpToolCatalog.js";
import { auxiliaryAnalysisProviderDeclarations } from "../composition/auxiliaryAnalysisProviders.js";
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
import { composeBinarySession } from "./BinarySessionComposition.js";
import { nativeHostCapabilities } from "../native/NativeHostCapabilities.js";
import { LazyAnalysisProvider } from "./LazyAnalysisProvider.js";
import { ManagedStaticProvider } from "../dotnet/ManagedStaticProvider.js";
import { SessionProviderRouter } from "./SessionProviderRouter.js";
@@ -24,47 +23,14 @@ export const createBinarySession = (
const hopper = new HopperProvider(config, logger);
const ghidra = new GhidraProvider(config, logger);
const ida = new IdaProvider(config);
const auxiliary = new Map(
GENERATED_AUXILIARY_PROVIDERS.map((provider) => [
provider.identity.id,
provider,
]),
);
const lazyProvider = (
id: string,
load: ConstructorParameters<typeof LazyAnalysisProvider>[0]["load"],
) => {
const generated = auxiliary.get(id);
if (generated === undefined)
throw new TypeError(`Missing generated provider metadata for ${id}`);
return new LazyAnalysisProvider({
...generated,
capabilities: nativeHostCapabilities(generated.capabilities),
load,
});
};
return composeBinarySession(
new AnalysisProviderRegistry(
[hopper, ghidra, ida],
config.analysisProvider,
),
[
lazyProvider("rea-artifact-graph", async () => {
const { ArtifactProvider } =
await import("../artifacts/ArtifactProvider.js");
return new ArtifactProvider();
}),
lazyProvider("native-macos", async () => {
const { NativeMacOSProvider } =
await import("../native/NativeMacOSProvider.js");
return new NativeMacOSProvider();
}),
lazyProvider("rea-dotnet-static", async () => {
const { ManagedStaticProvider } =
await import("../dotnet/ManagedStaticProvider.js");
return new ManagedStaticProvider();
}),
],
auxiliaryAnalysisProviderDeclarations().map(
(declaration) => new LazyAnalysisProvider(declaration),
),
);
};
+6 -3
View File
@@ -14,7 +14,7 @@ export const normalizeArtifactPath = (input: string): string => {
)
throw new ArtifactReaderFailure(
"path",
"Artifact path is absolute or unsafe",
`Artifact path is absolute or unsafe: ${JSON.stringify(input)}`,
);
const normalized = input.normalize("NFC").replace(/\/+$/u, "");
const parts = normalized.split("/");
@@ -23,7 +23,10 @@ export const normalizeArtifactPath = (input: string): string => {
parts.some((part) => part === "" || part === "." || part === "..") ||
posix.normalize(normalized) !== normalized
)
throw new ArtifactReaderFailure("path", "Artifact path is not normalized");
throw new ArtifactReaderFailure(
"path",
`Artifact path is not normalized: ${JSON.stringify(input)}`,
);
return normalized;
};
@@ -45,7 +48,7 @@ export class ArtifactPathRegistry {
if (child !== undefined && child.spelling !== part)
throw new ArtifactReaderFailure(
"path",
`Artifact path collision: ${path}`,
`Artifact path collision: ${path} differs only in case from ${[...parts.slice(0, index), child.spelling].join("/")}`,
);
if (child === undefined) {
child = { spelling: part, kind: undefined, children: new Map() };
+11 -40
View File
@@ -27,54 +27,20 @@ import type { JsonValue } from "../domain/jsonValue.js";
import { interfaceBuilderLimitsSchema } from "../domain/interfaceBuilderGraph.js";
import { err, ok } from "../domain/result.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
import {
ARTIFACT_PROVIDER_IDENTITY as IDENTITY,
artifactCapabilities,
} from "./ArtifactProviderMetadata.js";
import { createEvidence } from "../domain/evidence.js";
import { createArtifactInspection } from "../domain/artifactInspection.js";
import { resolveArtifactIntegrityPolicy } from "../application/ArtifactInventory/policy.js";
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(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" ||
operation === "inspect_artifact" ||
operation === "inventory_artifact",
changesPermissions: false,
requiresRoot: false,
}),
limitations: Object.freeze([
"DMG child inventory automatically uses a read-only native macOS mount; 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 },
);
}),
);
this.#capabilities = artifactCapabilities(platform);
}
identity(): ProviderIdentity {
@@ -343,7 +309,12 @@ const translateFailure = (
cause: unknown,
): AnalysisError => {
if (cause instanceof ArtifactReaderFailure)
return new ArtifactOperationError(operation, cause.reason, cause.details);
return new ArtifactOperationError(
operation,
cause.reason,
cause.details,
cause.message,
);
return new ArtifactOperationError(operation, "io");
};
+53
View File
@@ -0,0 +1,53 @@
import type {
CapabilityDescriptor,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
import { ARTIFACT_ANALYSIS_OPERATIONS } from "../contracts/artifactToolContracts.js";
/** Identity of artifact inventory and owned extraction observations. */
export const ARTIFACT_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze(
ARTIFACT_GRAPH_PROVIDER,
);
const IDENTITY = ARTIFACT_PROVIDER_IDENTITY;
/** Declare artifact coverage without constructing readers or acquiring resources. */
export const artifactCapabilities = (
platform: NodeJS.Platform = process.platform,
): readonly CapabilityDescriptor[] =>
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" ||
operation === "inspect_artifact" ||
operation === "inventory_artifact",
changesPermissions: false,
requiresRoot: false,
}),
limitations: Object.freeze([
"DMG child inventory automatically uses a read-only native macOS mount; 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 },
);
}),
);
+6 -21
View File
@@ -3,6 +3,7 @@ import { TextDecoder } from "node:util";
import { parse, parseBinary } from "plist";
import { z } from "zod";
import type { JsonValue } from "../domain/jsonValue.js";
import { projectPlistValue } from "../domain/plistValue.js";
import {
keyedArchiveInputSchema,
keyedArchiveResultSchema,
@@ -50,27 +51,11 @@ const decodeXmlPlistText = (bytes: Buffer): string => {
return text;
};
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);
const normalizePlist = (value: unknown): JsonValue => {
const projected = projectPlistValue(value);
if (projected.unknownRealCount > 0)
throw new RangeError("Keyed archive contains a non-finite real");
return projected.value;
};
/** Read exactly one regular, contained bundle entry without following symlinks. */
@@ -0,0 +1,50 @@
import type { LazyAnalysisProvider } from "../application/LazyAnalysisProvider.js";
import {
ARTIFACT_PROVIDER_IDENTITY,
artifactCapabilities,
} from "../artifacts/ArtifactProviderMetadata.js";
import {
MANAGED_STATIC_PROVIDER_IDENTITY,
managedStaticCapabilities,
} from "../dotnet/ManagedStaticProviderMetadata.js";
import {
NATIVE_MACOS_PROVIDER_IDENTITY,
nativeMacOSCapabilities,
} from "../native/NativeMacOSProviderMetadata.js";
type AuxiliaryProviderDeclaration = ConstructorParameters<
typeof LazyAnalysisProvider
>[0];
/** Wire the three existing auxiliary AnalysisProvider implementations lazily. */
export const auxiliaryAnalysisProviderDeclarations = (
platform: NodeJS.Platform = process.platform,
): readonly AuxiliaryProviderDeclaration[] => [
{
identity: ARTIFACT_PROVIDER_IDENTITY,
capabilities: artifactCapabilities(platform),
load: async () => {
const { ArtifactProvider } =
await import("../artifacts/ArtifactProvider.js");
return new ArtifactProvider(platform);
},
},
{
identity: NATIVE_MACOS_PROVIDER_IDENTITY,
capabilities: nativeMacOSCapabilities(platform),
load: async () => {
const { NativeMacOSProvider } =
await import("../native/NativeMacOSProvider.js");
return new NativeMacOSProvider(undefined, platform);
},
},
{
identity: MANAGED_STATIC_PROVIDER_IDENTITY,
capabilities: managedStaticCapabilities(),
load: async () => {
const { ManagedStaticProvider } =
await import("../dotnet/ManagedStaticProvider.js");
return new ManagedStaticProvider();
},
},
];
+2 -2
View File
@@ -13,7 +13,7 @@ export const FIRMWARE_TOOL_CONTRACTS = [
...toolContractMetadata("inspect_firmware_regions"),
kind: "firmware-provider",
description:
"Inspect signature candidates in a local firmware file with Binwalk 3.1.0. Returns offsets, reported lengths, descriptions and raw confidence values. Length validation and runtime addresses remain unknown. No extraction or target execution. Linux, caller-supplied tool and util-linux prlimit required; 128 MiB input limit, one worker and 120-second deadline.",
"Inspect signature candidates in a local firmware file with Binwalk 3.1.x (verified with 3.1.0). Returns offsets, reported lengths, descriptions and raw confidence values. Length validation and runtime addresses remain unknown. No extraction or target execution. Linux, caller-supplied tool and util-linux prlimit required; 128 MiB input limit, one worker and 120-second deadline.",
inputSchema: firmwareInputSchemas.inspect_firmware_regions,
outputSchema: evidenceResultOf(
firmwareResultSchemas.inspect_firmware_regions,
@@ -30,7 +30,7 @@ export const FIRMWARE_TOOL_CONTRACTS = [
...toolContractMetadata("extract_firmware"),
kind: "firmware-provider",
description:
"Extract caller-selected firmware bytes with Unblob 26.6.4 into an absent output directory. Returns verified child paths/digests, task derivations, unknown chunks and extraction diagnostics inline. Preserves the default sandbox; publishes regular files only. Linux, caller-supplied tool, format-specific extractors and util-linux prlimit required. No mounts or extracted-code execution. Select a returned native file with open_binary for Ghidra analysis; decompressed offsets are not original-file addresses.",
"Extract caller-selected firmware bytes with Unblob 26.6.x (verified with 26.6.4) into an absent output directory. Returns verified child paths/digests, task derivations, unknown chunks and extraction diagnostics inline. Preserves the default sandbox; publishes regular files only. Linux, caller-supplied tool, format-specific extractors and util-linux prlimit required. No mounts or extracted-code execution. Select a returned native file with open_binary for Ghidra analysis; decompressed offsets are not original-file addresses.",
inputSchema: firmwareInputSchemas.extract_firmware,
outputSchema: evidenceResultOf(firmwareResultSchemas.extract_firmware),
examples: [
+1
View File
@@ -216,6 +216,7 @@ const artifactStateErrorDetails = (
operation: error.operation,
reason: error.reason,
...(error.reason === "limit" ? { truncated: true } : {}),
...(error.detail === undefined ? {} : { detail: error.detail }),
};
if (error instanceof UnknownRegistryError) return { reason: error.reason };
if (error instanceof EvidenceFileError)
+2
View File
@@ -28,6 +28,8 @@ export class ArtifactOperationError extends AnalysisError {
calculatedSha256: string | null;
unpacked: boolean;
}>,
/** The specific constraint that failed, such as the colliding path. */
readonly detail?: string,
) {
super(
artifactDetails === undefined
+40
View File
@@ -0,0 +1,40 @@
import { expect, it } from "vitest";
import { projectPlistValue } from "./plistValue.js";
it("projects plist data, dates, and non-finite reals as typed values", () => {
expect(
projectPlistValue({
blob: new Uint8Array([0, 1, 2]),
when: new Date("2020-01-01T00:00:00Z"),
nested: [{ ratio: 0.5, missing: Number.NaN, unbounded: -Infinity }],
plain: { "": "empty key", flag: true, count: 42 },
}),
).toEqual({
value: {
blob: { $plist_type: "data", base64: "AAEC" },
when: { $plist_type: "date", iso8601: "2020-01-01T00:00:00.000Z" },
nested: [
{
ratio: 0.5,
missing: { $plist_type: "real", value: null },
unbounded: { $plist_type: "real", value: null },
},
],
plain: { "": "empty key", flag: true, count: 42 },
},
unknownRealCount: 2,
});
});
it("rejects values a plist decoder cannot produce", () => {
expect(() => projectPlistValue({ value: Symbol("x") })).toThrow();
const deep: unknown[] = [];
let cursor = deep;
for (let depth = 0; depth < 200; depth += 1) {
const next: unknown[] = [];
cursor.push(next);
cursor = next;
}
expect(() => projectPlistValue(deep)).toThrow(RangeError);
});
+50
View File
@@ -0,0 +1,50 @@
import { z } from "zod";
import type { JsonValue } from "./jsonValue.js";
const MAX_PLIST_DEPTH = 128;
/** A decoded plist projected into JSON, with values JSON cannot express. */
export interface ProjectedPlistValue {
readonly value: JsonValue;
/** Reals decoded as NaN, which the decoder also uses for ±infinity. */
readonly unknownRealCount: number;
}
/**
* Project a decoded plist into JSON. Data and dates become explicit
* `$plist_type` objects; a non-finite real becomes an explicit unknown
* because the XML decoder reports NaN and ±infinity alike.
*/
export const projectPlistValue = (value: unknown): ProjectedPlistValue => {
let unknownRealCount = 0;
const project = (item: unknown, depth: number): JsonValue => {
if (depth > MAX_PLIST_DEPTH)
throw new RangeError(
`Plist exceeds ${String(MAX_PLIST_DEPTH)} nesting levels`,
);
if (item instanceof Uint8Array)
return {
$plist_type: "data",
base64: Buffer.from(item).toString("base64"),
};
if (item instanceof Date)
return { $plist_type: "date", iso8601: item.toISOString() };
if (typeof item === "number" && !Number.isFinite(item)) {
unknownRealCount += 1;
return { $plist_type: "real", value: null };
}
if (Array.isArray(item))
return item.map((entry: unknown) => project(entry, depth + 1));
if (item !== null && typeof item === "object")
return Object.fromEntries(
Object.entries(item).map(([key, entry]) => [
key,
project(entry, depth + 1),
]),
);
return z.union([z.string(), z.number(), z.boolean(), z.null()]).parse(item);
};
const projected = project(value, 0);
return { value: projected, unknownRealCount };
};
+1 -36
View File
@@ -4,43 +4,8 @@ import {
parseArtifactInventoryEvidence,
tryAssembleInventorySet,
} from "./artifactInventoryEvidence.js";
import { EvidenceReferenceError } from "./evidenceErrors.js";
import type { ReferenceSourceReaderError } from "../reference/ReferenceSourceReaderTypes.js";
/**
* The three validation taxonomies and their disjoint codes:
* - Filesystem reader: cancelled | invalid-root | io | unsupported
* (per-entry: cancelled | changed | io | symlink | unsupported).
* - Session evidence references: missing | wrong_operation |
* wrong_predicate | identity_mismatch.
* - Inventory assembly: TypeError strings, migrating to Result leaves
* starting with the empty-pages code below.
*/
const readerCodes: readonly ReferenceSourceReaderError["code"][] = [
"cancelled",
"invalid-root",
"io",
"unsupported",
];
const referenceReasons = (
[
"missing",
"wrong_operation",
"wrong_predicate",
"identity_mismatch",
] as const
).map(
(reason) =>
new EvidenceReferenceError("ev_test", reason, "expected", null).reason,
);
describe("validation taxonomy mapping", () => {
it("keeps session reference reasons disjoint from reader codes", () => {
for (const reason of referenceReasons)
expect(readerCodes).not.toContain(reason);
});
describe("inventory validation failure channels", () => {
it("returns the empty-pages leaf as Result without throwing", () => {
const result = tryAssembleInventorySet([]);
expect(result).toEqual({
+6 -41
View File
@@ -11,7 +11,10 @@ import {
type ExecutionOptions,
type ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { MANAGED_STATIC_PROVIDER } from "../application/InvestigationProviders.js";
import {
MANAGED_STATIC_PROVIDER_IDENTITY as IDENTITY,
managedStaticCapabilities,
} from "./ManagedStaticProviderMetadata.js";
import {
MANAGED_TOOL_CONTRACTS,
managedArtifactInputSchema,
@@ -38,30 +41,10 @@ import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import { inspectManagedNativeBoundariesBytes } from "./ManagedNativeBoundaryInspector.js";
const IDENTITY: ProviderIdentity = Object.freeze(MANAGED_STATIC_PROVIDER);
/** Execution-free managed PE/CLI auxiliary provider. */
export class ManagedStaticProvider implements AnalysisProvider {
readonly #capabilities: readonly CapabilityDescriptor[] = Object.freeze(
MANAGED_TOOL_CONTRACTS.map((contract) =>
Object.freeze({
provider: IDENTITY,
operation: contract.name,
available: true as const,
reason: null,
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
}),
limitations: limitationsFor(contract.name),
}),
),
);
readonly #capabilities: readonly CapabilityDescriptor[] =
managedStaticCapabilities();
identity(): ProviderIdentity {
return IDENTITY;
@@ -196,24 +179,6 @@ const isManagedOperation = (
): operation is ManagedToolName =>
MANAGED_TOOL_CONTRACTS.some(({ name }) => name === operation);
const limitationsFor = (operation: ManagedToolName): readonly string[] =>
Object.freeze(
operation === "inspect_managed_artifact"
? [
"This capability inventories PE/CLI identity only; inspect_managed_members admits metadata members, signatures, and CIL anchors.",
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
]
: operation === "inspect_managed_native_boundaries"
? [
"This capability inventories managed declarations for native boundaries only; native exports, thunks, and addresses require separate native-provider evidence.",
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
]
: [
"This capability decodes PE/CLI metadata members, signatures, and file-backed method bodies; decompiled C# reconstruction and cross-build member comparison are separate operations.",
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
],
);
const inspectManagedOperation = (
operation: ManagedToolName,
parameters: Readonly<Record<string, JsonValue>>,
@@ -0,0 +1,56 @@
import type {
CapabilityDescriptor,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { MANAGED_STATIC_PROVIDER } from "../application/InvestigationProviders.js";
import {
MANAGED_TOOL_CONTRACTS,
type ManagedToolName,
} from "../contracts/managedToolContracts.js";
/** Identity of execution-free managed metadata observations. */
export const MANAGED_STATIC_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze(
MANAGED_STATIC_PROVIDER,
);
const IDENTITY = MANAGED_STATIC_PROVIDER_IDENTITY;
/** Declare managed metadata coverage without opening or loading an assembly. */
export const managedStaticCapabilities = (): readonly CapabilityDescriptor[] =>
Object.freeze(
MANAGED_TOOL_CONTRACTS.map((contract) =>
Object.freeze({
provider: IDENTITY,
operation: contract.name,
available: true as const,
reason: null,
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
}),
limitations: limitationsFor(contract.name),
}),
),
);
const limitationsFor = (operation: ManagedToolName): readonly string[] =>
Object.freeze(
operation === "inspect_managed_artifact"
? [
"This capability inventories PE/CLI identity only; inspect_managed_members admits metadata members, signatures, and CIL anchors.",
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
]
: operation === "inspect_managed_native_boundaries"
? [
"This capability inventories managed declarations for native boundaries only; native exports, thunks, and addresses require separate native-provider evidence.",
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
]
: [
"This capability decodes PE/CLI metadata members, signatures, and file-backed method bodies; decompiled C# reconstruction and cross-build member comparison are separate operations.",
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
],
);
+22 -14
View File
@@ -24,10 +24,10 @@ import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { publishFirmwareExtraction } from "./FirmwarePublication.js";
import {
FIRMWARE_LIMITS,
FIRMWARE_RELEASES,
BINWALK_PROVIDER_IDENTITY,
UNBLOB_PROVIDER_IDENTITY,
} from "./FirmwareRelease.js";
import { admitFirmwareVersion } from "./FirmwareVersion.js";
import {
resolveFirmwareCommand,
runFirmwareCommand,
@@ -143,21 +143,22 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
});
const versionRun = await run(["--version"]);
const version = versionRun.stdout.text.trim();
const expected = FIRMWARE_RELEASES[engineName].version;
if (
versionRun.stdout.bytes > 1024 ||
(engineName === "binwalk"
? version !== `binwalk ${expected}`
: version !== expected)
)
if (versionRun.stdout.bytes > 1024)
throw new AnalysisCapabilityUnavailableError(
engineName,
request.operation,
`Unsupported tool version ${version}; this adapter is verified against ${expected}`,
`Tool version banner is ${String(versionRun.stdout.bytes)} bytes; expected a short ${engineName} version line.`,
);
const admitted = admitFirmwareVersion(engineName, version);
if (admitted.status === "unsupported" || admitted.status === "unresolved")
throw new AnalysisCapabilityUnavailableError(
engineName,
request.operation,
admitted.message,
);
const engine = {
name: engineName,
version: expected,
version: admitted.version,
executable_path: command.command,
executable_sha256: command.sha256,
source_revision: null,
@@ -259,16 +260,23 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
});
raw = { report, execution: processRun, version_execution: versionRun };
}
const catalog =
engineName === "binwalk"
? BINWALK_PROVIDER_IDENTITY
: UNBLOB_PROVIDER_IDENTITY;
outcome = ok(
createAnalysisExecution(
result,
engineName === "binwalk"
? BINWALK_PROVIDER_IDENTITY
: UNBLOB_PROVIDER_IDENTITY,
{ ...catalog, version: admitted.version },
{
subject: target.subject,
rawResult: raw,
limitations,
limitations: [
...limitations,
...(admitted.status === "compatible"
? [admitted.limitation]
: []),
],
locations: [
{
kind: "file-offset-range",
+1 -1
View File
@@ -12,7 +12,7 @@ export const FIRMWARE_RELEASES = {
},
} as const;
/** Catalog identities; Evidence uses the version observed from the executed tool. */
/** Catalog identity for the verified Binwalk release. Evidence replaces version with the observed banner. */
export const BINWALK_PROVIDER_IDENTITY = {
id: "binwalk",
name: "Binwalk",
+50
View File
@@ -0,0 +1,50 @@
import { describe, expect, it } from "vitest";
import { admitFirmwareVersion } from "./FirmwareVersion.js";
describe("firmware release lines", () => {
it("accepts the verified banners without an extra limitation", () => {
expect(admitFirmwareVersion("binwalk", "binwalk 3.1.0")).toEqual({
status: "verified",
version: "3.1.0",
});
expect(admitFirmwareVersion("unblob", "26.6.4")).toEqual({
status: "verified",
version: "26.6.4",
});
});
it.each([
["binwalk", "binwalk 3.1.2", "3.1.2"],
["binwalk", "binwalk 3.1.0-1", "3.1.0-1"],
["unblob", "26.6.5", "26.6.5"],
] as const)(
"accepts %s %s on the verified line",
(engine, banner, version) => {
const admitted = admitFirmwareVersion(engine, banner);
expect(admitted).toMatchObject({ status: "compatible", version });
if (admitted.status !== "compatible")
throw new Error("expected a compatible release");
expect(admitted.limitation).toContain(version);
expect(admitted.limitation).toContain(
engine === "binwalk" ? "3.1.0" : "26.6.4",
);
},
);
it.each([
["binwalk", "binwalk 3.2.0", "Binwalk 3.1.x"],
["binwalk", "unsupported", "Binwalk 3.1.x"],
["binwalk", "3.1.2", "Binwalk 3.1.x"],
["unblob", "26.7.0", "Unblob 26.6.x"],
["unblob", "unblob 26.6.4", "Unblob 26.6.x"],
["unblob", "", "missing"],
] as const)("rejects %s banner %j", (engine, banner, detail) => {
const admitted = admitFirmwareVersion(engine, banner);
expect(
admitted.status === "verified" || admitted.status === "compatible",
).toBe(false);
if (admitted.status === "verified" || admitted.status === "compatible")
throw new Error("expected a rejected banner");
expect(admitted.message).toContain(detail);
});
});
+116
View File
@@ -0,0 +1,116 @@
import { FIRMWARE_RELEASES } from "./FirmwareRelease.js";
/** Caller-supplied firmware engine selected by the operation. */
export type FirmwareEngineName = keyof typeof FIRMWARE_RELEASES;
interface ReleaseNumber {
readonly major: number;
readonly minor: number;
readonly patch: number;
readonly suffix: string;
readonly token: string;
}
const TOKEN = /^(\d+)\.(\d+)\.(\d+)([-+][0-9A-Za-z.-]+)?$/u;
const parseToken = (token: string): ReleaseNumber | undefined => {
const match = TOKEN.exec(token);
if (match === null) return undefined;
const major = Number(match[1]);
const minor = Number(match[2]);
const patch = Number(match[3]);
if (![major, minor, patch].every((part) => Number.isSafeInteger(part)))
return undefined;
const suffix = match[4] ?? "";
return { major, minor, patch, suffix, token };
};
const verifiedRelease = (engine: FirmwareEngineName): ReleaseNumber => {
const parsed = parseToken(FIRMWARE_RELEASES[engine].version);
if (parsed === undefined || parsed.suffix !== "")
throw new Error(
`FIRMWARE_RELEASES.${engine}.version is not a release number`,
);
return parsed;
};
/** Caller-facing engine name. */
export const firmwareEngineLabel = (engine: FirmwareEngineName): string => {
switch (engine) {
case "binwalk":
return "Binwalk";
case "unblob":
return "Unblob";
default: {
const unreachable: never = engine;
return unreachable;
}
}
};
/** Release line accepted for one engine, such as `Binwalk 3.1.x`. */
export const firmwareReleaseLine = (engine: FirmwareEngineName): string => {
const verified = verifiedRelease(engine);
return `${firmwareEngineLabel(engine)} ${String(verified.major)}.${String(verified.minor)}.x`;
};
/** Admission of one observed `--version` banner. */
export type FirmwareVersionAdmission =
| { readonly status: "verified"; readonly version: string }
| {
readonly status: "compatible";
readonly version: string;
readonly limitation: string;
}
| { readonly status: "unsupported"; readonly message: string }
| { readonly status: "unresolved"; readonly message: string };
/**
* Classify a `--version` banner against the audited release line.
* Binwalk prints `binwalk <version>`; Unblob prints the version alone.
*/
export const admitFirmwareVersion = (
engine: FirmwareEngineName,
banner: string,
): FirmwareVersionAdmission => {
const token = versionToken(engine, banner);
const parsed = token === undefined ? undefined : parseToken(token);
const verified = verifiedRelease(engine);
const accepted = `accepted releases are ${firmwareReleaseLine(engine)} (verified with ${verified.token})`;
if (parsed === undefined)
return {
status: "unresolved",
message: `Unsupported tool version ${banner.length === 0 ? "missing" : banner}; ${accepted}.`,
};
if (parsed.major !== verified.major || parsed.minor !== verified.minor)
return {
status: "unsupported",
message: `Unsupported tool version ${banner}; ${accepted}.`,
};
if (parsed.token === verified.token)
return { status: "verified", version: parsed.token };
const line = `${String(verified.major)}.${String(verified.minor)}.x`;
return {
status: "compatible",
version: parsed.token,
limitation: `This session uses ${firmwareEngineLabel(engine)} ${parsed.token}. The report parser is verified against ${verified.token}; other ${line} builds are accepted and the observed version is reported.`,
};
};
const versionToken = (
engine: FirmwareEngineName,
banner: string,
): string | undefined => {
switch (engine) {
case "binwalk":
return banner.startsWith("binwalk ")
? banner.slice("binwalk ".length)
: undefined;
case "unblob":
return banner;
default: {
const unreachable: never = engine;
return unreachable;
}
}
};
File diff suppressed because one or more lines are too long
+116 -1
View File
@@ -60,7 +60,7 @@ describe("Ghidra installation inspection", () => {
});
});
it("accepts only the exact Linux x64 Ghidra and JDK commitment", () => {
it("accepts the verified Linux x64 Ghidra release and JDK", () => {
expect(
inspectGhidraInstallation(
{ installDir: INSTALL, platform: "linux", architecture: "x64" },
@@ -74,6 +74,40 @@ describe("Ghidra installation inspection", () => {
});
});
it.each([
["12.1.2", "27", 27],
["12.1.2-2.1", "27", 27],
["12.1.0", "21.0.2", 21],
[SUPPORTED_GHIDRA_VERSION, "25.0.1", 25],
])(
"accepts Ghidra %s with JDK %s on the verified release line",
(providerVersion, javaVersion, major) => {
const result = inspectGhidraInstallation(
{ installDir: INSTALL, platform: "linux", architecture: "x64" },
host({
readText: () =>
`application.version=${providerVersion}\napplication.java.min=21\napplication.java.max=\n`,
probeJava: () => ({
...JAVA,
version: javaVersion,
major,
}),
}),
);
expect(result.status).toBe("available");
expect(result).toMatchObject({ providerVersion, javaVersion });
expect(
result.checks.find(({ name }) => name === "version"),
).toMatchObject({
status: "passed",
detail:
providerVersion === SUPPORTED_GHIDRA_VERSION
? SUPPORTED_GHIDRA_VERSION
: expect.stringContaining("verified build"),
});
},
);
it.each(["x64", "arm64"] as const)(
"accepts macOS %s with matching native tools",
(architecture) => {
@@ -247,3 +281,84 @@ describe("Ghidra installation rejection diagnostics", () => {
});
});
});
describe("Ghidra release line and JDK bounds", () => {
it.each([
{
name: "JDK above the installation maximum",
readText: () =>
"application.version=12.1.4\napplication.java.min=21\napplication.java.max=25\n",
probeJava: () => ({ ...JAVA, major: 27, version: "27" }),
failed: "java",
code: "unsupported_version",
},
{
name: "unreadable Java minimum",
readText: () =>
"application.version=12.1.4\napplication.java.min=latest\n",
probeJava: () => JAVA,
failed: "java",
code: "version_unresolved",
},
{
name: "unparseable Ghidra version",
readText: () => "application.version=latest\n",
probeJava: () => JAVA,
failed: "version",
code: "version_unresolved",
},
{
name: "different Ghidra line",
readText: () => "application.version=12.2.0\n",
probeJava: () => JAVA,
failed: "version",
code: "unsupported_version",
},
])("distinguishes $name", ({ readText, probeJava, failed, code }) => {
const result = inspectGhidraInstallation(
{ installDir: INSTALL, platform: "linux", architecture: "x64" },
host({ readText, probeJava }),
);
expect(result.status).toBe("unavailable");
expect(
result.checks.find(({ status }) => status === "failed"),
).toMatchObject({ name: failed, code });
});
it("names the accepted Ghidra line and JDK range in failure remediation", () => {
const result = inspectGhidraInstallation(
{
installDir: INSTALL,
javaHome: "/usr/lib/jvm/java-17-openjdk",
platform: "linux",
architecture: "x64",
},
host({
readText: () =>
"application.version=12.0.4\napplication.java.min=21\napplication.java.max=\n",
probeJava: () => ({ ...JAVA, major: 17, version: "17.0.20.1" }),
}),
);
expect(result.status).toBe("unavailable");
if (result.status !== "unavailable") return;
expect(result.rejection.reason).toContain("12.1.x");
expect(result.rejection.reason).toContain(SUPPORTED_GHIDRA_VERSION);
expect(result.checks.find(({ name }) => name === "java")).toMatchObject({
status: "failed",
remediation: expect.stringContaining("JDK 21 or newer"),
});
});
it("honors an installation that declares a lower Java minimum", () => {
expect(
inspectGhidraInstallation(
{ installDir: INSTALL, platform: "linux", architecture: "x64" },
host({
readText: () =>
`application.version=${SUPPORTED_GHIDRA_VERSION}\napplication.java.min=17\n`,
probeJava: () => ({ ...JAVA, major: 17, version: "17.0.20.1" }),
}),
),
).toMatchObject({ status: "available", javaVersion: "17.0.20.1" });
});
});
+66 -37
View File
@@ -5,11 +5,22 @@ import { posix, win32 } from "node:path";
import type { ProviderRejectionCode } from "../contracts/providerSelection.js";
import type { JsonValue } from "../domain/jsonValue.js";
import {
ghidraApplicationProperties,
ghidraJavaMajorAccepted,
ghidraJavaRangeLabel,
ghidraJavaRequirement,
ghidraReleaseAccepted,
ghidraReleaseCompatibility,
ghidraReleaseLine,
ghidraVersionDetail,
SUPPORTED_GHIDRA_JAVA_MAJOR,
SUPPORTED_GHIDRA_VERSION,
type GhidraApplicationProperties,
type GhidraJavaRequirement,
} from "./GhidraInstallationPolicy.js";
/** Exact Ghidra build whose Java bridge contract this REA release supports. */
export const SUPPORTED_GHIDRA_VERSION = "12.1.4";
/** Exact JDK major documented by the supported Ghidra release. */
export const SUPPORTED_GHIDRA_JAVA_MAJOR = 21;
export { SUPPORTED_GHIDRA_JAVA_MAJOR, SUPPORTED_GHIDRA_VERSION };
/** Caller-owned paths and host coordinates used for one installation probe. */
export interface GhidraInstallationOptions {
@@ -110,7 +121,7 @@ interface GhidraInstallationCoordinates {
readonly applicationPropertiesPath: string | null;
readonly analyzeHeadlessPath: string | null;
readonly nativeDecompilerPath: string | null;
readonly properties: Readonly<{ providerVersion: string | null }> | undefined;
readonly properties: GhidraApplicationProperties | undefined;
readonly javaCommand: string;
readonly java: GhidraJavaObservation | undefined;
}
@@ -269,7 +280,7 @@ const installationCoordinates = (
properties:
properties === undefined
? undefined
: { providerVersion: propertyValue(properties, "application.version") },
: ghidraApplicationProperties(properties),
javaCommand,
java: host.probeJava(
javaCommand,
@@ -290,8 +301,7 @@ const installationChecks = ({
passed: coordinates.installDir !== null,
code: "not_configured",
detail: coordinates.installDir ?? "GHIDRA_INSTALL_DIR is not set",
remediation:
"Set GHIDRA_INSTALL_DIR to an extracted Ghidra 12.1.4 release directory.",
remediation: `Set GHIDRA_INSTALL_DIR to an extracted Ghidra ${ghidraReleaseLine()} release directory.`,
}),
installationCheck({
name: "platform",
@@ -323,18 +333,7 @@ const installationChecks = ({
remediation:
"Point GHIDRA_INSTALL_DIR at the root of an extracted official Ghidra release.",
}),
installationCheck({
name: "version",
passed:
coordinates.properties?.providerVersion === SUPPORTED_GHIDRA_VERSION,
code:
coordinates.properties?.providerVersion === null ||
coordinates.properties?.providerVersion === undefined
? "version_unresolved"
: "unsupported_version",
detail: coordinates.properties?.providerVersion ?? "unknown",
remediation: `Install Ghidra ${SUPPORTED_GHIDRA_VERSION}, or update REA for a different Ghidra build.`,
}),
versionCheck(coordinates.properties),
installationCheck({
name: "headless",
passed:
@@ -357,7 +356,12 @@ const installationChecks = ({
remediation:
"REA does not build native tools. Build Ghidra's native components for this macOS architecture or provide an installation containing Ghidra/Features/Decompiler/os/<platform>/decompile.",
}),
javaCheck(coordinates.java, coordinates.javaCommand, javaHome),
javaCheck(
coordinates.java,
coordinates.javaCommand,
javaHome,
coordinates.properties,
),
];
/** Project an installation probe into caller-visible, secret-free diagnostics. */
@@ -428,40 +432,65 @@ const installationCheck = (options: {
remediation: options.remediation,
};
const versionCheck = (
properties: GhidraApplicationProperties | undefined,
): GhidraInstallationCheck => {
const raw = properties?.providerVersion;
return installationCheck({
name: "version",
passed: ghidraReleaseAccepted(raw),
code:
ghidraReleaseCompatibility(raw).status === "unsupported"
? "unsupported_version"
: "version_unresolved",
detail: ghidraVersionDetail(raw),
remediation: `Install a Ghidra ${ghidraReleaseLine()} release (verified with ${SUPPORTED_GHIDRA_VERSION}), or update REA for another Ghidra line.`,
});
};
const javaCheck = (
observation: GhidraJavaObservation | undefined,
command: string,
configuredHome: string | undefined,
properties: GhidraApplicationProperties | undefined,
): GhidraInstallationCheck => {
const requirement = ghidraJavaRequirement(properties);
const range = ghidraJavaRangeLabel(requirement);
const supported =
observation !== undefined &&
observation.major === SUPPORTED_GHIDRA_JAVA_MAJOR &&
ghidraJavaMajorAccepted(observation.major, requirement) &&
observation.bits === 64 &&
observation.runtime === "jdk";
const detail =
observation === undefined
? command
: `${observation.version}; ${String(observation.bits)}-bit; ${observation.runtime === "jdk" ? "JDK" : "runtime only"}; ${observation.home}`;
? requirement.unresolved === null
? command
: `${command}; ${requirement.unresolved}`
: `${observation.version}; ${String(observation.bits)}-bit; ${observation.runtime === "jdk" ? "JDK" : "runtime only"}; ${observation.home}; accepted ${range}`;
return installationCheck({
name: "java",
passed: supported,
code: observation === undefined ? "runtime_missing" : "unsupported_version",
code:
requirement.unresolved !== null
? "version_unresolved"
: observation === undefined
? "runtime_missing"
: "unsupported_version",
detail,
remediation:
configuredHome === undefined
? "Install a 64-bit JDK 21 or set JAVA_HOME before starting REA."
: "Update JAVA_HOME to the root of a 64-bit JDK 21 installation.",
remediation: javaRemediation(requirement, configuredHome, range),
});
};
const propertyValue = (content: string, name: string): string | null => {
for (const line of content.split(/\r?\n/u)) {
const separator = line.indexOf("=");
if (separator < 0 || line.slice(0, separator).trim() !== name) continue;
const value = line.slice(separator + 1).trim();
return value.length === 0 ? null : value;
}
return null;
const javaRemediation = (
requirement: GhidraJavaRequirement,
configuredHome: string | undefined,
range: string,
): string => {
if (requirement.unresolved !== null)
return `The Ghidra installation's Java bounds could not be read (${requirement.unresolved}). Install a 64-bit full JDK inside the declared application.java.min and application.java.max.`;
return configuredHome === undefined
? `Install ${range}, or set JAVA_HOME before starting REA.`
: `Update JAVA_HOME to the root of ${range} installation.`;
};
const systemGhidraInstallationHost = (): GhidraInstallationHost => ({
+220
View File
@@ -0,0 +1,220 @@
/** Ghidra build whose bridge behavior this REA release verifies. */
export const SUPPORTED_GHIDRA_VERSION = "12.1.4";
/**
* JDK major used when an installation omits `application.java.min`.
* Admission uses that installation's `application.java.min` and
* `application.java.max`. An empty maximum means the release sets no upper bound.
*/
export const SUPPORTED_GHIDRA_JAVA_MAJOR = 21;
/** Numeric Ghidra release read from `application.version`. */
interface GhidraReleaseVersion {
readonly major: number;
readonly minor: number;
readonly patch: number;
}
/** How an observed Ghidra release relates to this adapter's bridge. */
type GhidraReleaseCompatibility =
| {
readonly status: "verified";
readonly version: GhidraReleaseVersion;
readonly raw: string;
}
| {
readonly status: "compatible";
readonly version: GhidraReleaseVersion;
readonly raw: string;
}
| {
readonly status: "unsupported";
readonly version: GhidraReleaseVersion;
readonly raw: string;
}
| { readonly status: "unresolved"; readonly raw: string | null };
/** One Java major bound declared by `application.properties`. */
type GhidraJavaBound =
| { readonly status: "absent" }
| { readonly status: "major"; readonly major: number }
| { readonly status: "unresolved"; readonly raw: string };
/** JDK majors this installation admits, after reading its own properties. */
export interface GhidraJavaRequirement {
readonly minimumMajor: number;
readonly maximumMajor: number | null;
readonly unresolved: string | null;
}
/** Version and Java bounds read from one `application.properties` file. */
export interface GhidraApplicationProperties {
readonly providerVersion: string | null;
readonly javaMinimum: GhidraJavaBound;
readonly javaMaximum: GhidraJavaBound;
}
const GHIDRA_RELEASE_PATTERN = /^(\d+)\.(\d+)(?:\.(\d+))?([-+].*)?$/u;
const JAVA_MAJOR_PATTERN = /^(\d+)(?:\.\d+)*$/u;
/** Read the version and Java bounds Ghidra publishes for one installation. */
export const ghidraApplicationProperties = (
content: string,
): GhidraApplicationProperties => ({
providerVersion: propertyValue(content, "application.version"),
javaMinimum: parseJavaBound(propertyValue(content, "application.java.min")),
javaMaximum: parseJavaBound(propertyValue(content, "application.java.max")),
});
/** Classify `application.version` against the verified release line. */
export const ghidraReleaseCompatibility = (
raw: string | null | undefined,
): GhidraReleaseCompatibility => {
if (raw === null || raw === undefined)
return { status: "unresolved", raw: null };
const version = parseGhidraRelease(raw);
if (version === undefined) return { status: "unresolved", raw };
if (raw === SUPPORTED_GHIDRA_VERSION)
return { status: "verified", version, raw };
const verified = verifiedGhidraRelease();
return version.major === verified.major && version.minor === verified.minor
? { status: "compatible", version, raw }
: { status: "unsupported", version, raw };
};
/**
* Limitation recorded when a session runs a compatible build other than the
* verified release. The observed version stays on the provider identity.
*/
export const unverifiedGhidraBuildLimitation = (
providerVersion: string,
): string | undefined => {
const compatibility = ghidraReleaseCompatibility(providerVersion);
if (compatibility.status !== "compatible") return undefined;
return `This session uses Ghidra ${providerVersion}. The bridge is verified against ${SUPPORTED_GHIDRA_VERSION}; other ${ghidraReleaseLine()} builds are accepted and the observed version is reported.`;
};
/** Release line accepted by this bridge, such as `12.1.x`. */
export const ghidraReleaseLine = (): string => {
const verified = verifiedGhidraRelease();
return `${String(verified.major)}.${String(verified.minor)}.x`;
};
/** Detail for the installation version check, including the accepted line. */
export const ghidraVersionDetail = (raw: string | null | undefined): string => {
const compatibility = ghidraReleaseCompatibility(raw);
switch (compatibility.status) {
case "unresolved":
return compatibility.raw ?? "unknown";
case "verified":
return compatibility.raw;
case "compatible":
return `${compatibility.raw}; compatible ${ghidraReleaseLine()} release (verified build ${SUPPORTED_GHIDRA_VERSION})`;
case "unsupported":
return `${compatibility.raw}; accepted releases are ${ghidraReleaseLine()} (verified build ${SUPPORTED_GHIDRA_VERSION})`;
default: {
const unreachable: never = compatibility;
return unreachable;
}
}
};
/** Whether this release line can run the packaged bridge. */
export const ghidraReleaseAccepted = (
raw: string | null | undefined,
): boolean => {
const status = ghidraReleaseCompatibility(raw).status;
return status === "verified" || status === "compatible";
};
/** Resolve JDK majors from `application.java.min` and `application.java.max`. */
export const ghidraJavaRequirement = (
properties: GhidraApplicationProperties | undefined,
): GhidraJavaRequirement => {
const minimum = properties?.javaMinimum ?? { status: "absent" };
const maximum = properties?.javaMaximum ?? { status: "absent" };
if (minimum.status === "unresolved")
return unresolvedJavaRequirement(`application.java.min=${minimum.raw}`);
if (maximum.status === "unresolved")
return unresolvedJavaRequirement(`application.java.max=${maximum.raw}`);
const minimumMajor =
minimum.status === "major" ? minimum.major : SUPPORTED_GHIDRA_JAVA_MAJOR;
const maximumMajor = maximum.status === "major" ? maximum.major : null;
if (maximumMajor !== null && maximumMajor < minimumMajor)
return unresolvedJavaRequirement(
`application.java.max=${String(maximumMajor)} is below application.java.min=${String(minimumMajor)}`,
);
return { minimumMajor, maximumMajor, unresolved: null };
};
/** Caller-facing description of one resolved or unreadable JDK range. */
export const ghidraJavaRangeLabel = (
requirement: GhidraJavaRequirement,
): string => {
if (requirement.unresolved !== null)
return "a 64-bit full JDK matching the installation's declared Java bounds";
if (requirement.maximumMajor === null)
return `a 64-bit full JDK ${String(requirement.minimumMajor)} or newer`;
if (requirement.maximumMajor === requirement.minimumMajor)
return `a 64-bit full JDK ${String(requirement.minimumMajor)}`;
return `a 64-bit full JDK ${String(requirement.minimumMajor)} through ${String(requirement.maximumMajor)}`;
};
/** Whether an observed JDK satisfies the installation's declared range. */
export const ghidraJavaMajorAccepted = (
major: number,
requirement: GhidraJavaRequirement,
): boolean =>
requirement.unresolved === null &&
major >= requirement.minimumMajor &&
(requirement.maximumMajor === null || major <= requirement.maximumMajor);
const verifiedGhidraRelease = (): GhidraReleaseVersion => {
const version = parseGhidraRelease(SUPPORTED_GHIDRA_VERSION);
if (version === undefined)
throw new TypeError(
`SUPPORTED_GHIDRA_VERSION ${SUPPORTED_GHIDRA_VERSION} is not a Ghidra release`,
);
return version;
};
const parseGhidraRelease = (raw: string): GhidraReleaseVersion | undefined => {
const match = GHIDRA_RELEASE_PATTERN.exec(raw);
const major = integerGroup(match?.[1]);
const minor = integerGroup(match?.[2]);
if (match === null || major === undefined || minor === undefined)
return undefined;
const patch = match[3] === undefined ? 0 : integerGroup(match[3]);
return patch === undefined ? undefined : { major, minor, patch };
};
const parseJavaBound = (raw: string | null): GhidraJavaBound => {
if (raw === null) return { status: "absent" };
const major = integerGroup(JAVA_MAJOR_PATTERN.exec(raw)?.[1]);
return major === undefined
? { status: "unresolved", raw }
: { status: "major", major };
};
const integerGroup = (value: string | undefined): number | undefined => {
if (value === undefined) return undefined;
const parsed = Number(value);
return Number.isSafeInteger(parsed) ? parsed : undefined;
};
const unresolvedJavaRequirement = (
unresolved: string,
): GhidraJavaRequirement => ({
minimumMajor: SUPPORTED_GHIDRA_JAVA_MAJOR,
maximumMajor: null,
unresolved,
});
const propertyValue = (content: string, name: string): string | null => {
for (const line of content.split(/\r?\n/u)) {
const separator = line.indexOf("=");
if (separator < 0 || line.slice(0, separator).trim() !== name) continue;
const value = line.slice(separator + 1).trim();
return value.length === 0 ? null : value;
}
return null;
};
@@ -791,3 +791,70 @@ describe("Ghidra extension failures", () => {
},
);
});
describe("compatible Ghidra builds", () => {
it("accepts the build and reports that it is unverified", async () => {
const ghidra = provider(
{
...installationHost(),
readText: () =>
"application.version=12.1.2\napplication.java.min=21\napplication.java.max=\n",
probeJava: () => ({
version: "27",
major: 27,
home: "/usr/lib/jvm/java-27-openjdk",
bits: 64,
runtime: "jdk",
}),
},
() => ({
start: () =>
Promise.resolve(
ok({
...sessionInfo(),
provider: { id: "ghidra", version: "12.1.2" },
}),
),
callTool: () =>
Promise.resolve(
ok([
{
address: "0x1000",
value: "fixture_main",
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
},
]),
),
close: () => Promise.resolve(),
}),
);
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
if (!resolved.ok || resolved.value.profile === null)
throw new Error("expected a compatible Ghidra profile");
const client = ghidra.createClient(
executableTarget("elf", "x86_64"),
resolved.value.profile,
);
const health = await client.execute("health", {});
const procedures = await client.execute("list_procedures", {});
expect(ghidra.inspectAvailability()).toMatchObject({
status: "available",
diagnostics: { provider_version: "12.1.2", java_version: "27" },
});
expect(health.ok && health.value.provider.version).toBe("12.1.2");
const unverified = expect.stringContaining("12.1.2");
expect(health.ok && health.value.limitations).toEqual(
expect.arrayContaining([unverified]),
);
expect(procedures.ok && procedures.value.limitations).toEqual(
expect.arrayContaining([unverified]),
);
expect(procedures.ok && procedures.value.provider.version).toBe("12.1.2");
});
});
+12 -12
View File
@@ -59,6 +59,7 @@ import {
type GhidraInstallationHost,
type GhidraInstallationInspection,
} from "./GhidraInstallation.js";
import { unverifiedGhidraBuildLimitation } from "./GhidraInstallationPolicy.js";
import { GhidraHeadlessLauncher } from "./GhidraLauncher.js";
import { resolveGhidraAnalysisProfile } from "./GhidraAnalysisProfile.js";
import type { GhidraSessionError } from "./GhidraSessionError.js";
@@ -332,6 +333,15 @@ export class GhidraProvider implements AnalysisProviderCandidate {
await client.close();
return extensionFailure;
};
const releaseLimitation = unverifiedGhidraBuildLimitation(
prerequisites.value.providerVersion,
);
const sessionLimitations = [
...providerLimitations,
...targetLimitations,
...ghidraExtensionLimitations(extensions),
...(releaseLimitation === undefined ? [] : [releaseLimitation]),
];
return {
execute: async (operation, parameters, options) => {
if (extensionFailure !== undefined) return err(extensionFailure);
@@ -356,12 +366,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
return ok(
createAnalysisExecution(started.value, committedProfile.provider, {
analysisProfile: committedProfile,
limitations: [
...healthLimitations,
...providerLimitations,
...targetLimitations,
...ghidraExtensionLimitations(extensions),
],
limitations: [...healthLimitations, ...sessionLimitations],
}),
);
}
@@ -435,12 +440,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
createAnalysisExecution(normalized, committedProfile.provider, {
rawResult: called.value,
analysisProfile: committedProfile,
limitations: [
...limitationsFor(operation),
...providerLimitations,
...targetLimitations,
...ghidraExtensionLimitations(extensions),
],
limitations: [...limitationsFor(operation), ...sessionLimitations],
}),
);
},
-29
View File
@@ -1,29 +0,0 @@
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;
});
};
+35 -54
View File
@@ -1,3 +1,8 @@
import {
NATIVE_MACOS_PROVIDER_IDENTITY as IDENTITY,
nativeMacOSCapabilities,
} from "./NativeMacOSProviderMetadata.js";
export { NATIVE_MACOS_PROVIDER_IDENTITY } from "./NativeMacOSProviderMetadata.js";
import { inspectAppleDispatchMetadata } from "./AppleDispatchMetadata.js";
import { observeNativeUi } from "./NativeUiObservation.js";
import { dirname, isAbsolute, resolve } from "node:path";
@@ -45,20 +50,12 @@ import {
import { parseCodeSignature } from "./parsers/codesign.js";
import { parseDemangledSymbols } from "./parsers/demangle.js";
import { parseLipoArchitectures } from "./parsers/lipo.js";
import { parsePlistJson } from "./parsers/plist.js";
import { parsePlistJson, parsePlistXml } from "./parsers/plist.js";
import {
architectureLocations,
inspectNativeMacho,
} from "./NativeMachoInspection.js";
/** Public identity committed by macOS-native inspection observations. */
export const NATIVE_MACOS_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
id: "native-macos",
name: "macOS native inspection utilities",
version: null,
});
const IDENTITY = NATIVE_MACOS_PROVIDER_IDENTITY;
/** Read-only semantic provider composed from Xcode command-line utilities. */
export class NativeMacOSProvider implements AnalysisProvider {
readonly #capabilities: readonly CapabilityDescriptor[];
@@ -67,41 +64,7 @@ export class NativeMacOSProvider implements AnalysisProvider {
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(),
platform: NodeJS.Platform = process.platform,
) {
const available = platform === "darwin";
this.#capabilities = Object.freeze(
[
...NATIVE_TOOL_CONTRACTS,
{ name: "inspect_native_dispatch_metadata" as const },
].map((contract): CapabilityDescriptor => {
const availability = available
? ({ available: true, reason: null } as const)
: ({
available: false,
availabilityCode: "unsupported_host",
reason: "Native macOS utilities require macOS.",
} as const);
return Object.freeze({
provider: IDENTITY,
operation: contract.name,
...availability,
effects: Object.freeze({
mutatesArtifact: 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,
}),
limitations: Object.freeze([
"Availability and textual formats depend on the installed macOS/Xcode toolchain.",
]),
});
}),
);
this.#capabilities = nativeMacOSCapabilities(platform);
}
identity(): ProviderIdentity {
@@ -460,33 +423,51 @@ class NativeMacOSClient implements AnalysisClient {
{ signal },
);
if (!classified.ok) return classified;
const capture = await this.#run(
const json = await this.#run(
"inspect_plist",
"plutil",
["-convert", "json", "-o", "-", "--", plist.value],
{ signal },
{ signal, acceptNonZero: true },
);
if (!capture.ok) return capture;
const parsed = parsePlistJson(capture.value.stdout);
if (!json.ok) return json;
// JSON cannot express data, dates, or non-finite reals; plutil rejects
// such plists, so decode its lossless XML conversion instead.
const xml =
json.value.exitCode === 0
? undefined
: await this.#run(
"inspect_plist",
"plutil",
["-convert", "xml1", "-o", "-", "--", plist.value],
{ signal },
);
if (xml !== undefined && !xml.ok) return xml;
const parsed =
xml === undefined
? parsePlistJson(json.value.stdout)
: parsePlistXml(xml.value.stdout);
if (!parsed.ok) return parsed;
const provenance = [classified.value, capture.value].map((item) =>
invocation(item, plist.value, "$PLIST"),
);
const provenance = [
classified.value,
json.value,
...(xml === undefined ? [] : [xml.value]),
].map((item) => invocation(item, plist.value, "$PLIST"));
const result = inspectPlistSchema.parse({
format: /binary property list/iu.test(classified.value.stdout)
? "binary"
: /XML|text/iu.test(classified.value.stdout)
? "xml"
: "unknown",
...parsed.value,
value: parsed.value.value,
bundle: parsed.value.bundle,
source_path: plist.value,
provenance,
limitations: [],
limitations: parsed.value.limitations,
});
return ok({
result: jsonValueSchema.parse(result),
provenance,
limitations: [],
limitations: parsed.value.limitations,
locations: [{ kind: "artifact-path", path: plist.value }],
});
}
+53
View File
@@ -0,0 +1,53 @@
import type {
CapabilityDescriptor,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { NATIVE_TOOL_CONTRACTS } from "../contracts/nativeToolContracts.js";
/** Public identity committed by macOS-native inspection observations. */
export const NATIVE_MACOS_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
id: "native-macos",
name: "macOS native inspection utilities",
version: null,
});
const IDENTITY = NATIVE_MACOS_PROVIDER_IDENTITY;
/** Declare native host coverage without creating a command runner. */
export const nativeMacOSCapabilities = (
platform: NodeJS.Platform = process.platform,
): readonly CapabilityDescriptor[] => {
const available = platform === "darwin";
return Object.freeze(
[
...NATIVE_TOOL_CONTRACTS,
{ name: "inspect_native_dispatch_metadata" as const },
].map((contract): CapabilityDescriptor => {
const availability = available
? ({ available: true, reason: null } as const)
: ({
available: false,
availabilityCode: "unsupported_host",
reason: "Native macOS utilities require macOS.",
} as const);
return Object.freeze({
provider: IDENTITY,
operation: contract.name,
...availability,
effects: Object.freeze({
mutatesArtifact: 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,
}),
limitations: Object.freeze([
"Availability and textual formats depend on the installed macOS/Xcode toolchain.",
]),
});
}),
);
};
+73
View File
@@ -0,0 +1,73 @@
import { expect, it } from "vitest";
import { parsePlistJson, parsePlistXml } from "./plist.js";
it("keeps exact decimal text for JSON integers beyond the safe range", () => {
const parsed = parsePlistJson(
'{"Max":18446744073709551615,"Min":-9223372036854775808,"Safe":9007199254740991,"Real":1e21,"Ratio":0.5}',
);
if (!parsed.ok) throw new Error("expected plist JSON to parse");
expect(parsed.value.value).toEqual({
Max: { $plist_type: "integer", decimal: "18446744073709551615" },
Min: { $plist_type: "integer", decimal: "-9223372036854775808" },
Safe: 9007199254740991,
Real: 1e21,
Ratio: 0.5,
});
expect(parsed.value.limitations).toEqual([
expect.stringContaining("2 integer value(s)"),
]);
});
it("reports no limitation when every JSON integer is exact", () => {
const parsed = parsePlistJson('{"Count":42,"Nested":[-1,0]}');
if (!parsed.ok) throw new Error("expected plist JSON to parse");
expect(parsed.value.value).toEqual({ Count: 42, Nested: [-1, 0] });
expect(parsed.value.limitations).toEqual([]);
});
it("recovers exact XML integers from their element literals", () => {
const parsed = parsePlistXml(
"<plist><dict><key>Max</key><integer>18446744073709551615</integer><key>Safe</key><integer>7</integer><key>Blob</key><data>AA==</data></dict></plist>",
);
if (!parsed.ok) throw new Error("expected plist XML to parse");
expect(parsed.value.value).toEqual({
Max: { $plist_type: "integer", decimal: "18446744073709551615" },
Safe: 7,
Blob: { $plist_type: "data", base64: "AA==" },
});
expect(parsed.value.limitations).toEqual([
expect.stringContaining("XML conversion"),
expect.stringContaining("1 integer value(s)"),
]);
});
it("keeps integral XML reals beyond the safe range as reals", () => {
const parsed = parsePlistXml(
"<plist><dict><key>Real</key><real>9007199254740992</real><key>Blob</key><data>AA==</data></dict></plist>",
);
if (!parsed.ok) throw new Error("expected plist XML to parse");
expect(parsed.value.value).toEqual({
Real: 9007199254740992,
Blob: { $plist_type: "data", base64: "AA==" },
});
expect(parsed.value.limitations).toEqual([
expect.stringContaining("XML conversion"),
]);
});
it("reports XML numbers whose integer or real origin is ambiguous", () => {
const parsed = parsePlistXml(
"<plist><array><integer>9007199254740993</integer><real>9007199254740992</real><data>AA==</data></array></plist>",
);
if (!parsed.ok) throw new Error("expected plist XML to parse");
expect(parsed.value.value).toEqual([
9007199254740992,
9007199254740992,
{ $plist_type: "data", base64: "AA==" },
]);
expect(parsed.value.limitations).toEqual([
expect.stringContaining("XML conversion"),
expect.stringContaining("2 number(s)"),
]);
});
+165 -30
View File
@@ -1,50 +1,185 @@
import { parse as parseXmlPlist } from "plist";
import { z } from "zod";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import {
projectPlistValue,
type ProjectedPlistValue,
} from "../../domain/plistValue.js";
import { err, ok, type Result } from "../../domain/result.js";
import { safeParseJson } from "../../domain/safeJson.js";
const plistObject = z.record(z.string(), z.unknown());
/** Stable bundle metadata projected from one plist value. */
export interface PlistBundleMetadata {
readonly identifier: string | null;
readonly executable: string | null;
readonly name: string | null;
readonly version: string | null;
readonly short_version: string | null;
}
/** One decoded plist with bundle metadata and decoding limitations. */
export interface ParsedPlist {
readonly value: unknown;
readonly bundle: PlistBundleMetadata;
readonly limitations: readonly string[];
}
/** Parse plutil JSON output and project stable bundle metadata. */
export const parsePlistJson = (
output: string,
): Result<
{
readonly value: unknown;
readonly bundle: {
readonly identifier: string | null;
readonly executable: string | null;
readonly name: string | null;
readonly version: string | null;
readonly short_version: string | null;
};
},
AnalysisOutputError
> => {
): Result<ParsedPlist, AnalysisOutputError> => {
// plutil output can carry a UTF-8 BOM, which JSON.parse rejects outright.
const parsed = safeParseJson(output.replace(/^\uFEFF/u, ""));
if (!parsed.ok)
const text = output.replace(/^\uFEFF/u, "");
let exactIntegerCount = 0;
// A plist integer can exceed the exact range of a JavaScript number; keep
// its decimal text from the JSON source instead of a rounded value.
const keepExactIntegers = (
_key: string,
item: unknown,
context?: { readonly source?: string },
): unknown => {
const source = context?.source;
if (
typeof item !== "number" ||
Number.isSafeInteger(item) ||
source === undefined ||
!/^-?\d+$/u.test(source)
)
return item;
exactIntegerCount += 1;
return { $plist_type: "integer", decimal: source };
};
let value: unknown;
try {
value = JSON.parse(text, keepExactIntegers);
} catch (cause: unknown) {
return err(
new AnalysisOutputError("inspect_plist", parsed.error, {
cause: parsed.cause,
}),
new AnalysisOutputError(
"inspect_plist",
cause instanceof Error ? cause.message : String(cause),
{ cause },
),
);
const value: unknown = parsed.value;
}
return ok({
value,
bundle: projectPlistBundle(value),
limitations:
exactIntegerCount === 0
? []
: [largeIntegerLimitation(exactIntegerCount)],
});
};
/**
* Parse plutil XML output for a plist that JSON cannot express, such as one
* containing data, dates, or non-finite reals.
*/
export const parsePlistXml = (
output: string,
): Result<ParsedPlist, AnalysisOutputError> => {
let projected: ProjectedPlistValue;
try {
projected = projectPlistValue(parseXmlPlist(output));
} catch (cause: unknown) {
return err(
new AnalysisOutputError(
"inspect_plist",
"plutil XML conversion was not a readable plist",
{ cause },
),
);
}
// The XML decoder turns <integer> and <real> into numbers before REA sees
// them, rounding integers beyond the exact range. plutil escapes "<" in keys
// and strings, so the element literals can be read from the XML text.
const unsafeIntegers = new Map<number, Set<string>>();
for (const [, decimal = ""] of output.matchAll(
/<integer>\s*([+-]?\d+)\s*<\/integer>/gu,
)) {
const rounded = Number(decimal);
if (Number.isSafeInteger(rounded)) continue;
const exact = BigInt(decimal).toString();
unsafeIntegers.set(
rounded,
(unsafeIntegers.get(rounded) ?? new Set()).add(exact),
);
}
const reals = new Set(
[...output.matchAll(/<real>([^<]*)<\/real>/gu)].map(([, text = ""]) =>
Number.parseFloat(text),
),
);
let exactIntegerCount = 0;
let ambiguousNumberCount = 0;
const value = mapJsonNumbers(projected.value, (item) => {
const decimals = unsafeIntegers.get(item);
if (decimals === undefined) return item;
const [decimal] = decimals;
if (decimals.size !== 1 || decimal === undefined || reals.has(item)) {
ambiguousNumberCount += 1;
return item;
}
exactIntegerCount += 1;
return { $plist_type: "integer", decimal };
});
return ok({
value,
bundle: projectPlistBundle(value),
limitations: [
'plutil cannot express this plist as JSON, so it was decoded from plutil\'s XML conversion; data and date values are typed objects such as { "$plist_type": "data", "base64": ... }.',
...(projected.unknownRealCount === 0
? []
: [
`${String(projected.unknownRealCount)} non-finite real value(s) are reported as { "$plist_type": "real", "value": null } because the XML decoder does not distinguish NaN from infinity.`,
]),
...(exactIntegerCount === 0
? []
: [largeIntegerLimitation(exactIntegerCount)]),
...(ambiguousNumberCount === 0
? []
: [
`${String(ambiguousNumberCount)} number(s) beyond the exact range of a JSON number are reported as decoded because the XML literal they came from, a rounded <integer> or a <real>, cannot be identified.`,
]),
],
});
};
const largeIntegerLimitation = (count: number): string =>
`${String(count)} integer value(s) exceed the exact range of a JSON number and are reported as { "$plist_type": "integer", "decimal": "<exact digits>" }.`;
const mapJsonNumbers = (
value: JsonValue,
map: (item: number) => JsonValue,
): JsonValue => {
if (typeof value === "number") return map(value);
if (Array.isArray(value))
return value.map((item) => mapJsonNumbers(item, map));
if (value !== null && typeof value === "object")
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [
key,
mapJsonNumbers(item, map),
]),
);
return value;
};
const projectPlistBundle = (value: unknown): PlistBundleMetadata => {
const object = plistObject.safeParse(value);
const field = (name: string): string | null => {
if (!object.success) return null;
const candidate = object.data[name];
return typeof candidate === "string" ? candidate : null;
};
return ok({
value,
bundle: {
identifier: field("CFBundleIdentifier"),
executable: field("CFBundleExecutable"),
name: field("CFBundleName"),
version: field("CFBundleVersion"),
short_version: field("CFBundleShortVersionString"),
},
});
return {
identifier: field("CFBundleIdentifier"),
executable: field("CFBundleExecutable"),
name: field("CFBundleName"),
version: field("CFBundleVersion"),
short_version: field("CFBundleShortVersionString"),
};
};
+2 -1
View File
@@ -1,3 +1,4 @@
import type { EvidenceReader } from "../application/investigation/InvestigationRecordPort.js";
import { z } from "zod";
import { uniqueSorted } from "../domain/canonicalOrdering.js";
@@ -138,7 +139,7 @@ const evidenceCandidates = (
};
type LedgerEvidence = ReturnType<
BinarySessionPort["exportEvidenceBundle"]
EvidenceReader["exportEvidenceBundle"]
>["records"][number];
const evidenceValues = (
+2 -2
View File
@@ -1,6 +1,6 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
import { AndroidAnalysisService } from "../application/AndroidAnalysisService.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { ToolContract } from "../contracts/toolContractTypes.js";
import type { AndroidOperation } from "../domain/androidAnalysis.js";
@@ -14,7 +14,7 @@ export const registerAndroidTools = (
server: McpServer,
service: AndroidAnalysisService,
logger: Logger,
recordEvidence?: BinarySessionPort["recordEvidence"],
recordEvidence?: EvidenceWriter["recordEvidence"],
): void => {
const handler = (contract: ToolContract<AndroidOperation>) => {
const name = contract.name;
+8 -4
View File
@@ -1,12 +1,16 @@
import type { BinarySessionPort } from "../../application/BinarySession.js";
import type {
EvidenceWriter,
EvidenceReader,
EvidenceUnknownWriter,
} from "../../application/investigation/InvestigationRecordPort.js";
import type { Logger } from "../../logger.js";
/** Shared services for registering JavaScript application graph workflows. */
export interface ApplicationToolRegistration {
readonly logger: Logger;
readonly evidenceById: BinarySessionPort["evidenceById"] | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly evidenceById: EvidenceReader["evidenceById"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
readonly recordEvidenceWithUnknown:
| BinarySessionPort["recordEvidenceWithUnknown"]
| EvidenceUnknownWriter["recordEvidenceWithUnknown"]
| undefined;
}
+2 -2
View File
@@ -1,7 +1,7 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import type { McpServer } from "@modelcontextprotocol/server";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { ARTIFACT_TOOL_CONTRACTS } from "../contracts/artifactToolContracts.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { Logger } from "../logger.js";
@@ -15,7 +15,7 @@ export const registerArtifactTools = (
options: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
},
): void => {
registerEvidenceTools(server, analysis, ARTIFACT_TOOL_CONTRACTS, {
+4 -4
View File
@@ -1,3 +1,4 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import {
optionalProviderUnavailable,
type OptionalProviderLoadFailure,
@@ -5,10 +6,9 @@ import {
import { err } from "../domain/result.js";
import type { McpServer } from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySession.js";
import type { BrowserScenarioCapturePort } from "../application/BrowserScenarioCapturePort.js";
import { captureBrowserScenario } from "../application/BrowserScenarioCaptureService.js";
import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "../contracts/browserScenarioToolContracts.js";
import { toolContract } from "../contracts/toolContracts.js";
import { browserScenarioSchema } from "../domain/browserScenario.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
@@ -19,7 +19,7 @@ interface BrowserScenarioToolRegistration {
readonly logger: Logger;
readonly loadFailure?: OptionalProviderLoadFailure | undefined;
readonly provider: BrowserScenarioCapturePort | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
}
/** Register the browser scenario tool with execution-time provider diagnostics. */
@@ -27,7 +27,7 @@ export const registerBrowserScenarioTool = (
server: McpServer,
options: BrowserScenarioToolRegistration,
): void => {
const [contract] = BROWSER_SCENARIO_TOOL_CONTRACTS;
const contract = toolContract("capture_browser_scenario");
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
+11 -14
View File
@@ -1,3 +1,4 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import {
optionalProviderUnavailable,
type OptionalProviderLoadFailure,
@@ -5,7 +6,6 @@ import {
import { err } from "../domain/result.js";
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySession.js";
import type { BrowserObservationPort } from "../application/BrowserObservationPort.js";
import {
analyzeWebBundle,
@@ -18,8 +18,7 @@ import {
observeWebSession,
} from "../application/BrowserObservationService.js";
import type { ProgressReporter } from "../application/ProgressReporter.js";
import { BROWSER_TOOL_CONTRACTS } from "../contracts/browserToolContracts.js";
import type { ToolContract } from "../contracts/toolContracts.js";
import { toolContract, type ToolContract } from "../contracts/toolContracts.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Evidence } from "../domain/evidence.js";
import { analyzeWebBundleInputSchema } from "../domain/webBundleAnalysis.js";
@@ -35,7 +34,7 @@ interface BrowserToolRegistration {
readonly logger: Logger;
readonly loadFailure?: OptionalProviderLoadFailure | undefined;
readonly browser: BrowserObservationPort | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
}
interface BrowserToolContext {
@@ -49,16 +48,14 @@ export const registerBrowserTools = (
server: McpServer,
options: BrowserToolRegistration,
): void => {
const [
listContract,
inspectContract,
analyzeContract,
sessionContract,
webMcpContract,
captureDiffContract,
screenshotContract,
screenshotDiffContract,
] = BROWSER_TOOL_CONTRACTS;
const listContract = toolContract("list_browser_targets");
const inspectContract = toolContract("inspect_web_page");
const analyzeContract = toolContract("analyze_web_bundle");
const sessionContract = toolContract("observe_web_session");
const webMcpContract = toolContract("discover_webmcp_tools");
const captureDiffContract = toolContract("compare_web_captures");
const screenshotContract = toolContract("capture_web_screenshot");
const screenshotDiffContract = toolContract("compare_web_screenshots");
server.registerTool(
listContract.name,
+8 -11
View File
@@ -1,3 +1,4 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import {
optionalProviderUnavailable,
type OptionalProviderLoadFailure,
@@ -5,7 +6,6 @@ import {
import { err } from "../domain/result.js";
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySession.js";
import type { ElectronActiveObservationPort } from "../application/ElectronActiveObservationPort.js";
import { captureElectronScenario } from "../application/ElectronActiveObservationService.js";
import type { ElectronObservationPort } from "../application/ElectronObservationPort.js";
@@ -16,8 +16,7 @@ import {
import { analyzeJavaScriptApplicationValidated } from "../application/JavaScriptApplicationService.js";
import { reconcileJavaScriptRuntimeEvidenceValidated } from "../application/JavaScriptRuntimeReconciliationService.js";
import type { ProgressReporter } from "../application/ProgressReporter.js";
import { ELECTRON_TOOL_CONTRACTS } from "../contracts/electronToolContracts.js";
import type { ToolContract } from "../contracts/toolContracts.js";
import { toolContract, type ToolContract } from "../contracts/toolContracts.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Evidence } from "../domain/evidence.js";
import type { Result } from "../domain/result.js";
@@ -34,7 +33,7 @@ interface ElectronToolRegistration {
readonly activeLoadFailure?: OptionalProviderLoadFailure | undefined;
readonly electron: ElectronObservationPort | undefined;
readonly electronActive: ElectronActiveObservationPort | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
}
interface ElectronToolContext {
@@ -48,13 +47,11 @@ export const registerElectronTools = (
server: McpServer,
options: ElectronToolRegistration,
): void => {
const [
listContract,
inspectContract,
analyzeContract,
reconcileContract,
activeContract,
] = ELECTRON_TOOL_CONTRACTS;
const listContract = toolContract("list_electron_targets");
const inspectContract = toolContract("inspect_electron_page");
const analyzeContract = toolContract("analyze_javascript_application");
const reconcileContract = toolContract("reconcile_javascript_runtime");
const activeContract = toolContract("capture_electron_scenario");
server.registerTool(
listContract.name,
+8 -5
View File
@@ -1,3 +1,7 @@
import type {
EvidenceWriter,
UnknownRegistryPort,
} from "../application/investigation/InvestigationRecordPort.js";
import type {
CallToolResult,
McpServer,
@@ -5,7 +9,6 @@ import type {
} from "@modelcontextprotocol/server";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import {
EnhancedTools,
type ValidatedEnhancedCall,
@@ -34,8 +37,8 @@ export interface EnhancedToolRegistration {
readonly analysisProfile:
| (() => AnalysisProfileCommitment | undefined)
| undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordUnknown: BinarySessionPort["recordUnknown"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
readonly recordUnknown: UnknownRegistryPort["recordUnknown"] | undefined;
}
/** Register composed workflows against the same port as direct bridge tools. */
@@ -319,7 +322,7 @@ interface WorkflowUnknownInput {
readonly name: string;
readonly result: JsonValue;
readonly evidenceId: string;
readonly recordUnknown: BinarySessionPort["recordUnknown"] | undefined;
readonly recordUnknown: UnknownRegistryPort["recordUnknown"] | undefined;
}
const recordWorkflowUnknowns = ({
@@ -328,7 +331,7 @@ const recordWorkflowUnknowns = ({
evidenceId,
recordUnknown,
}: WorkflowUnknownInput):
| ReturnType<BinarySessionPort["recordUnknown"]>
| ReturnType<UnknownRegistryPort["recordUnknown"]>
| { readonly ok: true; readonly value: null } => {
if (
!["trace_feature", "trace_call_path", "inspect_native_api"].includes(
+2 -2
View File
@@ -1,10 +1,10 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import type { McpServer } from "@modelcontextprotocol/server";
import type {
AnalysisOperation,
AnalysisOperationPort,
} from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import type { ToolContract } from "../contracts/toolContracts.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
@@ -19,7 +19,7 @@ import { createArtifactExtractionDestination } from "../application/ArtifactExtr
interface EvidenceToolRegistration {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
readonly sourceEvidence?: (
operation: Exclude<AnalysisOperation, "health">,
result: import("../domain/jsonValue.js").JsonValue,
+2 -2
View File
@@ -1,6 +1,6 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
import type { FirmwareAnalysisService } from "../application/FirmwareAnalysisService.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { ToolContract } from "../contracts/toolContractTypes.js";
import type { FirmwareOperation } from "../domain/firmwareAnalysis.js";
@@ -14,7 +14,7 @@ export const registerFirmwareTools = (
server: McpServer,
service: FirmwareAnalysisService,
logger: Logger,
recordEvidence?: BinarySessionPort["recordEvidence"],
recordEvidence?: EvidenceWriter["recordEvidence"],
): void => {
const handler =
(contract: ToolContract<FirmwareOperation>) =>
@@ -1,3 +1,4 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import {
optionalProviderUnavailable,
type OptionalProviderLoadFailure,
@@ -5,14 +6,12 @@ import {
import { err } from "../domain/result.js";
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySession.js";
import type { JavaScriptRuntimeObservationPort } from "../application/JavaScriptRuntimeObservationPort.js";
import {
listJavaScriptRuntimeTargets,
observeJavaScriptRuntime,
} from "../application/JavaScriptRuntimeObservationService.js";
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "../contracts/javascriptRuntimeObservationToolContracts.js";
import type { ToolContract } from "../contracts/toolContracts.js";
import { toolContract, type ToolContract } from "../contracts/toolContracts.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Evidence } from "../domain/evidence.js";
import type { Result } from "../domain/result.js";
@@ -26,7 +25,7 @@ interface RuntimeToolRegistration {
readonly logger: Logger;
readonly loadFailure?: OptionalProviderLoadFailure | undefined;
readonly runtime: JavaScriptRuntimeObservationPort | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
}
/** Register passive Inspector tools even when policy keeps them unavailable. */
@@ -34,8 +33,8 @@ export const registerJavaScriptRuntimeObservationTools = (
server: McpServer,
options: RuntimeToolRegistration,
): void => {
const [listContract, observeContract] =
JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS;
const listContract = toolContract("list_javascript_runtime_targets");
const observeContract = toolContract("observe_javascript_runtime");
server.registerTool(
listContract.name,
toolRegistrationOptions(listContract),
+2 -1
View File
@@ -1,3 +1,4 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import type { McpServer } from "@modelcontextprotocol/server";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
@@ -18,7 +19,7 @@ export const registerManagedTools = (
options: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
readonly session: BinarySessionPort | undefined;
},
): void => {
@@ -1,12 +1,16 @@
import type {
EvidenceWriter,
EvidenceUnknownWriter,
} from "../../application/investigation/InvestigationRecordPort.js";
import type { BinarySessionPort } from "../../application/BinarySession.js";
import type { Logger } from "../../logger.js";
/** Shared services for registering managed-code workflow tools. */
export interface ManagedWorkflowToolRegistration {
readonly logger: Logger;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
readonly recordEvidenceWithUnknown:
| BinarySessionPort["recordEvidenceWithUnknown"]
| EvidenceUnknownWriter["recordEvidenceWithUnknown"]
| undefined;
readonly session: BinarySessionPort;
}
+2 -2
View File
@@ -1,7 +1,7 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import type { McpServer } from "@modelcontextprotocol/server";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { NATIVE_TOOL_CONTRACTS } from "../contracts/nativeToolContracts.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { Logger } from "../logger.js";
@@ -14,7 +14,7 @@ export const registerNativeTools = (
options: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
},
): void => {
registerEvidenceTools(server, analysis, NATIVE_TOOL_CONTRACTS, options);
+3 -3
View File
@@ -1,3 +1,4 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
import { z } from "zod";
@@ -5,7 +6,6 @@ import type {
AnalysisExecution,
AnalysisOperationPort,
} from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import type { ProgressReporter } from "../application/ProgressReporter.js";
import type { ToolContract } from "../contracts/toolContracts.js";
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/officialToolContracts.js";
@@ -28,7 +28,7 @@ import { toCallToolResult } from "./toolResult.js";
export interface OfficialToolRegistration {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
}
/** Register direct bridge proxies, preserving MCP cancellation and typed errors. */
@@ -53,7 +53,7 @@ const registerOfficialTool = (
registration: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
},
): void => {
server.registerTool(
+2 -2
View File
@@ -1,6 +1,6 @@
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import type { McpServer } from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { exportWebScriptsValidated } from "../application/WebScriptExportService.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "../logger.js";
@@ -13,7 +13,7 @@ export const registerWebScriptTool = (
server: McpServer,
options: {
readonly logger: Logger;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
},
): void => {
const contract = toolContract("export_web_scripts");
+2 -2
View File
@@ -1,11 +1,11 @@
import type { BinarySessionPort } from "../application/BinarySession.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import type { Evidence } from "../domain/evidence.js";
import { ok, type Result } from "../domain/result.js";
/** Record source evidence in order, stopping at the first session rejection. */
export const recordSessionEvidenceSources = (
recordEvidence: BinarySessionPort["recordEvidence"] | undefined,
recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
sources: readonly Evidence[],
): Result<null, EvidenceIntegrityError> => {
for (const source of sources) {