Add evidence-backed investigation workflows
This commit is contained in:
@@ -6,6 +6,11 @@ import { promisify } from "node:util";
|
||||
|
||||
import { HopperCancelledError, HopperStartError } from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
type ProcessCleanupResult,
|
||||
} from "../application/ProcessOwnership.js";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const HOPPER_BACKGROUND_STARTUP_MS = 5_000;
|
||||
@@ -15,12 +20,14 @@ export interface BridgeSession {
|
||||
readonly directory: string;
|
||||
readonly socketPath: string;
|
||||
readonly token: string;
|
||||
readonly runId: string;
|
||||
}
|
||||
|
||||
/** Process handle returned by a bridge launcher. */
|
||||
export interface BridgeLaunch {
|
||||
readonly process: ChildProcess;
|
||||
readonly ownsProcessLifetime: boolean;
|
||||
readonly cleanup?: () => Promise<ProcessCleanupResult>;
|
||||
}
|
||||
|
||||
/** Application-owned capability that starts the in-Hopper bridge. */
|
||||
@@ -49,8 +56,9 @@ export interface HopperApplicationLauncherOptions {
|
||||
* supported launcher; callers must treat possible foreground UI as an upstream
|
||||
* Hopper constraint, not as evidence that analysis failed.
|
||||
*
|
||||
* The returned process is the short-lived launcher helper, not the Hopper app,
|
||||
* so REA does not claim ownership of the application's lifetime.
|
||||
* REA owns only the short-lived launcher helper's run-token-authenticated
|
||||
* process group. It does not claim ownership of the Hopper GUI process that
|
||||
* macOS LaunchServices may create or reuse.
|
||||
*/
|
||||
export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
constructor(readonly options: HopperApplicationLauncherOptions) {}
|
||||
@@ -63,6 +71,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
const source = [
|
||||
`REA_SOCKET = ${JSON.stringify(session.socketPath)}`,
|
||||
`REA_TOKEN = ${JSON.stringify(session.token)}`,
|
||||
`REA_RUN_ID = ${JSON.stringify(session.runId)}`,
|
||||
`exec(compile(open(${JSON.stringify(this.options.bridgeScriptPath)}, 'rb').read(), ${JSON.stringify(this.options.bridgeScriptPath)}, 'exec'))`,
|
||||
"",
|
||||
].join("\n");
|
||||
@@ -93,6 +102,8 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
if (!prepared) return err(new HopperCancelledError());
|
||||
const child = spawn(this.options.launcherPath, args, {
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
detached: process.platform !== "win32",
|
||||
env: { ...process.env, REA_PROCESS_RUN_ID: session.runId },
|
||||
});
|
||||
const started = await new Promise<Result<undefined, HopperStartError>>(
|
||||
(resolve) => {
|
||||
@@ -109,7 +120,44 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
},
|
||||
);
|
||||
if (!started.ok) return started;
|
||||
return ok({ process: child, ownsProcessLifetime: false });
|
||||
const pid = child.pid;
|
||||
if (pid === undefined)
|
||||
return err(
|
||||
new HopperStartError({ cause: new Error("missing launcher PID") }),
|
||||
);
|
||||
const ownership = {
|
||||
schema_version: 1,
|
||||
run_id: session.runId,
|
||||
pid,
|
||||
process_group_id: pid,
|
||||
parent_pid: process.pid,
|
||||
launcher: this.options.launcherPath,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
try {
|
||||
await writeFileAtomic(
|
||||
join(session.directory, "ownership.json"),
|
||||
`${JSON.stringify(ownership)}\n`,
|
||||
{ encoding: "utf8", mode: 0o600 },
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
await cleanupOwnedProcessGroup({
|
||||
runId: session.runId,
|
||||
leaderPid: pid,
|
||||
processGroupId: pid,
|
||||
});
|
||||
return err(new HopperStartError({ cause }));
|
||||
}
|
||||
return ok({
|
||||
process: child,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup: () =>
|
||||
cleanupOwnedProcessGroup({
|
||||
runId: session.runId,
|
||||
leaderPid: pid,
|
||||
processGroupId: pid,
|
||||
}),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return err(new HopperStartError({ cause }));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { randomBytes, randomUUID } from "node:crypto";
|
||||
import { access, mkdtemp, rm } from "node:fs/promises";
|
||||
import { createConnection, type Socket } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -101,11 +101,13 @@ export class HopperClient {
|
||||
}
|
||||
const socketPath = join(this.#directory, "bridge.sock");
|
||||
this.#token = randomBytes(32).toString("hex");
|
||||
const runId = randomUUID();
|
||||
const launched = await this.#options.launcher.launch(
|
||||
{
|
||||
directory: this.#directory,
|
||||
socketPath,
|
||||
token: this.#token,
|
||||
runId,
|
||||
},
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
@@ -132,7 +134,7 @@ export class HopperClient {
|
||||
await this.close();
|
||||
return health;
|
||||
}
|
||||
const parsed = parseServerInfo(health.value);
|
||||
const parsed = parseServerInfo(health.value, runId);
|
||||
if (!parsed.ok) await this.close();
|
||||
return parsed;
|
||||
}
|
||||
@@ -170,7 +172,14 @@ export class HopperClient {
|
||||
socket?.destroy();
|
||||
this.#socket = undefined;
|
||||
if (this.#launch?.ownsProcessLifetime === true) {
|
||||
this.#launch.process.kill("SIGTERM");
|
||||
if (this.#launch.cleanup !== undefined) {
|
||||
const cleanup = await this.#launch.cleanup();
|
||||
if (!cleanup.cleaned)
|
||||
this.#logger.warn(
|
||||
{ reason: cleanup.reason },
|
||||
"Owned launcher cleanup failed closed",
|
||||
);
|
||||
} else this.#launch.process.kill("SIGTERM");
|
||||
}
|
||||
this.#launch = undefined;
|
||||
if (this.#directory !== undefined) {
|
||||
@@ -388,13 +397,15 @@ const connectOnce = async (
|
||||
|
||||
const parseServerInfo = (
|
||||
value: JsonValue,
|
||||
expectedRunId: string,
|
||||
): Result<HopperServerInfo, HopperProtocolError> => {
|
||||
if (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
!Array.isArray(value) &&
|
||||
value.name === "REA Hopper bridge" &&
|
||||
typeof value.version === "string"
|
||||
typeof value.version === "string" &&
|
||||
value.run_id === expectedRunId
|
||||
) {
|
||||
return ok({ name: value.name, version: value.version });
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { createAnalysisExecution } from "../application/AnalysisProvider.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisProvider,
|
||||
@@ -9,42 +10,66 @@ import type {
|
||||
import type { AppConfig } from "../config.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../domain/errors.js";
|
||||
import { err } from "../domain/result.js";
|
||||
import {
|
||||
ENHANCED_TOOL_CONTRACTS,
|
||||
OFFICIAL_TOOL_CONTRACTS,
|
||||
} from "../contracts/toolContracts.js";
|
||||
import { HopperApplicationLauncher } from "./BridgeLauncher.js";
|
||||
import { HopperClient } from "./HopperClient.js";
|
||||
|
||||
const IDENTITY: ProviderIdentity = {
|
||||
const IDENTITY: ProviderIdentity = Object.freeze({
|
||||
id: "hopper",
|
||||
name: "Hopper Disassembler",
|
||||
version: null,
|
||||
};
|
||||
});
|
||||
const MUTATING_OPERATIONS = new Set([
|
||||
"set_address_name",
|
||||
"set_addresses_names",
|
||||
"set_bookmark",
|
||||
"set_comment",
|
||||
"set_inline_comment",
|
||||
"unset_bookmark",
|
||||
]);
|
||||
|
||||
const OPERATIONS = [
|
||||
"direct-analysis",
|
||||
"decompilation",
|
||||
"disassembly",
|
||||
"cross-references",
|
||||
"containing-procedure-resolution",
|
||||
"procedure-references",
|
||||
"analysis-metadata-mutation",
|
||||
] as const;
|
||||
const PROVIDER_TOOL_CONTRACTS = [
|
||||
...OFFICIAL_TOOL_CONTRACTS,
|
||||
...ENHANCED_TOOL_CONTRACTS.filter(
|
||||
(contract) => contract.name === "analyze_function",
|
||||
),
|
||||
];
|
||||
|
||||
const CAPABILITIES: readonly CapabilityDescriptor[] = OPERATIONS.map(
|
||||
(operation) => ({
|
||||
operation,
|
||||
version: 1,
|
||||
available: true,
|
||||
pagination: "none",
|
||||
exhaustive: false,
|
||||
effects: {
|
||||
mutatesArtifact: operation === "analysis-metadata-mutation",
|
||||
launchesProcess: true,
|
||||
mayShowUi: true,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: operation === "analysis-metadata-mutation",
|
||||
requiresPrivileges: false,
|
||||
},
|
||||
limitations: ["Results depend on Hopper's completed static analysis."],
|
||||
}),
|
||||
const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
PROVIDER_TOOL_CONTRACTS.map((contract) =>
|
||||
Object.freeze({
|
||||
provider: IDENTITY,
|
||||
operation: contract.name,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "offset" in contract.inputSchema.shape ? "offset" : "none",
|
||||
exhaustive: false,
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: MUTATING_OPERATIONS.has(contract.name),
|
||||
launchesProcess: true,
|
||||
mayShowUi: true,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: MUTATING_OPERATIONS.has(contract.name),
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limits: Object.freeze({
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
}),
|
||||
limitations: Object.freeze([
|
||||
"Results depend on Hopper's completed static analysis.",
|
||||
]),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
/** Concrete analysis provider backed by REA's private Hopper bridge. */
|
||||
@@ -63,6 +88,20 @@ export class HopperProvider implements AnalysisProvider {
|
||||
}
|
||||
|
||||
createClient(target: BinaryTarget): AnalysisClient {
|
||||
if (target.kind !== "executable" && target.kind !== "database")
|
||||
return {
|
||||
execute: (operation) =>
|
||||
Promise.resolve(
|
||||
err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
IDENTITY.id,
|
||||
operation,
|
||||
`Hopper cannot open ${target.kind} targets directly. Inventory or extract the artifact first.`,
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
};
|
||||
const client = new HopperClient({
|
||||
launcher: new HopperApplicationLauncher({
|
||||
launcherPath: this.config.hopperLauncherPath,
|
||||
@@ -79,8 +118,19 @@ export class HopperProvider implements AnalysisProvider {
|
||||
logger: this.logger.child({ layer: "bridge" }),
|
||||
});
|
||||
return {
|
||||
execute: (operation, parameters, options) =>
|
||||
client.callTool(operation, parameters, options),
|
||||
execute: async (operation, parameters, options) => {
|
||||
const result = await client.callTool(operation, parameters, options);
|
||||
return result.ok
|
||||
? {
|
||||
ok: true,
|
||||
value: createAnalysisExecution(result.value, IDENTITY, {
|
||||
limitations: [
|
||||
"Results depend on Hopper's completed static analysis.",
|
||||
],
|
||||
}),
|
||||
}
|
||||
: result;
|
||||
},
|
||||
close: () => client.close(),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user