feat(ghidra): add private headless provider session

This commit is contained in:
N0zoM1z0
2026-07-16 01:27:54 +09:00
committed by N0zoM1z0
parent ed17e76473
commit f0e625d7ee
234 changed files with 8968 additions and 513 deletions
+116 -2
View File
@@ -40,6 +40,27 @@ export interface DoctorCheck {
readonly detail?: string;
readonly remediation?: string;
}
/** One provider-owned check projected without importing its adapter types. */
export interface DoctorProviderCheck {
readonly name: string;
readonly ok: boolean;
readonly code: string | null;
readonly detail: string;
readonly remediation: string | null;
readonly classification: Exclude<DoctorCheck["classification"], "healthy">;
}
/** Read-only provider inspection supplied by an outer composition adapter. */
export interface DoctorProviderInspection {
readonly id: string;
readonly configured: boolean;
readonly available: boolean;
readonly providerVersion: string | null;
/** Exact non-secret variables safe to persist in an approved registration. */
readonly registrationEnvironment: Readonly<Record<string, string>>;
readonly checks: readonly DoctorProviderCheck[];
}
/** Read-only host capabilities required by diagnostics. */
export interface DoctorHost {
readonly platform: NodeJS.Platform;
@@ -53,6 +74,7 @@ export interface DoctorHost {
linuxDemoRuntimeReady(): Promise<boolean>;
brewHopperPath(): Promise<string | undefined>;
manualHopperPaths(): Promise<readonly string[]>;
providerInspections?(): Promise<readonly DoctorProviderInspection[]>;
installationPaths?(): Promise<readonly string[]>;
installedSkillVersion?(): Promise<string | undefined>;
clientRegistrations?(): Promise<readonly ClientRegistrationStatus[]>;
@@ -69,6 +91,7 @@ export const runDoctor = async (
): Promise<{
readonly healthy: boolean;
readonly hopperPath?: string;
readonly providerInspections?: readonly DoctorProviderInspection[];
readonly checks: readonly DoctorCheck[];
readonly identity?: {
readonly cli_package_version: string;
@@ -168,6 +191,7 @@ export const runDoctor = async (
},
),
);
const providerInspections = await inspectDoctorProviders(host, checks);
if (host.platform === "linux" && hopperPath !== undefined)
checks.push(
check(
@@ -203,8 +227,17 @@ export const runDoctor = async (
"Run rea setup, then restart the affected client.",
});
return {
healthy: checks.every(({ ok }) => ok),
healthy: doctorHealthy(checks, {
hopperAvailable:
hopperPath !== undefined &&
checks
.filter(({ name }) => name.startsWith("hopper"))
.every(({ ok }) => ok),
hopperConfigured: host.configuredHopperPath !== undefined,
providerInspections,
}),
...(hopperPath === undefined ? {} : { hopperPath }),
...(providerInspections === undefined ? {} : { providerInspections }),
checks,
identity: {
cli_package_version: PRODUCT_IDENTITY.packageVersion,
@@ -249,8 +282,17 @@ const unsupportedHopperRemediation = (configured: boolean): string =>
? "Unset or update HOPPER_LAUNCHER_PATH, install the Hopper build supported by this REA release, or update REA."
: "Install the Hopper build supported by this REA release, or update REA for a newer Hopper build.";
/** Optional outer-adapter diagnostics composed without reversing dependencies. */
export interface SystemDoctorHostOptions {
readonly providerInspections?: () => Promise<
readonly DoctorProviderInspection[]
>;
}
/** Create diagnostics backed by the current process and host commands. */
export const systemDoctorHost = (): DoctorHost => ({
export const systemDoctorHost = (
options: SystemDoctorHostOptions = {},
): DoctorHost => ({
platform: process.platform,
nodeVersion: process.versions.node,
...(process.env.HOPPER_LAUNCHER_PATH === undefined
@@ -330,6 +372,9 @@ export const systemDoctorHost = (): DoctorHost => ({
}
return paths;
},
...(options.providerInspections === undefined
? {}
: { providerInspections: options.providerInspections }),
async installationPaths() {
try {
const command = process.platform === "win32" ? "where" : "which";
@@ -383,3 +428,72 @@ const check = (
...(detail === undefined ? {} : { detail }),
...(ok ? {} : { remediation: failure.remediation }),
});
const providerDoctorChecks = (
inspection: DoctorProviderInspection,
): readonly DoctorCheck[] =>
inspection.checks.map((candidate) => ({
name:
candidate.name === "configuration"
? inspection.id
: `${inspection.id}-${candidate.name}`,
ok: candidate.ok,
classification: candidate.ok ? "healthy" : candidate.classification,
detail: candidate.detail,
...(candidate.remediation === null
? {}
: { remediation: candidate.remediation }),
}));
const inspectDoctorProviders = async (
host: DoctorHost,
checks: DoctorCheck[],
): Promise<readonly DoctorProviderInspection[] | undefined> => {
const inspections = await host.providerInspections?.();
if (inspections === undefined) return undefined;
for (const inspection of inspections)
checks.push(...providerDoctorChecks(inspection));
return inspections;
};
const doctorHealthy = (
checks: readonly DoctorCheck[],
providers: {
readonly hopperAvailable: boolean;
readonly hopperConfigured: boolean;
readonly providerInspections:
| readonly DoctorProviderInspection[]
| undefined;
},
): boolean => {
if (providers.providerInspections === undefined)
return checks.every(({ ok }) => ok);
const providerChecks = checks.filter(
({ name }) =>
name.startsWith("hopper") ||
providers.providerInspections?.some((inspection) =>
providerCheckName(inspection.id, name),
) === true,
);
const coreHealthy = checks
.filter((candidate) => !providerChecks.includes(candidate))
.every(({ ok }) => ok);
const configuredProvidersHealthy = providerChecks
.filter(({ name }) => {
if (name.startsWith("hopper")) return providers.hopperConfigured;
return providers.providerInspections?.some(
(inspection) =>
inspection.configured && providerCheckName(inspection.id, name),
);
})
.every(({ ok }) => ok);
return (
coreHealthy &&
configuredProvidersHealthy &&
(providers.hopperAvailable ||
providers.providerInspections.some(({ available }) => available))
);
};
const providerCheckName = (providerId: string, name: string): boolean =>
name === providerId || name.startsWith(`${providerId}-`);
+108 -48
View File
@@ -16,7 +16,12 @@ import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
import { PRODUCT_IDENTITY } from "../identity.js";
import { supportsNodeVersion } from "../domain/runtimeVersion.js";
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
import { runDoctor, systemDoctorHost } from "./Doctor.js";
import {
runDoctor,
systemDoctorHost,
type DoctorHost,
type DoctorProviderInspection,
} from "./Doctor.js";
import {
installLinuxHopper,
readLinuxDistribution,
@@ -38,6 +43,9 @@ import {
} from "./SetupInstallFailure.js";
export type { SetupHopperInstallResult } from "./SetupInstallFailure.js";
/** Exact non-secret provider variables propagated into managed registrations. */
export type SetupProviderEnvironment = Readonly<Record<string, string>>;
export {
canonicalSkillNeedsInstall,
installCanonicalSkill,
@@ -70,15 +78,16 @@ export interface SetupHost {
linuxDistribution(): Promise<LinuxDistribution | undefined>;
hopperPath(): Promise<string | undefined>;
installHopper(replaceExisting: boolean): Promise<SetupHopperInstallResult>;
providerEnvironment?(): Promise<SetupProviderEnvironment>;
detectedClients(): Promise<readonly SetupClient[]>;
configureClient(
client: SetupClient,
hopperPath: string | undefined,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<ClientConfigurationResult>;
clientNeedsConfigure(
client: SetupClient,
hopperPath: string | undefined,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<boolean>;
skillNeedsInstall(): Promise<boolean>;
@@ -141,12 +150,13 @@ export const runSetup = async (
doctor: await host.doctor(),
remediation,
});
const unsupported = await hostRemediation(host);
const unsupported = await hostRemediation(host, options.installHopper);
if (unsupported !== undefined) return fail(unsupported);
let hopperPath = await host.hopperPath();
let providerEnvironment = await initialProviderEnvironment(host, hopperPath);
const discovery = await discoverSetupActions(
host,
hopperPath,
providerEnvironment,
options.installHopper,
);
const { installHopper, installSkill } = discovery;
@@ -182,18 +192,22 @@ export const runSetup = async (
remediation: installed.remediation,
};
hopperPath = installed.launcherPath;
providerEnvironment = {
...providerEnvironment,
HOPPER_LAUNCHER_PATH: installed.launcherPath,
};
appliedActions.push("installed_hopper");
detectedClients = await filterClientsNeedingConfigure(
host,
detectedClients,
hopperPath,
providerEnvironment,
registrationCommand(),
);
}
const clientFailure = await configureDetectedClients({
host,
detectedClients,
hopperPath,
providerEnvironment,
command: registrationCommand(),
clients,
appliedActions,
@@ -226,7 +240,7 @@ export const runSetup = async (
const discoverSetupActions = async (
host: SetupHost,
hopperPath: string | undefined,
providerEnvironment: SetupProviderEnvironment,
forceHopperInstall: boolean,
) => {
const initialDoctor = await host.doctor();
@@ -237,7 +251,9 @@ const discoverSetupActions = async (
(name === "hopper-version" && detail === "/opt/hopper/bin/Hopper")),
);
const installHopper =
forceHopperInstall || hopperPath === undefined || linuxHopperRepairNeeded;
forceHopperInstall ||
Object.keys(providerEnvironment).length === 0 ||
linuxHopperRepairNeeded;
const [detectedClients, installSkill] = await Promise.all([
host.detectedClients(),
host.skillNeedsInstall(),
@@ -248,7 +264,7 @@ const discoverSetupActions = async (
: await filterClientsNeedingConfigure(
host,
detectedClients,
hopperPath,
providerEnvironment,
command,
);
const plannedActions = setupPlan(
@@ -256,6 +272,7 @@ const discoverSetupActions = async (
installHopper,
installSkill,
clients,
providerEnvironment,
);
return {
installHopper,
@@ -268,17 +285,25 @@ const discoverSetupActions = async (
const filterClientsNeedingConfigure = async (
host: SetupHost,
detectedClients: readonly SetupClient[],
hopperPath: string | undefined,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<readonly SetupClient[]> => {
const needs = await Promise.all(
detectedClients.map((client) =>
host.clientNeedsConfigure(client, hopperPath, command),
host.clientNeedsConfigure(client, providerEnvironment, command),
),
);
return detectedClients.filter((_, index) => needs[index]);
};
const initialProviderEnvironment = async (
host: SetupHost,
hopperPath: string | undefined,
): Promise<SetupProviderEnvironment> => ({
...(await host.providerEnvironment?.()),
...(hopperPath === undefined ? {} : { HOPPER_LAUNCHER_PATH: hopperPath }),
});
const finalSetupRemediation = (
platform: NodeJS.Platform,
installedHopper: boolean,
@@ -295,6 +320,7 @@ const finalSetupRemediation = (
const hostRemediation = async (
host: SetupHost,
forceHopperInstall: boolean,
): Promise<string | undefined> => {
if (host.platform !== "darwin" && host.platform !== "linux")
return "REA supports Hopper on macOS and selected 64-bit Linux distributions.";
@@ -306,20 +332,36 @@ const hostRemediation = async (
? "Upgrade to macOS 12 or newer."
: undefined;
}
return (await host.linuxDistribution())?.supported === true
? undefined
: "REA supports Hopper on Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux.";
if ((await host.linuxDistribution())?.supported === true) return undefined;
const providerEnvironment = await host.providerEnvironment?.();
if (
!forceHopperInstall &&
providerEnvironment !== undefined &&
Object.keys(providerEnvironment).length > 0
)
return undefined;
return "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux; configure an existing supported provider instead.";
};
/** Production setup effects for Hopper, agent configuration, and the canonical skill directory. */
const systemSetupHost = (): SetupHost => {
const doctorHost = systemDoctorHost();
export const systemSetupHost = (
doctorHost: DoctorHost = systemDoctorHost(),
): SetupHost => {
return {
platform: process.platform,
nodeVersion: process.versions.node,
macosVersion: () => doctorHost.macosVersion(),
linuxDistribution: readLinuxDistribution,
hopperPath: async () => (await runDoctor(undefined, doctorHost)).hopperPath,
providerEnvironment: async () => {
const diagnosis = await runDoctor(undefined, doctorHost);
return {
...providerRegistrationEnvironment(diagnosis.providerInspections ?? []),
...(diagnosis.hopperPath === undefined
? {}
: { HOPPER_LAUNCHER_PATH: diagnosis.hopperPath }),
};
},
installHopper: async (replaceExisting) => {
const result =
process.platform === "linux"
@@ -329,14 +371,14 @@ const systemSetupHost = (): SetupHost => {
return setupInstallFailure(result.reason);
},
detectedClients: () => detectClients(homedir()),
configureClient: (client, hopperPath, command) =>
configureClient: (client, providerEnvironment, command) =>
client.format === "unsupported"
? Promise.resolve({ status: "skipped" })
: client.format === "toml"
? configureTomlClient(client, hopperPath, command)
: configureJsonClient(client, hopperPath, command),
clientNeedsConfigure: (client, hopperPath, command) =>
clientConfigurationAligned(client, hopperPath, command).then(
? configureTomlClient(client, providerEnvironment, command)
: configureJsonClient(client, providerEnvironment, command),
clientNeedsConfigure: (client, providerEnvironment, command) =>
clientConfigurationAligned(client, providerEnvironment, command).then(
(aligned) => !aligned,
),
skillNeedsInstall: () => canonicalSkillNeedsInstall(homedir()),
@@ -359,7 +401,7 @@ export const detectClients = async (
/** Back up, atomically update, and semantically read back one JSON MCP configuration. */
export const configureJsonClient = async (
client: SetupClient,
hopperPath?: string,
environment: SetupProviderEnvironment | string = {},
command: readonly string[] = [
"npx",
"-y",
@@ -386,13 +428,10 @@ export const configureJsonClient = async (
} catch {
return { status: "failed", reason: "readback" };
}
const desired = {
command: command[0] ?? PRODUCT_IDENTITY.cliBinary,
args: command.slice(1),
...(hopperPath === undefined
? {}
: { env: { HOPPER_LAUNCHER_PATH: hopperPath } }),
};
const desired = clientConfigurationDesired(
normalizeProviderEnvironment(environment),
command,
);
if (
JSON.stringify(servers[PRODUCT_IDENTITY.mcpServerKey]) ===
JSON.stringify(desired)
@@ -440,7 +479,7 @@ export const configureJsonClient = async (
/** Back up, atomically update, and semantically read back Codex TOML configuration. */
export const configureTomlClient = async (
client: SetupClient,
hopperPath?: string,
environment: SetupProviderEnvironment | string = {},
command: readonly string[] = [
"npx",
"-y",
@@ -467,13 +506,10 @@ export const configureTomlClient = async (
} catch {
return { status: "failed", reason: "readback" };
}
const desired = {
command: command[0] ?? PRODUCT_IDENTITY.cliBinary,
args: command.slice(1),
...(hopperPath === undefined
? {}
: { env: { HOPPER_LAUNCHER_PATH: hopperPath } }),
};
const desired = clientConfigurationDesired(
normalizeProviderEnvironment(environment),
command,
);
if (
JSON.stringify(servers[PRODUCT_IDENTITY.mcpServerKey]) ===
JSON.stringify(desired)
@@ -558,22 +594,27 @@ const restoreConfig = async (
};
const clientConfigurationDesired = (
hopperPath: string | undefined,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
) => ({
command: command[0] ?? PRODUCT_IDENTITY.cliBinary,
args: command.slice(1),
...(hopperPath === undefined
? {}
: { env: { HOPPER_LAUNCHER_PATH: hopperPath } }),
});
) => {
const environment = Object.fromEntries(
Object.entries(providerEnvironment).sort(([left], [right]) =>
left.localeCompare(right),
),
);
return {
command: command[0] ?? PRODUCT_IDENTITY.cliBinary,
args: command.slice(1),
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
};
};
const clientConfigurationAligned = async (
client: SetupClient,
hopperPath: string | undefined,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<boolean> => {
const desired = clientConfigurationDesired(hopperPath, command);
const desired = clientConfigurationDesired(providerEnvironment, command);
try {
const original = await readFile(client.configPath, "utf8");
if (client.format === "toml") {
@@ -594,3 +635,22 @@ const clientConfigurationAligned = async (
return false;
}
};
const normalizeProviderEnvironment = (
environment: SetupProviderEnvironment | string,
): SetupProviderEnvironment =>
typeof environment === "string"
? { HOPPER_LAUNCHER_PATH: environment }
: environment;
const providerRegistrationEnvironment = (
inspections: readonly DoctorProviderInspection[],
): SetupProviderEnvironment =>
Object.fromEntries(
inspections
.filter(({ available }) => available)
.flatMap(({ registrationEnvironment }) =>
Object.entries(registrationEnvironment),
)
.sort(([left], [right]) => left.localeCompare(right)),
);
+3 -2
View File
@@ -2,6 +2,7 @@ import type {
ClientConfigurationResult,
SetupClient,
SetupHost,
SetupProviderEnvironment,
} from "./Setup.js";
const failedConfigurationMessage = (
@@ -20,7 +21,7 @@ const failedConfigurationMessage = (
export const configureDetectedClients = async (options: {
readonly host: SetupHost;
readonly detectedClients: readonly SetupClient[];
readonly hopperPath: string | undefined;
readonly providerEnvironment: SetupProviderEnvironment;
readonly command: readonly string[];
readonly clients: Record<string, ClientConfigurationResult>;
readonly appliedActions: string[];
@@ -29,7 +30,7 @@ export const configureDetectedClients = async (options: {
for (const client of options.detectedClients) {
const result = await options.host.configureClient(
client,
options.hopperPath,
options.providerEnvironment,
options.command,
);
options.clients[client.name] = result;
+19 -2
View File
@@ -1,4 +1,8 @@
import type { SetupAction, SetupClient } from "./Setup.js";
import type {
SetupAction,
SetupClient,
SetupProviderEnvironment,
} from "./Setup.js";
/** Build the complete setup mutation plan before approval. */
export const setupPlan = (
@@ -6,6 +10,7 @@ export const setupPlan = (
installHopper: boolean,
installSkill: boolean,
clients: readonly SetupClient[],
providerEnvironment: SetupProviderEnvironment,
): readonly SetupAction[] => [
...(installHopper
? [
@@ -29,7 +34,7 @@ export const setupPlan = (
(client): SetupAction => ({
kind: "configure_client",
target: client.configPath,
detail: `Add the REA MCP registration for ${client.name}; preserve unrelated configuration.`,
detail: clientConfigurationDetail(client.name, providerEnvironment),
external: false,
}),
),
@@ -44,3 +49,15 @@ export const setupPlan = (
]
: []),
];
const clientConfigurationDetail = (
client: string,
environment: SetupProviderEnvironment,
): string => {
const entries = Object.entries(environment)
.sort(([left], [right]) => left.localeCompare(right))
.map(([name, value]) => `${name}=${value}`);
const suffix =
entries.length === 0 ? "" : ` Environment: ${entries.join(", ")}.`;
return `Add the REA MCP registration for ${client}; preserve unrelated configuration.${suffix}`;
};
+3 -1
View File
@@ -1,6 +1,7 @@
import type { AppConfig } from "../config.js";
import { BinarySession } from "./BinarySession.js";
import { HopperProvider } from "../hopper/HopperProvider.js";
import { GhidraProvider } from "../ghidra/GhidraProvider.js";
import { NativeMacOSProvider } from "../native/NativeMacOSProvider.js";
import { ArtifactProvider } from "../artifacts/ArtifactProvider.js";
import { silentLogger, type Logger } from "../logger.js";
@@ -17,9 +18,10 @@ export const createBinarySession = (
logger: Logger = silentLogger,
): BinarySession => {
const hopper = new HopperProvider(config, logger);
const ghidra = new GhidraProvider(config, logger);
return new BinarySession(
SessionProviderRouter.selectable(
new AnalysisProviderRegistry([hopper], config.analysisProvider),
new AnalysisProviderRegistry([hopper, ghidra], config.analysisProvider),
[
new ArtifactProvider(
config.artifactNativeMountEnabled,
+14 -1
View File
@@ -9,6 +9,7 @@ import {
BrowserObservationError,
type BrowserObservationOperation,
} from "../domain/errors.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
const HTTP_TIMEOUT_MS = 5_000;
const MAX_VERSION_BYTES = 64 * 1_024;
@@ -111,7 +112,7 @@ export const discoverCdpEndpoint = async (
targets: targets.map((target) => ({
id: target.id,
type: target.type,
title: target.title,
title: sanitizeTargetTitle(target.title),
url: target.url,
attached: target.attached,
...targetWebSocket(endpoint, target, operation),
@@ -119,6 +120,18 @@ export const discoverCdpEndpoint = async (
};
};
const sanitizeTargetTitle = (value: string): string => {
let url: URL;
try {
url = new URL(value);
} catch {
return value;
}
return url.protocol === "http:" || url.protocol === "https:"
? sanitizeBrowserUrl(value).url.slice(0, 16_384)
: value;
};
/** Select a browser attachment socket or a direct socket for one page target. */
export const cdpTargetWebSocket = (
discovery: CdpEndpointDiscovery,
+10 -3
View File
@@ -8,7 +8,11 @@ import {
runProviderAnalysis,
runSessionStatus,
} from "./application/DirectAnalysis.js";
import { runSetup, type SetupAction } from "./application/Setup.js";
import {
runSetup,
systemSetupHost,
type SetupAction,
} from "./application/Setup.js";
import { runUninstall } from "./application/Uninstall.js";
import { runUpgrade, systemUpgradeHost } from "./application/Upgrade.js";
import { PRODUCT_IDENTITY } from "./identity.js";
@@ -35,6 +39,7 @@ import {
analysisProviderSelectorSchema,
type AnalysisProviderSelector,
} from "./contracts/providerSelection.js";
import { createSystemDoctorHost } from "./doctorRuntime.js";
/**
* Build the one-shot Incur CLI without starting Hopper at import time.
@@ -180,7 +185,7 @@ const registerSetupCommands = (
installHopper: options.installHopper,
structured: formatExplicit,
},
undefined,
systemSetupHost(createSystemDoctorHost()),
options.yes || formatExplicit || process.stdin.isTTY !== true
? undefined
: confirmSetup,
@@ -193,7 +198,9 @@ const registerSetupCommands = (
target: z.string().optional().describe("Optional app path to check"),
}),
run: ({ options }) =>
logCliCommand(logger, "doctor", () => runDoctor(options.target)),
logCliCommand(logger, "doctor", () =>
runDoctor(options.target, createSystemDoctorHost()),
),
});
cli.command(CLI_COMMANDS.uninstall, {
description: "Remove REA-owned agent configuration and skill files",
+16 -1
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { isAbsolute } from "node:path";
import { ConfigurationError } from "./domain/errors.js";
import { err, ok, type Result } from "./domain/result.js";
@@ -30,6 +31,8 @@ const defaultHopperLauncherPath = (): string =>
export interface AppConfig {
readonly analysisProvider: AnalysisProviderSelector;
readonly ghidraInstallDir: string | undefined;
readonly ghidraJavaHome: string | undefined;
readonly hopperLauncherPath: string;
readonly hopperTargetPath: string | undefined;
readonly hopperTargetKind: "executable" | "database";
@@ -57,6 +60,16 @@ export interface AppConfig {
const environmentSchema = z
.object({
REA_ANALYSIS_PROVIDER: analysisProviderSelectorSchema.default("auto"),
GHIDRA_INSTALL_DIR: z
.string()
.min(1)
.refine(isAbsolute, "GHIDRA_INSTALL_DIR must be absolute")
.optional(),
JAVA_HOME: z
.string()
.min(1)
.refine(isAbsolute, "JAVA_HOME must be absolute")
.optional(),
HOPPER_LAUNCHER_PATH: z.string().min(1).optional(),
HOPPER_TARGET_PATH: z.string().min(1).optional(),
HOPPER_TARGET_KIND: z
@@ -234,7 +247,7 @@ const parseLoaderArgs = (
};
/**
* Parse Hopper launcher configuration once at the composition root.
* Parse provider and authority configuration once at the composition root.
* Explicit loader arguments override REA's header-derived defaults for a
* supported target, allowing callers to refine Hopper's loader behavior without
* bypassing REA's path and executable-header checks.
@@ -364,6 +377,8 @@ export const parseConfig = (
] satisfies readonly PermissionCeiling[];
return ok({
analysisProvider: parsedEnvironment.data.REA_ANALYSIS_PROVIDER,
ghidraInstallDir: parsedEnvironment.data.GHIDRA_INSTALL_DIR,
ghidraJavaHome: parsedEnvironment.data.JAVA_HOME,
hopperLauncherPath:
parsedEnvironment.data.HOPPER_LAUNCHER_PATH ??
defaultHopperLauncherPath(),
+8
View File
@@ -0,0 +1,8 @@
import { systemDoctorHost, type DoctorHost } from "./application/Doctor.js";
import { inspectSystemGhidraProvider } from "./ghidra/GhidraDoctor.js";
/** Compose provider diagnostics at the outer CLI adapter boundary. */
export const createSystemDoctorHost = (): DoctorHost =>
systemDoctorHost({
providerInspections: async () => [await inspectSystemGhidraProvider()],
});
+18 -2
View File
@@ -212,16 +212,26 @@ const providerSelectionUserMessage = (
}
};
/** A provider adapter failed outside its more precise typed variants. */
export interface ProviderAdapterErrorOptions extends ErrorOptions {
readonly diagnostics?: Readonly<Record<string, JsonValue>>;
}
/** A provider adapter failed outside its more precise typed variants. */
export class ProviderAdapterError extends AnalysisError {
readonly _tag = "ProviderAdapterError";
readonly diagnostics: Readonly<Record<string, JsonValue>> | undefined;
constructor(
readonly providerId: string,
readonly operation: string,
options?: ErrorOptions,
options: ProviderAdapterErrorOptions = {},
) {
super(`Provider ${providerId} adapter failed during ${operation}`, options);
this.diagnostics =
options.diagnostics === undefined
? undefined
: structuredClone(options.diagnostics);
}
}
@@ -702,7 +712,13 @@ const errorDetails = (
})),
};
if (error instanceof ProviderAdapterError)
return { provider_id: error.providerId, operation: error.operation };
return {
provider_id: error.providerId,
operation: error.operation,
...(error.diagnostics === undefined
? {}
: { diagnostics: error.diagnostics }),
};
if (error instanceof BrowserObservationError)
return { operation: error.operation, reason: error.reason };
if (error instanceof HopperRemoteError)
+61
View File
@@ -0,0 +1,61 @@
import type {
AnalysisProfileResolution,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { createAnalysisProfile } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
AnalysisCancelledError,
ProviderAdapterError,
type AnalysisError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import {
GHIDRA_ANALYSIS_TIMEOUT_SECONDS,
GHIDRA_MAX_CPU,
GHIDRA_MAX_HEAP,
} from "./GhidraDefaults.js";
import type { GhidraInstallationInspection } from "./GhidraInstallation.js";
/** Resolve version-bound, deterministic semantics before Ghidra imports a target. */
export const resolveGhidraAnalysisProfile = (
target: BinaryTarget,
identity: ProviderIdentity,
installation: GhidraInstallationInspection,
signal?: AbortSignal,
): Promise<Result<AnalysisProfileResolution, AnalysisError>> => {
if (signal?.aborted === true)
return Promise.resolve(err(new AnalysisCancelledError("open_binary")));
if (target.kind !== "executable")
return Promise.resolve(ok({ profile: null, compatibility: {} }));
const version = installation.providerVersion;
if (!installation.available || version === null)
return Promise.resolve(
err(new ProviderAdapterError(identity.id, "resolve_analysis_profile")),
);
const provider = { ...identity, version };
return Promise.resolve(
ok({
profile: createAnalysisProfile(provider, 1, {
target_kind: target.kind,
target_format: target.format,
architecture: target.architecture ?? null,
available_architectures: [
...(target.availableArchitectures ?? []),
].sort(),
import_mode: "ephemeral-read-only",
loader: "auto-from-header",
language_id: "auto-from-header",
compiler_spec_id: "auto-default",
analyzer_preset: "ghidra-default",
analysis_timeout_seconds: GHIDRA_ANALYSIS_TIMEOUT_SECONDS,
max_cpu: GHIDRA_MAX_CPU,
max_heap: GHIDRA_MAX_HEAP,
}),
compatibility: {
languageId: "auto",
compilerSpecId: "auto",
},
}),
);
};
+528
View File
@@ -0,0 +1,528 @@
import { randomBytes, randomUUID } from "node:crypto";
import { access } from "node:fs/promises";
import type { Socket } from "node:net";
import { join } from "node:path";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { silentLogger, type Logger } from "../logger.js";
import { PendingOperations } from "../process/PendingOperations.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
import {
type ProviderProcessDiagnostic,
type ProviderProcessSnapshot,
ProviderProcessSupervisor,
} from "../process/ProviderProcess.js";
import {
GHIDRA_MAX_LINE_BYTES,
GHIDRA_REQUEST_TIMEOUT_MS,
GHIDRA_STARTUP_TIMEOUT_MS,
} from "./GhidraDefaults.js";
import type {
GhidraClientOptions,
GhidraStartResult,
} from "./GhidraClientTypes.js";
import { createGhidraDiagnostics } from "./GhidraDiagnostics.js";
import type { GhidraLaunch } from "./GhidraLauncher.js";
import { GhidraResponseBuffer } from "./GhidraResponseBuffer.js";
import { GhidraResponseRouter } from "./GhidraResponseRouter.js";
import { GhidraSessionError } from "./GhidraSessionError.js";
import {
isGhidraShutdownAcknowledgement,
parseGhidraSessionInfo,
type GhidraSessionInfo,
} from "./GhidraSessionValues.js";
import {
attachGhidraSocket,
connectGhidraSocketOnce,
} from "./GhidraSocketConnection.js";
const SHUTDOWN_TIMEOUT_MS = 10_000;
const SESSION_ROOT = "/tmp";
export type {
GhidraClientOptions,
GhidraDiagnostic,
GhidraStartResult,
} from "./GhidraClientTypes.js";
/** Owns one authenticated, private, read-only Ghidra headless session. */
export class GhidraClient {
readonly #options: Required<
Pick<GhidraClientOptions, "requestTimeoutMs" | "startupTimeoutMs">
> &
GhidraClientOptions;
readonly #pending = new PendingOperations<
number,
Result<JsonValue, GhidraSessionError>
>();
readonly #logger: Logger;
#socket: Socket | undefined;
#detachSocket: (() => void) | undefined;
#launch: GhidraLaunch | undefined;
#process: ProviderProcessSupervisor | undefined;
#runtimeRoot: PrivateRuntimeRoot | undefined;
#token: string | undefined;
#runId: string | undefined;
#nextId = 1;
#closing = false;
#processSnapshot: ProviderProcessSnapshot | undefined;
#lastDiagnostics: Readonly<Record<string, JsonValue>> = {};
#startupController: AbortController | undefined;
#startPromise: Promise<GhidraStartResult> | undefined;
#closePromise: Promise<void> | undefined;
readonly #responseRouter = new GhidraResponseRouter({
pending: this.#pending,
nextId: () => this.#nextId,
remoteFailure: (message, cause) => this.#failure("remote", message, cause),
protocolFailure: (message, cause) => this.#abortProtocol(message, cause),
});
readonly #responseBuffer = new GhidraResponseBuffer({
maxLineBytes: GHIDRA_MAX_LINE_BYTES,
onLine: (line) => this.#responseRouter.route(line),
onFailure: (message) => this.#abortProtocol(message),
});
readonly #onSocketData = (chunk: string): void =>
this.#responseBuffer.push(chunk);
readonly #onSocketError = (): void => {
this.#failAll(this.#failure("process", "Ghidra bridge socket failed"));
};
readonly #onSocketClose = (): void => {
if (!this.#closing)
this.#failAll(this.#failure("process", "Ghidra bridge socket closed"));
};
constructor(options: GhidraClientOptions) {
this.#logger = options.logger ?? silentLogger;
this.#options = {
...options,
requestTimeoutMs: options.requestTimeoutMs ?? GHIDRA_REQUEST_TIMEOUT_MS,
startupTimeoutMs: options.startupTimeoutMs ?? GHIDRA_STARTUP_TIMEOUT_MS,
};
}
/** Launch Ghidra once and require its exact post-analysis handshake. */
start(signal?: AbortSignal): Promise<GhidraStartResult> {
if (this.#closePromise !== undefined)
return this.#closePromise.then(() => this.start(signal));
if (this.#startPromise !== undefined) return this.#startPromise;
const controller = new AbortController();
const onAbort = (): void => controller.abort(signal?.reason);
if (signal?.aborted === true) onAbort();
else signal?.addEventListener("abort", onAbort, { once: true });
const started = this.#start(controller.signal);
this.#startupController = controller;
this.#startPromise = started;
const reset = (): void => {
signal?.removeEventListener("abort", onAbort);
if (this.#startPromise === started) {
this.#startPromise = undefined;
if (this.#startupController === controller)
this.#startupController = undefined;
}
};
void started.then((result) => {
signal?.removeEventListener("abort", onAbort);
if (!result.ok) reset();
}, reset);
return started;
}
/** Revalidate live bridge, provider, run, and profile metadata. */
async ping(
options: {
readonly signal?: AbortSignal;
readonly timeoutMs?: number;
} = {},
): Promise<Result<GhidraSessionInfo, GhidraSessionError>> {
const started = await this.start(options.signal);
if (!started.ok) return started;
const result = await this.#request("ping", {}, options);
if (!result.ok) return result;
return this.#parseSessionInfo(result.value);
}
/** Stop the owned process group and remove all project/runtime artifacts. */
close(): Promise<void> {
const starting = this.#startPromise;
const controller = this.#startupController;
controller?.abort();
this.#closePromise ??= Promise.resolve().then(() =>
this.#close(starting, controller),
);
return this.#closePromise;
}
/** Latest bounded local diagnostics, with bearer material redacted. */
diagnostics(): Readonly<Record<string, JsonValue>> {
return structuredClone(this.#diagnostics());
}
async #start(signal: AbortSignal): Promise<GhidraStartResult> {
if (signal.aborted)
return err(this.#failure("cancelled", "Ghidra startup was cancelled"));
if (this.#socket !== undefined || this.#runtimeRoot !== undefined)
return err(this.#failure("protocol", "Ghidra client is already started"));
const deadline = new ProviderStartupDeadline(
this.#options.startupTimeoutMs,
signal,
);
try {
return await this.#startWithin(deadline);
} finally {
deadline.dispose();
}
}
async #startWithin(
deadline: ProviderStartupDeadline,
): Promise<GhidraStartResult> {
try {
this.#runtimeRoot = await PrivateRuntimeRoot.create({
parent: SESSION_ROOT,
prefix: "rea-ghidra-",
});
} catch (cause: unknown) {
return err(
this.#failure("start", "Ghidra runtime root creation failed", cause),
);
}
if (deadline.signal.aborted) return this.#startupInterrupted(deadline);
const socketPath = join(this.#runtimeRoot.path, "bridge.sock");
this.#token = randomBytes(32).toString("hex");
this.#runId = randomUUID();
const launched = await this.#options.launcher
.launch(
{
runtimeRoot: this.#runtimeRoot.path,
socketPath,
token: this.#token,
runId: this.#runId,
targetPath: this.#options.targetPath,
providerVersion: this.#options.providerVersion,
profileDigest: this.#options.profileDigest,
},
{ signal: deadline.signal },
)
.catch((cause: unknown) =>
err(this.#failure("start", "Ghidra launcher failed", cause)),
);
if (!launched.ok) {
const failure = deadline.signal.aborted
? this.#interruptionFailure(deadline)
: launched.error instanceof GhidraSessionError
? launched.error
: this.#failure("start", launched.error.message, launched.error);
await this.#cleanup();
return err(failure);
}
this.#launch = launched.value;
this.#process = new ProviderProcessSupervisor(launched.value, {
onDiagnostic: (event) => this.#onProcessDiagnostic(event),
});
const connected = await this.#connect(socketPath, deadline);
if (!connected.ok) {
const failure = connected.error;
await this.#cleanup();
return err(failure);
}
const ping = await this.#request(
"ping",
{},
{
signal: deadline.signal,
timeoutMs: deadline.remainingMs(),
},
);
if (!ping.ok) {
const failure = deadline.signal.aborted
? this.#interruptionFailure(deadline)
: ping.error;
await this.#cleanup();
return err(failure);
}
const parsed = this.#parseSessionInfo(ping.value);
if (!parsed.ok || parsed.value.analysis_timed_out) {
const failure = parsed.ok
? this.#failure(
"analysis_timeout",
"Ghidra auto-analysis reached its per-file deadline",
)
: parsed.error;
await this.#cleanup();
return err(failure);
}
return parsed;
}
async #connect(
socketPath: string,
deadline: ProviderStartupDeadline,
): Promise<Result<undefined, GhidraSessionError>> {
while (deadline.remainingMs() > 0) {
if (deadline.signal.aborted)
return err(this.#interruptionFailure(deadline));
if (this.#closing)
return err(this.#failure("cancelled", "Ghidra startup was closed"));
if (this.#processSnapshot?.exitCode !== undefined)
return err(
this.#failure("process", "Ghidra exited before bridge startup"),
);
try {
await access(socketPath);
} catch {
if ((await deadline.wait(50)) === "aborted")
return err(this.#interruptionFailure(deadline));
continue;
}
const connected = await connectGhidraSocketOnce(
socketPath,
deadline.signal,
);
if (connected.ok) {
this.#socket = connected.value;
this.#detachSocket = attachGhidraSocket(connected.value, {
data: this.#onSocketData,
error: this.#onSocketError,
close: this.#onSocketClose,
});
return ok(undefined);
}
if ((await deadline.wait(50)) === "aborted")
return err(this.#interruptionFailure(deadline));
}
return err(
this.#failure("timeout", "Ghidra startup deadline elapsed", undefined, {
timeoutMs: this.#options.startupTimeoutMs,
}),
);
}
async #request(
method: string,
params: JsonValue,
options: { readonly signal?: AbortSignal; readonly timeoutMs?: number },
): Promise<Result<JsonValue, GhidraSessionError>> {
const socket = this.#socket;
const token = this.#token;
if (socket === undefined || socket.destroyed || token === undefined)
return err(this.#failure("process", "Ghidra bridge is unavailable"));
if (options.signal?.aborted === true)
return err(this.#failure("cancelled", "Ghidra request was cancelled"));
const id = this.#nextId++;
const timeoutMs = options.timeoutMs ?? this.#options.requestTimeoutMs;
if (timeoutMs <= 0)
return err(
this.#failure("timeout", "Ghidra request deadline elapsed", undefined, {
timeoutMs,
}),
);
const response = this.#pending.wait(id, {
timeoutMs,
...(options.signal === undefined ? {} : { signal: options.signal }),
timeoutValue: () =>
err(
this.#failure(
"timeout",
"Ghidra bridge request timed out",
undefined,
{ timeoutMs },
),
),
cancelledValue: () =>
err(this.#failure("cancelled", "Ghidra request was cancelled")),
});
socket.write(
`${JSON.stringify({ id, token, method, params })}\n`,
(cause) => {
if (cause !== undefined && cause !== null)
this.#pending.settle(
id,
err(this.#failure("process", "Ghidra bridge write failed", cause)),
);
},
);
const result = await response;
this.#logger[result.ok ? "debug" : "warn"](
{ method, status: result.ok ? "ok" : "error" },
"Ghidra bridge request completed",
);
return result;
}
#parseSessionInfo(
value: JsonValue,
): Result<GhidraSessionInfo, GhidraSessionError> {
const runId = this.#runId;
if (runId === undefined)
return err(this.#failure("protocol", "Ghidra run identity is missing"));
const parsed = parseGhidraSessionInfo(value, {
runId,
providerVersion: this.#options.providerVersion,
profileDigest: this.#options.profileDigest,
});
return parsed.ok
? parsed
: err(
this.#failure(
"protocol",
"Ghidra bridge handshake is invalid",
parsed.error,
),
);
}
async #close(
starting: Promise<GhidraStartResult> | undefined,
controller: AbortController | undefined,
): Promise<void> {
try {
await starting?.catch(() => undefined);
await this.#cleanup();
} finally {
if (this.#startPromise === starting) this.#startPromise = undefined;
if (this.#startupController === controller)
this.#startupController = undefined;
this.#closePromise = undefined;
}
}
async #cleanup(): Promise<void> {
this.#closing = true;
try {
const socket = this.#socket;
if (socket !== undefined && !socket.destroyed) {
const shutdown = await this.#request(
"shutdown",
{},
{
timeoutMs: SHUTDOWN_TIMEOUT_MS,
},
).catch(() =>
err(this.#failure("process", "Ghidra shutdown request failed")),
);
if (!shutdown.ok || !isGhidraShutdownAcknowledgement(shutdown.value))
this.#logger.warn(
{ status: shutdown.ok ? "invalid-acknowledgement" : "failed" },
"Ghidra bridge shutdown was not confirmed",
);
}
this.#failAll(this.#failure("process", "Ghidra session closed"));
this.#detachSocket?.();
this.#detachSocket = undefined;
socket?.destroy();
this.#socket = undefined;
if (this.#process !== undefined) {
await this.#process.waitForExit(500);
this.#processSnapshot = this.#process.snapshot();
const stopped = await this.#process.stop();
this.#processSnapshot = this.#process.snapshot();
if (stopped.status === "incomplete") {
this.#options.onDiagnostic?.({
type: "cleanup-incomplete",
reason: stopped.reason,
});
this.#logger.warn(
{ reason: stopped.reason },
"Ghidra process cleanup failed closed",
);
}
}
this.#lastDiagnostics = this.#diagnostics();
this.#process = undefined;
this.#launch = undefined;
const runtimeRoot = this.#runtimeRoot;
this.#runtimeRoot = undefined;
await runtimeRoot?.close();
this.#token = undefined;
this.#runId = undefined;
this.#responseBuffer.reset();
} finally {
this.#closing = false;
}
}
#onProcessDiagnostic(event: ProviderProcessDiagnostic): void {
if (event.type === "output") {
this.#options.onDiagnostic?.({
type: "launcher-output",
stream: event.stream,
bytes: event.bytes,
totalBytes: event.totalBytes,
truncated: event.truncated,
});
return;
}
if (event.type === "error") {
this.#logger.warn(
{ message: event.message },
"Ghidra process emitted an error",
);
return;
}
this.#processSnapshot = event.snapshot;
this.#options.onDiagnostic?.({
type: "launcher-exit",
code: event.code,
signal: event.signal,
});
if (!this.#closing)
this.#failAll(this.#failure("process", "Ghidra process exited"));
}
#abortProtocol(message: string, cause?: Error): void {
this.#failAll(this.#failure("protocol", message, cause));
this.#socket?.destroy();
}
#failAll(error: GhidraSessionError): void {
this.#pending.failAll(() => err(error));
}
async #startupInterrupted(
deadline: ProviderStartupDeadline,
): Promise<GhidraStartResult> {
const failure = this.#interruptionFailure(deadline);
await this.#cleanup();
return err(failure);
}
#interruptionFailure(deadline: ProviderStartupDeadline): GhidraSessionError {
return deadline.cancelled
? this.#failure("cancelled", "Ghidra startup was cancelled")
: this.#failure("timeout", "Ghidra startup deadline elapsed", undefined, {
timeoutMs: deadline.timeoutMs,
});
}
#failure(
kind: GhidraSessionError["kind"],
message: string,
cause?: unknown,
options: { readonly timeoutMs?: number } = {},
): GhidraSessionError {
return new GhidraSessionError(kind, message, this.#diagnostics(), {
...(cause === undefined ? {} : { cause }),
...(options.timeoutMs === undefined
? {}
: { timeoutMs: options.timeoutMs }),
});
}
#diagnostics(): Readonly<Record<string, JsonValue>> {
const snapshot = this.#process?.snapshot() ?? this.#processSnapshot;
return createGhidraDiagnostics({
targetPath: this.#options.targetPath,
providerVersion: this.#options.providerVersion,
profileDigest: this.#options.profileDigest,
...(this.#runtimeRoot === undefined
? {}
: { runtimeRoot: this.#runtimeRoot.path }),
...(this.#launch === undefined ? {} : { launch: this.#launch }),
...(snapshot === undefined ? {} : { snapshot }),
...(this.#token === undefined ? {} : { token: this.#token }),
previous: this.#lastDiagnostics,
});
}
}
+36
View File
@@ -0,0 +1,36 @@
import type { Logger } from "../logger.js";
import type { Result } from "../domain/result.js";
import type { GhidraLauncher } from "./GhidraLauncher.js";
import type { GhidraSessionError } from "./GhidraSessionError.js";
import type { GhidraSessionInfo } from "./GhidraSessionValues.js";
/** Result of opening and authenticating one headless Ghidra session. */
export type GhidraStartResult = Result<GhidraSessionInfo, GhidraSessionError>;
/** Safe lifecycle telemetry for one isolated Ghidra headless process. */
export type GhidraDiagnostic =
| {
readonly type: "launcher-output";
readonly stream: "stdout" | "stderr";
readonly bytes: number;
readonly totalBytes: number;
readonly truncated: boolean;
}
| {
readonly type: "launcher-exit";
readonly code: number | null;
readonly signal: NodeJS.Signals | null;
}
| { readonly type: "cleanup-incomplete"; readonly reason: string };
/** Dependencies and exact profile commitment for one headless import. */
export interface GhidraClientOptions {
readonly launcher: GhidraLauncher;
readonly targetPath: string;
readonly providerVersion: string;
readonly profileDigest: string;
readonly requestTimeoutMs?: number;
readonly startupTimeoutMs?: number;
readonly onDiagnostic?: (event: GhidraDiagnostic) => void;
readonly logger?: Logger;
}
+14
View File
@@ -0,0 +1,14 @@
/** Maximum wall-clock analysis time passed to Ghidra for one imported file. */
export const GHIDRA_ANALYSIS_TIMEOUT_SECONDS = 300;
/** Maximum CPU cores made available to one headless analysis. */
export const GHIDRA_MAX_CPU = 2;
/** Explicit JVM heap ceiling for one headless provider process. */
export const GHIDRA_MAX_HEAP = "2G";
/** Absolute import, analysis, bridge, and health startup deadline. */
export const GHIDRA_STARTUP_TIMEOUT_MS = 330_000;
/** Default bounded wait for one established bridge request. */
export const GHIDRA_REQUEST_TIMEOUT_MS = 10_000;
/** Maximum encoded response line accepted from the Java bridge. */
export const GHIDRA_MAX_LINE_BYTES = 1024 * 1024;
/** Version of REA's Java bridge handshake and request protocol. */
export const GHIDRA_BRIDGE_VERSION = 1;
+68
View File
@@ -0,0 +1,68 @@
import type { JsonValue } from "../domain/jsonValue.js";
import type { ProviderProcessSnapshot } from "../process/ProviderProcess.js";
import type { GhidraLaunch } from "./GhidraLauncher.js";
/** Inputs needed to project bounded diagnostics for one Ghidra runtime. */
export interface GhidraDiagnosticsOptions {
readonly targetPath: string;
readonly providerVersion: string;
readonly profileDigest: string;
readonly runtimeRoot?: string;
readonly launch?: GhidraLaunch;
readonly snapshot?: ProviderProcessSnapshot;
readonly token?: string;
readonly previous: Readonly<Record<string, JsonValue>>;
}
/** Preserve actionable runtime coordinates after cleanup and redact bearer data. */
export const createGhidraDiagnostics = (
options: GhidraDiagnosticsOptions,
): Readonly<Record<string, JsonValue>> => {
if (
options.runtimeRoot === undefined &&
options.launch === undefined &&
Object.keys(options.previous).length > 0
)
return options.previous;
const redacted = (value: string): string =>
options.token === undefined
? value
: value.replaceAll(options.token, "[REDACTED]");
return {
target_path: options.targetPath,
provider_version: options.providerVersion,
profile_digest: options.profileDigest,
...(options.runtimeRoot === undefined
? {}
: {
runtime_root: options.runtimeRoot,
socket_path: `${options.runtimeRoot}/bridge.sock`,
}),
...(options.launch === undefined
? {}
: {
project_root: options.launch.projectRoot,
ghidra_log_path: options.launch.ghidraLogPath,
script_log_path: options.launch.scriptLogPath,
process_id: options.launch.process.pid ?? null,
}),
...(options.snapshot === undefined
? {}
: {
exit_code: options.snapshot.exitCode ?? null,
exit_signal: options.snapshot.signal ?? null,
stdout: boundedStream(options.snapshot.stdout, redacted),
stderr: boundedStream(options.snapshot.stderr, redacted),
}),
};
};
const boundedStream = (
stream: ProviderProcessSnapshot["stdout"],
redact: (value: string) => string,
): JsonValue => ({
text: redact(stream.text),
bytes: stream.bytes,
retained_bytes: stream.retainedBytes,
truncated: stream.truncated,
});
+90
View File
@@ -0,0 +1,90 @@
import type {
DoctorProviderCheck,
DoctorProviderInspection,
} from "../application/Doctor.js";
import {
inspectGhidraInstallation,
type GhidraInstallationCheck,
type GhidraInstallationInspection,
} from "./GhidraInstallation.js";
/** Project adapter-owned installation facts into the generic doctor contract. */
export const projectGhidraDoctorInspection = (
inspection: GhidraInstallationInspection,
): DoctorProviderInspection => ({
id: "ghidra",
configured: inspection.installDir !== null,
available: inspection.available,
providerVersion: inspection.providerVersion,
registrationEnvironment:
inspection.available && inspection.installDir !== null
? {
GHIDRA_INSTALL_DIR: inspection.installDir,
...(inspection.javaHome === null
? {}
: { JAVA_HOME: inspection.javaHome }),
}
: {},
checks: selectedChecks(inspection).map((check) =>
projectCheck(check, inspection.installDir !== null),
),
});
/** Inspect the process-configured BYO Ghidra installation for `rea doctor`. */
export const inspectSystemGhidraProvider =
(): Promise<DoctorProviderInspection> =>
Promise.resolve(
projectGhidraDoctorInspection(
inspectGhidraInstallation({
...(process.env.GHIDRA_INSTALL_DIR === undefined
? {}
: { installDir: process.env.GHIDRA_INSTALL_DIR }),
...(process.env.JAVA_HOME === undefined
? {}
: { javaHome: process.env.JAVA_HOME }),
}),
),
);
const selectedChecks = (
inspection: GhidraInstallationInspection,
): readonly GhidraInstallationCheck[] => {
const byName = new Map(
inspection.checks.map((candidate) => [candidate.name, candidate]),
);
const configuration = byName.get("configuration");
if (configuration === undefined) return [];
if (!configuration.ok) return [configuration];
const installation = byName.get("installation");
return [
configuration,
byName.get("platform"),
byName.get("architecture"),
installation,
...(installation?.ok === true
? [byName.get("version"), byName.get("headless")]
: []),
byName.get("java"),
].filter((candidate): candidate is GhidraInstallationCheck =>
Boolean(candidate),
);
};
const projectCheck = (
check: GhidraInstallationCheck,
configured: boolean,
): DoctorProviderCheck => ({
name: check.name,
ok: check.ok,
code: check.code,
detail: check.detail,
remediation: check.remediation,
classification:
check.name === "platform" || check.name === "architecture"
? "unsupported_host"
: check.name === "java" && check.code === "runtime_missing"
? "missing_dependency"
: configured
? "config_drift"
: "missing_analysis_engine",
});
+378
View File
@@ -0,0 +1,378 @@
import { spawnSync } from "node:child_process";
import { constants } from "node:fs";
import { accessSync, readFileSync } from "node:fs";
import { delimiter, join } from "node:path";
import type { ProviderRejectionCode } from "../contracts/providerSelection.js";
import type { JsonValue } from "../domain/jsonValue.js";
/** Exact Ghidra build whose Java bridge contract this REA release supports. */
export const SUPPORTED_GHIDRA_VERSION = "12.1.2";
/** Exact JDK major documented by the supported Ghidra release. */
export const SUPPORTED_GHIDRA_JAVA_MAJOR = 21;
/** Caller-owned paths and host coordinates used for one installation probe. */
export interface GhidraInstallationOptions {
readonly installDir?: string;
readonly javaHome?: string;
readonly platform?: NodeJS.Platform;
readonly architecture?: NodeJS.Architecture;
}
/** One independently actionable part of the supported-installation contract. */
export interface GhidraInstallationCheck {
readonly name:
| "configuration"
| "platform"
| "architecture"
| "installation"
| "version"
| "headless"
| "java";
readonly ok: boolean;
readonly code: ProviderRejectionCode | null;
readonly detail: string;
readonly remediation: string | null;
}
/** Bounded observation of a BYO Ghidra installation and JDK. */
export interface GhidraInstallationInspection {
readonly available: boolean;
readonly platform: NodeJS.Platform;
readonly architecture: NodeJS.Architecture;
readonly installDir: string | null;
readonly analyzeHeadlessPath: string | null;
readonly applicationPropertiesPath: string | null;
readonly providerVersion: string | null;
readonly javaCommand: string;
readonly javaHome: string | null;
readonly javaVersion: string | null;
readonly checks: readonly GhidraInstallationCheck[];
readonly rejectionCode: ProviderRejectionCode | null;
readonly reason: string | null;
}
/** Parsed identity of the JDK selected for Ghidra. */
export interface GhidraJavaObservation {
readonly version: string;
readonly major: number;
readonly home: string;
readonly bits: number;
readonly jdk: boolean;
}
/** Narrow synchronous seam used by provider discovery without launching Ghidra. */
export interface GhidraInstallationHost {
readText(path: string): string | undefined;
executable(path: string): boolean;
probeJava(
command: string,
environment: NodeJS.ProcessEnv,
): GhidraJavaObservation | undefined;
}
interface GhidraInstallationCoordinates {
readonly installDir: string | null;
readonly applicationPropertiesPath: string | null;
readonly analyzeHeadlessPath: string | null;
readonly propertiesAvailable: boolean;
readonly providerVersion: string | null;
readonly javaCommand: string;
readonly java: GhidraJavaObservation | undefined;
}
interface GhidraInstallationCheckContext {
readonly coordinates: GhidraInstallationCoordinates;
readonly platform: NodeJS.Platform;
readonly architecture: NodeJS.Architecture;
readonly javaHome: string | undefined;
readonly host: GhidraInstallationHost;
}
/** Inspect an installation without importing a target or modifying Ghidra. */
export const inspectGhidraInstallation = (
options: GhidraInstallationOptions,
host: GhidraInstallationHost = systemGhidraInstallationHost(),
): GhidraInstallationInspection => {
const platform = options.platform ?? process.platform;
const architecture = options.architecture ?? process.arch;
const coordinates = installationCoordinates(options, host);
const checks = installationChecks({
coordinates,
platform,
architecture,
javaHome: options.javaHome,
host,
});
const failed = checks.find(({ ok }) => !ok);
return {
available: failed === undefined,
platform,
architecture,
installDir: coordinates.installDir,
analyzeHeadlessPath: coordinates.analyzeHeadlessPath,
applicationPropertiesPath: coordinates.applicationPropertiesPath,
providerVersion: coordinates.providerVersion,
javaCommand: coordinates.javaCommand,
javaHome: coordinates.java?.home ?? options.javaHome ?? null,
javaVersion: coordinates.java?.version ?? null,
checks,
rejectionCode: failed?.code ?? null,
reason: failed?.remediation ?? null,
};
};
const installationCoordinates = (
options: GhidraInstallationOptions,
host: GhidraInstallationHost,
): GhidraInstallationCoordinates => {
const installDir = options.installDir ?? null;
const applicationPropertiesPath =
installDir === null
? null
: join(installDir, "Ghidra", "application.properties");
const analyzeHeadlessPath =
installDir === null ? null : join(installDir, "support", "analyzeHeadless");
const properties =
applicationPropertiesPath === null
? undefined
: host.readText(applicationPropertiesPath);
const javaCommand =
options.javaHome === undefined
? "java"
: join(options.javaHome, "bin", "java");
return {
installDir,
applicationPropertiesPath,
analyzeHeadlessPath,
propertiesAvailable: properties !== undefined,
providerVersion:
properties === undefined
? null
: propertyValue(properties, "application.version"),
javaCommand,
java: host.probeJava(javaCommand, ghidraJavaEnvironment(options.javaHome)),
};
};
const installationChecks = ({
coordinates,
platform,
architecture,
javaHome,
host,
}: GhidraInstallationCheckContext): readonly GhidraInstallationCheck[] => [
installationCheck({
name: "configuration",
ok: 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.2 release directory.",
}),
installationCheck({
name: "platform",
ok: platform === "linux",
code: "unsupported_host",
detail: platform,
remediation: "REA's Ghidra v1 adapter currently supports Linux only.",
}),
installationCheck({
name: "architecture",
ok: architecture === "x64",
code: "unsupported_host",
detail: architecture,
remediation:
"Use the official Linux x86-64 Ghidra distribution on an x64 host.",
}),
installationCheck({
name: "installation",
ok: coordinates.propertiesAvailable,
code: "executable_missing",
detail:
coordinates.applicationPropertiesPath ??
"Ghidra application properties unavailable",
remediation:
"Point GHIDRA_INSTALL_DIR at the root of an extracted official Ghidra release.",
}),
installationCheck({
name: "version",
ok: coordinates.providerVersion === SUPPORTED_GHIDRA_VERSION,
code:
coordinates.providerVersion === null
? "version_unresolved"
: "unsupported_version",
detail: coordinates.providerVersion ?? "unknown",
remediation: `Install Ghidra ${SUPPORTED_GHIDRA_VERSION}, or update REA for a different Ghidra build.`,
}),
installationCheck({
name: "headless",
ok:
coordinates.analyzeHeadlessPath !== null &&
host.executable(coordinates.analyzeHeadlessPath),
code: "executable_missing",
detail: coordinates.analyzeHeadlessPath ?? "analyzeHeadless unavailable",
remediation:
"Restore the executable support/analyzeHeadless script from the official Ghidra release.",
}),
javaCheck(coordinates.java, coordinates.javaCommand, javaHome),
];
/** Project an installation probe into caller-visible, secret-free diagnostics. */
export const ghidraInstallationDiagnostics = (
inspection: GhidraInstallationInspection,
): Readonly<Record<string, JsonValue>> => ({
install_dir: inspection.installDir,
analyze_headless_path: inspection.analyzeHeadlessPath,
application_properties_path: inspection.applicationPropertiesPath,
provider_version: inspection.providerVersion,
java_command: inspection.javaCommand,
java_home: inspection.javaHome,
java_version: inspection.javaVersion,
platform: inspection.platform,
architecture: inspection.architecture,
checks: inspection.checks.map((check) => ({
name: check.name,
ok: check.ok,
code: check.code,
detail: check.detail,
})),
});
/** Environment that makes an explicitly selected JDK win over PATH discovery. */
export const ghidraJavaEnvironment = (
javaHome: string | undefined,
environment: NodeJS.ProcessEnv = process.env,
): NodeJS.ProcessEnv => {
const boundedEnvironment = {
...environment,
_JAVA_OPTIONS: "",
JAVA_TOOL_OPTIONS: "",
JDK_JAVA_OPTIONS: "",
GHIDRA_JAVA_OPTIONS: "",
};
return javaHome === undefined
? boundedEnvironment
: {
...boundedEnvironment,
JAVA_HOME: javaHome,
PATH: `${join(javaHome, "bin")}${delimiter}${environment.PATH ?? ""}`,
};
};
const installationCheck = (
options: Omit<GhidraInstallationCheck, "code" | "remediation"> & {
readonly code: ProviderRejectionCode;
readonly remediation: string;
},
): GhidraInstallationCheck => ({
name: options.name,
ok: options.ok,
code: options.ok ? null : options.code,
detail: options.detail,
remediation: options.ok ? null : options.remediation,
});
const javaCheck = (
observation: GhidraJavaObservation | undefined,
command: string,
configuredHome: string | undefined,
): GhidraInstallationCheck => {
const supported =
observation !== undefined &&
observation.major === SUPPORTED_GHIDRA_JAVA_MAJOR &&
observation.bits === 64 &&
observation.jdk;
const detail =
observation === undefined
? command
: `${observation.version}; ${String(observation.bits)}-bit; ${observation.jdk ? "JDK" : "runtime only"}; ${observation.home}`;
return installationCheck({
name: "java",
ok: supported,
code: 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.",
});
};
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 systemGhidraInstallationHost = (): GhidraInstallationHost => ({
readText(path) {
try {
return readFileSync(path, "utf8");
} catch {
return undefined;
}
},
executable(path) {
try {
accessSync(path, constants.X_OK);
return true;
} catch {
return false;
}
},
probeJava(command, environment) {
const observed = spawnSync(
command,
["-XshowSettings:properties", "-version"],
{
encoding: "utf8",
env: environment,
timeout: 5_000,
maxBuffer: 128 * 1024,
windowsHide: true,
},
);
if (observed.error !== undefined || observed.status !== 0) return undefined;
const output = `${observed.stdout ?? ""}\n${observed.stderr ?? ""}`;
const version = javaProperty(output, "java.version");
const home = javaProperty(output, "java.home");
const bits = Number.parseInt(
javaProperty(output, "sun.arch.data.model") ?? "0",
10,
);
if (version === null || home === null) return undefined;
return {
version,
major: javaMajor(version),
home,
bits,
jdk: executablePath(join(home, "bin", "javac")),
};
},
});
const executablePath = (path: string): boolean => {
try {
accessSync(path, constants.X_OK);
return true;
} catch {
return false;
}
};
const javaProperty = (output: string, name: string): string | null =>
new RegExp(
`^\\s*${name.replaceAll(".", "\\.")}\\s*=\\s*(.+?)\\s*$`,
"mu",
).exec(output)?.[1] ?? null;
const javaMajor = (version: string): number => {
const first = Number.parseInt(version.split(".")[0] ?? "0", 10);
if (first !== 1) return first;
return Number.parseInt(version.split(".")[1] ?? "0", 10);
};
+217
View File
@@ -0,0 +1,217 @@
import { mkdir } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import writeFileAtomic from "write-file-atomic";
import { AnalysisCancelledError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
import {
type ProviderProcessLaunch,
type SpawnedOwnedProviderProcess,
spawnOwnedProviderProcess,
} from "../process/ProviderProcess.js";
import {
GHIDRA_ANALYSIS_TIMEOUT_SECONDS,
GHIDRA_MAX_CPU,
GHIDRA_MAX_HEAP,
} from "./GhidraDefaults.js";
import { ghidraJavaEnvironment } from "./GhidraInstallation.js";
/** Private paths and identity material for one headless Ghidra import. */
export interface GhidraLaunchSession {
readonly runtimeRoot: string;
readonly socketPath: string;
readonly token: string;
readonly runId: string;
readonly targetPath: string;
readonly providerVersion: string;
readonly profileDigest: string;
}
/** Process plus private log coordinates returned by a Ghidra launcher. */
export interface GhidraLaunch extends ProviderProcessLaunch {
readonly projectRoot: string;
readonly ghidraLogPath: string;
readonly scriptLogPath: string;
}
/** Provider-owned capability that starts one isolated headless analysis. */
export interface GhidraLauncher {
launch(
session: GhidraLaunchSession,
options?: { readonly signal?: AbortSignal },
): Promise<Result<GhidraLaunch, GhidraLaunchError | AnalysisCancelledError>>;
}
/** Local launch failure retained as the cause of a provider-neutral error. */
export class GhidraLaunchError extends Error {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = "GhidraLaunchError";
}
}
/** Static coordinates for an extracted Ghidra release and packaged script. */
export interface GhidraHeadlessLauncherOptions {
readonly analyzeHeadlessPath: string;
readonly javaHome?: string;
readonly bridgeScriptPath: string;
}
/** Launch Ghidra without copying scripts into or modifying its installation. */
export class GhidraHeadlessLauncher implements GhidraLauncher {
constructor(readonly options: GhidraHeadlessLauncherOptions) {}
async launch(
session: GhidraLaunchSession,
options: { readonly signal?: AbortSignal } = {},
): Promise<Result<GhidraLaunch, GhidraLaunchError | AnalysisCancelledError>> {
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const paths = ghidraRuntimePaths(session.runtimeRoot);
let started: SpawnedOwnedProviderProcess | undefined;
try {
await Promise.all(
[
paths.projectRoot,
paths.homeRoot,
paths.tempRoot,
paths.cacheRoot,
paths.configRoot,
paths.dataRoot,
].map((path) => mkdir(path, { recursive: true, mode: 0o700 })),
);
await writeFileAtomic(
paths.descriptorPath,
`${JSON.stringify({
schema_version: 1,
socket_path: session.socketPath,
token: session.token,
run_id: session.runId,
provider_version: session.providerVersion,
profile_digest: session.profileDigest,
})}\n`,
{ encoding: "utf8", mode: 0o600 },
);
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
started = await spawnOwnedProviderProcess({
command: this.options.analyzeHeadlessPath,
arguments: ghidraHeadlessArguments({
projectRoot: paths.projectRoot,
targetPath: session.targetPath,
bridgeScriptPath: this.options.bridgeScriptPath,
descriptorPath: paths.descriptorPath,
ghidraLogPath: paths.ghidraLogPath,
scriptLogPath: paths.scriptLogPath,
}),
runId: session.runId,
// analyzeHeadless is an interpreter-driven script. Parent identity and
// the per-process run token remain the cleanup authority.
expectedCommand: null,
env: ghidraLaunchEnvironment(paths, this.options.javaHome),
});
await writeFileAtomic(
paths.ownershipPath,
`${JSON.stringify({
schema_version: 1,
run_id: session.runId,
pid: started.ownership.leaderPid,
process_group_id: started.ownership.processGroupId,
parent_pid: process.pid,
launcher: this.options.analyzeHeadlessPath,
created_at: new Date().toISOString(),
})}\n`,
{ encoding: "utf8", mode: 0o600 },
);
if (isAborted(options.signal)) {
await cleanupOwnedProcessGroup(started.ownership);
return err(new AnalysisCancelledError("open_binary"));
}
const ownership = started.ownership;
return ok({
process: started.process,
ownsProcessLifetime: true,
cleanup: () => cleanupOwnedProcessGroup(ownership),
projectRoot: paths.projectRoot,
ghidraLogPath: paths.ghidraLogPath,
scriptLogPath: paths.scriptLogPath,
});
} catch (cause: unknown) {
if (started !== undefined)
await cleanupOwnedProcessGroup(started.ownership).catch(
() => undefined,
);
return isAborted(options.signal)
? err(new AnalysisCancelledError("open_binary"))
: err(
new GhidraLaunchError("Ghidra headless launch failed", { cause }),
);
}
}
}
/** Paths encoded into one bounded analyzeHeadless invocation. */
export interface GhidraHeadlessArgumentOptions {
readonly projectRoot: string;
readonly targetPath: string;
readonly bridgeScriptPath: string;
readonly descriptorPath: string;
readonly ghidraLogPath: string;
readonly scriptLogPath: string;
}
/** Build the complete read-only headless invocation in deterministic order. */
export const ghidraHeadlessArguments = (
options: GhidraHeadlessArgumentOptions,
): readonly string[] => [
options.projectRoot,
"rea-project",
"-import",
options.targetPath,
"-readOnly",
"-deleteProject",
"-analysisTimeoutPerFile",
String(GHIDRA_ANALYSIS_TIMEOUT_SECONDS),
"-max-cpu",
String(GHIDRA_MAX_CPU),
"-log",
options.ghidraLogPath,
"-scriptlog",
options.scriptLogPath,
"-scriptPath",
dirname(options.bridgeScriptPath),
"-postScript",
basename(options.bridgeScriptPath),
options.descriptorPath,
];
const ghidraRuntimePaths = (runtimeRoot: string) => ({
projectRoot: join(runtimeRoot, "project"),
homeRoot: join(runtimeRoot, "home"),
tempRoot: join(runtimeRoot, "tmp"),
cacheRoot: join(runtimeRoot, "cache"),
configRoot: join(runtimeRoot, "config"),
dataRoot: join(runtimeRoot, "data"),
descriptorPath: join(runtimeRoot, "session.json"),
ownershipPath: join(runtimeRoot, "ownership.json"),
ghidraLogPath: join(runtimeRoot, "ghidra.log"),
scriptLogPath: join(runtimeRoot, "script.log"),
});
const ghidraLaunchEnvironment = (
paths: ReturnType<typeof ghidraRuntimePaths>,
javaHome: string | undefined,
): NodeJS.ProcessEnv => ({
...ghidraJavaEnvironment(javaHome),
HOME: paths.homeRoot,
TMPDIR: paths.tempRoot,
XDG_CACHE_HOME: paths.cacheRoot,
XDG_CONFIG_HOME: paths.configRoot,
XDG_DATA_HOME: paths.dataRoot,
GHIDRA_HEADLESS_MAXMEM: GHIDRA_MAX_HEAP,
GHIDRA_HEADLESS_JAVA_OPTIONS: `-Duser.home=${paths.homeRoot} -Djava.io.tmpdir=${paths.tempRoot}`,
});
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
+275
View File
@@ -0,0 +1,275 @@
import { fileURLToPath } from "node:url";
import {
createAnalysisExecution,
type AnalysisClient,
type AnalysisOperation,
type AnalysisProfileResolutionOptions,
type AnalysisProviderCandidate,
type CapabilityDescriptor,
type ProviderAvailability,
type ProviderIdentity,
type ProviderTargetSupport,
} from "../application/AnalysisProvider.js";
import type { AppConfig } from "../config.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
type AnalysisError,
AnalysisTimeoutError,
ProviderAdapterError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { Logger } from "../logger.js";
import { GhidraClient } from "./GhidraClient.js";
import {
GHIDRA_ANALYSIS_TIMEOUT_SECONDS,
GHIDRA_STARTUP_TIMEOUT_MS,
} from "./GhidraDefaults.js";
import {
ghidraInstallationDiagnostics,
inspectGhidraInstallation,
type GhidraInstallationHost,
type GhidraInstallationInspection,
} from "./GhidraInstallation.js";
import { GhidraHeadlessLauncher } from "./GhidraLauncher.js";
import { resolveGhidraAnalysisProfile } from "./GhidraAnalysisProfile.js";
import type { GhidraSessionError } from "./GhidraSessionError.js";
/** Public identity committed by every Ghidra-backed observation. */
export const GHIDRA_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
id: "ghidra",
name: "Ghidra",
version: null,
});
/** PR07 intentionally exposes session health but no binary operation contract. */
export const GHIDRA_PROVIDER_TOOL_CONTRACTS: readonly CapabilityDescriptor[] =
Object.freeze([]);
const SUPPORTED_ARCHITECTURES = new Set(["x86", "x86_64", "arm", "arm64"]);
const SUPPORTED_FORMATS = new Set(["elf", "pe", "mach-o"]);
/** Linux Ghidra candidate backed by an isolated read-only headless import. */
export class GhidraProvider implements AnalysisProviderCandidate {
#installation: GhidraInstallationInspection | undefined;
constructor(
private readonly config: AppConfig,
private readonly logger: Logger,
private readonly installationHost?: GhidraInstallationHost,
) {}
identity(): ProviderIdentity {
return GHIDRA_PROVIDER_IDENTITY;
}
capabilities(): readonly CapabilityDescriptor[] {
return GHIDRA_PROVIDER_TOOL_CONTRACTS;
}
inspectAvailability(): ProviderAvailability {
const installation = this.#inspectInstallation();
const diagnostics = ghidraInstallationDiagnostics(installation);
return installation.available
? {
status: "available",
code: null,
reason: null,
diagnostics,
}
: {
status: "unavailable",
code: installation.rejectionCode ?? "not_configured",
reason:
installation.reason ?? "Ghidra installation is not available.",
diagnostics,
};
}
inspectTargetSupport(target: BinaryTarget): ProviderTargetSupport {
const diagnostics = {
target_kind: target.kind,
target_format: target.format,
architecture: target.architecture ?? null,
};
if (target.kind !== "executable")
return {
status: "unsupported",
code: "target_kind_unsupported",
reason: `Ghidra v1 imports executable targets, not ${target.kind} targets.`,
diagnostics,
};
if (!SUPPORTED_FORMATS.has(target.format))
return {
status: "unsupported",
code: "target_format_unsupported",
reason: `Ghidra v1 does not import ${target.format} through this adapter.`,
diagnostics,
};
if (
target.architecture === undefined ||
!SUPPORTED_ARCHITECTURES.has(target.architecture)
)
return {
status: "unsupported",
code: "architecture_unsupported",
reason:
"Ghidra v1 requires a concrete x86, x86_64, arm, or arm64 target architecture.",
diagnostics,
};
return {
status: "supported",
code: null,
reason: null,
diagnostics,
};
}
resolveAnalysisProfile(
target: BinaryTarget,
options?: AnalysisProfileResolutionOptions,
) {
return resolveGhidraAnalysisProfile(
target,
GHIDRA_PROVIDER_IDENTITY,
this.#inspectInstallation(),
options?.signal,
);
}
createClient(
target: BinaryTarget,
profile?: AnalysisProfileCommitment,
): AnalysisClient {
const installation = this.#inspectInstallation();
const prerequisites = ghidraClientPrerequisites(
target,
profile,
installation,
);
if (!prerequisites.ok) return unavailableClient(prerequisites.error);
const committedProfile = prerequisites.value.profile;
const client = new GhidraClient({
launcher: new GhidraHeadlessLauncher({
analyzeHeadlessPath: prerequisites.value.analyzeHeadlessPath,
...(this.config.ghidraJavaHome === undefined
? {}
: { javaHome: this.config.ghidraJavaHome }),
bridgeScriptPath: fileURLToPath(
new URL("../../bridge/ghidra/ReaGhidraBridge.java", import.meta.url),
),
}),
targetPath: target.path,
providerVersion: prerequisites.value.providerVersion,
profileDigest: committedProfile.digest,
logger: this.logger.child({ layer: "ghidra-bridge" }),
});
return {
execute: async (operation, _parameters, options) => {
if (operation !== "health")
return err(
new AnalysisCapabilityUnavailableError(
GHIDRA_PROVIDER_IDENTITY.id,
operation,
"Ghidra binary operations are not declared by this adapter release.",
),
);
const started = await client.start(options?.signal);
if (!started.ok)
return err(projectSessionError(operation, started.error));
return ok(
createAnalysisExecution(started.value, committedProfile.provider, {
analysisProfile: committedProfile,
limitations: [
"The session proves completed default Ghidra auto-analysis but exposes no binary operations in this release.",
"The imported program and project are ephemeral and externally read-only.",
],
}),
);
},
close: () => client.close(),
};
}
#inspectInstallation(): GhidraInstallationInspection {
const options = {
...(this.config.ghidraInstallDir === undefined
? {}
: { installDir: this.config.ghidraInstallDir }),
...(this.config.ghidraJavaHome === undefined
? {}
: { javaHome: this.config.ghidraJavaHome }),
};
this.#installation ??=
this.installationHost === undefined
? inspectGhidraInstallation(options)
: inspectGhidraInstallation(options, this.installationHost);
return this.#installation;
}
}
interface GhidraClientCoordinates {
readonly analyzeHeadlessPath: string;
readonly providerVersion: string;
readonly profile: AnalysisProfileCommitment;
}
const ghidraClientPrerequisites = (
target: BinaryTarget,
profile: AnalysisProfileCommitment | undefined,
installation: GhidraInstallationInspection,
): Result<GhidraClientCoordinates, AnalysisError> => {
if (target.kind !== "executable")
return err(
new AnalysisCapabilityUnavailableError(
"ghidra",
"health",
`Ghidra cannot import ${target.kind} targets through this adapter.`,
),
);
if (
!installation.available ||
installation.analyzeHeadlessPath === null ||
installation.providerVersion === null
)
return err(
new ProviderAdapterError("ghidra", "health", {
diagnostics: ghidraInstallationDiagnostics(installation),
}),
);
if (profile === undefined || profile.provider.id !== "ghidra")
return err(new ProviderAdapterError("ghidra", "health"));
return ok({
analyzeHeadlessPath: installation.analyzeHeadlessPath,
providerVersion: installation.providerVersion,
profile,
});
};
const unavailableClient = (failure: AnalysisError): AnalysisClient => ({
execute: () => Promise.resolve(err(failure)),
close: () => Promise.resolve(),
});
const projectSessionError = (
operation: AnalysisOperation,
failure: GhidraSessionError,
): AnalysisError => {
if (failure.kind === "cancelled")
return new AnalysisCancelledError(operation);
if (failure.kind === "timeout" || failure.kind === "analysis_timeout")
return new AnalysisTimeoutError(
operation,
failure.timeoutMs ??
(failure.kind === "analysis_timeout"
? GHIDRA_ANALYSIS_TIMEOUT_SECONDS * 1_000
: GHIDRA_STARTUP_TIMEOUT_MS),
);
return new ProviderAdapterError("ghidra", operation, {
cause: failure,
diagnostics: failure.diagnostics,
});
};
+42
View File
@@ -0,0 +1,42 @@
/** Callbacks for one bounded newline-delimited Ghidra response stream. */
export interface GhidraResponseBufferOptions {
readonly maxLineBytes: number;
readonly onLine: (line: string) => void;
readonly onFailure: (message: string) => void;
}
/** Splits fragmented UTF-8 socket data while enforcing a byte limit per line. */
export class GhidraResponseBuffer {
readonly #options: GhidraResponseBufferOptions;
#buffer = "";
constructor(options: GhidraResponseBufferOptions) {
this.#options = options;
}
/** Consume one decoded socket chunk. */
push(chunk: string): void {
this.#buffer += chunk;
let newline = this.#buffer.indexOf("\n");
while (newline >= 0) {
const encodedLine = this.#buffer.slice(0, newline);
this.#buffer = this.#buffer.slice(newline + 1);
if (Buffer.byteLength(encodedLine) > this.#options.maxLineBytes) {
this.#options.onFailure(
"Ghidra response exceeded the maximum line size",
);
return;
}
const line = encodedLine.trim();
if (line.length > 0) this.#options.onLine(line);
newline = this.#buffer.indexOf("\n");
}
if (Buffer.byteLength(this.#buffer) > this.#options.maxLineBytes)
this.#options.onFailure("Ghidra response exceeded the maximum line size");
}
/** Drop any incomplete line when a session closes. */
reset(): void {
this.#buffer = "";
}
}
+46
View File
@@ -0,0 +1,46 @@
import type { JsonValue } from "../domain/jsonValue.js";
import { err, type Result } from "../domain/result.js";
import type { PendingOperations } from "../process/PendingOperations.js";
import type { GhidraSessionError } from "./GhidraSessionError.js";
import { ghidraResponseResult, parseGhidraResponseLine } from "./protocol.js";
/** Dependencies for correlating validated bridge responses. */
export interface GhidraResponseRouterOptions {
readonly pending: PendingOperations<
number,
Result<JsonValue, GhidraSessionError>
>;
readonly nextId: () => number;
readonly remoteFailure: (message: string, cause: Error) => GhidraSessionError;
readonly protocolFailure: (message: string, cause?: Error) => void;
}
/** Routes validated response IDs without giving the wire protocol client state. */
export class GhidraResponseRouter {
readonly #options: GhidraResponseRouterOptions;
constructor(options: GhidraResponseRouterOptions) {
this.#options = options;
}
/** Parse and settle one complete response line. */
route(line: string): void {
const parsed = parseGhidraResponseLine(line);
if (!parsed.ok) {
this.#options.protocolFailure(parsed.error.message, parsed.error);
return;
}
if (!this.#options.pending.has(parsed.value.id)) {
if (parsed.value.id >= this.#options.nextId())
this.#options.protocolFailure("Ghidra returned an unknown response id");
return;
}
const result = ghidraResponseResult(parsed.value);
this.#options.pending.settle(
parsed.value.id,
result.ok
? result
: err(this.#options.remoteFailure(result.error.message, result.error)),
);
}
}
+34
View File
@@ -0,0 +1,34 @@
import type { JsonValue } from "../domain/jsonValue.js";
/** Stable failure phase for one private Ghidra headless session. */
export type GhidraSessionFailureKind =
| "cancelled"
| "timeout"
| "start"
| "process"
| "protocol"
| "remote"
| "analysis_timeout";
/** Additional structured context for a Ghidra session failure. */
export interface GhidraSessionErrorOptions extends ErrorOptions {
readonly timeoutMs?: number;
}
/** Provider-owned failure with bounded, token-redacted local diagnostics. */
export class GhidraSessionError extends Error {
readonly diagnostics: Readonly<Record<string, JsonValue>>;
readonly timeoutMs: number | undefined;
constructor(
readonly kind: GhidraSessionFailureKind,
message: string,
diagnostics: Readonly<Record<string, JsonValue>> = {},
options: GhidraSessionErrorOptions = {},
) {
super(message, options);
this.name = "GhidraSessionError";
this.diagnostics = structuredClone(diagnostics);
this.timeoutMs = options.timeoutMs;
}
}
+66
View File
@@ -0,0 +1,66 @@
import { z } from "zod";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { GHIDRA_BRIDGE_VERSION } from "./GhidraDefaults.js";
const sessionInfoSchema = z
.object({
name: z.literal("REA Ghidra bridge"),
bridge_version: z.literal(GHIDRA_BRIDGE_VERSION),
run_id: z.string().uuid(),
profile_digest: z.string().regex(/^[a-f0-9]{64}$/u),
provider: z
.object({
id: z.literal("ghidra"),
version: z.string().min(1),
})
.strict(),
read_only: z.literal(true),
analysis_complete: z.boolean(),
analysis_timed_out: z.boolean(),
capabilities: z.array(z.enum(["ping", "shutdown"])).max(2),
target: z
.object({
name: z.string().min(1),
language_id: z.string().min(1),
compiler_spec_id: z.string().min(1),
})
.strict(),
})
.strict();
/** Authenticated metadata produced after Ghidra finishes auto-analysis. */
export type GhidraSessionInfo = z.infer<typeof sessionInfoSchema>;
/** Require exact run, provider, and profile identity from the Java bridge. */
export const parseGhidraSessionInfo = (
value: JsonValue,
expected: {
readonly runId: string;
readonly providerVersion: string;
readonly profileDigest: string;
},
): Result<GhidraSessionInfo, Error> => {
const parsed = sessionInfoSchema.safeParse(value);
if (
!parsed.success ||
parsed.data.run_id !== expected.runId ||
parsed.data.provider.version !== expected.providerVersion ||
parsed.data.profile_digest !== expected.profileDigest ||
new Set(parsed.data.capabilities).size !== 2 ||
!parsed.data.capabilities.includes("ping") ||
!parsed.data.capabilities.includes("shutdown") ||
parsed.data.analysis_complete === parsed.data.analysis_timed_out
)
return err(new Error("Ghidra bridge handshake identity is invalid"));
return ok(parsed.data);
};
/** Require acknowledgement that the private bridge loop has ended. */
export const isGhidraShutdownAcknowledgement = (value: JsonValue): boolean =>
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
value.shutdown === true &&
value.project_ephemeral === true;
+74
View File
@@ -0,0 +1,74 @@
import { createConnection, type Socket } from "node:net";
import { err, ok, type Result } from "../domain/result.js";
import { GhidraSessionError } from "./GhidraSessionError.js";
/** Stable listeners attached for the lifetime of one bridge socket. */
export interface GhidraSocketHandlers {
readonly data: (chunk: string) => void;
readonly error: () => void;
readonly close: () => void;
}
/** Attach decoded bridge listeners and return an idempotent detach callback. */
export const attachGhidraSocket = (
socket: Socket,
handlers: GhidraSocketHandlers,
): (() => void) => {
socket.setEncoding("utf8");
socket.on("data", handlers.data);
socket.on("error", handlers.error);
socket.on("close", handlers.close);
return () => {
socket.off("data", handlers.data);
socket.off("error", handlers.error);
socket.off("close", handlers.close);
};
};
/** Open one abort-aware Ghidra Unix-socket connection attempt. */
export const connectGhidraSocketOnce = (
socketPath: string,
signal: AbortSignal,
): Promise<Result<Socket, GhidraSessionError>> =>
new Promise((resolve) => {
const socket = createConnection(socketPath);
const detach = (): void => {
socket.off("connect", onConnect);
socket.off("error", onError);
signal.removeEventListener("abort", onAbort);
};
const onConnect = (): void => {
detach();
resolve(ok(socket));
};
const onError = (cause: Error): void => {
detach();
socket.destroy();
resolve(
err(
new GhidraSessionError("start", "Ghidra bridge connection failed", {
socket_path: socketPath,
error: cause.message,
}),
),
);
};
const onAbort = (): void => {
detach();
socket.destroy();
resolve(
err(
new GhidraSessionError(
"cancelled",
"Ghidra bridge connection was cancelled",
{ socket_path: socketPath },
),
),
);
};
socket.once("connect", onConnect);
socket.once("error", onError);
signal.addEventListener("abort", onAbort, { once: true });
if (signal.aborted) onAbort();
});
+77
View File
@@ -0,0 +1,77 @@
import { z } from "zod";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
const responseSchema = z
.object({
id: z.number().int().positive(),
ok: z.boolean(),
result: jsonValueSchema.optional(),
error: z
.object({
code: z.string().min(1).max(128),
message: z.string().min(1).max(4_096),
})
.strict()
.optional(),
})
.strict()
.superRefine((value, context) => {
if (value.ok && value.result === undefined)
context.addIssue({
code: "custom",
path: ["result"],
message: "Successful Ghidra response requires a result",
});
if (!value.ok && value.error === undefined)
context.addIssue({
code: "custom",
path: ["error"],
message: "Failed Ghidra response requires an error",
});
if (!value.ok && value.result !== undefined)
context.addIssue({
code: "custom",
path: ["result"],
message: "Failed Ghidra response cannot include a result",
});
if (value.ok && value.error !== undefined)
context.addIssue({
code: "custom",
path: ["error"],
message: "Successful Ghidra response cannot include an error",
});
});
/** Validated response emitted by REA's packaged Ghidra script. */
export type GhidraBridgeResponse = z.infer<typeof responseSchema>;
/** Parse one complete Java-bridge response without accepting extra fields. */
export const parseGhidraResponseLine = (
line: string,
): Result<GhidraBridgeResponse, Error> => {
try {
const parsed: unknown = JSON.parse(line);
const response = responseSchema.safeParse(parsed);
return response.success
? ok(response.data)
: err(new Error("Ghidra bridge response has an invalid shape"));
} catch (cause: unknown) {
return err(
new Error("Ghidra bridge response is not valid JSON", { cause }),
);
}
};
/** Project one validated response into its result or remote failure. */
export const ghidraResponseResult = (
response: GhidraBridgeResponse,
): Result<JsonValue, Error> =>
response.ok
? ok(response.result ?? null)
: err(
new Error(
`${response.error?.code ?? "bridge_error"}: ${response.error?.message ?? "Ghidra bridge request failed"}`,
),
);
+5 -2
View File
@@ -15,7 +15,8 @@ export interface OwnedProviderProcessSpawnOptions {
readonly command: string;
readonly arguments: readonly string[];
readonly runId: string;
readonly expectedCommand?: string;
/** Null disables argv-prefix matching for interpreter-driven launch scripts. */
readonly expectedCommand?: string | null;
readonly cwd?: string;
readonly env?: NodeJS.ProcessEnv;
}
@@ -120,8 +121,10 @@ export const spawnOwnedProviderProcess = async (
runId: options.runId,
leaderPid: pid,
processGroupId: pid,
expectedCommand: options.expectedCommand ?? options.command,
expectedParentPid: process.pid,
...(options.expectedCommand === null
? {}
: { expectedCommand: options.expectedCommand ?? options.command }),
};
return { process: child, ownership };
};