refactor(adapters): split oversized provider workflows
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
export function sourceMapSummary(sourceMaps) {
|
||||
return {
|
||||
status: sourceMaps.status,
|
||||
requested: sourceMaps.requested,
|
||||
processed: sourceMaps.processed,
|
||||
dropped: sourceMaps.dropped,
|
||||
items: sourceMaps.items.map((item) => ({
|
||||
status: item.status,
|
||||
declaredUrl: item.declared_url,
|
||||
sources: item.original_sources.map(({ source }) => source),
|
||||
edgeSpecifiers: item.original_module_edges.map(({ specifier }) =>
|
||||
specifier.slice(0, 256),
|
||||
),
|
||||
mappings: item.mappings.length,
|
||||
limitation: item.limitation,
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { names } from "./catalog-core.mjs";
|
||||
|
||||
/** Build tool-family counts and sorted tool-name lists. */
|
||||
export const toolFamilyCatalog = (sources) => {
|
||||
const families = [
|
||||
{
|
||||
id: "direct",
|
||||
surface: "official-proxy",
|
||||
contracts: sources.toolContracts.OFFICIAL_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "enhanced",
|
||||
surface: "enhanced",
|
||||
contracts: sources.toolContracts.ENHANCED_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "native",
|
||||
surface: "native-provider",
|
||||
contracts: sources.nativeContracts.NATIVE_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "artifact",
|
||||
surface: "artifact-provider",
|
||||
contracts: sources.artifactContracts.ARTIFACT_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "managed",
|
||||
surface: "managed",
|
||||
contracts: [
|
||||
...sources.managedContracts.MANAGED_TOOL_CONTRACTS,
|
||||
...sources.managedWorkflowContracts.MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "browser",
|
||||
surface: "browser-provider",
|
||||
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "electron",
|
||||
surface: "electron-provider",
|
||||
contracts: sources.electronContracts.ELECTRON_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "application",
|
||||
surface: "application-workflow",
|
||||
contracts: sources.applicationContracts.APPLICATION_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "session",
|
||||
surface: "session",
|
||||
contracts: sources.toolContracts.SESSION_TOOL_CONTRACTS,
|
||||
},
|
||||
].map(({ id, surface, contracts }) => ({
|
||||
id,
|
||||
surface,
|
||||
count: contracts.length,
|
||||
tools: names(contracts),
|
||||
}));
|
||||
const familyTotal = families.reduce(
|
||||
(total, family) => total + family.count,
|
||||
0,
|
||||
);
|
||||
if (
|
||||
familyTotal !== sources.toolContracts.TOOL_CONTRACTS.length ||
|
||||
familyTotal !== sources.catalogIdentity.CATALOG_IDENTITY.counts.mcp_tools
|
||||
)
|
||||
throw new Error("Tool family inventory does not match TOOL_CONTRACTS");
|
||||
return { total: familyTotal, families };
|
||||
};
|
||||
|
||||
/** Build provider identities with their sorted capability names. */
|
||||
export const providerCatalog = (sources) => {
|
||||
const applicationContracts =
|
||||
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
|
||||
({ name }) => name === "analyze_javascript_application",
|
||||
);
|
||||
const reconciliationContracts =
|
||||
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
|
||||
({ name }) => name === "reconcile_javascript_runtime",
|
||||
);
|
||||
const observationContracts =
|
||||
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
|
||||
({ name }) =>
|
||||
name !== "analyze_javascript_application" &&
|
||||
name !== "reconcile_javascript_runtime",
|
||||
);
|
||||
if (
|
||||
applicationContracts.length !== 1 ||
|
||||
reconciliationContracts.length !== 1 ||
|
||||
observationContracts.length !== 2
|
||||
)
|
||||
throw new Error("Electron provider capability ownership drifted");
|
||||
return [
|
||||
{
|
||||
identity: sources.hopperProvider.HOPPER_PROVIDER_IDENTITY,
|
||||
contracts: sources.hopperProvider.HOPPER_PROVIDER_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.ghidraProvider.GHIDRA_PROVIDER_IDENTITY,
|
||||
contracts: sources.ghidraProvider.GHIDRA_PROVIDER_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.nativeProvider.NATIVE_MACOS_PROVIDER_IDENTITY,
|
||||
contracts: sources.nativeContracts.NATIVE_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.artifactProviders.ARTIFACT_GRAPH_PROVIDER,
|
||||
contracts: sources.artifactContracts.ARTIFACT_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.artifactProviders.MANAGED_STATIC_PROVIDER,
|
||||
contracts: sources.managedContracts.MANAGED_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.artifactProviders.MANAGED_WORKFLOW_PROVIDER,
|
||||
contracts:
|
||||
sources.managedWorkflowContracts.MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.browserProvider.CDP_BROWSER_PROVIDER_IDENTITY,
|
||||
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.electronProvider.CDP_ELECTRON_PROVIDER_IDENTITY,
|
||||
contracts: observationContracts,
|
||||
},
|
||||
{
|
||||
identity: sources.artifactProviders.JAVASCRIPT_APPLICATION_PROVIDER,
|
||||
contracts: applicationContracts,
|
||||
},
|
||||
{
|
||||
identity:
|
||||
sources.artifactProviders.JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
|
||||
contracts: reconciliationContracts,
|
||||
},
|
||||
{
|
||||
identity:
|
||||
sources.artifactProviders.JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER,
|
||||
contracts: sources.applicationContracts.APPLICATION_TOOL_CONTRACTS,
|
||||
},
|
||||
]
|
||||
.map(({ identity, contracts }) => ({
|
||||
id: identity.id,
|
||||
name: identity.name,
|
||||
version: identity.version,
|
||||
capabilities: names(contracts),
|
||||
}))
|
||||
.sort((left, right) => left.id.localeCompare(right.id));
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Cli } from "incur";
|
||||
import { z } from "zod";
|
||||
|
||||
/** Read primary names and aliases from the actual Incur command router. */
|
||||
export const createCliInventory = (cli) => {
|
||||
const commands = Cli.toCommands.get(cli);
|
||||
if (commands === undefined)
|
||||
throw new Error("Incur did not expose the registered REA CLI commands");
|
||||
const primary = [];
|
||||
const aliases = [];
|
||||
for (const [name, entry] of commands) {
|
||||
if ("_alias" in entry) aliases.push({ name, target: entry.target });
|
||||
else primary.push(name);
|
||||
}
|
||||
return {
|
||||
primary: primary.sort((left, right) => left.localeCompare(right)),
|
||||
aliases: aliases.sort((left, right) => left.name.localeCompare(right.name)),
|
||||
};
|
||||
};
|
||||
|
||||
/** Read one primary command's declared option names from the Incur router. */
|
||||
export const cliCommandOptionNames = (cli, name) => {
|
||||
const commands = Cli.toCommands.get(cli);
|
||||
const command = commands?.get(name);
|
||||
if (
|
||||
command === undefined ||
|
||||
"_alias" in command ||
|
||||
!("options" in command) ||
|
||||
command.options === undefined
|
||||
)
|
||||
return [];
|
||||
const schema = z.toJSONSchema(command.options);
|
||||
return Object.keys(schema.properties ?? {}).sort((left, right) =>
|
||||
left.localeCompare(right),
|
||||
);
|
||||
};
|
||||
|
||||
/** Report primary CLI fields whose generated JSON Schema lacks help text. */
|
||||
export const cliCommandDescriptionIssues = (cli) => {
|
||||
const commands = Cli.toCommands.get(cli);
|
||||
if (commands === undefined)
|
||||
throw new Error("Incur did not expose the registered REA CLI commands");
|
||||
const missing = [];
|
||||
for (const [commandName, command] of commands) {
|
||||
if ("_alias" in command) continue;
|
||||
for (const groupName of ["args", "options"]) {
|
||||
if (!(groupName in command) || command[groupName] === undefined) continue;
|
||||
const properties = z.toJSONSchema(command[groupName]).properties ?? {};
|
||||
for (const [propertyName, property] of Object.entries(properties)) {
|
||||
if (
|
||||
typeof property !== "object" ||
|
||||
property === null ||
|
||||
typeof property.description !== "string" ||
|
||||
property.description.trim() === ""
|
||||
)
|
||||
missing.push(`${commandName}.${groupName}.${propertyName}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return missing;
|
||||
};
|
||||
@@ -0,0 +1,78 @@
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
const load = (root, path) => import(pathToFileURL(join(root, path)).href);
|
||||
|
||||
/** Sort tool/provider names alphabetically. */
|
||||
export const names = (contracts) =>
|
||||
contracts
|
||||
.map(({ name }) => name)
|
||||
.sort((left, right) => left.localeCompare(right));
|
||||
|
||||
/** Throw when two name lists diverge. */
|
||||
export const assertSameNames = (label, actual, expected) => {
|
||||
const actualSet = new Set(actual);
|
||||
const expectedSet = new Set(expected);
|
||||
const missing = [...expectedSet].filter((name) => !actualSet.has(name));
|
||||
const extra = [...actualSet].filter((name) => !expectedSet.has(name));
|
||||
if (missing.length === 0 && extra.length === 0) return;
|
||||
throw new Error(
|
||||
`${label} drifted (missing: ${missing.join(", ") || "none"}; extra: ${extra.join(", ") || "none"})`,
|
||||
);
|
||||
};
|
||||
|
||||
const SOURCE_PATHS = {
|
||||
packageMetadata: "dist/generatedPackageMetadata.js",
|
||||
catalogIdentity: "dist/catalogIdentity.js",
|
||||
cli: "dist/cli.js",
|
||||
toolContracts: "dist/contracts/toolContracts.js",
|
||||
nativeContracts: "dist/contracts/nativeToolContracts.js",
|
||||
artifactContracts: "dist/contracts/artifactToolContracts.js",
|
||||
managedContracts: "dist/contracts/managedToolContracts.js",
|
||||
managedWorkflowContracts: "dist/contracts/managedWorkflowToolContracts.js",
|
||||
browserContracts: "dist/contracts/browserToolContracts.js",
|
||||
electronContracts: "dist/contracts/electronToolContracts.js",
|
||||
applicationContracts: "dist/contracts/applicationToolContracts.js",
|
||||
supportedClients: "dist/application/SupportedClients.js",
|
||||
hopperProvider: "dist/hopper/HopperProvider.js",
|
||||
ghidraProvider: "dist/ghidra/GhidraProvider.js",
|
||||
nativeProvider: "dist/native/NativeMacOSProvider.js",
|
||||
artifactProviders: "dist/application/InvestigationProviders.js",
|
||||
browserProvider: "dist/browser/CdpBrowserProvider.js",
|
||||
electronProvider: "dist/browser/CdpElectronProvider.js",
|
||||
evidence: "dist/domain/evidence.js",
|
||||
evidenceBundle: "dist/domain/evidenceBundle.js",
|
||||
processCapture: "dist/domain/processCapture.js",
|
||||
analysisSnapshot: "dist/domain/analysisSnapshot.js",
|
||||
artifactGraph: "dist/domain/artifactGraph.js",
|
||||
investigationWorkspace: "dist/domain/investigationWorkspace.js",
|
||||
browserObservation: "dist/domain/browserObservation.js",
|
||||
browserSession: "dist/domain/browserSession.js",
|
||||
electronObservation: "dist/domain/electronObservation.js",
|
||||
webBundleAnalysis: "dist/domain/webBundleAnalysis.js",
|
||||
webCaptureDiff: "dist/domain/webCaptureDiff.js",
|
||||
managedArtifact: "dist/domain/managedArtifact.js",
|
||||
managedComparison: "dist/domain/managedMemberComparison.js",
|
||||
managedNativeVerification: "dist/domain/managedNativeVerification.js",
|
||||
webMcpDiscovery: "dist/domain/webMcpDiscovery.js",
|
||||
webScreenshot: "dist/domain/webScreenshot.js",
|
||||
javascriptApplicationGraph: "dist/domain/javascriptApplicationGraph.js",
|
||||
javascriptApplicationAnalysis: "dist/domain/javascriptApplicationAnalysis.js",
|
||||
javascriptFeatureTrace: "dist/domain/javascriptFeatureTraceSchemas.js",
|
||||
javascriptVersionComparison:
|
||||
"dist/domain/javascriptApplicationVersionComparisonSchemas.js",
|
||||
reconstructionVerification:
|
||||
"dist/domain/reconstructionVerificationSchemas.js",
|
||||
residualUnknown: "dist/domain/residualUnknown.js",
|
||||
};
|
||||
|
||||
/** Load every compiled source module referenced by the catalog. */
|
||||
export const loadSources = async (root) =>
|
||||
Object.fromEntries(
|
||||
await Promise.all(
|
||||
Object.entries(SOURCE_PATHS).map(async ([key, path]) => [
|
||||
key,
|
||||
await load(root, path),
|
||||
]),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,204 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const valuesAt = (node, path) => {
|
||||
if (typeof node !== "object" || node === null) return [];
|
||||
if ("anyOf" in node && Array.isArray(node.anyOf))
|
||||
return node.anyOf.flatMap((alternative) => valuesAt(alternative, path));
|
||||
if (path.length === 0)
|
||||
return "const" in node &&
|
||||
(typeof node.const === "number" || typeof node.const === "string")
|
||||
? [node.const]
|
||||
: [];
|
||||
if (
|
||||
!("properties" in node) ||
|
||||
typeof node.properties !== "object" ||
|
||||
node.properties === null
|
||||
)
|
||||
return [];
|
||||
const [segment, ...remaining] = path;
|
||||
return segment !== undefined && segment in node.properties
|
||||
? valuesAt(node.properties[segment], remaining)
|
||||
: [];
|
||||
};
|
||||
|
||||
const versionAt = (schema, path) => {
|
||||
const versions = [
|
||||
...new Set(valuesAt(z.toJSONSchema(schema), path).map(String)),
|
||||
];
|
||||
if (versions.length !== 1)
|
||||
throw new Error(
|
||||
`Schema version path ${path.join(".")} has ${String(versions.length)} constant values`,
|
||||
);
|
||||
const version = versions[0];
|
||||
if (version === undefined) throw new Error("Schema version disappeared");
|
||||
return /^\d+$/u.test(version) ? Number(version) : version;
|
||||
};
|
||||
|
||||
const durableSchemaDefinitions = (sources) => [
|
||||
[
|
||||
"analysis_snapshot",
|
||||
sources.analysisSnapshot.analysisSnapshotSchema,
|
||||
["snapshot_version"],
|
||||
],
|
||||
[
|
||||
"artifact_graph",
|
||||
sources.artifactGraph.artifactInventoryResultSchema,
|
||||
["manifest", "schema_version"],
|
||||
],
|
||||
[
|
||||
"artifact_extraction",
|
||||
sources.artifactGraph.artifactExtractionResultSchema,
|
||||
["extraction_manifest", "schema_version"],
|
||||
],
|
||||
["evidence", sources.evidence.evidenceSchema, ["schema_version"]],
|
||||
[
|
||||
"evidence_bundle",
|
||||
sources.evidenceBundle.evidenceBundleSchema,
|
||||
["bundle_version"],
|
||||
],
|
||||
[
|
||||
"investigation_run",
|
||||
sources.investigationWorkspace.investigationRunSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"investigation_run_summary",
|
||||
sources.investigationWorkspace.investigationRunSummarySchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"investigation_workspace",
|
||||
sources.investigationWorkspace.investigationWorkspaceSchema,
|
||||
["workspace_version"],
|
||||
],
|
||||
[
|
||||
"javascript_application_graph",
|
||||
sources.javascriptApplicationGraph.javascriptApplicationGraphSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"javascript_application_version_comparison",
|
||||
sources.javascriptVersionComparison
|
||||
.applicationVersionComparisonResultSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"javascript_feature_trace",
|
||||
sources.javascriptFeatureTrace.applicationFeatureTraceResultSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"process_capture",
|
||||
sources.processCapture.processCaptureSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"reconstruction_verification",
|
||||
sources.reconstructionVerification.reconstructionSpecificationSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"residual_unknown",
|
||||
sources.residualUnknown.residualUnknownSchema,
|
||||
["registry_version"],
|
||||
],
|
||||
];
|
||||
|
||||
const observationSchemaDefinitions = (sources) => [
|
||||
[
|
||||
"managed_artifact_inspection",
|
||||
sources.managedArtifact.managedArtifactInspectionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"managed_member_inspection",
|
||||
sources.managedArtifact.managedMemberInspectionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"managed_native_boundary_inspection",
|
||||
sources.managedArtifact.managedNativeBoundaryInspectionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"managed_member_comparison",
|
||||
sources.managedComparison.managedMemberComparisonResultSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"managed_native_verification",
|
||||
sources.managedNativeVerification.managedNativeVerificationResultSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"browser_target_list",
|
||||
sources.browserObservation.browserTargetListSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"electron_page_inspection",
|
||||
sources.electronObservation.electronPageInspectionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"electron_target_list",
|
||||
sources.electronObservation.electronTargetListSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"javascript_application_analysis",
|
||||
sources.javascriptApplicationAnalysis
|
||||
.javascriptApplicationAnalysisResultSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_bundle_analysis",
|
||||
sources.webBundleAnalysis.webBundleAnalysisSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_capture_diff",
|
||||
sources.webCaptureDiff.webCaptureDiffSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_mcp_discovery",
|
||||
sources.webMcpDiscovery.webMcpDiscoverySchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_observation_session",
|
||||
sources.browserSession.webObservationSessionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_page_inspection",
|
||||
sources.browserObservation.webPageInspectionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_screenshot",
|
||||
sources.webScreenshot.webScreenshotSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_screenshot_diff",
|
||||
sources.webScreenshot.webScreenshotDiffSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
];
|
||||
|
||||
/** Derive the catalog of durable and observation schema versions. */
|
||||
export const schemaCatalog = (sources) =>
|
||||
[
|
||||
...durableSchemaDefinitions(sources),
|
||||
...observationSchemaDefinitions(sources),
|
||||
]
|
||||
.map(([id, schema, path]) => {
|
||||
try {
|
||||
return { id, version: versionAt(schema, path) };
|
||||
} catch (cause) {
|
||||
throw new Error(`Could not derive ${id} schema version`, { cause });
|
||||
}
|
||||
})
|
||||
.sort((left, right) => left.id.localeCompare(right.id));
|
||||
+12
-482
@@ -1,490 +1,20 @@
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Cli } from "incur";
|
||||
import { format } from "prettier";
|
||||
import { z } from "zod";
|
||||
|
||||
const load = (root, path) => import(pathToFileURL(join(root, path)).href);
|
||||
const names = (contracts) =>
|
||||
contracts
|
||||
.map(({ name }) => name)
|
||||
.sort((left, right) => left.localeCompare(right));
|
||||
import { assertSameNames, loadSources } from "./catalog-core.mjs";
|
||||
import {
|
||||
createCliInventory,
|
||||
cliCommandDescriptionIssues,
|
||||
cliCommandOptionNames,
|
||||
} from "./catalog-cli.mjs";
|
||||
import { providerCatalog, toolFamilyCatalog } from "./catalog-builders.mjs";
|
||||
import { schemaCatalog } from "./catalog-schemas.mjs";
|
||||
|
||||
const valuesAt = (node, path) => {
|
||||
if (typeof node !== "object" || node === null) return [];
|
||||
if ("anyOf" in node && Array.isArray(node.anyOf))
|
||||
return node.anyOf.flatMap((alternative) => valuesAt(alternative, path));
|
||||
if (path.length === 0)
|
||||
return "const" in node &&
|
||||
(typeof node.const === "number" || typeof node.const === "string")
|
||||
? [node.const]
|
||||
: [];
|
||||
if (
|
||||
!("properties" in node) ||
|
||||
typeof node.properties !== "object" ||
|
||||
node.properties === null
|
||||
)
|
||||
return [];
|
||||
const [segment, ...remaining] = path;
|
||||
return segment !== undefined && segment in node.properties
|
||||
? valuesAt(node.properties[segment], remaining)
|
||||
: [];
|
||||
export {
|
||||
createCliInventory,
|
||||
cliCommandDescriptionIssues,
|
||||
cliCommandOptionNames,
|
||||
};
|
||||
|
||||
const versionAt = (schema, path) => {
|
||||
const versions = [
|
||||
...new Set(valuesAt(z.toJSONSchema(schema), path).map(String)),
|
||||
];
|
||||
if (versions.length !== 1)
|
||||
throw new Error(
|
||||
`Schema version path ${path.join(".")} has ${String(versions.length)} constant values`,
|
||||
);
|
||||
const version = versions[0];
|
||||
if (version === undefined) throw new Error("Schema version disappeared");
|
||||
return /^\d+$/u.test(version) ? Number(version) : version;
|
||||
};
|
||||
|
||||
/** Read primary names and aliases from the actual Incur command router. */
|
||||
export const createCliInventory = (cli) => {
|
||||
const commands = Cli.toCommands.get(cli);
|
||||
if (commands === undefined)
|
||||
throw new Error("Incur did not expose the registered REA CLI commands");
|
||||
const primary = [];
|
||||
const aliases = [];
|
||||
for (const [name, entry] of commands) {
|
||||
if ("_alias" in entry) aliases.push({ name, target: entry.target });
|
||||
else primary.push(name);
|
||||
}
|
||||
return {
|
||||
primary: primary.sort((left, right) => left.localeCompare(right)),
|
||||
aliases: aliases.sort((left, right) => left.name.localeCompare(right.name)),
|
||||
};
|
||||
};
|
||||
|
||||
/** Read one primary command's declared option names from the Incur router. */
|
||||
export const cliCommandOptionNames = (cli, name) => {
|
||||
const commands = Cli.toCommands.get(cli);
|
||||
const command = commands?.get(name);
|
||||
if (
|
||||
command === undefined ||
|
||||
"_alias" in command ||
|
||||
!("options" in command) ||
|
||||
command.options === undefined
|
||||
)
|
||||
return [];
|
||||
const schema = z.toJSONSchema(command.options);
|
||||
return Object.keys(schema.properties ?? {}).sort((left, right) =>
|
||||
left.localeCompare(right),
|
||||
);
|
||||
};
|
||||
|
||||
/** Report primary CLI fields whose generated JSON Schema lacks help text. */
|
||||
export const cliCommandDescriptionIssues = (cli) => {
|
||||
const commands = Cli.toCommands.get(cli);
|
||||
if (commands === undefined)
|
||||
throw new Error("Incur did not expose the registered REA CLI commands");
|
||||
const missing = [];
|
||||
for (const [commandName, command] of commands) {
|
||||
if ("_alias" in command) continue;
|
||||
for (const groupName of ["args", "options"]) {
|
||||
if (!(groupName in command) || command[groupName] === undefined) continue;
|
||||
const properties = z.toJSONSchema(command[groupName]).properties ?? {};
|
||||
for (const [propertyName, property] of Object.entries(properties)) {
|
||||
if (
|
||||
typeof property !== "object" ||
|
||||
property === null ||
|
||||
typeof property.description !== "string" ||
|
||||
property.description.trim() === ""
|
||||
)
|
||||
missing.push(`${commandName}.${groupName}.${propertyName}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return missing;
|
||||
};
|
||||
|
||||
const assertSameNames = (label, actual, expected) => {
|
||||
const actualSet = new Set(actual);
|
||||
const expectedSet = new Set(expected);
|
||||
const missing = [...expectedSet].filter((name) => !actualSet.has(name));
|
||||
const extra = [...actualSet].filter((name) => !expectedSet.has(name));
|
||||
if (missing.length === 0 && extra.length === 0) return;
|
||||
throw new Error(
|
||||
`${label} drifted (missing: ${missing.join(", ") || "none"}; extra: ${extra.join(", ") || "none"})`,
|
||||
);
|
||||
};
|
||||
|
||||
const SOURCE_PATHS = {
|
||||
packageMetadata: "dist/generatedPackageMetadata.js",
|
||||
catalogIdentity: "dist/catalogIdentity.js",
|
||||
cli: "dist/cli.js",
|
||||
toolContracts: "dist/contracts/toolContracts.js",
|
||||
nativeContracts: "dist/contracts/nativeToolContracts.js",
|
||||
artifactContracts: "dist/contracts/artifactToolContracts.js",
|
||||
managedContracts: "dist/contracts/managedToolContracts.js",
|
||||
managedWorkflowContracts: "dist/contracts/managedWorkflowToolContracts.js",
|
||||
browserContracts: "dist/contracts/browserToolContracts.js",
|
||||
electronContracts: "dist/contracts/electronToolContracts.js",
|
||||
applicationContracts: "dist/contracts/applicationToolContracts.js",
|
||||
supportedClients: "dist/application/SupportedClients.js",
|
||||
hopperProvider: "dist/hopper/HopperProvider.js",
|
||||
ghidraProvider: "dist/ghidra/GhidraProvider.js",
|
||||
nativeProvider: "dist/native/NativeMacOSProvider.js",
|
||||
artifactProviders: "dist/application/InvestigationProviders.js",
|
||||
browserProvider: "dist/browser/CdpBrowserProvider.js",
|
||||
electronProvider: "dist/browser/CdpElectronProvider.js",
|
||||
evidence: "dist/domain/evidence.js",
|
||||
evidenceBundle: "dist/domain/evidenceBundle.js",
|
||||
processCapture: "dist/domain/processCapture.js",
|
||||
analysisSnapshot: "dist/domain/analysisSnapshot.js",
|
||||
artifactGraph: "dist/domain/artifactGraph.js",
|
||||
investigationWorkspace: "dist/domain/investigationWorkspace.js",
|
||||
browserObservation: "dist/domain/browserObservation.js",
|
||||
browserSession: "dist/domain/browserSession.js",
|
||||
electronObservation: "dist/domain/electronObservation.js",
|
||||
webBundleAnalysis: "dist/domain/webBundleAnalysis.js",
|
||||
webCaptureDiff: "dist/domain/webCaptureDiff.js",
|
||||
managedArtifact: "dist/domain/managedArtifact.js",
|
||||
managedComparison: "dist/domain/managedMemberComparison.js",
|
||||
managedNativeVerification: "dist/domain/managedNativeVerification.js",
|
||||
webMcpDiscovery: "dist/domain/webMcpDiscovery.js",
|
||||
webScreenshot: "dist/domain/webScreenshot.js",
|
||||
javascriptApplicationGraph: "dist/domain/javascriptApplicationGraph.js",
|
||||
javascriptApplicationAnalysis: "dist/domain/javascriptApplicationAnalysis.js",
|
||||
javascriptFeatureTrace: "dist/domain/javascriptFeatureTraceSchemas.js",
|
||||
javascriptVersionComparison:
|
||||
"dist/domain/javascriptApplicationVersionComparisonSchemas.js",
|
||||
reconstructionVerification:
|
||||
"dist/domain/reconstructionVerificationSchemas.js",
|
||||
residualUnknown: "dist/domain/residualUnknown.js",
|
||||
};
|
||||
|
||||
const loadSources = async (root) =>
|
||||
Object.fromEntries(
|
||||
await Promise.all(
|
||||
Object.entries(SOURCE_PATHS).map(async ([key, path]) => [
|
||||
key,
|
||||
await load(root, path),
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
const toolFamilyCatalog = (sources) => {
|
||||
const families = [
|
||||
{
|
||||
id: "direct",
|
||||
surface: "official-proxy",
|
||||
contracts: sources.toolContracts.OFFICIAL_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "enhanced",
|
||||
surface: "enhanced",
|
||||
contracts: sources.toolContracts.ENHANCED_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "native",
|
||||
surface: "native-provider",
|
||||
contracts: sources.nativeContracts.NATIVE_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "artifact",
|
||||
surface: "artifact-provider",
|
||||
contracts: sources.artifactContracts.ARTIFACT_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "managed",
|
||||
surface: "managed",
|
||||
contracts: [
|
||||
...sources.managedContracts.MANAGED_TOOL_CONTRACTS,
|
||||
...sources.managedWorkflowContracts.MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "browser",
|
||||
surface: "browser-provider",
|
||||
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "electron",
|
||||
surface: "electron-provider",
|
||||
contracts: sources.electronContracts.ELECTRON_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "application",
|
||||
surface: "application-workflow",
|
||||
contracts: sources.applicationContracts.APPLICATION_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
id: "session",
|
||||
surface: "session",
|
||||
contracts: sources.toolContracts.SESSION_TOOL_CONTRACTS,
|
||||
},
|
||||
].map(({ id, surface, contracts }) => ({
|
||||
id,
|
||||
surface,
|
||||
count: contracts.length,
|
||||
tools: names(contracts),
|
||||
}));
|
||||
const familyTotal = families.reduce(
|
||||
(total, family) => total + family.count,
|
||||
0,
|
||||
);
|
||||
if (
|
||||
familyTotal !== sources.toolContracts.TOOL_CONTRACTS.length ||
|
||||
familyTotal !== sources.catalogIdentity.CATALOG_IDENTITY.counts.mcp_tools
|
||||
)
|
||||
throw new Error("Tool family inventory does not match TOOL_CONTRACTS");
|
||||
return { total: familyTotal, families };
|
||||
};
|
||||
|
||||
const providerCatalog = (sources) => {
|
||||
const applicationContracts =
|
||||
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
|
||||
({ name }) => name === "analyze_javascript_application",
|
||||
);
|
||||
const reconciliationContracts =
|
||||
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
|
||||
({ name }) => name === "reconcile_javascript_runtime",
|
||||
);
|
||||
const observationContracts =
|
||||
sources.electronContracts.ELECTRON_TOOL_CONTRACTS.filter(
|
||||
({ name }) =>
|
||||
name !== "analyze_javascript_application" &&
|
||||
name !== "reconcile_javascript_runtime",
|
||||
);
|
||||
if (
|
||||
applicationContracts.length !== 1 ||
|
||||
reconciliationContracts.length !== 1 ||
|
||||
observationContracts.length !== 2
|
||||
)
|
||||
throw new Error("Electron provider capability ownership drifted");
|
||||
return [
|
||||
{
|
||||
identity: sources.hopperProvider.HOPPER_PROVIDER_IDENTITY,
|
||||
contracts: sources.hopperProvider.HOPPER_PROVIDER_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.ghidraProvider.GHIDRA_PROVIDER_IDENTITY,
|
||||
contracts: sources.ghidraProvider.GHIDRA_PROVIDER_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.nativeProvider.NATIVE_MACOS_PROVIDER_IDENTITY,
|
||||
contracts: sources.nativeContracts.NATIVE_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.artifactProviders.ARTIFACT_GRAPH_PROVIDER,
|
||||
contracts: sources.artifactContracts.ARTIFACT_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.artifactProviders.MANAGED_STATIC_PROVIDER,
|
||||
contracts: sources.managedContracts.MANAGED_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.artifactProviders.MANAGED_WORKFLOW_PROVIDER,
|
||||
contracts:
|
||||
sources.managedWorkflowContracts.MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.browserProvider.CDP_BROWSER_PROVIDER_IDENTITY,
|
||||
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.electronProvider.CDP_ELECTRON_PROVIDER_IDENTITY,
|
||||
contracts: observationContracts,
|
||||
},
|
||||
{
|
||||
identity: sources.artifactProviders.JAVASCRIPT_APPLICATION_PROVIDER,
|
||||
contracts: applicationContracts,
|
||||
},
|
||||
{
|
||||
identity:
|
||||
sources.artifactProviders.JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
|
||||
contracts: reconciliationContracts,
|
||||
},
|
||||
{
|
||||
identity:
|
||||
sources.artifactProviders.JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER,
|
||||
contracts: sources.applicationContracts.APPLICATION_TOOL_CONTRACTS,
|
||||
},
|
||||
]
|
||||
.map(({ identity, contracts }) => ({
|
||||
id: identity.id,
|
||||
name: identity.name,
|
||||
version: identity.version,
|
||||
capabilities: names(contracts),
|
||||
}))
|
||||
.sort((left, right) => left.id.localeCompare(right.id));
|
||||
};
|
||||
|
||||
const durableSchemaDefinitions = (sources) => [
|
||||
[
|
||||
"analysis_snapshot",
|
||||
sources.analysisSnapshot.analysisSnapshotSchema,
|
||||
["snapshot_version"],
|
||||
],
|
||||
[
|
||||
"artifact_graph",
|
||||
sources.artifactGraph.artifactInventoryResultSchema,
|
||||
["manifest", "schema_version"],
|
||||
],
|
||||
[
|
||||
"artifact_extraction",
|
||||
sources.artifactGraph.artifactExtractionResultSchema,
|
||||
["extraction_manifest", "schema_version"],
|
||||
],
|
||||
["evidence", sources.evidence.evidenceSchema, ["schema_version"]],
|
||||
[
|
||||
"evidence_bundle",
|
||||
sources.evidenceBundle.evidenceBundleSchema,
|
||||
["bundle_version"],
|
||||
],
|
||||
[
|
||||
"investigation_run",
|
||||
sources.investigationWorkspace.investigationRunSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"investigation_run_summary",
|
||||
sources.investigationWorkspace.investigationRunSummarySchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"investigation_workspace",
|
||||
sources.investigationWorkspace.investigationWorkspaceSchema,
|
||||
["workspace_version"],
|
||||
],
|
||||
[
|
||||
"javascript_application_graph",
|
||||
sources.javascriptApplicationGraph.javascriptApplicationGraphSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"javascript_application_version_comparison",
|
||||
sources.javascriptVersionComparison
|
||||
.applicationVersionComparisonResultSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"javascript_feature_trace",
|
||||
sources.javascriptFeatureTrace.applicationFeatureTraceResultSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"process_capture",
|
||||
sources.processCapture.processCaptureSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"reconstruction_verification",
|
||||
sources.reconstructionVerification.reconstructionSpecificationSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"residual_unknown",
|
||||
sources.residualUnknown.residualUnknownSchema,
|
||||
["registry_version"],
|
||||
],
|
||||
];
|
||||
|
||||
const observationSchemaDefinitions = (sources) => [
|
||||
[
|
||||
"managed_artifact_inspection",
|
||||
sources.managedArtifact.managedArtifactInspectionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"managed_member_inspection",
|
||||
sources.managedArtifact.managedMemberInspectionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"managed_native_boundary_inspection",
|
||||
sources.managedArtifact.managedNativeBoundaryInspectionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"managed_member_comparison",
|
||||
sources.managedComparison.managedMemberComparisonResultSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"managed_native_verification",
|
||||
sources.managedNativeVerification.managedNativeVerificationResultSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"browser_target_list",
|
||||
sources.browserObservation.browserTargetListSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"electron_page_inspection",
|
||||
sources.electronObservation.electronPageInspectionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"electron_target_list",
|
||||
sources.electronObservation.electronTargetListSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"javascript_application_analysis",
|
||||
sources.javascriptApplicationAnalysis
|
||||
.javascriptApplicationAnalysisResultSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_bundle_analysis",
|
||||
sources.webBundleAnalysis.webBundleAnalysisSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_capture_diff",
|
||||
sources.webCaptureDiff.webCaptureDiffSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_mcp_discovery",
|
||||
sources.webMcpDiscovery.webMcpDiscoverySchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_observation_session",
|
||||
sources.browserSession.webObservationSessionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_page_inspection",
|
||||
sources.browserObservation.webPageInspectionSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_screenshot",
|
||||
sources.webScreenshot.webScreenshotSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
[
|
||||
"web_screenshot_diff",
|
||||
sources.webScreenshot.webScreenshotDiffSchema,
|
||||
["schema_version"],
|
||||
],
|
||||
];
|
||||
|
||||
const schemaCatalog = (sources) =>
|
||||
[
|
||||
...durableSchemaDefinitions(sources),
|
||||
...observationSchemaDefinitions(sources),
|
||||
]
|
||||
.map(([id, schema, path]) => {
|
||||
try {
|
||||
return { id, version: versionAt(schema, path) };
|
||||
} catch (cause) {
|
||||
throw new Error(`Could not derive ${id} schema version`, { cause });
|
||||
}
|
||||
})
|
||||
.sort((left, right) => left.id.localeCompare(right.id));
|
||||
|
||||
/** Project current runtime contracts into deterministic, machine-readable facts. */
|
||||
export const createProductCatalog = async (root) => {
|
||||
const sources = await loadSources(root);
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { lstat } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
/** Promisified child_process execution helper. */
|
||||
export const exec = promisify(execFile);
|
||||
|
||||
/** Run a command and return its stdout. */
|
||||
export const run = async (command, args, env) =>
|
||||
(await exec(command, args, { env })).stdout;
|
||||
|
||||
/** Run a command and treat exit code 1 as a non-throwing status result. */
|
||||
export const runWithStatus = async (command, args, env) => {
|
||||
try {
|
||||
return { stdout: await run(command, args, env), status: 0 };
|
||||
} catch (cause) {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
cause.code === 1 &&
|
||||
typeof cause.stdout === "string"
|
||||
)
|
||||
return { stdout: cause.stdout, status: 1 };
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** Parse JSON from a command output string. */
|
||||
export const json = (text) => JSON.parse(text);
|
||||
|
||||
/** Check whether a path exists on disk. */
|
||||
export const pathExists = async (path) => {
|
||||
try {
|
||||
await lstat(path);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
||||
return false;
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** Synthetic function dossier for managed/native verification fixtures. */
|
||||
export const functionDossier = (name) => {
|
||||
const emptyPage = {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
};
|
||||
return {
|
||||
procedure: {
|
||||
address: "0x401000",
|
||||
name,
|
||||
classification: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
provenance: "synthetic-provider",
|
||||
},
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "",
|
||||
total_chars: 0,
|
||||
returned_chars: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: emptyPage,
|
||||
comments: emptyPage,
|
||||
callers: emptyPage,
|
||||
callees: emptyPage,
|
||||
incoming_references: emptyPage,
|
||||
outgoing_references: emptyPage,
|
||||
referenced_strings: emptyPage,
|
||||
referenced_names: emptyPage,
|
||||
basic_blocks: emptyPage,
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
limitations: [],
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
|
||||
import { json, run } from "./lib/verify-package-core.mjs";
|
||||
|
||||
/** Run inventory-artifact and analyze-javascript-application against packaged fixtures. */
|
||||
export async function verifyPackageArtifactAndElectron({
|
||||
cli,
|
||||
workspace,
|
||||
environment,
|
||||
}) {
|
||||
const artifactArchive = join(workspace, "artifact.zip");
|
||||
const artifactWriter = new ZipWriter(new Uint8ArrayWriter());
|
||||
await artifactWriter.add("app/main.js", new TextReader("main();"));
|
||||
await writeFile(artifactArchive, await artifactWriter.close());
|
||||
const artifactInventory = json(
|
||||
await run(
|
||||
cli,
|
||||
["inventory-artifact", artifactArchive, "--limit", "500", "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
artifactInventory.operation !== "inventory_artifact" ||
|
||||
artifactInventory.provider?.id !== "rea-artifact-graph" ||
|
||||
artifactInventory.normalized_result?.manifest?.root_format !== "zip"
|
||||
)
|
||||
throw new Error("packaged artifact inventory CLI failed");
|
||||
const applicationRoot = join(workspace, "electron-app");
|
||||
await mkdir(applicationRoot);
|
||||
await writeFile(
|
||||
join(applicationRoot, "package.json"),
|
||||
'{"name":"packaged-electron-fixture","main":"main.js"}\n',
|
||||
);
|
||||
await writeFile(
|
||||
join(applicationRoot, "main.js"),
|
||||
'const { BrowserWindow, ipcMain } = require("electron");\nnew BrowserWindow({ webPreferences: { preload: path.join(__dirname, "preload.js"), contextIsolation: true } });\nipcMain.handle("rea:ping", () => true);\n',
|
||||
);
|
||||
await writeFile(
|
||||
join(applicationRoot, "preload.js"),
|
||||
'const { contextBridge, ipcRenderer } = require("electron");\ncontextBridge.exposeInMainWorld("rea", { ping: () => ipcRenderer.invoke("rea:ping") });\n',
|
||||
);
|
||||
const applicationAnalysis = json(
|
||||
await run(
|
||||
cli,
|
||||
[
|
||||
"analyze-javascript-application",
|
||||
applicationRoot,
|
||||
"--approved",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
applicationAnalysis.operation !== "analyze_javascript_application" ||
|
||||
applicationAnalysis.provider?.id !== "rea-javascript-application" ||
|
||||
applicationAnalysis.normalized_result?.summary?.browser_windows !== 1 ||
|
||||
applicationAnalysis.normalized_result?.summary?.ipc
|
||||
?.paired_renderer_transmissions !== 1
|
||||
)
|
||||
throw new Error("packaged JavaScript application analysis CLI failed");
|
||||
|
||||
return { artifactArchive };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { json, run } from "./lib/verify-package-core.mjs";
|
||||
|
||||
/** Verify packaged capabilities, providers, and non-Linux search results. */
|
||||
export async function verifyPackageCapabilitiesAndSearch({ cli, environment }) {
|
||||
const capabilities = json(
|
||||
await run(cli, ["capabilities", "--json"], environment),
|
||||
);
|
||||
if (!Array.isArray(capabilities.capabilities))
|
||||
throw new Error("packaged capabilities CLI failed");
|
||||
const providers = json(await run(cli, ["providers", "--json"], environment));
|
||||
if (
|
||||
!Array.isArray(providers.providers) ||
|
||||
providers.providers.some(({ id }) => typeof id !== "string") ||
|
||||
providers.analysis_provider_binding !== null ||
|
||||
providers.analysis_provider_candidates?.find(
|
||||
({ provider }) => provider?.id === "hopper",
|
||||
)?.target_support?.status !== "unknown"
|
||||
)
|
||||
throw new Error("packaged providers CLI failed");
|
||||
if (process.platform !== "linux") {
|
||||
const searchResult = json(
|
||||
await run(
|
||||
cli,
|
||||
["search", process.execPath, "fixture", "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
searchResult.operation !== "search_strings" ||
|
||||
searchResult.normalized_result?.items?.length !== 1
|
||||
)
|
||||
throw new Error(
|
||||
`packaged search CLI failed: ${JSON.stringify(searchResult)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { json, run, runWithStatus } from "./lib/verify-package-core.mjs";
|
||||
|
||||
const REQUIRED_HELP_COMMANDS = [
|
||||
"setup",
|
||||
"upgrade",
|
||||
"inventory-artifact",
|
||||
"extract-artifact",
|
||||
"investigate-versions",
|
||||
"import-reference-source",
|
||||
"list-browser-targets",
|
||||
"inspect-web-page",
|
||||
"analyze-javascript-application",
|
||||
"compare",
|
||||
];
|
||||
|
||||
const REQUIRED_LLM_TOPICS = [
|
||||
"decompile",
|
||||
"function",
|
||||
"search",
|
||||
"inspect",
|
||||
"xrefs",
|
||||
"trace",
|
||||
"capabilities",
|
||||
"providers",
|
||||
"inventory-artifact",
|
||||
"list-browser-targets",
|
||||
"inspect-web-page",
|
||||
"analyze-javascript-application",
|
||||
];
|
||||
|
||||
/** Validate --help, --llms, and doctor output and determine host setup support. */
|
||||
export async function verifyPackageDiscovery({ cli, environment }) {
|
||||
const help = await run(cli, ["--help"], environment);
|
||||
const llms = await run(cli, ["--llms"], environment);
|
||||
const doctorExecution = await runWithStatus(
|
||||
cli,
|
||||
["doctor", "--json"],
|
||||
environment,
|
||||
);
|
||||
const doctor = json(doctorExecution.stdout);
|
||||
const supportedSetupHost =
|
||||
doctor.checks?.find(({ name }) => name === "host")?.ok === true;
|
||||
const expectedDoctorHealth = doctor.checks?.every(({ ok }) => ok) === true;
|
||||
const missingHelp = REQUIRED_HELP_COMMANDS.filter(
|
||||
(command) => !help.includes(command),
|
||||
);
|
||||
const missingLlms = REQUIRED_LLM_TOPICS.filter(
|
||||
(topic) => !llms.includes(topic),
|
||||
);
|
||||
if (
|
||||
missingHelp.length !== 0 ||
|
||||
missingLlms.length !== 0 ||
|
||||
doctor.healthy !== expectedDoctorHealth ||
|
||||
doctorExecution.status !== (expectedDoctorHealth ? 0 : 1) ||
|
||||
doctor.checks?.find(({ name }) => name === "hopper")?.ok !== true
|
||||
)
|
||||
throw new Error(
|
||||
`packaged CLI discovery or doctor failed: ${JSON.stringify({ helpSetup: help.includes("setup"), llmsDecompile: llms.includes("decompile"), doctor })}`,
|
||||
);
|
||||
return { supportedSetupHost };
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { chmod, mkdir, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
/** Create an isolated prefix, fake PATH, client configs, and environment. */
|
||||
export async function verifyPackageEnvironment({
|
||||
root,
|
||||
workspace,
|
||||
evidenceRoot,
|
||||
referenceRoot,
|
||||
}) {
|
||||
const prefix = join(workspace, "prefix");
|
||||
const home = join(workspace, "home");
|
||||
const fakeBin = join(workspace, "bin");
|
||||
await mkdir(fakeBin, { recursive: true });
|
||||
await Promise.all([
|
||||
mkdir(evidenceRoot, { recursive: true }),
|
||||
mkdir(join(referenceRoot, "src"), { recursive: true }),
|
||||
]);
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(referenceRoot, "src", "main.ts"),
|
||||
'import "./dependency";\n',
|
||||
),
|
||||
writeFile(
|
||||
join(referenceRoot, "src", "dependency.ts"),
|
||||
"export const value = 1;\n",
|
||||
),
|
||||
writeFile(join(referenceRoot, ".env"), "PACKAGE_SECRET_SENTINEL=1\n"),
|
||||
]);
|
||||
const brew = join(fakeBin, "brew");
|
||||
const swVers = join(fakeBin, "sw_vers");
|
||||
const npx = join(fakeBin, "npx");
|
||||
const npxLog = join(workspace, "npx.log");
|
||||
const hopper = join(workspace, "hopper");
|
||||
await writeFile(
|
||||
brew,
|
||||
'#!/bin/sh\nif [ "$1" = "--prefix" ]; then echo /fake/cask; fi\nexit 0\n',
|
||||
);
|
||||
await writeFile(swVers, "#!/bin/sh\necho 14.5\n");
|
||||
await writeFile(
|
||||
npx,
|
||||
'#!/bin/sh\nprintf "%s\\n" "$*" > "$REA_NPX_LOG"\necho "│ ✓ Cursor: isolated │"\n',
|
||||
);
|
||||
await writeFile(hopper, "#!/bin/sh\nexit 0\n");
|
||||
await Promise.all([
|
||||
chmod(brew, 0o755),
|
||||
chmod(swVers, 0o755),
|
||||
chmod(hopper, 0o755),
|
||||
chmod(npx, 0o755),
|
||||
]);
|
||||
const claudeDir = join(home, "Library/Application Support/Claude");
|
||||
const codexDir = join(home, ".codex");
|
||||
const cursorDir = join(home, ".cursor");
|
||||
await Promise.all([
|
||||
mkdir(claudeDir, { recursive: true }),
|
||||
mkdir(codexDir, { recursive: true }),
|
||||
mkdir(cursorDir, { recursive: true }),
|
||||
]);
|
||||
const claudeConfig = join(claudeDir, "claude_desktop_config.json");
|
||||
const codexConfig = join(codexDir, "config.toml");
|
||||
const codexTarget = join(home, "managed-codex.toml");
|
||||
const cursorConfig = join(cursorDir, "mcp.json");
|
||||
const cursorTarget = join(home, "managed-cursor.json");
|
||||
await writeFile(claudeConfig, '{"existing":true}\n');
|
||||
await writeFile(codexTarget, 'model = "gpt-5"\n');
|
||||
await writeFile(cursorTarget, '{"existing":true}\n');
|
||||
await symlink(codexTarget, codexConfig);
|
||||
await symlink(cursorTarget, cursorConfig);
|
||||
const environment = {
|
||||
...process.env,
|
||||
HOME: home,
|
||||
XDG_CONFIG_HOME: join(home, ".config"),
|
||||
PATH: `${fakeBin}:${process.env.PATH ?? ""}`,
|
||||
REA_ANALYSIS_PROVIDER: "auto",
|
||||
HOPPER_LAUNCHER_PATH: process.execPath,
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify([
|
||||
join(root, "tests/fixtures/fakeLauncher.mjs"),
|
||||
]),
|
||||
REA_NPX_LOG: npxLog,
|
||||
REA_EVIDENCE_ROOTS_JSON: JSON.stringify([evidenceRoot]),
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([workspace]),
|
||||
REA_REFERENCE_ROOTS_JSON: JSON.stringify([referenceRoot]),
|
||||
REA_REFERENCE_SECRET_PATTERNS_JSON: JSON.stringify([".env"]),
|
||||
};
|
||||
return {
|
||||
prefix,
|
||||
home,
|
||||
npxLog,
|
||||
claudeConfig,
|
||||
codexConfig,
|
||||
codexTarget,
|
||||
cursorConfig,
|
||||
cursorTarget,
|
||||
environment,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createEvidence } from "../dist/domain/evidence.js";
|
||||
import { json, run } from "./lib/verify-package-core.mjs";
|
||||
|
||||
/** Round-trip historical reference import and evidence bundles. */
|
||||
export async function verifyPackageEvidence({
|
||||
cli,
|
||||
evidenceRoot,
|
||||
referenceRoot,
|
||||
environment,
|
||||
}) {
|
||||
const referenceImport = json(
|
||||
await run(
|
||||
cli,
|
||||
["import-reference-source", referenceRoot, "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
referenceImport.authority !== "historical-reference" ||
|
||||
referenceImport.root_alias !== "$REFERENCE_ROOT" ||
|
||||
referenceImport.relationships?.[0]?.resolution !== "internal" ||
|
||||
JSON.stringify(referenceImport).includes("PACKAGE_SECRET_SENTINEL")
|
||||
)
|
||||
throw new Error("packaged historical reference import CLI failed");
|
||||
const { createEvidenceBundle, serializeEvidenceBundle } = await import(
|
||||
new URL("../dist/domain/evidenceBundle.js", import.meta.url)
|
||||
);
|
||||
const sourceBundle = createEvidenceBundle([
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: "package", name: "Package verifier", version: "1" },
|
||||
{ operation: "health", parameters: {}, result: true },
|
||||
),
|
||||
]);
|
||||
const sourceBundlePath = join(evidenceRoot, "source.json");
|
||||
const canonicalBundlePath = join(evidenceRoot, "canonical.json");
|
||||
await writeFile(sourceBundlePath, serializeEvidenceBundle(sourceBundle));
|
||||
const importedBundle = json(
|
||||
await run(
|
||||
cli,
|
||||
["evidence-import", sourceBundlePath, "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
const exportedBundle = json(
|
||||
await run(
|
||||
cli,
|
||||
["evidence-export", sourceBundlePath, canonicalBundlePath, "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
const comparedBundle = json(
|
||||
await run(
|
||||
cli,
|
||||
["compare", sourceBundlePath, canonicalBundlePath, "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
importedBundle.imported !== 1 ||
|
||||
importedBundle.total !== 1 ||
|
||||
exportedBundle.records !== 1 ||
|
||||
(await readFile(canonicalBundlePath, "utf8")) !==
|
||||
serializeEvidenceBundle(sourceBundle) ||
|
||||
comparedBundle.status !== "unchanged" ||
|
||||
comparedBundle.summary?.records_unchanged !== 1
|
||||
)
|
||||
throw new Error(
|
||||
"packaged CLI evidence bundle comparison round trip failed",
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { exec, json, run } from "./lib/verify-package-core.mjs";
|
||||
|
||||
/** Install the packed CLI globally with and without optional dependencies and verify PTY degradation. */
|
||||
export async function verifyPackageInstall({
|
||||
root,
|
||||
tarball,
|
||||
prefix,
|
||||
workspace,
|
||||
environment,
|
||||
}) {
|
||||
await exec(
|
||||
"npm",
|
||||
[
|
||||
"install",
|
||||
"--global",
|
||||
"--ignore-scripts",
|
||||
"--prefix",
|
||||
prefix,
|
||||
join(root, tarball),
|
||||
],
|
||||
{ env: environment },
|
||||
);
|
||||
const cli = join(prefix, "bin", "rea");
|
||||
const processCaptureCapabilityUrl = pathToFileURL(
|
||||
join(
|
||||
prefix,
|
||||
"lib/node_modules/rea-agents/dist/application/ProcessCaptureCapability.js",
|
||||
),
|
||||
).href;
|
||||
const processCaptureCapability = json(
|
||||
(
|
||||
await exec(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"--eval",
|
||||
`const { probeProcessCaptureCapability } = await import(${JSON.stringify(processCaptureCapabilityUrl)}); process.stdout.write(JSON.stringify(await probeProcessCaptureCapability()));`,
|
||||
],
|
||||
{ env: environment },
|
||||
)
|
||||
).stdout,
|
||||
);
|
||||
if (processCaptureCapability.available !== true)
|
||||
throw new Error(
|
||||
`packaged PTY backend failed without lifecycle scripts: ${JSON.stringify(processCaptureCapability)}`,
|
||||
);
|
||||
const noOptionalPrefix = join(workspace, "prefix-no-optional");
|
||||
await exec(
|
||||
"npm",
|
||||
[
|
||||
"install",
|
||||
"--global",
|
||||
"--ignore-scripts",
|
||||
"--omit=optional",
|
||||
"--prefix",
|
||||
noOptionalPrefix,
|
||||
join(root, tarball),
|
||||
],
|
||||
{ env: environment },
|
||||
);
|
||||
const noOptionalCli = join(noOptionalPrefix, "bin", "rea");
|
||||
await rm(
|
||||
join(
|
||||
noOptionalPrefix,
|
||||
"lib/node_modules/rea-agents/node_modules/@lydell",
|
||||
`node-pty-${process.platform}-${process.arch}`,
|
||||
),
|
||||
{ recursive: true, force: true },
|
||||
);
|
||||
const noOptionalCapabilityUrl = pathToFileURL(
|
||||
join(
|
||||
noOptionalPrefix,
|
||||
"lib/node_modules/rea-agents/dist/application/ProcessCaptureCapability.js",
|
||||
),
|
||||
).href;
|
||||
const noOptionalCapability = json(
|
||||
(
|
||||
await exec(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"--eval",
|
||||
`const { probeProcessCaptureCapability } = await import(${JSON.stringify(noOptionalCapabilityUrl)}); process.stdout.write(JSON.stringify(await probeProcessCaptureCapability()));`,
|
||||
],
|
||||
{ env: environment },
|
||||
)
|
||||
).stdout,
|
||||
);
|
||||
if (
|
||||
!(await run(noOptionalCli, ["--help"], environment)).includes("setup") ||
|
||||
noOptionalCapability.available !== false
|
||||
)
|
||||
throw new Error(
|
||||
`packaged CLI did not degrade without the optional PTY binary: ${JSON.stringify(noOptionalCapability)}`,
|
||||
);
|
||||
return { cli };
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createEvidence } from "../dist/domain/evidence.js";
|
||||
import { buildManagedPeFixture } from "./lib/managed-pe-fixture.mjs";
|
||||
import { functionDossier, json, run } from "./lib/verify-package-core.mjs";
|
||||
|
||||
const buildManagedFixtures = async (workspace) => {
|
||||
const managedPath = join(workspace, "managed-fixture.exe");
|
||||
const managedRightPath = join(workspace, "managed-fixture-right.exe");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
managedPath,
|
||||
buildManagedPeFixture({
|
||||
pinvoke: {
|
||||
moduleName: "user32.dll",
|
||||
importName: "MessageBoxW",
|
||||
mappingFlags: 0x0345,
|
||||
},
|
||||
}),
|
||||
),
|
||||
writeFile(
|
||||
managedRightPath,
|
||||
buildManagedPeFixture({
|
||||
mvid: Buffer.from([
|
||||
0xde, 0xad, 0xbe, 0xef, 0x44, 0x33, 0x66, 0x55, 0xaa, 0xbb, 0xcc,
|
||||
0xdd, 0xee, 0xff, 0x11, 0x22,
|
||||
]),
|
||||
}),
|
||||
),
|
||||
]);
|
||||
return { managedPath, managedRightPath };
|
||||
};
|
||||
|
||||
const verifyManagedArtifact = async ({ cli, managedPath, environment }) => {
|
||||
const managedArtifact = json(
|
||||
await run(
|
||||
cli,
|
||||
["inspect-managed-artifact", managedPath, "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
managedArtifact.operation !== "inspect_managed_artifact" ||
|
||||
managedArtifact.provider?.id !== "rea-dotnet-static" ||
|
||||
managedArtifact.normalized_result?.classification?.status !== "managed"
|
||||
)
|
||||
throw new Error("packaged managed artifact CLI failed");
|
||||
return managedArtifact;
|
||||
};
|
||||
|
||||
const verifyManagedMembers = async ({ cli, managedPath, environment }) => {
|
||||
const managedMembers = json(
|
||||
await run(
|
||||
cli,
|
||||
["inspect-managed-members", managedPath, "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
managedMembers.operation !== "inspect_managed_members" ||
|
||||
managedMembers.normalized_result?.methods?.total !== 1
|
||||
)
|
||||
throw new Error("packaged managed member CLI failed");
|
||||
return managedMembers;
|
||||
};
|
||||
|
||||
const verifyManagedReconstruction = async ({
|
||||
cli,
|
||||
managedMembers,
|
||||
managedMethod,
|
||||
environment,
|
||||
}) => {
|
||||
const managedReconstructionInput = {
|
||||
static_members: managedMembers,
|
||||
decompiler: {
|
||||
name: "ilspycmd",
|
||||
version: "9.1.0.7988",
|
||||
family: "ilspy",
|
||||
executable_sha256: null,
|
||||
options: ["--type", "Fixture.Program"],
|
||||
},
|
||||
methods: [
|
||||
{
|
||||
token: managedMethod.token,
|
||||
signature_sha256: managedMethod.signature.raw_sha256,
|
||||
normalized_il_sha256: managedMethod.body.normalized_il_sha256,
|
||||
reconstruction: {
|
||||
kind: "decompiled-csharp",
|
||||
language: "csharp",
|
||||
text: "internal static void Main() { }",
|
||||
},
|
||||
},
|
||||
],
|
||||
notes: ["packaged synthetic reconstruction import"],
|
||||
};
|
||||
const managedReconstruction = json(
|
||||
await run(
|
||||
cli,
|
||||
[
|
||||
"import-managed-reconstruction",
|
||||
JSON.stringify(managedReconstructionInput),
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
managedReconstruction.operation !== "import_managed_reconstruction" ||
|
||||
managedReconstruction.provider?.id !== "rea-dotnet-workflows" ||
|
||||
managedReconstruction.normalized_result?.executed !== false ||
|
||||
managedReconstruction.normalized_result?.methods?.[0]?.validation
|
||||
?.canonical_observation !== false
|
||||
)
|
||||
throw new Error("packaged managed reconstruction import CLI failed");
|
||||
};
|
||||
|
||||
const verifyManagedRuntimePlan = async ({
|
||||
cli,
|
||||
managedMembers,
|
||||
managedMethod,
|
||||
workspace,
|
||||
environment,
|
||||
}) => {
|
||||
const managedRuntimePlanInput = {
|
||||
static_members: managedMembers,
|
||||
method: {
|
||||
token: managedMethod.token,
|
||||
signature_sha256: managedMethod.signature.raw_sha256,
|
||||
normalized_il_sha256: managedMethod.body.normalized_il_sha256,
|
||||
},
|
||||
requested_effect: "attach",
|
||||
host: {
|
||||
os: "linux",
|
||||
clr_family: "dotnet",
|
||||
architecture: "x86_64",
|
||||
},
|
||||
bounds: {
|
||||
timeout_ms: 5_000,
|
||||
max_threads: 32,
|
||||
max_output_bytes: 65_536,
|
||||
allow_network: false,
|
||||
allow_ui: false,
|
||||
},
|
||||
};
|
||||
const managedRuntimePlan = json(
|
||||
await run(
|
||||
cli,
|
||||
[
|
||||
"plan-managed-runtime-correlation",
|
||||
JSON.stringify(managedRuntimePlanInput),
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
...environment,
|
||||
REA_MANAGED_RUNTIME_ENABLED: "true",
|
||||
REA_MANAGED_RUNTIME_ROOTS_JSON: JSON.stringify([workspace]),
|
||||
REA_MANAGED_RUNTIME_EXECUTABLE_PATH: process.execPath,
|
||||
},
|
||||
),
|
||||
);
|
||||
if (
|
||||
managedRuntimePlan.operation !== "plan_managed_runtime_correlation" ||
|
||||
managedRuntimePlan.provider?.id !== "rea-dotnet-workflows" ||
|
||||
managedRuntimePlan.normalized_result?.executed !== false ||
|
||||
managedRuntimePlan.normalized_result?.authority_model?.capability !==
|
||||
"managed_runtime" ||
|
||||
managedRuntimePlan.normalized_result?.effect_taxonomy?.attaches_process !==
|
||||
true ||
|
||||
managedRuntimePlan.normalized_result?.effect_taxonomy
|
||||
?.invokes_target_code !== false
|
||||
)
|
||||
throw new Error("packaged managed runtime-correlation CLI failed");
|
||||
};
|
||||
|
||||
const verifyManagedBoundaries = async ({ cli, managedPath, environment }) => {
|
||||
const managedBoundaries = json(
|
||||
await run(
|
||||
cli,
|
||||
["inspect-managed-native-boundaries", managedPath, "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
managedBoundaries.operation !== "inspect_managed_native_boundaries" ||
|
||||
managedBoundaries.normalized_result?.pinvoke_imports?.total !== 1 ||
|
||||
managedBoundaries.normalized_result?.pinvoke_imports?.items?.[0]
|
||||
?.verification !== "managed-declaration-only"
|
||||
)
|
||||
throw new Error("packaged managed native-boundary CLI failed");
|
||||
return managedBoundaries;
|
||||
};
|
||||
|
||||
const verifyManagedApplicationGraph = async ({
|
||||
cli,
|
||||
managedArtifact,
|
||||
managedMembers,
|
||||
managedBoundaries,
|
||||
environment,
|
||||
}) => {
|
||||
const managedApplicationGraphInput = {
|
||||
managed_artifact: managedArtifact,
|
||||
managed_members: managedMembers,
|
||||
managed_native_boundaries: managedBoundaries,
|
||||
limits: {
|
||||
max_types: 100,
|
||||
max_methods: 100,
|
||||
max_fields: 100,
|
||||
max_pinvoke_imports: 100,
|
||||
max_native_implementations: 100,
|
||||
},
|
||||
};
|
||||
const managedApplicationGraph = json(
|
||||
await run(
|
||||
cli,
|
||||
[
|
||||
"project-managed-application-graph",
|
||||
JSON.stringify(managedApplicationGraphInput),
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
managedApplicationGraph.operation !== "project_managed_application_graph" ||
|
||||
managedApplicationGraph.provider?.id !== "rea-dotnet-workflows" ||
|
||||
managedApplicationGraph.confidence !== "inferred" ||
|
||||
managedApplicationGraph.normalized_result?.summary?.pinvoke_imports !== 1 ||
|
||||
managedApplicationGraph.normalized_result?.graph?.schema !==
|
||||
"JavaScriptApplicationGraph" ||
|
||||
!managedApplicationGraph.normalized_result?.graph?.nodes?.some(
|
||||
({ kind }) => kind === "managed-pinvoke-import",
|
||||
)
|
||||
)
|
||||
throw new Error("packaged managed application-graph CLI failed");
|
||||
};
|
||||
|
||||
const verifyManagedNativeVerification = async ({
|
||||
cli,
|
||||
managedBoundaries,
|
||||
environment,
|
||||
}) => {
|
||||
const managedNativeVerificationInput = {
|
||||
managed_boundaries: managedBoundaries,
|
||||
native_observations: [
|
||||
createEvidence(
|
||||
{
|
||||
path: "/system/user32.dll",
|
||||
sha256: "9".repeat(64),
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
},
|
||||
{
|
||||
id: "ghidra",
|
||||
name: "Ghidra",
|
||||
version: "12.1.2",
|
||||
},
|
||||
{
|
||||
operation: "analyze_function",
|
||||
parameters: { procedure: "MessageBoxW" },
|
||||
result: functionDossier("MessageBoxW"),
|
||||
rawResult: null,
|
||||
limitations: [],
|
||||
locations: [{ kind: "address", address: "0x401000" }],
|
||||
},
|
||||
),
|
||||
],
|
||||
limits: {
|
||||
max_native_observations: 20,
|
||||
max_candidates_per_import: 25,
|
||||
},
|
||||
};
|
||||
const managedNativeVerification = json(
|
||||
await run(
|
||||
cli,
|
||||
[
|
||||
"verify-managed-native-boundaries",
|
||||
JSON.stringify(managedNativeVerificationInput),
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
managedNativeVerification.operation !==
|
||||
"verify_managed_native_boundaries" ||
|
||||
managedNativeVerification.provider?.id !== "rea-dotnet-workflows" ||
|
||||
managedNativeVerification.normalized_result?.summary?.verified !== 1 ||
|
||||
managedNativeVerification.normalized_result?.algorithm
|
||||
?.token_to_address_mapping !== "not-inferred"
|
||||
)
|
||||
throw new Error("packaged managed/native verification CLI failed");
|
||||
};
|
||||
|
||||
const verifyManagedComparison = async ({
|
||||
cli,
|
||||
managedPath,
|
||||
managedRightPath,
|
||||
environment,
|
||||
}) => {
|
||||
const managedComparison = json(
|
||||
await run(
|
||||
cli,
|
||||
["compare-managed-members", managedPath, managedRightPath, "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
managedComparison.operation !== "compare_managed_members" ||
|
||||
managedComparison.provider?.id !== "rea-dotnet-workflows" ||
|
||||
managedComparison.normalized_result?.algorithm?.name_matching !== "not-used"
|
||||
)
|
||||
throw new Error("packaged managed comparison CLI failed");
|
||||
};
|
||||
|
||||
/** Exercise all packaged managed static and workflow CLIs. */
|
||||
export async function verifyManaged({ cli, workspace, environment }) {
|
||||
const { managedPath, managedRightPath } =
|
||||
await buildManagedFixtures(workspace);
|
||||
const managedArtifact = await verifyManagedArtifact({
|
||||
cli,
|
||||
managedPath,
|
||||
environment,
|
||||
});
|
||||
const managedMembers = await verifyManagedMembers({
|
||||
cli,
|
||||
managedPath,
|
||||
environment,
|
||||
});
|
||||
const managedMethod = managedMembers.normalized_result.methods.items[0];
|
||||
await verifyManagedReconstruction({
|
||||
cli,
|
||||
managedMembers,
|
||||
managedMethod,
|
||||
environment,
|
||||
});
|
||||
await verifyManagedRuntimePlan({
|
||||
cli,
|
||||
managedMembers,
|
||||
managedMethod,
|
||||
workspace,
|
||||
environment,
|
||||
});
|
||||
const managedBoundaries = await verifyManagedBoundaries({
|
||||
cli,
|
||||
managedPath,
|
||||
environment,
|
||||
});
|
||||
await verifyManagedApplicationGraph({
|
||||
cli,
|
||||
managedArtifact,
|
||||
managedMembers,
|
||||
managedBoundaries,
|
||||
environment,
|
||||
});
|
||||
await verifyManagedNativeVerification({
|
||||
cli,
|
||||
managedBoundaries,
|
||||
environment,
|
||||
});
|
||||
await verifyManagedComparison({
|
||||
cli,
|
||||
managedPath,
|
||||
managedRightPath,
|
||||
environment,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
|
||||
import * as prompts from "./verify-package-prompts.mjs";
|
||||
import { json } from "./lib/verify-package-core.mjs";
|
||||
|
||||
const verifyMcpToolsAndPrompts = async (client, mcpOptions) => {
|
||||
if (
|
||||
(await client.listTools(undefined, mcpOptions)).tools.length !==
|
||||
TOOL_CONTRACTS.length
|
||||
)
|
||||
throw new Error("packaged MCP tool inventory diverged from contracts");
|
||||
await prompts.verifyPromptCatalog(client, mcpOptions, prompts.names);
|
||||
await prompts.verifyPromptCompletion(client, mcpOptions, false);
|
||||
};
|
||||
|
||||
const verifyMcpReplay = async (client, mcpOptions, investigationReplay) => {
|
||||
const replay = await client.callTool(
|
||||
{
|
||||
name: "find_changed_behavior",
|
||||
arguments: { investigation_run: investigationReplay.arguments },
|
||||
},
|
||||
mcpOptions,
|
||||
);
|
||||
const replayEvidence = json(prompts.mcpText(replay));
|
||||
const replayWorkspace = json(
|
||||
await readFile(investigationReplay.workspacePath, "utf8"),
|
||||
);
|
||||
if (
|
||||
replay.isError === true ||
|
||||
replayEvidence.evidence_id !== investigationReplay.evidenceId ||
|
||||
replayWorkspace.revision !== investigationReplay.revision
|
||||
)
|
||||
throw new Error(
|
||||
"packaged MCP did not replay with workspace-only authority",
|
||||
);
|
||||
};
|
||||
|
||||
const verifyMcpTargetFree = async (client, mcpOptions) => {
|
||||
const result = await client.callTool(
|
||||
{ name: "current_document", arguments: {} },
|
||||
mcpOptions,
|
||||
);
|
||||
if (result.isError !== true)
|
||||
throw new Error("packaged target-free MCP omitted no-target error");
|
||||
};
|
||||
|
||||
const verifyMcpUnknownProvider = async (client, mcpOptions) => {
|
||||
const unknownProvider = await client.callTool(
|
||||
{
|
||||
name: "open_binary",
|
||||
arguments: {
|
||||
path: process.execPath,
|
||||
provider_id: "missing-provider",
|
||||
},
|
||||
},
|
||||
mcpOptions,
|
||||
);
|
||||
if (
|
||||
unknownProvider.isError !== true ||
|
||||
unknownProvider.structuredContent?.error?.details?.selection_reason !==
|
||||
"unknown_provider"
|
||||
)
|
||||
throw new Error("packaged MCP accepted an unknown analysis provider");
|
||||
};
|
||||
|
||||
const verifyMcpOpenAndBind = async (client, mcpOptions) => {
|
||||
const opened = await client.callTool(
|
||||
{
|
||||
name: "open_binary",
|
||||
arguments: { path: process.execPath, provider_id: "hopper" },
|
||||
},
|
||||
mcpOptions,
|
||||
);
|
||||
if (opened.isError === true)
|
||||
throw new Error("packaged MCP could not open a binary");
|
||||
const providerStatusEnvelope = json(
|
||||
prompts.mcpText(
|
||||
await client.callTool(
|
||||
{ name: "binary_session", arguments: {} },
|
||||
mcpOptions,
|
||||
),
|
||||
),
|
||||
);
|
||||
const providerStatus = providerStatusEnvelope.result;
|
||||
if (
|
||||
providerStatus.analysis_provider_binding?.provider?.id !== "hopper" ||
|
||||
providerStatus.analysis_provider_binding?.selection_source !== "request"
|
||||
)
|
||||
throw new Error("packaged MCP omitted its explicit Hopper binding");
|
||||
};
|
||||
|
||||
const verifyMcpLinuxCurrentDocument = async (client, mcpOptions, current) => {
|
||||
if (
|
||||
current.isError !== true ||
|
||||
!prompts
|
||||
.mcpText(current)
|
||||
.includes("not supported for unattended Linux analysis")
|
||||
)
|
||||
throw new Error("packaged Linux MCP did not reject an unpinned Hopper");
|
||||
};
|
||||
|
||||
const verifyMcpNonLinuxCurrentDocument = async (
|
||||
client,
|
||||
mcpOptions,
|
||||
current,
|
||||
) => {
|
||||
if (json(prompts.mcpText(current)).result !== "fixture")
|
||||
throw new Error("packaged MCP bridge call failed");
|
||||
const batch = await client.callTool(
|
||||
{
|
||||
name: "batch_decompile",
|
||||
arguments: { addresses: ["0x1000"] },
|
||||
},
|
||||
mcpOptions,
|
||||
);
|
||||
const batchResult = json(prompts.mcpText(batch)).result;
|
||||
if (
|
||||
batch.isError === true ||
|
||||
batchResult?.total !== 1 ||
|
||||
batchResult?.succeeded !== 1 ||
|
||||
batchResult?.failed !== 0 ||
|
||||
batchResult?.items?.[0]?.status !== "ok" ||
|
||||
batchResult?.items?.[0]?.pseudocode !== "return 0;"
|
||||
)
|
||||
throw new Error("packaged MCP structured batch result failed");
|
||||
};
|
||||
|
||||
const verifyMcpBinaryLifecycle = async (client, mcpOptions) => {
|
||||
await verifyMcpOpenAndBind(client, mcpOptions);
|
||||
await prompts.verifyPromptCompletion(
|
||||
client,
|
||||
mcpOptions,
|
||||
process.platform !== "linux",
|
||||
);
|
||||
const current = await client.callTool(
|
||||
{ name: "current_document", arguments: {} },
|
||||
mcpOptions,
|
||||
);
|
||||
if (process.platform === "linux") {
|
||||
await verifyMcpLinuxCurrentDocument(client, mcpOptions, current);
|
||||
} else {
|
||||
await verifyMcpNonLinuxCurrentDocument(client, mcpOptions, current);
|
||||
}
|
||||
const closed = await client.callTool(
|
||||
{ name: "close_binary", arguments: {} },
|
||||
mcpOptions,
|
||||
);
|
||||
if (closed.isError === true)
|
||||
throw new Error("packaged MCP could not close its binary");
|
||||
await prompts.verifyPromptCompletion(client, mcpOptions, false);
|
||||
};
|
||||
|
||||
const verifyMcpEvidenceBundle = async (client, mcpOptions, evidenceRoot) => {
|
||||
const mcpBundlePath = join(evidenceRoot, "mcp.json");
|
||||
const mcpExport = await client.callTool(
|
||||
{ name: "export_evidence_bundle", arguments: { path: mcpBundlePath } },
|
||||
mcpOptions,
|
||||
);
|
||||
if (mcpExport.isError === true)
|
||||
throw new Error("packaged MCP evidence export failed");
|
||||
const mcpImport = await client.callTool(
|
||||
{ name: "import_evidence_bundle", arguments: { path: mcpBundlePath } },
|
||||
mcpOptions,
|
||||
);
|
||||
if (mcpImport.isError === true)
|
||||
throw new Error("packaged MCP evidence import failed");
|
||||
};
|
||||
|
||||
/** Connect to the packaged MCP server and exercise the target-free catalog. */
|
||||
export async function verifyPackageMcp({
|
||||
cli,
|
||||
environment,
|
||||
evidenceRoot,
|
||||
investigationReplay,
|
||||
}) {
|
||||
const transport = new StdioClientTransport({
|
||||
command: cli,
|
||||
args: ["mcp"],
|
||||
env: {
|
||||
...environment,
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([]),
|
||||
},
|
||||
stderr: "pipe",
|
||||
});
|
||||
let mcpStderr = "";
|
||||
transport.stderr?.on("data", (chunk) => {
|
||||
mcpStderr += chunk.toString();
|
||||
});
|
||||
const client = new Client({ name: "package-smoke", version: "1.0.0" });
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const mcpOptions = { timeout: 15_000 };
|
||||
await verifyMcpToolsAndPrompts(client, mcpOptions);
|
||||
await verifyMcpReplay(client, mcpOptions, investigationReplay);
|
||||
await verifyMcpTargetFree(client, mcpOptions);
|
||||
await verifyMcpUnknownProvider(client, mcpOptions);
|
||||
await verifyMcpBinaryLifecycle(client, mcpOptions);
|
||||
await verifyMcpEvidenceBundle(client, mcpOptions, evidenceRoot);
|
||||
} catch (cause) {
|
||||
throw new Error(`packaged MCP smoke failed: ${mcpStderr}`, { cause });
|
||||
} finally {
|
||||
await client.close();
|
||||
await transport.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { join } from "node:path";
|
||||
|
||||
import { exec } from "./lib/verify-package-core.mjs";
|
||||
import { verifyPackedBridge } from "./verify-packed-bridge.mjs";
|
||||
|
||||
/** Create a tarball and assert production packaging constraints. */
|
||||
export async function verifyPackagePack({ root, workspace }) {
|
||||
const tarball = (
|
||||
await exec("npm", ["pack", "--silent"], { cwd: root })
|
||||
).stdout.trim();
|
||||
const packedFiles = (
|
||||
await exec("tar", ["-tf", join(root, tarball)])
|
||||
).stdout.split("\n");
|
||||
const packedManifest = JSON.parse(
|
||||
(await exec("tar", ["-xOf", join(root, tarball), "package/package.json"]))
|
||||
.stdout,
|
||||
);
|
||||
if (
|
||||
packedManifest.scripts?.postinstall !== undefined ||
|
||||
packedManifest.dependencies?.["node-pty"] !== undefined ||
|
||||
packedManifest.dependencies?.["@lydell/node-pty"] !== "1.1.0"
|
||||
)
|
||||
throw new Error("package retained a lifecycle-dependent PTY installation");
|
||||
if (
|
||||
packedFiles.some(
|
||||
(path) => path.includes("__pycache__") || path.endsWith(".pyc"),
|
||||
)
|
||||
) {
|
||||
throw new Error("package contained generated Python bytecode");
|
||||
}
|
||||
await verifyPackedBridge({ root, workspace, tarball, packedFiles });
|
||||
return { tarball };
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { json, run, runWithStatus } from "./lib/verify-package-core.mjs";
|
||||
|
||||
/** Run platform-specific deep-analysis smoke tests. */
|
||||
export async function verifyPackagePlatform({ cli, environment }) {
|
||||
if (process.platform === "linux") {
|
||||
const unsupportedExecution = await runWithStatus(
|
||||
cli,
|
||||
["analyze", process.execPath, "--json"],
|
||||
environment,
|
||||
);
|
||||
const unsupported = json(unsupportedExecution.stdout);
|
||||
if (
|
||||
unsupportedExecution.status !== 1 ||
|
||||
unsupported.details?.failure_code !== "unsupported_hopper_build"
|
||||
)
|
||||
throw new Error(
|
||||
`packaged Linux Hopper verification did not fail closed: ${JSON.stringify(unsupported)}`,
|
||||
);
|
||||
} else {
|
||||
const overview = json(
|
||||
await run(cli, ["analyze", process.execPath, "--json"], environment),
|
||||
);
|
||||
if (
|
||||
overview.operation !== "binary_overview" ||
|
||||
overview.normalized_result?.procedure_count < 1
|
||||
)
|
||||
throw new Error(
|
||||
`packaged Hopper-backed analyze CLI failed: ${JSON.stringify(overview)}`,
|
||||
);
|
||||
const inspected = json(
|
||||
await run(
|
||||
cli,
|
||||
[
|
||||
"inspect",
|
||||
process.execPath,
|
||||
"--detail",
|
||||
"detailed",
|
||||
"--limit",
|
||||
"1",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
inspected.operation !== "binary_overview" ||
|
||||
inspected.normalized_result?.detail !== "detailed"
|
||||
)
|
||||
throw new Error("packaged inspect CLI failed");
|
||||
const functionResult = json(
|
||||
await run(
|
||||
cli,
|
||||
["function", process.execPath, "0x1000", "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
functionResult.operation !== "analyze_function" ||
|
||||
functionResult.provider?.id !== "hopper" ||
|
||||
functionResult.normalized_result?.procedure?.address !== "0x1000"
|
||||
)
|
||||
throw new Error(
|
||||
`packaged function CLI failed: ${JSON.stringify(functionResult)}`,
|
||||
);
|
||||
const xrefs = json(
|
||||
await run(
|
||||
cli,
|
||||
["xrefs", process.execPath, "0x1000", "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (
|
||||
xrefs.operation !== "xrefs" ||
|
||||
JSON.stringify(xrefs.normalized_result) !== JSON.stringify(["0x1000"])
|
||||
)
|
||||
throw new Error(`packaged xrefs CLI failed: ${JSON.stringify(xrefs)}`);
|
||||
const trace = json(
|
||||
await run(
|
||||
cli,
|
||||
["trace", process.execPath, "fixture", "--json"],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
if (trace.operation !== "trace_feature")
|
||||
throw new Error(`packaged trace CLI failed: ${JSON.stringify(trace)}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
import {
|
||||
lstat,
|
||||
mkdir,
|
||||
readFile,
|
||||
rm,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
|
||||
import {
|
||||
json,
|
||||
pathExists,
|
||||
run,
|
||||
runWithStatus,
|
||||
} from "./lib/verify-package-core.mjs";
|
||||
|
||||
const verifyMcpAdd = async ({ cli, environment, npxLog }) => {
|
||||
await run(cli, ["mcp", "add"], environment);
|
||||
const mcpRegistration = await readFile(npxLog, "utf8");
|
||||
if (
|
||||
!mcpRegistration.includes("add-mcp npx -y rea-agents@latest mcp --name rea")
|
||||
)
|
||||
throw new Error("Incur mcp add did not register the latest npx command");
|
||||
};
|
||||
|
||||
const verifySetupPlan = async ({
|
||||
cli,
|
||||
environment,
|
||||
claudeConfig,
|
||||
cursorConfig,
|
||||
codexTarget,
|
||||
supportedSetupHost,
|
||||
}) => {
|
||||
const plannedExecution = await runWithStatus(
|
||||
cli,
|
||||
["setup", "--json"],
|
||||
environment,
|
||||
);
|
||||
const planned = json(plannedExecution.stdout);
|
||||
if (supportedSetupHost) {
|
||||
const plannedClaudeConfig = await readFile(claudeConfig, "utf8");
|
||||
const plannedCodexConfig = await readFile(codexTarget, "utf8");
|
||||
const plannedCursorConfig = await readFile(cursorConfig, "utf8");
|
||||
if (
|
||||
planned.status !== "needs_confirmation" ||
|
||||
plannedExecution.status !== 1 ||
|
||||
planned.appliedActions.length !== 0 ||
|
||||
!planned.plannedActions.some(({ kind }) => kind === "configure_client") ||
|
||||
!planned.plannedActions.some(({ kind }) => kind === "install_skill") ||
|
||||
plannedClaudeConfig !== '{"existing":true}\n' ||
|
||||
plannedCodexConfig !== 'model = "gpt-5"\n' ||
|
||||
plannedCursorConfig !== '{"existing":true}\n'
|
||||
)
|
||||
throw new Error(
|
||||
`packaged setup plan was not read-only: ${JSON.stringify({ status: planned.status, exitCode: plannedExecution.status, plannedKinds: planned.plannedActions.map(({ kind }) => kind), appliedKinds: planned.appliedActions.map(({ kind }) => kind), claudeConfig: plannedClaudeConfig, codexConfig: plannedCodexConfig, cursorConfig: plannedCursorConfig })}`,
|
||||
);
|
||||
}
|
||||
return { planned };
|
||||
};
|
||||
|
||||
const verifySetupApply = async ({ cli, environment, supportedSetupHost }) => {
|
||||
const status = process.platform === "linux" ? "needs_human" : "ready";
|
||||
const firstExecution = await runWithStatus(
|
||||
cli,
|
||||
["setup", "--yes", "--json"],
|
||||
environment,
|
||||
);
|
||||
const first = json(firstExecution.stdout);
|
||||
const alignedExecution = await runWithStatus(
|
||||
cli,
|
||||
["setup", "--json"],
|
||||
environment,
|
||||
);
|
||||
const aligned = json(alignedExecution.stdout);
|
||||
const secondExecution = await runWithStatus(
|
||||
cli,
|
||||
["setup", "--install-hopper", "--json"],
|
||||
environment,
|
||||
);
|
||||
const second = json(secondExecution.stdout);
|
||||
if (supportedSetupHost) {
|
||||
if (
|
||||
first.status !== status ||
|
||||
second.status !== "needs_confirmation" ||
|
||||
firstExecution.status !== (status === "ready" ? 0 : 1) ||
|
||||
secondExecution.status !== 1 ||
|
||||
aligned.status !== status ||
|
||||
alignedExecution.status !== (status === "ready" ? 0 : 1) ||
|
||||
aligned.plannedActions.length !== 0 ||
|
||||
aligned.appliedActions.length !== 0 ||
|
||||
!second.plannedActions.some(({ kind }) => kind === "install_hopper") ||
|
||||
second.appliedActions.length !== 0
|
||||
)
|
||||
throw new Error(
|
||||
`packaged setup did not preserve idempotent defaults and explicit Hopper reinstall behavior: ${JSON.stringify({ first, aligned, second })}`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
first,
|
||||
aligned,
|
||||
second,
|
||||
firstExecution,
|
||||
alignedExecution,
|
||||
secondExecution,
|
||||
status,
|
||||
};
|
||||
};
|
||||
|
||||
const assertClientConfig = async (cli, configPath) => {
|
||||
const config = json(await readFile(configPath, "utf8"));
|
||||
if (
|
||||
config.existing !== true ||
|
||||
config.mcpServers?.rea?.command !== cli ||
|
||||
JSON.stringify(config.mcpServers?.rea?.args) !== JSON.stringify(["mcp"])
|
||||
)
|
||||
throw new Error("packaged client readback failed");
|
||||
if (
|
||||
!(await readFile(`${configPath}.rea.backup`, "utf8")).includes("existing")
|
||||
)
|
||||
throw new Error("packaged client backup failed");
|
||||
};
|
||||
|
||||
const assertCodexSymlink = async ({
|
||||
cli,
|
||||
codexConfig,
|
||||
cursorConfig,
|
||||
codexTarget,
|
||||
}) => {
|
||||
const codex = await readFile(codexTarget, "utf8");
|
||||
if (
|
||||
!(await lstat(codexConfig)).isSymbolicLink() ||
|
||||
!(await lstat(cursorConfig)).isSymbolicLink() ||
|
||||
!codex.includes("[mcp_servers.rea]") ||
|
||||
!codex.includes(`command = "${cli}"`) ||
|
||||
(await readFile(`${codexConfig}.rea.backup`, "utf8")) !==
|
||||
'model = "gpt-5"\n' ||
|
||||
(await readFile(`${cursorConfig}.rea.backup`, "utf8")) !==
|
||||
'{"existing":true}\n'
|
||||
)
|
||||
throw new Error("packaged setup did not preserve config symlinks");
|
||||
};
|
||||
|
||||
const assertSkill = async ({ skillPath, siblingSkillPath, root }) => {
|
||||
const skill = await readFile(skillPath, "utf8");
|
||||
const canonicalSkill = await readFile(
|
||||
join(root, "skills/reverse-engineer-anything/SKILL.md"),
|
||||
"utf8",
|
||||
);
|
||||
if (skill !== canonicalSkill)
|
||||
throw new Error("packaged skill did not match its canonical source");
|
||||
if ((await readFile(siblingSkillPath, "utf8")) !== "unrelated skill\n")
|
||||
throw new Error("packaged skill installation modified a sibling skill");
|
||||
};
|
||||
|
||||
const assertAlignedDoctor = async (cli, environment) => {
|
||||
const alignedDoctorExecution = await runWithStatus(
|
||||
cli,
|
||||
["doctor", "--json"],
|
||||
environment,
|
||||
);
|
||||
const alignedDoctor = json(alignedDoctorExecution.stdout);
|
||||
if (
|
||||
alignedDoctorExecution.status !== (alignedDoctor.healthy ? 0 : 1) ||
|
||||
alignedDoctor.identity?.skill?.state !== "aligned" ||
|
||||
alignedDoctor.identity?.skill?.installed_tool_count !==
|
||||
TOOL_CONTRACTS.length ||
|
||||
alignedDoctor.checks?.some(({ name }) => name === "skill:identity")
|
||||
)
|
||||
throw new Error(
|
||||
"packaged doctor did not report the upgraded skill aligned",
|
||||
);
|
||||
};
|
||||
|
||||
const verifyConfigReadback = async ({
|
||||
cli,
|
||||
environment,
|
||||
claudeConfig,
|
||||
cursorConfig,
|
||||
codexConfig,
|
||||
codexTarget,
|
||||
root,
|
||||
skillPath,
|
||||
siblingSkillPath,
|
||||
}) => {
|
||||
await assertClientConfig(cli, claudeConfig);
|
||||
await assertClientConfig(cli, cursorConfig);
|
||||
await assertCodexSymlink({
|
||||
cli,
|
||||
codexConfig,
|
||||
cursorConfig,
|
||||
codexTarget,
|
||||
});
|
||||
await assertSkill({ skillPath, siblingSkillPath, root });
|
||||
await assertAlignedDoctor(cli, environment);
|
||||
};
|
||||
|
||||
const verifySetupFailureRecovery = async ({
|
||||
cli,
|
||||
environment,
|
||||
claudeConfig,
|
||||
cursorConfig,
|
||||
status,
|
||||
}) => {
|
||||
await writeFile(claudeConfig, "malformed");
|
||||
await writeFile(cursorConfig, '{"existing":true}\n');
|
||||
const failedExecution = await runWithStatus(
|
||||
cli,
|
||||
["setup", "--yes", "--json"],
|
||||
environment,
|
||||
);
|
||||
const failed = json(failedExecution.stdout);
|
||||
if (
|
||||
failed.status !== "needs_human" ||
|
||||
failedExecution.status !== 1 ||
|
||||
failed.clients?.claude_desktop?.status !== "failed" ||
|
||||
failed.clients?.cursor?.status !== "configured" ||
|
||||
!failed.appliedActions.includes("configured_cursor") ||
|
||||
(await readFile(claudeConfig, "utf8")) !== "malformed" ||
|
||||
json(await readFile(cursorConfig, "utf8")).mcpServers?.rea?.command !== cli
|
||||
)
|
||||
throw new Error(
|
||||
`packaged setup did not continue after an earlier client failure: ${JSON.stringify(failed)}`,
|
||||
);
|
||||
await writeFile(claudeConfig, "{}\n");
|
||||
const recoveredExecution = await runWithStatus(
|
||||
cli,
|
||||
["setup", "--yes", "--json"],
|
||||
environment,
|
||||
);
|
||||
const recovered = json(recoveredExecution.stdout);
|
||||
if (
|
||||
recovered.status !== status ||
|
||||
recoveredExecution.status !== (status === "ready" ? 0 : 1)
|
||||
)
|
||||
throw new Error("packaged setup did not recover");
|
||||
};
|
||||
|
||||
const verifyDanglingSymlink = async ({ cli, environment, home }) => {
|
||||
const geminiDir = join(home, ".gemini");
|
||||
const geminiConfig = join(geminiDir, "settings.json");
|
||||
await mkdir(geminiDir, { recursive: true });
|
||||
await symlink(join(home, "missing-gemini.json"), geminiConfig);
|
||||
const danglingExecution = await runWithStatus(
|
||||
cli,
|
||||
["setup", "--yes", "--json"],
|
||||
environment,
|
||||
);
|
||||
const dangling = json(danglingExecution.stdout);
|
||||
if (
|
||||
dangling.status !== "needs_human" ||
|
||||
danglingExecution.status !== 1 ||
|
||||
dangling.clients?.gemini_cli?.status !== "failed" ||
|
||||
dangling.clients?.gemini_cli?.reason !== "path" ||
|
||||
!(await lstat(geminiConfig)).isSymbolicLink() ||
|
||||
(await pathExists(`${geminiConfig}.rea.backup`))
|
||||
)
|
||||
throw new Error(
|
||||
`packaged setup did not reject a dangling config symlink before mutation: ${JSON.stringify(dangling)}`,
|
||||
);
|
||||
await rm(geminiDir, { recursive: true });
|
||||
};
|
||||
|
||||
const verifyUninstall = async ({
|
||||
cli,
|
||||
environment,
|
||||
cursorConfig,
|
||||
codexConfig,
|
||||
cursorTarget,
|
||||
codexTarget,
|
||||
}) => {
|
||||
const uninstallExecution = await runWithStatus(
|
||||
cli,
|
||||
["uninstall", "--json"],
|
||||
environment,
|
||||
);
|
||||
const uninstall = json(uninstallExecution.stdout);
|
||||
const cursorAfterUninstall = json(await readFile(cursorTarget, "utf8"));
|
||||
const codexAfterUninstall = await readFile(codexTarget, "utf8");
|
||||
if (
|
||||
uninstall.status !== "complete" ||
|
||||
uninstallExecution.status !== 0 ||
|
||||
uninstall.items?.find(({ name }) => name === "cursor")?.status !==
|
||||
"removed" ||
|
||||
uninstall.items?.find(({ name }) => name === "codex")?.status !==
|
||||
"removed" ||
|
||||
!(await lstat(cursorConfig)).isSymbolicLink() ||
|
||||
!(await lstat(codexConfig)).isSymbolicLink() ||
|
||||
cursorAfterUninstall.existing !== true ||
|
||||
cursorAfterUninstall.mcpServers?.rea !== undefined ||
|
||||
!codexAfterUninstall.includes('model = "gpt-5"') ||
|
||||
codexAfterUninstall.includes("mcp_servers.rea") ||
|
||||
!(await readFile(`${cursorConfig}.rea.backup`, "utf8")).includes('"rea"') ||
|
||||
!(await readFile(`${codexConfig}.rea.backup`, "utf8")).includes(
|
||||
"[mcp_servers.rea]",
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
`packaged uninstall did not preserve config symlinks: ${JSON.stringify(uninstall)}`,
|
||||
);
|
||||
};
|
||||
|
||||
/** Verify setup transactions, skill installation, and uninstall for supported hosts. */
|
||||
export async function verifyPackageSetup({
|
||||
cli,
|
||||
environment,
|
||||
home,
|
||||
npxLog,
|
||||
claudeConfig,
|
||||
codexConfig,
|
||||
cursorConfig,
|
||||
codexTarget,
|
||||
cursorTarget,
|
||||
supportedSetupHost,
|
||||
root,
|
||||
}) {
|
||||
await verifyMcpAdd({ cli, environment, npxLog });
|
||||
const skillPath = join(
|
||||
home,
|
||||
".agents/skills/reverse-engineer-anything/SKILL.md",
|
||||
);
|
||||
const siblingSkillPath = join(home, ".agents/skills/unrelated/SKILL.md");
|
||||
if (supportedSetupHost) {
|
||||
await mkdir(join(home, ".agents/skills/unrelated"), { recursive: true });
|
||||
await writeFile(siblingSkillPath, "unrelated skill\n");
|
||||
}
|
||||
await verifySetupPlan({
|
||||
cli,
|
||||
environment,
|
||||
claudeConfig,
|
||||
cursorConfig,
|
||||
codexTarget,
|
||||
supportedSetupHost,
|
||||
});
|
||||
const apply = await verifySetupApply({
|
||||
cli,
|
||||
environment,
|
||||
supportedSetupHost,
|
||||
});
|
||||
if (supportedSetupHost) {
|
||||
await verifyConfigReadback({
|
||||
cli,
|
||||
environment,
|
||||
claudeConfig,
|
||||
cursorConfig,
|
||||
codexConfig,
|
||||
codexTarget,
|
||||
root,
|
||||
skillPath,
|
||||
siblingSkillPath,
|
||||
});
|
||||
await verifySetupFailureRecovery({
|
||||
cli,
|
||||
environment,
|
||||
claudeConfig,
|
||||
cursorConfig,
|
||||
status: apply.status,
|
||||
});
|
||||
await verifyDanglingSymlink({ cli, environment, home });
|
||||
await verifyUninstall({
|
||||
cli,
|
||||
environment,
|
||||
cursorConfig,
|
||||
codexConfig,
|
||||
cursorTarget,
|
||||
codexTarget,
|
||||
});
|
||||
} else if (
|
||||
apply.first.status !== "needs_human" ||
|
||||
apply.aligned.status !== "needs_human" ||
|
||||
apply.second.status !== "needs_human"
|
||||
) {
|
||||
throw new Error("packaged setup did not reject an unsupported host");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { json, runWithStatus } from "./lib/verify-package-core.mjs";
|
||||
|
||||
/** Verify that an unknown --provider is rejected by the packaged CLI. */
|
||||
export async function verifyUnknownProvider({ cli, environment }) {
|
||||
const unknownProviderExecution = await runWithStatus(
|
||||
cli,
|
||||
["analyze", process.execPath, "--provider", "missing-provider", "--json"],
|
||||
environment,
|
||||
);
|
||||
const unknownProvider = json(unknownProviderExecution.stdout);
|
||||
if (
|
||||
unknownProviderExecution.status !== 1 ||
|
||||
unknownProvider.details?.selection_reason !== "unknown_provider" ||
|
||||
unknownProvider.details?.requested_provider_id !== "missing-provider"
|
||||
)
|
||||
throw new Error(
|
||||
`packaged CLI provider selection failed: ${JSON.stringify(unknownProvider)}`,
|
||||
);
|
||||
}
|
||||
+83
-1190
File diff suppressed because it is too large
Load Diff
@@ -20,6 +20,7 @@ import {
|
||||
} from "../dist/domain/webScreenshot.js";
|
||||
import { startBrowserVerifierSite } from "./fixtures/browser-verifier-site.mjs";
|
||||
import { startPageCdpProxy } from "./fixtures/page-cdp-proxy.mjs";
|
||||
import { sourceMapSummary } from "./lib/browser-verifier-assertions.mjs";
|
||||
|
||||
const SECRET_VALUES = [
|
||||
"network-secret-value",
|
||||
@@ -334,6 +335,13 @@ async function pageTarget(provider, endpoint, origin) {
|
||||
}
|
||||
|
||||
function assertObservation(result, origin) {
|
||||
assertObservationInventory(result, origin);
|
||||
assertObservationEvents(result);
|
||||
assertObservationPrivacy(result);
|
||||
assertObservationMetadata(result);
|
||||
}
|
||||
|
||||
function assertObservationInventory(result, origin) {
|
||||
if (result.target.origin !== origin)
|
||||
throw new Error("Real Chrome target origin was not preserved exactly");
|
||||
if (result.frames.length < 1 || result.dom.nodes.length < 1)
|
||||
@@ -353,6 +361,9 @@ function assertObservation(result, origin) {
|
||||
throw new Error("Real Chrome script metadata was missing");
|
||||
if (!result.resources.some((resource) => resource.url.includes("/app.js")))
|
||||
throw new Error("Real Chrome resource metadata was missing");
|
||||
}
|
||||
|
||||
function assertObservationEvents(result) {
|
||||
if (!result.network.requests.some((request) => request.url.includes("/api")))
|
||||
throw new Error(
|
||||
"Real Chrome attach-window network observation was missing",
|
||||
@@ -372,6 +383,9 @@ function assertObservation(result, origin) {
|
||||
);
|
||||
if (result.network.websocket_events.length < 1)
|
||||
throw new Error("Real Chrome WebSocket metadata was missing");
|
||||
}
|
||||
|
||||
function assertObservationPrivacy(result) {
|
||||
if (
|
||||
result.console.events.some(
|
||||
(event) => event.text_capture.status !== "not_approved",
|
||||
@@ -386,6 +400,9 @@ function assertObservation(result, origin) {
|
||||
throw new Error(
|
||||
"Sensitive text or payload shapes were retained without approval",
|
||||
);
|
||||
}
|
||||
|
||||
function assertObservationMetadata(result) {
|
||||
if (!result.storage.local_storage_keys.includes("rea-storage-key"))
|
||||
throw new Error("Real Chrome local-storage key inventory was missing");
|
||||
if (!result.storage.indexed_db_names.includes("rea-browser-db"))
|
||||
@@ -431,25 +448,6 @@ function assertBundleAnalysis(result) {
|
||||
);
|
||||
}
|
||||
|
||||
function sourceMapSummary(sourceMaps) {
|
||||
return {
|
||||
status: sourceMaps.status,
|
||||
requested: sourceMaps.requested,
|
||||
processed: sourceMaps.processed,
|
||||
dropped: sourceMaps.dropped,
|
||||
items: sourceMaps.items.map((item) => ({
|
||||
status: item.status,
|
||||
declaredUrl: item.declared_url,
|
||||
sources: item.original_sources.map(({ source }) => source),
|
||||
edgeSpecifiers: item.original_module_edges.map(({ specifier }) =>
|
||||
specifier.slice(0, 256),
|
||||
),
|
||||
mappings: item.mappings.length,
|
||||
limitation: item.limitation,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function assertSensitiveShapes(result) {
|
||||
const request = result.network.requests.find((item) =>
|
||||
item.url.includes("/api"),
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
import { access } from "node:fs/promises";
|
||||
|
||||
import { parseBinaryTarget } from "../dist/domain/binaryTarget.js";
|
||||
import { SUPPORTED_GHIDRA_VERSION } from "../dist/ghidra/GhidraInstallation.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "../dist/ghidra/GhidraSessionValues.js";
|
||||
|
||||
export function assertLocalProcedureInfo(info, expectedAddress) {
|
||||
if (
|
||||
info.entrypoint !== expectedAddress ||
|
||||
info.basicblock_count < 1 ||
|
||||
info.length < 1 ||
|
||||
typeof info.signature !== "string" ||
|
||||
info.signature.length === 0 ||
|
||||
info.classification.external ||
|
||||
info.classification.provenance !== "ghidra-function-manager"
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra procedure metadata drifted: ${JSON.stringify(info)}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function assertProviderText(assembly, pseudocode, expectedAddress) {
|
||||
if (
|
||||
typeof assembly !== "string" ||
|
||||
!assembly.includes(`${expectedAddress}:`) ||
|
||||
assembly.trim().length === 0
|
||||
)
|
||||
throw new Error("Ghidra assembly rendering lost its address-bearing lines");
|
||||
if (typeof pseudocode !== "string" || pseudocode.trim().length === 0)
|
||||
throw new Error("Ghidra local function pseudocode is unavailable");
|
||||
}
|
||||
|
||||
export function assertReferenceMetadata(observed) {
|
||||
if (
|
||||
observed.instructions_scanned < 1 ||
|
||||
observed.instruction_scan_truncated ||
|
||||
observed.references.items.length === 0 ||
|
||||
!observed.references.items.every(
|
||||
({ kind }) =>
|
||||
kind.available && kind.provenance === "ghidra-reference-manager",
|
||||
) ||
|
||||
!observed.references.items.some(({ kind }) => kind.call) ||
|
||||
!observed.references.items.some(({ kind }) => kind.data)
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra typed reference metadata drifted: ${JSON.stringify(observed)}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function assertDossier(
|
||||
dossier,
|
||||
{
|
||||
address,
|
||||
expectedCallees = [],
|
||||
expectedString = null,
|
||||
requireAssembly = false,
|
||||
requireMultiBlock = false,
|
||||
},
|
||||
) {
|
||||
assertDossierProcedure(dossier, address);
|
||||
assertDossierReferences(dossier);
|
||||
assertDossierCallees(dossier, expectedCallees);
|
||||
assertDossierStrings(dossier, expectedString);
|
||||
assertDossierAssembly(dossier, requireAssembly);
|
||||
assertDossierMultiBlock(dossier, requireMultiBlock);
|
||||
}
|
||||
|
||||
function assertDossierProcedure(dossier, address) {
|
||||
if (
|
||||
dossier.procedure.address !== address ||
|
||||
dossier.procedure.classification === null ||
|
||||
dossier.procedure.classification.provenance !== "ghidra-function-manager" ||
|
||||
dossier.procedure.classification.external ||
|
||||
dossier.pseudocode.text.trim().length === 0 ||
|
||||
dossier.pseudocode.returned_chars !== [...dossier.pseudocode.text].length ||
|
||||
dossier.instruction_scan.scanned < 1 ||
|
||||
dossier.instruction_scan.truncated ||
|
||||
!dossier.limitations.some((value) => /indirect|computed/u.test(value)) ||
|
||||
!dossier.limitations.some((value) => /Ghidra|Hopper|provider/u.test(value))
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra dossier truthfulness drifted: ${JSON.stringify(dossier)}`,
|
||||
);
|
||||
}
|
||||
|
||||
function assertDossierReferences(dossier) {
|
||||
if (
|
||||
![
|
||||
...dossier.incoming_references.items,
|
||||
...dossier.outgoing_references.items,
|
||||
].every(
|
||||
({ kind }) =>
|
||||
kind.available && kind.provenance === "ghidra-reference-manager",
|
||||
)
|
||||
)
|
||||
throw new Error("Ghidra dossier lost typed reference provenance");
|
||||
}
|
||||
|
||||
function assertDossierCallees(dossier, expectedCallees) {
|
||||
for (const expected of expectedCallees)
|
||||
if (!dossier.callees.items.some(({ address: value }) => value === expected))
|
||||
throw new Error(`Ghidra dossier missed callee ${expected}`);
|
||||
}
|
||||
|
||||
function assertDossierStrings(dossier, expectedString) {
|
||||
if (
|
||||
expectedString !== null &&
|
||||
!dossier.referenced_strings.items.some(
|
||||
({ value }) => value === expectedString,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra dossier missed referenced string ${expectedString}`,
|
||||
);
|
||||
}
|
||||
|
||||
function assertDossierAssembly(dossier, requireAssembly) {
|
||||
if (
|
||||
requireAssembly &&
|
||||
(dossier.assembly.items.length === 0 || dossier.assembly.truncated)
|
||||
)
|
||||
throw new Error("Ghidra dossier assembly was unavailable or truncated");
|
||||
}
|
||||
|
||||
function assertDossierMultiBlock(dossier, requireMultiBlock) {
|
||||
if (
|
||||
requireMultiBlock &&
|
||||
(dossier.basic_blocks.items.length < 2 ||
|
||||
!dossier.basic_blocks.items.some(
|
||||
({ successors }) => successors.length > 0,
|
||||
))
|
||||
)
|
||||
throw new Error(
|
||||
"Ghidra dossier CFG missed the multi-block branch structure",
|
||||
);
|
||||
}
|
||||
|
||||
export function dossierSummary(dossier) {
|
||||
return {
|
||||
address: dossier.procedure.address,
|
||||
pseudocode_chars: dossier.pseudocode.total_chars,
|
||||
instructions: dossier.instruction_scan.scanned,
|
||||
callees: dossier.callees.returned,
|
||||
outgoing_references: dossier.outgoing_references.returned,
|
||||
referenced_strings: dossier.referenced_strings.returned,
|
||||
basic_blocks: dossier.basic_blocks.returned,
|
||||
};
|
||||
}
|
||||
|
||||
export async function assertSession(
|
||||
session,
|
||||
expectedDigest,
|
||||
expectedTargetSha256,
|
||||
) {
|
||||
if (
|
||||
session.provider.id !== "ghidra" ||
|
||||
session.provider.version !== SUPPORTED_GHIDRA_VERSION ||
|
||||
session.profile_digest !== expectedDigest ||
|
||||
session.target.sha256 !== expectedTargetSha256 ||
|
||||
session.read_only !== true ||
|
||||
session.analysis_complete !== true ||
|
||||
session.analysis_timed_out !== false ||
|
||||
session.capabilities.join(",") !== GHIDRA_SESSION_CAPABILITIES.join(",") ||
|
||||
!/^0x[0-9a-f]+$/u.test(session.target.image_base) ||
|
||||
session.target.default_address_space.length === 0
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra session commitment drifted: ${JSON.stringify(session)}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function assertRuntimeCoordinates(coordinates) {
|
||||
for (const name of ["runtime_root", "endpoint_path", "project_root"])
|
||||
if (typeof coordinates[name] !== "string")
|
||||
throw new Error(`Ghidra verifier did not observe ${name}`);
|
||||
if (typeof coordinates.process_id !== "number")
|
||||
throw new Error("Ghidra verifier did not observe its process ID");
|
||||
}
|
||||
|
||||
export async function assertCleanup(coordinates) {
|
||||
for (const name of ["runtime_root", "endpoint_path", "project_root"]) {
|
||||
const path = coordinates[name];
|
||||
if (typeof path === "string" && (await exists(path)))
|
||||
throw new Error(`Ghidra cleanup left ${name}: ${path}`);
|
||||
}
|
||||
const pid = coordinates.process_id;
|
||||
if (typeof pid === "number" && processExists(pid))
|
||||
throw new Error(`Ghidra cleanup left process ${String(pid)}`);
|
||||
}
|
||||
|
||||
export function assertDebugFixture(observed) {
|
||||
if (
|
||||
!Array.isArray(observed.documents) ||
|
||||
observed.documents.length !== 1 ||
|
||||
!observed.documents[0].includes("debug")
|
||||
)
|
||||
throw new Error("Ghidra did not expose exactly one debug Program identity");
|
||||
const entry = findValue(observed.procedures, "rea_ghidra_inventory_entry");
|
||||
const leaf = findValue(observed.procedures, "rea_ghidra_inventory_leaf");
|
||||
const external = observed.procedures.find(
|
||||
(item) => item.procedure.external && symbolTail(item.value) === "puts",
|
||||
);
|
||||
if (entry === undefined || leaf === undefined || external === undefined)
|
||||
throw new Error(
|
||||
"Ghidra procedure inventory missed local or external functions",
|
||||
);
|
||||
if (
|
||||
!observed.procedures.some(
|
||||
(item) => item.procedure.thunk && item.procedure.thunk_target !== null,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
"Ghidra procedure inventory did not distinguish a resolved thunk",
|
||||
);
|
||||
const entryName = findValue(observed.names, "rea_ghidra_inventory_entry");
|
||||
if (entryName === undefined || !entryName.symbol.primary)
|
||||
throw new Error("Ghidra symbol inventory missed the primary entry symbol");
|
||||
if (!observed.names.some((item) => item.symbol.external))
|
||||
throw new Error("Ghidra symbol inventory missed external symbols");
|
||||
assertStrings(observed.strings);
|
||||
assertSegments(observed.segments, observed.session.target.image_base);
|
||||
}
|
||||
|
||||
export function assertStrippedFixture(observed) {
|
||||
if (
|
||||
observed.procedures.length === 0 ||
|
||||
observed.names.length === 0 ||
|
||||
findValue(observed.procedures, "rea_ghidra_inventory_entry") !== undefined
|
||||
)
|
||||
throw new Error(
|
||||
"Stripped Ghidra fixture did not preserve stripped semantics",
|
||||
);
|
||||
assertStrings(observed.strings);
|
||||
assertSegments(observed.segments, observed.session.target.image_base);
|
||||
}
|
||||
|
||||
export function assertCrossFixture(observed) {
|
||||
if (
|
||||
observed.procedures.length === 0 ||
|
||||
observed.names.length === 0 ||
|
||||
observed.probes === null ||
|
||||
typeof observed.probes.entry !== "string" ||
|
||||
observed.probes.string_owner.referenced_strings < 1 ||
|
||||
observed.probes.branch.basic_blocks < 2
|
||||
)
|
||||
throw new Error(
|
||||
`Cross-format Ghidra semantics drifted: ${JSON.stringify(summary(observed))}`,
|
||||
);
|
||||
assertSegments(observed.segments, observed.session.target.image_base);
|
||||
}
|
||||
|
||||
export async function assertMalformedFixture(path) {
|
||||
const parsed = await parseBinaryTarget(path);
|
||||
if (parsed.ok || parsed.error._tag !== "BinaryTargetError")
|
||||
throw new Error(
|
||||
"Malformed executable was not rejected before provider start",
|
||||
);
|
||||
}
|
||||
|
||||
export function assertStrings(strings) {
|
||||
for (const expected of [
|
||||
"REA_GHIDRA_INVENTORY_ENTRY",
|
||||
"REA_GHIDRA_LEAF_VALUE",
|
||||
]) {
|
||||
const item = strings.find((candidate) => candidate.value === expected);
|
||||
if (
|
||||
item === undefined ||
|
||||
item.value_truncated ||
|
||||
typeof item.string.encoding !== "string" ||
|
||||
item.string.byte_length < expected.length
|
||||
)
|
||||
throw new Error(`Ghidra string inventory missed ${expected}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertSegments(segments, imageBase) {
|
||||
if (
|
||||
!Array.isArray(segments) ||
|
||||
segments.length === 0 ||
|
||||
!segments.some((item) => item.executable) ||
|
||||
!segments.some((item) => item.writable) ||
|
||||
!segments.every(
|
||||
(item) =>
|
||||
item.permissions.available === true &&
|
||||
item.permissions.source === "ghidra-memory-block" &&
|
||||
item.image_base === imageBase,
|
||||
)
|
||||
)
|
||||
throw new Error("Ghidra memory-block permissions or image base drifted");
|
||||
}
|
||||
|
||||
export function findValue(items, expected) {
|
||||
return items.find((item) => symbolTail(item.value) === expected);
|
||||
}
|
||||
|
||||
export function requireProcedure(items, expected) {
|
||||
const observed = findValue(items, expected);
|
||||
if (observed === undefined)
|
||||
throw new Error(`Ghidra procedure probe is unavailable: ${expected}`);
|
||||
return observed;
|
||||
}
|
||||
|
||||
export function matchesSymbol(value, expected) {
|
||||
const tail = symbolTail(value);
|
||||
return tail === expected || tail === `_${expected}`;
|
||||
}
|
||||
|
||||
export function symbolTail(value) {
|
||||
if (typeof value !== "string") return undefined;
|
||||
return value.split("::").at(-1);
|
||||
}
|
||||
|
||||
export function summary(observed) {
|
||||
return {
|
||||
variant: observed.variant,
|
||||
target_path: observed.target.path,
|
||||
target_sha256: observed.target.sha256,
|
||||
analysis_profile_digest: observed.profile.digest,
|
||||
language_id: observed.session.target.language_id,
|
||||
compiler_spec_id: observed.session.target.compiler_spec_id,
|
||||
image_base: observed.session.target.image_base,
|
||||
procedures: observed.procedures.length,
|
||||
names: observed.names.length,
|
||||
strings: observed.strings.length,
|
||||
memory_blocks: observed.segments.length,
|
||||
};
|
||||
}
|
||||
|
||||
async function exists(path) {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function processExists(pid) {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
return !(
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
cause.code === "ESRCH"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
import {
|
||||
parseGhidraFunctionInput,
|
||||
parseGhidraFunctionResult,
|
||||
} from "../dist/ghidra/GhidraFunctionValues.js";
|
||||
|
||||
import {
|
||||
assertDossier,
|
||||
assertLocalProcedureInfo,
|
||||
assertProviderText,
|
||||
assertReferenceMetadata,
|
||||
dossierSummary,
|
||||
matchesSymbol,
|
||||
requireProcedure,
|
||||
} from "./verify-real-ghidra-assertions.mjs";
|
||||
|
||||
export async function functionCall(client, operation, parameters) {
|
||||
const input = parseGhidraFunctionInput(operation, parameters);
|
||||
if (!input.ok) throw input.error;
|
||||
const called = await client.callTool(operation, input.value);
|
||||
if (!called.ok)
|
||||
throw new Error(
|
||||
`Ghidra ${operation} failed for ${JSON.stringify(input.value)}: ${called.error.message}`,
|
||||
{ cause: called.error },
|
||||
);
|
||||
const parsed = parseGhidraFunctionResult(operation, called.value);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
return parsed.value;
|
||||
}
|
||||
|
||||
export async function verifyDebugFunctionOperations(
|
||||
client,
|
||||
{ procedures, strings, entry },
|
||||
) {
|
||||
const leaf = requireProcedure(procedures, "rea_ghidra_inventory_leaf");
|
||||
const branch = requireProcedure(procedures, "rea_ghidra_inventory_branch");
|
||||
const indirect = requireProcedure(
|
||||
procedures,
|
||||
"rea_ghidra_inventory_indirect",
|
||||
);
|
||||
const main = requireProcedure(procedures, "main");
|
||||
const entryString = strings.find(
|
||||
(item) => item.value === "REA_GHIDRA_INVENTORY_ENTRY",
|
||||
);
|
||||
if (entryString === undefined)
|
||||
throw new Error("Ghidra debug string function probe is unavailable");
|
||||
|
||||
const [info, assembly, pseudocode, callees, callers, outgoing, entryXrefs] =
|
||||
await collectEntryFunctionData(client, entry);
|
||||
assertLocalProcedureInfo(info, entry.address);
|
||||
assertProviderText(assembly, pseudocode, entry.address);
|
||||
assertEntryCallGraph({ branch, indirect, main, callees, callers });
|
||||
const { xrefOwners, xrefOwnerFailures } = await resolveXrefOwners(
|
||||
client,
|
||||
entryXrefs,
|
||||
);
|
||||
assertEntryXrefAttribution({
|
||||
entryXrefs,
|
||||
callers,
|
||||
xrefOwners,
|
||||
xrefOwnerFailures,
|
||||
main,
|
||||
});
|
||||
assertReferenceMetadata(outgoing);
|
||||
await assertStringXrefs(client, entryString.address);
|
||||
|
||||
const entryDossier = await analyzeEntryDossier(
|
||||
client,
|
||||
entry,
|
||||
branch,
|
||||
indirect,
|
||||
);
|
||||
const branchDossier = await analyzeBranchDossier(client, branch);
|
||||
const indirectDossier = await analyzeIndirectDossier(client, indirect);
|
||||
assertIndirectDossier(indirectDossier, leaf.address);
|
||||
|
||||
const { cancellation, timeout } = await verifyRequestCancellationAndTimeout(
|
||||
client,
|
||||
entry,
|
||||
);
|
||||
const concurrent = await verifyConcurrentRequests(client, entry, leaf);
|
||||
|
||||
return {
|
||||
entry: dossierSummary(entryDossier),
|
||||
branch: dossierSummary(branchDossier),
|
||||
indirect: dossierSummary(indirectDossier),
|
||||
cancellation,
|
||||
timeout,
|
||||
concurrency: concurrent,
|
||||
};
|
||||
}
|
||||
|
||||
async function collectEntryFunctionData(client, entry) {
|
||||
return Promise.all([
|
||||
functionCall(client, "procedure_info", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
}),
|
||||
functionCall(client, "procedure_assembly", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
}),
|
||||
functionCall(client, "procedure_pseudo_code", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
}),
|
||||
functionCall(client, "procedure_callees", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
}),
|
||||
functionCall(client, "procedure_callers", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
}),
|
||||
functionCall(client, "procedure_references", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
direction: "outgoing",
|
||||
}),
|
||||
functionCall(client, "xrefs", {
|
||||
document: null,
|
||||
address: entry.address,
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
function assertEntryCallGraph({ branch, indirect, main, callees, callers }) {
|
||||
for (const expected of [branch.address, indirect.address])
|
||||
if (!callees.includes(expected))
|
||||
throw new Error(`Ghidra call graph missed ${expected}`);
|
||||
if (!callers.includes(main.address))
|
||||
throw new Error("Ghidra caller or xref relation missed main");
|
||||
}
|
||||
|
||||
async function resolveXrefOwners(client, entryXrefs) {
|
||||
const xrefOwners = [];
|
||||
const xrefOwnerFailures = [];
|
||||
for (const address of entryXrefs) {
|
||||
try {
|
||||
xrefOwners.push(
|
||||
await functionCall(client, "resolve_containing_procedure", {
|
||||
document: null,
|
||||
address,
|
||||
}),
|
||||
);
|
||||
} catch (cause) {
|
||||
xrefOwnerFailures.push({
|
||||
address,
|
||||
message: cause instanceof Error ? cause.message : String(cause),
|
||||
});
|
||||
}
|
||||
}
|
||||
return { xrefOwners, xrefOwnerFailures };
|
||||
}
|
||||
|
||||
function assertEntryXrefAttribution({
|
||||
entryXrefs,
|
||||
callers,
|
||||
xrefOwners,
|
||||
xrefOwnerFailures,
|
||||
main,
|
||||
}) {
|
||||
if (
|
||||
!xrefOwners.some(
|
||||
(owner) => owner.found && owner.procedure.address === main.address,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra entry xrefs were not attributable to main: ${JSON.stringify({ entryXrefs, callers, xrefOwners, xrefOwnerFailures })}`,
|
||||
);
|
||||
}
|
||||
|
||||
async function assertStringXrefs(client, entryStringAddress) {
|
||||
const stringXrefs = await functionCall(client, "xrefs", {
|
||||
document: null,
|
||||
address: entryStringAddress,
|
||||
});
|
||||
if (stringXrefs.length === 0)
|
||||
throw new Error("Ghidra xrefs missed the entry string");
|
||||
}
|
||||
|
||||
async function analyzeEntryDossier(client, entry, branch, indirect) {
|
||||
const entryDossier = await functionCall(client, "analyze_function", {
|
||||
procedure: entry.address,
|
||||
include_assembly: true,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(entryDossier, {
|
||||
address: entry.address,
|
||||
expectedCallees: [branch.address, indirect.address],
|
||||
expectedString: "REA_GHIDRA_INVENTORY_ENTRY",
|
||||
requireAssembly: true,
|
||||
});
|
||||
return entryDossier;
|
||||
}
|
||||
|
||||
async function analyzeBranchDossier(client, branch) {
|
||||
const branchDossier = await functionCall(client, "analyze_function", {
|
||||
procedure: branch.address,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(branchDossier, {
|
||||
address: branch.address,
|
||||
requireMultiBlock: true,
|
||||
});
|
||||
return branchDossier;
|
||||
}
|
||||
|
||||
async function analyzeIndirectDossier(client, indirect) {
|
||||
const indirectDossier = await functionCall(client, "analyze_function", {
|
||||
procedure: indirect.address,
|
||||
include_assembly: true,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(indirectDossier, {
|
||||
address: indirect.address,
|
||||
requireAssembly: true,
|
||||
});
|
||||
return indirectDossier;
|
||||
}
|
||||
|
||||
function assertIndirectDossier(indirectDossier, leafAddress) {
|
||||
if (
|
||||
indirectDossier.callees.items.some(({ address }) => address === leafAddress)
|
||||
)
|
||||
throw new Error(
|
||||
"Ghidra dossier falsely resolved a targetless callback as the fixture leaf",
|
||||
);
|
||||
if (!/\bcall\b/iu.test(indirectDossier.assembly.items.join("\n")))
|
||||
throw new Error("Ghidra indirect-call fixture lost its computed call site");
|
||||
}
|
||||
|
||||
async function verifyRequestCancellationAndTimeout(client, entry) {
|
||||
const aborted = new AbortController();
|
||||
aborted.abort();
|
||||
const cancelled = await client.callTool(
|
||||
"procedure_info",
|
||||
{ document: null, procedure: entry.address },
|
||||
{ signal: aborted.signal },
|
||||
);
|
||||
if (cancelled.ok || cancelled.error.kind !== "cancelled")
|
||||
throw new Error("Ghidra established-request cancellation drifted");
|
||||
|
||||
const timedOut = await client.callTool(
|
||||
"procedure_info",
|
||||
{ document: null, procedure: entry.address },
|
||||
{ timeoutMs: 0 },
|
||||
);
|
||||
if (timedOut.ok || timedOut.error.kind !== "timeout")
|
||||
throw new Error("Ghidra established-request deadline drifted");
|
||||
|
||||
return {
|
||||
cancellation: "cancelled-before-wire",
|
||||
timeout: "expired-before-wire",
|
||||
};
|
||||
}
|
||||
|
||||
async function verifyConcurrentRequests(client, entry, leaf) {
|
||||
const concurrent = await Promise.all([
|
||||
functionCall(client, "procedure_info", {
|
||||
document: null,
|
||||
procedure: entry.address,
|
||||
}),
|
||||
functionCall(client, "xrefs", {
|
||||
document: null,
|
||||
address: leaf.address,
|
||||
}),
|
||||
]);
|
||||
if (concurrent.length !== 2)
|
||||
throw new Error("Ghidra serial request queue lost a concurrent result");
|
||||
return "serialized-two-results";
|
||||
}
|
||||
|
||||
export async function verifyStrippedFunctionOperations(client, entryString) {
|
||||
const stringXrefs = await functionCall(client, "xrefs", {
|
||||
document: null,
|
||||
address: entryString.address,
|
||||
});
|
||||
if (stringXrefs.length === 0)
|
||||
throw new Error("Ghidra stripped string xref probe is unavailable");
|
||||
const containing = await functionCall(
|
||||
client,
|
||||
"resolve_containing_procedure",
|
||||
{
|
||||
document: null,
|
||||
address: stringXrefs[0],
|
||||
},
|
||||
);
|
||||
if (!containing.found)
|
||||
throw new Error("Ghidra could not recover a stripped containing function");
|
||||
const procedure = containing.procedure;
|
||||
const pseudocode = await functionCall(client, "procedure_pseudo_code", {
|
||||
document: null,
|
||||
procedure: procedure.address,
|
||||
});
|
||||
if (typeof pseudocode !== "string" || pseudocode.trim().length === 0)
|
||||
throw new Error("Ghidra did not decompile the stripped function");
|
||||
const dossier = await functionCall(client, "analyze_function", {
|
||||
procedure: procedure.address,
|
||||
include_assembly: true,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(dossier, {
|
||||
address: procedure.address,
|
||||
expectedString: "REA_GHIDRA_INVENTORY_ENTRY",
|
||||
requireAssembly: true,
|
||||
});
|
||||
if (symbolTail(dossier.procedure.name) === "rea_ghidra_inventory_entry")
|
||||
throw new Error("Ghidra stripped dossier invented a source symbol");
|
||||
return dossierSummary(dossier);
|
||||
}
|
||||
|
||||
export async function verifyCrossFormatOperations({
|
||||
client,
|
||||
variant,
|
||||
procedures,
|
||||
names,
|
||||
strings,
|
||||
}) {
|
||||
const message = strings.find(
|
||||
(item) => item.value === "REA_GHIDRA_CROSS_FORMAT",
|
||||
);
|
||||
if (message === undefined)
|
||||
throw new Error(`${variant} string inventory missed the source oracle`);
|
||||
const entry =
|
||||
procedures.find((item) => matchesSymbol(item.value, "rea_cross_entry")) ??
|
||||
names.find((item) => matchesSymbol(item.value, "rea_cross_entry"));
|
||||
if (entry === undefined)
|
||||
throw new Error(`${variant} did not retain the exported entry symbol`);
|
||||
const entryAddress = entry.address;
|
||||
const info = await functionCall(client, "procedure_info", {
|
||||
document: null,
|
||||
procedure: entryAddress,
|
||||
});
|
||||
assertLocalProcedureInfo(info, entryAddress);
|
||||
const [pseudocode, assembly, callees, messageXrefs] = await Promise.all([
|
||||
functionCall(client, "procedure_pseudo_code", {
|
||||
document: null,
|
||||
procedure: entryAddress,
|
||||
}),
|
||||
functionCall(client, "procedure_assembly", {
|
||||
document: null,
|
||||
procedure: entryAddress,
|
||||
}),
|
||||
functionCall(client, "procedure_callees", {
|
||||
document: null,
|
||||
procedure: entryAddress,
|
||||
}),
|
||||
functionCall(client, "xrefs", {
|
||||
document: null,
|
||||
address: message.address,
|
||||
}),
|
||||
]);
|
||||
assertProviderText(assembly, pseudocode, entryAddress);
|
||||
if (callees.length < 2)
|
||||
throw new Error(`${variant} call graph missed direct fixture calls`);
|
||||
if (messageXrefs.length === 0)
|
||||
throw new Error(`${variant} xrefs missed the fixture string`);
|
||||
|
||||
const messageOwner = await findCrossStringOwner(client, messageXrefs);
|
||||
const stringDossier = await functionCall(client, "analyze_function", {
|
||||
procedure: messageOwner.procedure.address,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(stringDossier, {
|
||||
address: messageOwner.procedure.address,
|
||||
expectedString: "REA_GHIDRA_CROSS_FORMAT",
|
||||
});
|
||||
|
||||
const branchAddress = await findCrossBranchAddress(client, variant, callees);
|
||||
const branchDossier = await functionCall(client, "analyze_function", {
|
||||
procedure: branchAddress,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(branchDossier, {
|
||||
address: branchAddress,
|
||||
requireMultiBlock: true,
|
||||
});
|
||||
return {
|
||||
entry: entryAddress,
|
||||
exported_symbol: entry.value,
|
||||
string_owner: dossierSummary(stringDossier),
|
||||
branch: dossierSummary(branchDossier),
|
||||
};
|
||||
}
|
||||
|
||||
async function findCrossStringOwner(client, messageXrefs) {
|
||||
for (const address of messageXrefs) {
|
||||
const candidate = await functionCall(
|
||||
client,
|
||||
"resolve_containing_procedure",
|
||||
{
|
||||
document: null,
|
||||
address,
|
||||
},
|
||||
);
|
||||
if (candidate.found) return candidate;
|
||||
}
|
||||
throw new Error("Cross-format did not resolve the string-owning function");
|
||||
}
|
||||
|
||||
async function findCrossBranchAddress(client, variant, callees) {
|
||||
for (const address of callees) {
|
||||
const candidate = await functionCall(client, "procedure_info", {
|
||||
document: null,
|
||||
procedure: address,
|
||||
});
|
||||
if (candidate.basicblock_count > 1) return address;
|
||||
}
|
||||
throw new Error(`${variant} did not recover the multi-block callee`);
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import { parseGhidraInventoryResult } from "../dist/ghidra/GhidraInventoryValues.js";
|
||||
|
||||
import { findValue, symbolTail } from "./verify-real-ghidra-assertions.mjs";
|
||||
import {
|
||||
verifyCrossFormatOperations,
|
||||
verifyDebugFunctionOperations,
|
||||
verifyStrippedFunctionOperations,
|
||||
} from "./verify-real-ghidra-function.mjs";
|
||||
|
||||
export async function call(client, operation, parameters) {
|
||||
const called = await client.callTool(operation, parameters);
|
||||
if (!called.ok)
|
||||
throw new Error(
|
||||
`Ghidra ${operation} failed for ${JSON.stringify(parameters)}: ${called.error.message}`,
|
||||
{ cause: called.error },
|
||||
);
|
||||
const parsed = parseGhidraInventoryResult(operation, called.value);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
return parsed.value;
|
||||
}
|
||||
|
||||
export async function allItems(client, operation, parameters) {
|
||||
const items = [];
|
||||
let offset = 0;
|
||||
let total;
|
||||
while (true) {
|
||||
const page = await call(client, operation, {
|
||||
...parameters,
|
||||
offset,
|
||||
limit: 500,
|
||||
});
|
||||
if (typeof page !== "object" || page === null || Array.isArray(page))
|
||||
throw new Error(`${operation} did not return a page`);
|
||||
items.push(...page.items);
|
||||
total ??= page.total;
|
||||
if (page.total !== total)
|
||||
throw new Error(`${operation} total changed during immutable paging`);
|
||||
if (!page.has_more) break;
|
||||
if (page.next_offset === null || page.next_offset <= offset)
|
||||
throw new Error(`${operation} returned a non-advancing page`);
|
||||
offset = page.next_offset;
|
||||
}
|
||||
if (items.length !== total)
|
||||
throw new Error(`${operation} pagination was not exhaustive`);
|
||||
return items;
|
||||
}
|
||||
|
||||
export async function expectRemoteFailure(client, operation, parameters, code) {
|
||||
const result = await client.callTool(operation, parameters);
|
||||
if (
|
||||
result.ok ||
|
||||
result.error.kind !== "remote" ||
|
||||
result.error.remoteCode !== code ||
|
||||
result.error.diagnostics.remote_code !== code
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra ${operation} rejection drifted: ${JSON.stringify(result)}`,
|
||||
);
|
||||
return { operation, code };
|
||||
}
|
||||
|
||||
export async function verifyBridgeRejections(client) {
|
||||
return {
|
||||
unknownDocument: await expectRemoteFailure(
|
||||
client,
|
||||
"list_segments",
|
||||
{ document: "not-the-imported-program" },
|
||||
"not_found",
|
||||
),
|
||||
malformedParameter: await expectRemoteFailure(
|
||||
client,
|
||||
"procedure_address",
|
||||
{ document: null, procedure: 17 },
|
||||
"invalid_request",
|
||||
),
|
||||
unboundedRegex: await expectRemoteFailure(
|
||||
client,
|
||||
"search_strings",
|
||||
{
|
||||
pattern: "a+",
|
||||
mode: "regex",
|
||||
case_sensitive: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
document: null,
|
||||
},
|
||||
"invalid_request",
|
||||
),
|
||||
undeclaredMutation: await expectRemoteFailure(
|
||||
client,
|
||||
"set_comment",
|
||||
{},
|
||||
"method_unavailable",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export async function verifyInventoryOperations({
|
||||
client,
|
||||
variant,
|
||||
procedures,
|
||||
names,
|
||||
strings,
|
||||
}) {
|
||||
if (variant.startsWith("cross-"))
|
||||
return verifyCrossFormatOperations({
|
||||
client,
|
||||
variant,
|
||||
procedures,
|
||||
names,
|
||||
strings,
|
||||
});
|
||||
|
||||
const rejections =
|
||||
variant === "debug" ? await verifyBridgeRejections(client) : null;
|
||||
const stringSearch = await call(client, "search_strings", {
|
||||
pattern: String.raw`^REA_GHIDRA_(?:INVENTORY_ENTRY|LEAF_VALUE)$`,
|
||||
mode: "regex",
|
||||
case_sensitive: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
document: null,
|
||||
});
|
||||
if (stringSearch.total !== 2 || stringSearch.items.length !== 2)
|
||||
throw new Error("Ghidra bounded regex string search drifted");
|
||||
const stringItem = strings.find(
|
||||
(item) => item.value === "REA_GHIDRA_INVENTORY_ENTRY",
|
||||
);
|
||||
if (stringItem === undefined)
|
||||
throw new Error("Ghidra string probe address is unavailable");
|
||||
const filteredStrings = await call(client, "list_strings", {
|
||||
document: null,
|
||||
address: stringItem.address,
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
});
|
||||
if (
|
||||
filteredStrings.total !== 1 ||
|
||||
filteredStrings.items[0]?.address !== stringItem.address
|
||||
)
|
||||
throw new Error("Ghidra exact-address string filter drifted");
|
||||
|
||||
if (variant === "stripped") {
|
||||
const functionAnalysis = await verifyStrippedFunctionOperations(
|
||||
client,
|
||||
stringItem,
|
||||
);
|
||||
return { rejections, stringSearch, filteredStrings, functionAnalysis };
|
||||
}
|
||||
|
||||
const entry = findValue(procedures, "rea_ghidra_inventory_entry");
|
||||
if (entry === undefined)
|
||||
throw new Error("Ghidra entry procedure probe is unavailable");
|
||||
const debug = await verifyDebugInventoryCore({
|
||||
client,
|
||||
procedures,
|
||||
names,
|
||||
strings,
|
||||
entry,
|
||||
});
|
||||
return {
|
||||
rejections,
|
||||
stringSearch,
|
||||
filteredStrings,
|
||||
...debug,
|
||||
};
|
||||
}
|
||||
|
||||
async function verifyDebugInventoryCore({
|
||||
client,
|
||||
procedures,
|
||||
names,
|
||||
strings,
|
||||
entry,
|
||||
}) {
|
||||
const addressName = await call(client, "address_name", {
|
||||
document: null,
|
||||
address: entry.address,
|
||||
});
|
||||
if (symbolTail(addressName) !== "rea_ghidra_inventory_entry")
|
||||
throw new Error("Ghidra primary address-name resolution drifted");
|
||||
const resolvedAddress = await call(client, "procedure_address", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
});
|
||||
if (resolvedAddress !== entry.address)
|
||||
throw new Error("Ghidra procedure-name resolution drifted");
|
||||
const interior = `0x${(BigInt(entry.address) + 1n).toString(16)}`;
|
||||
const containing = await call(client, "resolve_containing_procedure", {
|
||||
document: null,
|
||||
address: interior,
|
||||
});
|
||||
if (!containing.found || containing.procedure.address !== entry.address)
|
||||
throw new Error("Ghidra containing-procedure resolution drifted");
|
||||
const procedureSearch = await call(client, "search_procedures", {
|
||||
pattern: "rea_ghidra_inventory_",
|
||||
mode: "literal",
|
||||
case_sensitive: true,
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
document: null,
|
||||
});
|
||||
if (
|
||||
procedureSearch.total < 2 ||
|
||||
procedureSearch.items.length !== 1 ||
|
||||
!procedureSearch.has_more ||
|
||||
procedureSearch.next_offset !== 1
|
||||
)
|
||||
throw new Error("Ghidra literal procedure-search pagination drifted");
|
||||
const name = names.find((item) => item.address === entry.address);
|
||||
if (name === undefined)
|
||||
throw new Error("Ghidra entry name probe is unavailable");
|
||||
const filteredNames = await call(client, "list_names", {
|
||||
document: null,
|
||||
address: entry.address,
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
});
|
||||
if (
|
||||
filteredNames.total < 1 ||
|
||||
!filteredNames.items.some((item) => item.value === name.value)
|
||||
)
|
||||
throw new Error("Ghidra exact-address name filter drifted");
|
||||
const functionAnalysis = await verifyDebugFunctionOperations(client, {
|
||||
procedures,
|
||||
strings,
|
||||
entry,
|
||||
});
|
||||
return {
|
||||
addressName,
|
||||
resolvedAddress,
|
||||
containing,
|
||||
procedureSearch,
|
||||
filteredNames,
|
||||
functionAnalysis,
|
||||
};
|
||||
}
|
||||
+18
-861
@@ -1,28 +1,38 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { execFile } from "node:child_process";
|
||||
import { access, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { isAbsolute, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { parseBinaryTarget } from "../dist/domain/binaryTarget.js";
|
||||
import { resolveGhidraAnalysisProfile } from "../dist/ghidra/GhidraAnalysisProfile.js";
|
||||
import { GhidraClient } from "../dist/ghidra/GhidraClient.js";
|
||||
import { GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS } from "../dist/ghidra/GhidraDefaults.js";
|
||||
import {
|
||||
parseGhidraFunctionInput,
|
||||
parseGhidraFunctionResult,
|
||||
} from "../dist/ghidra/GhidraFunctionValues.js";
|
||||
import { parseGhidraInventoryResult } from "../dist/ghidra/GhidraInventoryValues.js";
|
||||
import {
|
||||
inspectGhidraInstallation,
|
||||
SUPPORTED_GHIDRA_VERSION,
|
||||
} from "../dist/ghidra/GhidraInstallation.js";
|
||||
import { GhidraHeadlessLauncher } from "../dist/ghidra/GhidraLauncher.js";
|
||||
import { GHIDRA_PROVIDER_IDENTITY } from "../dist/ghidra/GhidraProvider.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "../dist/ghidra/GhidraSessionValues.js";
|
||||
import { parseBinaryTarget } from "../dist/domain/binaryTarget.js";
|
||||
|
||||
import {
|
||||
assertCleanup,
|
||||
assertCrossFixture,
|
||||
assertDebugFixture,
|
||||
assertMalformedFixture,
|
||||
assertRuntimeCoordinates,
|
||||
assertSession,
|
||||
assertStrippedFixture,
|
||||
summary,
|
||||
} from "./verify-real-ghidra-assertions.mjs";
|
||||
import {
|
||||
allItems,
|
||||
call,
|
||||
verifyInventoryOperations,
|
||||
} from "./verify-real-ghidra-inventory.mjs";
|
||||
|
||||
const exec = promisify(execFile);
|
||||
const installDir = process.env.GHIDRA_INSTALL_DIR;
|
||||
@@ -256,856 +266,3 @@ async function verifyTarget(targetPath, variant, expectedTarget = null) {
|
||||
await assertCleanup(runtimeCoordinates);
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyInventoryOperations({
|
||||
client,
|
||||
variant,
|
||||
procedures,
|
||||
names,
|
||||
strings,
|
||||
}) {
|
||||
if (variant.startsWith("cross-"))
|
||||
return verifyCrossFormatOperations({
|
||||
client,
|
||||
variant,
|
||||
procedures,
|
||||
names,
|
||||
strings,
|
||||
});
|
||||
const rejections =
|
||||
variant === "debug" ? await verifyBridgeRejections(client) : null;
|
||||
const stringSearch = await call(client, "search_strings", {
|
||||
pattern: String.raw`^REA_GHIDRA_(?:INVENTORY_ENTRY|LEAF_VALUE)$`,
|
||||
mode: "regex",
|
||||
case_sensitive: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
document: null,
|
||||
});
|
||||
if (stringSearch.total !== 2 || stringSearch.items.length !== 2)
|
||||
throw new Error("Ghidra bounded regex string search drifted");
|
||||
const stringItem = strings.find(
|
||||
(item) => item.value === "REA_GHIDRA_INVENTORY_ENTRY",
|
||||
);
|
||||
if (stringItem === undefined)
|
||||
throw new Error("Ghidra string probe address is unavailable");
|
||||
const filteredStrings = await call(client, "list_strings", {
|
||||
document: null,
|
||||
address: stringItem.address,
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
});
|
||||
if (
|
||||
filteredStrings.total !== 1 ||
|
||||
filteredStrings.items[0]?.address !== stringItem.address
|
||||
)
|
||||
throw new Error("Ghidra exact-address string filter drifted");
|
||||
if (variant === "stripped") {
|
||||
const functionAnalysis = await verifyStrippedFunctionOperations(
|
||||
client,
|
||||
stringItem,
|
||||
);
|
||||
return { rejections, stringSearch, filteredStrings, functionAnalysis };
|
||||
}
|
||||
|
||||
const entry = findValue(procedures, "rea_ghidra_inventory_entry");
|
||||
if (entry === undefined)
|
||||
throw new Error("Ghidra entry procedure probe is unavailable");
|
||||
const addressName = await call(client, "address_name", {
|
||||
document: null,
|
||||
address: entry.address,
|
||||
});
|
||||
if (symbolTail(addressName) !== "rea_ghidra_inventory_entry")
|
||||
throw new Error("Ghidra primary address-name resolution drifted");
|
||||
const resolvedAddress = await call(client, "procedure_address", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
});
|
||||
if (resolvedAddress !== entry.address)
|
||||
throw new Error("Ghidra procedure-name resolution drifted");
|
||||
const interior = `0x${(BigInt(entry.address) + 1n).toString(16)}`;
|
||||
const containing = await call(client, "resolve_containing_procedure", {
|
||||
document: null,
|
||||
address: interior,
|
||||
});
|
||||
if (!containing.found || containing.procedure.address !== entry.address)
|
||||
throw new Error("Ghidra containing-procedure resolution drifted");
|
||||
const procedureSearch = await call(client, "search_procedures", {
|
||||
pattern: "rea_ghidra_inventory_",
|
||||
mode: "literal",
|
||||
case_sensitive: true,
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
document: null,
|
||||
});
|
||||
if (
|
||||
procedureSearch.total < 2 ||
|
||||
procedureSearch.items.length !== 1 ||
|
||||
!procedureSearch.has_more ||
|
||||
procedureSearch.next_offset !== 1
|
||||
)
|
||||
throw new Error("Ghidra literal procedure-search pagination drifted");
|
||||
const name = names.find((item) => item.address === entry.address);
|
||||
if (name === undefined)
|
||||
throw new Error("Ghidra entry name probe is unavailable");
|
||||
const filteredNames = await call(client, "list_names", {
|
||||
document: null,
|
||||
address: entry.address,
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
});
|
||||
if (
|
||||
filteredNames.total < 1 ||
|
||||
!filteredNames.items.some((item) => item.value === name.value)
|
||||
)
|
||||
throw new Error("Ghidra exact-address name filter drifted");
|
||||
const functionAnalysis = await verifyDebugFunctionOperations(client, {
|
||||
procedures,
|
||||
strings,
|
||||
entry,
|
||||
});
|
||||
return {
|
||||
rejections,
|
||||
addressName,
|
||||
resolvedAddress,
|
||||
containing,
|
||||
procedureSearch,
|
||||
stringSearch,
|
||||
filteredNames,
|
||||
filteredStrings,
|
||||
functionAnalysis,
|
||||
};
|
||||
}
|
||||
|
||||
async function verifyDebugFunctionOperations(
|
||||
client,
|
||||
{ procedures, strings, entry },
|
||||
) {
|
||||
const leaf = requireProcedure(procedures, "rea_ghidra_inventory_leaf");
|
||||
const branch = requireProcedure(procedures, "rea_ghidra_inventory_branch");
|
||||
const indirect = requireProcedure(
|
||||
procedures,
|
||||
"rea_ghidra_inventory_indirect",
|
||||
);
|
||||
const main = requireProcedure(procedures, "main");
|
||||
const entryString = strings.find(
|
||||
(item) => item.value === "REA_GHIDRA_INVENTORY_ENTRY",
|
||||
);
|
||||
if (entryString === undefined)
|
||||
throw new Error("Ghidra debug string function probe is unavailable");
|
||||
|
||||
const [info, assembly, pseudocode, callees, callers, outgoing, entryXrefs] =
|
||||
await Promise.all([
|
||||
functionCall(client, "procedure_info", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
}),
|
||||
functionCall(client, "procedure_assembly", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
}),
|
||||
functionCall(client, "procedure_pseudo_code", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
}),
|
||||
functionCall(client, "procedure_callees", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
}),
|
||||
functionCall(client, "procedure_callers", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
}),
|
||||
functionCall(client, "procedure_references", {
|
||||
document: null,
|
||||
procedure: entry.value,
|
||||
direction: "outgoing",
|
||||
}),
|
||||
functionCall(client, "xrefs", {
|
||||
document: null,
|
||||
address: entry.address,
|
||||
}),
|
||||
]);
|
||||
assertLocalProcedureInfo(info, entry.address);
|
||||
assertProviderText(assembly, pseudocode, entry.address);
|
||||
for (const expected of [branch.address, indirect.address])
|
||||
if (!callees.includes(expected))
|
||||
throw new Error(`Ghidra call graph missed ${expected}`);
|
||||
if (!callers.includes(main.address) || entryXrefs.length === 0)
|
||||
throw new Error("Ghidra caller or xref relation missed main");
|
||||
const xrefOwners = [];
|
||||
const xrefOwnerFailures = [];
|
||||
for (const address of entryXrefs) {
|
||||
try {
|
||||
xrefOwners.push(
|
||||
await call(client, "resolve_containing_procedure", {
|
||||
document: null,
|
||||
address,
|
||||
}),
|
||||
);
|
||||
} catch (cause) {
|
||||
xrefOwnerFailures.push({
|
||||
address,
|
||||
message: cause instanceof Error ? cause.message : String(cause),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (
|
||||
!xrefOwners.some(
|
||||
(owner) => owner.found && owner.procedure.address === main.address,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra entry xrefs were not attributable to main: ${JSON.stringify({ entryXrefs, callers, xrefOwners, xrefOwnerFailures })}`,
|
||||
);
|
||||
assertReferenceMetadata(outgoing);
|
||||
const stringXrefs = await functionCall(client, "xrefs", {
|
||||
document: null,
|
||||
address: entryString.address,
|
||||
});
|
||||
if (stringXrefs.length === 0)
|
||||
throw new Error("Ghidra xrefs missed the entry string");
|
||||
|
||||
const entryDossier = await functionCall(client, "analyze_function", {
|
||||
procedure: entry.address,
|
||||
include_assembly: true,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(entryDossier, {
|
||||
address: entry.address,
|
||||
expectedCallees: [branch.address, indirect.address],
|
||||
expectedString: "REA_GHIDRA_INVENTORY_ENTRY",
|
||||
requireAssembly: true,
|
||||
});
|
||||
|
||||
const branchDossier = await functionCall(client, "analyze_function", {
|
||||
procedure: branch.address,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(branchDossier, {
|
||||
address: branch.address,
|
||||
expectedCallees: [leaf.address],
|
||||
requireMultiBlock: true,
|
||||
});
|
||||
|
||||
const indirectDossier = await functionCall(client, "analyze_function", {
|
||||
procedure: indirect.address,
|
||||
include_assembly: true,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(indirectDossier, {
|
||||
address: indirect.address,
|
||||
requireAssembly: true,
|
||||
});
|
||||
if (
|
||||
indirectDossier.callees.items.some(
|
||||
({ address }) => address === leaf.address,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
"Ghidra dossier falsely resolved a targetless callback as the fixture leaf",
|
||||
);
|
||||
if (!/\bcall\b/iu.test(indirectDossier.assembly.items.join("\n")))
|
||||
throw new Error("Ghidra indirect-call fixture lost its computed call site");
|
||||
|
||||
const aborted = new AbortController();
|
||||
aborted.abort();
|
||||
const cancelled = await client.callTool(
|
||||
"procedure_info",
|
||||
{ document: null, procedure: entry.address },
|
||||
{ signal: aborted.signal },
|
||||
);
|
||||
if (cancelled.ok || cancelled.error.kind !== "cancelled")
|
||||
throw new Error("Ghidra established-request cancellation drifted");
|
||||
const timedOut = await client.callTool(
|
||||
"procedure_info",
|
||||
{ document: null, procedure: entry.address },
|
||||
{ timeoutMs: 0 },
|
||||
);
|
||||
if (timedOut.ok || timedOut.error.kind !== "timeout")
|
||||
throw new Error("Ghidra established-request deadline drifted");
|
||||
const concurrent = await Promise.all([
|
||||
functionCall(client, "procedure_info", {
|
||||
document: null,
|
||||
procedure: entry.address,
|
||||
}),
|
||||
functionCall(client, "xrefs", {
|
||||
document: null,
|
||||
address: leaf.address,
|
||||
}),
|
||||
]);
|
||||
if (concurrent.length !== 2)
|
||||
throw new Error("Ghidra serial request queue lost a concurrent result");
|
||||
|
||||
return {
|
||||
entry: dossierSummary(entryDossier),
|
||||
branch: dossierSummary(branchDossier),
|
||||
indirect: dossierSummary(indirectDossier),
|
||||
cancellation: "cancelled-before-wire",
|
||||
timeout: "expired-before-wire",
|
||||
concurrency: "serialized-two-results",
|
||||
};
|
||||
}
|
||||
|
||||
async function verifyStrippedFunctionOperations(client, entryString) {
|
||||
const stringXrefs = await functionCall(client, "xrefs", {
|
||||
document: null,
|
||||
address: entryString.address,
|
||||
});
|
||||
if (stringXrefs.length === 0)
|
||||
throw new Error("Ghidra stripped string xref probe is unavailable");
|
||||
const containing = await call(client, "resolve_containing_procedure", {
|
||||
document: null,
|
||||
address: stringXrefs[0],
|
||||
});
|
||||
if (!containing.found)
|
||||
throw new Error("Ghidra could not recover a stripped containing function");
|
||||
const procedure = containing.procedure;
|
||||
const pseudocode = await functionCall(client, "procedure_pseudo_code", {
|
||||
document: null,
|
||||
procedure: procedure.address,
|
||||
});
|
||||
if (typeof pseudocode !== "string" || pseudocode.trim().length === 0)
|
||||
throw new Error("Ghidra did not decompile the stripped function");
|
||||
const dossier = await functionCall(client, "analyze_function", {
|
||||
procedure: procedure.address,
|
||||
include_assembly: true,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(dossier, {
|
||||
address: procedure.address,
|
||||
expectedString: "REA_GHIDRA_INVENTORY_ENTRY",
|
||||
requireAssembly: true,
|
||||
});
|
||||
if (symbolTail(dossier.procedure.name) === "rea_ghidra_inventory_entry")
|
||||
throw new Error("Ghidra stripped dossier invented a source symbol");
|
||||
return dossierSummary(dossier);
|
||||
}
|
||||
|
||||
async function verifyCrossFormatOperations({
|
||||
client,
|
||||
variant,
|
||||
procedures,
|
||||
names,
|
||||
strings,
|
||||
}) {
|
||||
const message = strings.find(
|
||||
(item) => item.value === "REA_GHIDRA_CROSS_FORMAT",
|
||||
);
|
||||
if (message === undefined)
|
||||
throw new Error(`${variant} string inventory missed the source oracle`);
|
||||
const entry =
|
||||
procedures.find((item) => matchesSymbol(item.value, "rea_cross_entry")) ??
|
||||
names.find((item) => matchesSymbol(item.value, "rea_cross_entry"));
|
||||
if (entry === undefined)
|
||||
throw new Error(`${variant} did not retain the exported entry symbol`);
|
||||
const entryAddress = entry.address;
|
||||
const info = await functionCall(client, "procedure_info", {
|
||||
document: null,
|
||||
procedure: entryAddress,
|
||||
});
|
||||
assertLocalProcedureInfo(info, entryAddress);
|
||||
const [pseudocode, assembly, callees, messageXrefs] = await Promise.all([
|
||||
functionCall(client, "procedure_pseudo_code", {
|
||||
document: null,
|
||||
procedure: entryAddress,
|
||||
}),
|
||||
functionCall(client, "procedure_assembly", {
|
||||
document: null,
|
||||
procedure: entryAddress,
|
||||
}),
|
||||
functionCall(client, "procedure_callees", {
|
||||
document: null,
|
||||
procedure: entryAddress,
|
||||
}),
|
||||
functionCall(client, "xrefs", {
|
||||
document: null,
|
||||
address: message.address,
|
||||
}),
|
||||
]);
|
||||
assertProviderText(assembly, pseudocode, entryAddress);
|
||||
if (callees.length < 2)
|
||||
throw new Error(`${variant} call graph missed direct fixture calls`);
|
||||
if (messageXrefs.length === 0)
|
||||
throw new Error(`${variant} xrefs missed the fixture string`);
|
||||
|
||||
let messageOwner = null;
|
||||
for (const address of messageXrefs) {
|
||||
const candidate = await call(client, "resolve_containing_procedure", {
|
||||
document: null,
|
||||
address,
|
||||
});
|
||||
if (candidate.found) {
|
||||
messageOwner = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (messageOwner === null)
|
||||
throw new Error(`${variant} did not resolve the string-owning function`);
|
||||
const stringDossier = await functionCall(client, "analyze_function", {
|
||||
procedure: messageOwner.procedure.address,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(stringDossier, {
|
||||
address: messageOwner.procedure.address,
|
||||
expectedString: "REA_GHIDRA_CROSS_FORMAT",
|
||||
});
|
||||
|
||||
let branchAddress = null;
|
||||
for (const address of callees) {
|
||||
const candidate = await functionCall(client, "procedure_info", {
|
||||
document: null,
|
||||
procedure: address,
|
||||
});
|
||||
if (candidate.basicblock_count > 1) {
|
||||
branchAddress = address;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (branchAddress === null)
|
||||
throw new Error(`${variant} did not recover the multi-block callee`);
|
||||
const branchDossier = await functionCall(client, "analyze_function", {
|
||||
procedure: branchAddress,
|
||||
limit: 500,
|
||||
max_pseudocode_chars: 100_000,
|
||||
max_instructions: 5_000,
|
||||
});
|
||||
assertDossier(branchDossier, {
|
||||
address: branchAddress,
|
||||
requireMultiBlock: true,
|
||||
});
|
||||
return {
|
||||
entry: entryAddress,
|
||||
exported_symbol: entry.value,
|
||||
string_owner: dossierSummary(stringDossier),
|
||||
branch: dossierSummary(branchDossier),
|
||||
};
|
||||
}
|
||||
|
||||
async function verifyBridgeRejections(client) {
|
||||
return {
|
||||
unknownDocument: await expectRemoteFailure(
|
||||
client,
|
||||
"list_segments",
|
||||
{ document: "not-the-imported-program" },
|
||||
"not_found",
|
||||
),
|
||||
malformedParameter: await expectRemoteFailure(
|
||||
client,
|
||||
"procedure_address",
|
||||
{ document: null, procedure: 17 },
|
||||
"invalid_request",
|
||||
),
|
||||
unboundedRegex: await expectRemoteFailure(
|
||||
client,
|
||||
"search_strings",
|
||||
{
|
||||
pattern: "a+",
|
||||
mode: "regex",
|
||||
case_sensitive: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
document: null,
|
||||
},
|
||||
"invalid_request",
|
||||
),
|
||||
undeclaredMutation: await expectRemoteFailure(
|
||||
client,
|
||||
"set_comment",
|
||||
{},
|
||||
"method_unavailable",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
async function expectRemoteFailure(client, operation, parameters, code) {
|
||||
const result = await client.callTool(operation, parameters);
|
||||
if (
|
||||
result.ok ||
|
||||
result.error.kind !== "remote" ||
|
||||
result.error.remoteCode !== code ||
|
||||
result.error.diagnostics.remote_code !== code
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra ${operation} rejection drifted: ${JSON.stringify(result)}`,
|
||||
);
|
||||
return { operation, code };
|
||||
}
|
||||
|
||||
async function call(client, operation, parameters) {
|
||||
const called = await client.callTool(operation, parameters);
|
||||
if (!called.ok)
|
||||
throw new Error(
|
||||
`Ghidra ${operation} failed for ${JSON.stringify(parameters)}: ${called.error.message}`,
|
||||
{ cause: called.error },
|
||||
);
|
||||
const parsed = parseGhidraInventoryResult(operation, called.value);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
return parsed.value;
|
||||
}
|
||||
|
||||
async function functionCall(client, operation, parameters) {
|
||||
const input = parseGhidraFunctionInput(operation, parameters);
|
||||
if (!input.ok) throw input.error;
|
||||
const called = await client.callTool(operation, input.value);
|
||||
if (!called.ok)
|
||||
throw new Error(
|
||||
`Ghidra ${operation} failed for ${JSON.stringify(input.value)}: ${called.error.message}`,
|
||||
{ cause: called.error },
|
||||
);
|
||||
const parsed = parseGhidraFunctionResult(operation, called.value);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
return parsed.value;
|
||||
}
|
||||
|
||||
function assertLocalProcedureInfo(info, expectedAddress) {
|
||||
if (
|
||||
info.entrypoint !== expectedAddress ||
|
||||
info.basicblock_count < 1 ||
|
||||
info.length < 1 ||
|
||||
typeof info.signature !== "string" ||
|
||||
info.signature.length === 0 ||
|
||||
info.classification.external ||
|
||||
info.classification.provenance !== "ghidra-function-manager"
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra procedure metadata drifted: ${JSON.stringify(info)}`,
|
||||
);
|
||||
}
|
||||
|
||||
function assertProviderText(assembly, pseudocode, expectedAddress) {
|
||||
if (
|
||||
typeof assembly !== "string" ||
|
||||
!assembly.includes(`${expectedAddress}:`) ||
|
||||
assembly.trim().length === 0
|
||||
)
|
||||
throw new Error("Ghidra assembly rendering lost its address-bearing lines");
|
||||
if (typeof pseudocode !== "string" || pseudocode.trim().length === 0)
|
||||
throw new Error("Ghidra local function pseudocode is unavailable");
|
||||
}
|
||||
|
||||
function assertReferenceMetadata(observed) {
|
||||
if (
|
||||
observed.instructions_scanned < 1 ||
|
||||
observed.instruction_scan_truncated ||
|
||||
observed.references.items.length === 0 ||
|
||||
!observed.references.items.every(
|
||||
({ kind }) =>
|
||||
kind.available && kind.provenance === "ghidra-reference-manager",
|
||||
) ||
|
||||
!observed.references.items.some(({ kind }) => kind.call) ||
|
||||
!observed.references.items.some(({ kind }) => kind.data)
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra typed reference metadata drifted: ${JSON.stringify(observed)}`,
|
||||
);
|
||||
}
|
||||
|
||||
function assertDossier(
|
||||
dossier,
|
||||
{
|
||||
address,
|
||||
expectedCallees = [],
|
||||
expectedString = null,
|
||||
requireAssembly = false,
|
||||
requireMultiBlock = false,
|
||||
},
|
||||
) {
|
||||
if (
|
||||
dossier.procedure.address !== address ||
|
||||
dossier.procedure.classification === null ||
|
||||
dossier.procedure.classification.provenance !== "ghidra-function-manager" ||
|
||||
dossier.procedure.classification.external ||
|
||||
dossier.pseudocode.text.trim().length === 0 ||
|
||||
dossier.pseudocode.returned_chars !== [...dossier.pseudocode.text].length ||
|
||||
dossier.instruction_scan.scanned < 1 ||
|
||||
dossier.instruction_scan.truncated ||
|
||||
!dossier.limitations.some((value) => /indirect|computed/u.test(value)) ||
|
||||
!dossier.limitations.some((value) => /Ghidra|Hopper|provider/u.test(value))
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra dossier truthfulness drifted: ${JSON.stringify(dossier)}`,
|
||||
);
|
||||
if (
|
||||
![
|
||||
...dossier.incoming_references.items,
|
||||
...dossier.outgoing_references.items,
|
||||
].every(
|
||||
({ kind }) =>
|
||||
kind.available && kind.provenance === "ghidra-reference-manager",
|
||||
)
|
||||
)
|
||||
throw new Error("Ghidra dossier lost typed reference provenance");
|
||||
for (const expected of expectedCallees)
|
||||
if (!dossier.callees.items.some(({ address: value }) => value === expected))
|
||||
throw new Error(`Ghidra dossier missed callee ${expected}`);
|
||||
if (
|
||||
expectedString !== null &&
|
||||
!dossier.referenced_strings.items.some(
|
||||
({ value }) => value === expectedString,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra dossier missed referenced string ${expectedString}`,
|
||||
);
|
||||
if (
|
||||
requireAssembly &&
|
||||
(dossier.assembly.items.length === 0 || dossier.assembly.truncated)
|
||||
)
|
||||
throw new Error("Ghidra dossier assembly was unavailable or truncated");
|
||||
if (
|
||||
requireMultiBlock &&
|
||||
(dossier.basic_blocks.items.length < 2 ||
|
||||
!dossier.basic_blocks.items.some(
|
||||
({ successors }) => successors.length > 0,
|
||||
))
|
||||
)
|
||||
throw new Error(
|
||||
"Ghidra dossier CFG missed the multi-block branch structure",
|
||||
);
|
||||
}
|
||||
|
||||
function dossierSummary(dossier) {
|
||||
return {
|
||||
address: dossier.procedure.address,
|
||||
pseudocode_chars: dossier.pseudocode.total_chars,
|
||||
instructions: dossier.instruction_scan.scanned,
|
||||
callees: dossier.callees.returned,
|
||||
outgoing_references: dossier.outgoing_references.returned,
|
||||
referenced_strings: dossier.referenced_strings.returned,
|
||||
basic_blocks: dossier.basic_blocks.returned,
|
||||
};
|
||||
}
|
||||
|
||||
async function allItems(client, operation, parameters) {
|
||||
const items = [];
|
||||
let offset = 0;
|
||||
let total;
|
||||
while (true) {
|
||||
const page = await call(client, operation, {
|
||||
...parameters,
|
||||
offset,
|
||||
limit: 500,
|
||||
});
|
||||
if (typeof page !== "object" || page === null || Array.isArray(page))
|
||||
throw new Error(`${operation} did not return a page`);
|
||||
items.push(...page.items);
|
||||
total ??= page.total;
|
||||
if (page.total !== total)
|
||||
throw new Error(`${operation} total changed during immutable paging`);
|
||||
if (!page.has_more) break;
|
||||
if (page.next_offset === null || page.next_offset <= offset)
|
||||
throw new Error(`${operation} returned a non-advancing page`);
|
||||
offset = page.next_offset;
|
||||
}
|
||||
if (items.length !== total)
|
||||
throw new Error(`${operation} pagination was not exhaustive`);
|
||||
return items;
|
||||
}
|
||||
|
||||
function assertDebugFixture(observed) {
|
||||
if (
|
||||
!Array.isArray(observed.documents) ||
|
||||
observed.documents.length !== 1 ||
|
||||
!observed.documents[0].includes("debug")
|
||||
)
|
||||
throw new Error("Ghidra did not expose exactly one debug Program identity");
|
||||
const entry = findValue(observed.procedures, "rea_ghidra_inventory_entry");
|
||||
const leaf = findValue(observed.procedures, "rea_ghidra_inventory_leaf");
|
||||
const external = observed.procedures.find(
|
||||
(item) => item.procedure.external && symbolTail(item.value) === "puts",
|
||||
);
|
||||
if (entry === undefined || leaf === undefined || external === undefined)
|
||||
throw new Error(
|
||||
"Ghidra procedure inventory missed local or external functions",
|
||||
);
|
||||
if (
|
||||
!observed.procedures.some(
|
||||
(item) => item.procedure.thunk && item.procedure.thunk_target !== null,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
"Ghidra procedure inventory did not distinguish a resolved thunk",
|
||||
);
|
||||
const entryName = findValue(observed.names, "rea_ghidra_inventory_entry");
|
||||
if (entryName === undefined || !entryName.symbol.primary)
|
||||
throw new Error("Ghidra symbol inventory missed the primary entry symbol");
|
||||
if (!observed.names.some((item) => item.symbol.external))
|
||||
throw new Error("Ghidra symbol inventory missed external symbols");
|
||||
assertStrings(observed.strings);
|
||||
assertSegments(observed.segments, observed.session.target.image_base);
|
||||
}
|
||||
|
||||
function assertStrippedFixture(observed) {
|
||||
if (
|
||||
observed.procedures.length === 0 ||
|
||||
observed.names.length === 0 ||
|
||||
findValue(observed.procedures, "rea_ghidra_inventory_entry") !== undefined
|
||||
)
|
||||
throw new Error(
|
||||
"Stripped Ghidra fixture did not preserve stripped semantics",
|
||||
);
|
||||
assertStrings(observed.strings);
|
||||
assertSegments(observed.segments, observed.session.target.image_base);
|
||||
}
|
||||
|
||||
function assertCrossFixture(observed) {
|
||||
if (
|
||||
observed.procedures.length === 0 ||
|
||||
observed.names.length === 0 ||
|
||||
observed.probes === null ||
|
||||
typeof observed.probes.entry !== "string" ||
|
||||
observed.probes.string_owner.referenced_strings < 1 ||
|
||||
observed.probes.branch.basic_blocks < 2
|
||||
)
|
||||
throw new Error(
|
||||
`Cross-format Ghidra semantics drifted: ${JSON.stringify(summary(observed))}`,
|
||||
);
|
||||
assertSegments(observed.segments, observed.session.target.image_base);
|
||||
}
|
||||
|
||||
async function assertMalformedFixture(path) {
|
||||
const parsed = await parseBinaryTarget(path);
|
||||
if (parsed.ok || parsed.error._tag !== "BinaryTargetError")
|
||||
throw new Error(
|
||||
"Malformed executable was not rejected before provider start",
|
||||
);
|
||||
}
|
||||
|
||||
function assertStrings(strings) {
|
||||
for (const expected of [
|
||||
"REA_GHIDRA_INVENTORY_ENTRY",
|
||||
"REA_GHIDRA_LEAF_VALUE",
|
||||
]) {
|
||||
const item = strings.find((candidate) => candidate.value === expected);
|
||||
if (
|
||||
item === undefined ||
|
||||
item.value_truncated ||
|
||||
typeof item.string.encoding !== "string" ||
|
||||
item.string.byte_length < expected.length
|
||||
)
|
||||
throw new Error(`Ghidra string inventory missed ${expected}`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertSegments(segments, imageBase) {
|
||||
if (
|
||||
!Array.isArray(segments) ||
|
||||
segments.length === 0 ||
|
||||
!segments.some((item) => item.executable) ||
|
||||
!segments.some((item) => item.writable) ||
|
||||
!segments.every(
|
||||
(item) =>
|
||||
item.permissions.available === true &&
|
||||
item.permissions.source === "ghidra-memory-block" &&
|
||||
item.image_base === imageBase,
|
||||
)
|
||||
)
|
||||
throw new Error("Ghidra memory-block permissions or image base drifted");
|
||||
}
|
||||
|
||||
function findValue(items, expected) {
|
||||
return items.find((item) => symbolTail(item.value) === expected);
|
||||
}
|
||||
|
||||
function requireProcedure(items, expected) {
|
||||
const observed = findValue(items, expected);
|
||||
if (observed === undefined)
|
||||
throw new Error(`Ghidra procedure probe is unavailable: ${expected}`);
|
||||
return observed;
|
||||
}
|
||||
|
||||
function matchesSymbol(value, expected) {
|
||||
const tail = symbolTail(value);
|
||||
return tail === expected || tail === `_${expected}`;
|
||||
}
|
||||
|
||||
function symbolTail(value) {
|
||||
if (typeof value !== "string") return undefined;
|
||||
return value.split("::").at(-1);
|
||||
}
|
||||
|
||||
function assertSession(session, expectedDigest, expectedTargetSha256) {
|
||||
if (
|
||||
session.provider.id !== "ghidra" ||
|
||||
session.provider.version !== SUPPORTED_GHIDRA_VERSION ||
|
||||
session.profile_digest !== expectedDigest ||
|
||||
session.target.sha256 !== expectedTargetSha256 ||
|
||||
session.read_only !== true ||
|
||||
session.analysis_complete !== true ||
|
||||
session.analysis_timed_out !== false ||
|
||||
session.capabilities.join(",") !== GHIDRA_SESSION_CAPABILITIES.join(",") ||
|
||||
!/^0x[0-9a-f]+$/u.test(session.target.image_base) ||
|
||||
session.target.default_address_space.length === 0
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra session commitment drifted: ${JSON.stringify(session)}`,
|
||||
);
|
||||
}
|
||||
|
||||
function assertRuntimeCoordinates(coordinates) {
|
||||
for (const name of ["runtime_root", "endpoint_path", "project_root"])
|
||||
if (typeof coordinates[name] !== "string")
|
||||
throw new Error(`Ghidra verifier did not observe ${name}`);
|
||||
if (typeof coordinates.process_id !== "number")
|
||||
throw new Error("Ghidra verifier did not observe its process ID");
|
||||
}
|
||||
|
||||
async function assertCleanup(coordinates) {
|
||||
for (const name of ["runtime_root", "endpoint_path", "project_root"]) {
|
||||
const path = coordinates[name];
|
||||
if (typeof path === "string" && (await exists(path)))
|
||||
throw new Error(`Ghidra cleanup left ${name}: ${path}`);
|
||||
}
|
||||
const pid = coordinates.process_id;
|
||||
if (typeof pid === "number" && processExists(pid))
|
||||
throw new Error(`Ghidra cleanup left process ${String(pid)}`);
|
||||
}
|
||||
|
||||
function summary(observed) {
|
||||
return {
|
||||
variant: observed.variant,
|
||||
target_path: observed.target.path,
|
||||
target_sha256: observed.target.sha256,
|
||||
analysis_profile_digest: observed.profile.digest,
|
||||
language_id: observed.session.target.language_id,
|
||||
compiler_spec_id: observed.session.target.compiler_spec_id,
|
||||
image_base: observed.session.target.image_base,
|
||||
procedures: observed.procedures.length,
|
||||
names: observed.names.length,
|
||||
strings: observed.strings.length,
|
||||
memory_blocks: observed.segments.length,
|
||||
};
|
||||
}
|
||||
|
||||
async function exists(path) {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function processExists(pid) {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
return !(
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
cause.code === "ESRCH"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import type {
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
@@ -13,6 +12,7 @@ import {
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { exclusionReasonForUrl } from "./CdpCaptureEventHelpers.js";
|
||||
import type { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
|
||||
export type CapturedResource = Omit<
|
||||
@@ -183,14 +183,14 @@ export const captureDom = (
|
||||
.map((value) => indexedString(strings, value).slice(0, 256))
|
||||
.slice(0, 200),
|
||||
});
|
||||
const metadata = domMetadata(
|
||||
const metadata = domMetadata({
|
||||
strings,
|
||||
attributeIndexes,
|
||||
attributes: attributeIndexes,
|
||||
documentUrl,
|
||||
nodeIndex,
|
||||
nodeName,
|
||||
allowedOrigins,
|
||||
);
|
||||
});
|
||||
for (const url of metadata.urls) {
|
||||
if (urls.length >= input.limits.max_resources) {
|
||||
completeness?.truncate("metadata");
|
||||
@@ -312,17 +312,29 @@ const numberArray = (value: unknown): readonly number[] =>
|
||||
})
|
||||
: [];
|
||||
|
||||
interface DomMetadataOptions {
|
||||
readonly strings: readonly string[];
|
||||
readonly attributes: readonly number[];
|
||||
readonly documentUrl: string;
|
||||
readonly nodeIndex: number;
|
||||
readonly nodeName: string;
|
||||
readonly allowedOrigins: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
const domMetadata = (
|
||||
strings: readonly string[],
|
||||
attributes: readonly number[],
|
||||
documentUrl: string,
|
||||
nodeIndex: number,
|
||||
nodeName: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
options: DomMetadataOptions,
|
||||
): {
|
||||
readonly urls: WebPageInspection["metadata"]["dom_urls"];
|
||||
readonly agentHints: WebPageInspection["metadata"]["agent_hints"];
|
||||
} => {
|
||||
const {
|
||||
strings,
|
||||
attributes,
|
||||
documentUrl,
|
||||
nodeIndex,
|
||||
nodeName,
|
||||
allowedOrigins,
|
||||
} = options;
|
||||
const pairs = new Map<string, string>();
|
||||
for (let index = 0; index + 1 < attributes.length; index += 2) {
|
||||
const name = indexedString(strings, attributes[index]).toLowerCase();
|
||||
@@ -403,15 +415,6 @@ const boundedUtf8 = (
|
||||
return { text, bytes, truncated: true };
|
||||
};
|
||||
|
||||
const exclusionReasonForUrl = (
|
||||
value: string | undefined,
|
||||
): "disallowed_origin" | "unsupported_url" | "unattributed_origin" =>
|
||||
value === undefined || value === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(value)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url";
|
||||
|
||||
const domUrlAttributes = [
|
||||
"href",
|
||||
"src",
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { inferJsonShape, type JsonShape } from "../domain/jsonShape.js";
|
||||
import {
|
||||
recordValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { decodeBase64, isJsonContentType } from "./CdpCaptureEventHelpers.js";
|
||||
import type { CdpCaptureEventsState } from "./CdpCaptureEventState.js";
|
||||
import type { NetworkState } from "./CdpCaptureEventTypes.js";
|
||||
|
||||
export const ingestResponseBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
requestId: string,
|
||||
value: unknown,
|
||||
): void => {
|
||||
const result = recordValue(value);
|
||||
const body = stringValue(result?.body);
|
||||
if (body === undefined) {
|
||||
invalidResponseBodyShape(state, requestId);
|
||||
return;
|
||||
}
|
||||
const decoded =
|
||||
result?.base64Encoded === true
|
||||
? decodeBase64(body)?.toString("utf8")
|
||||
: body;
|
||||
if (decoded === undefined) {
|
||||
invalidResponseBodyShape(state, requestId);
|
||||
return;
|
||||
}
|
||||
const inferred = inferBodyShape(state, decoded);
|
||||
updateResponseBodyShape(state, requestId, inferred.shape, inferred.truncated);
|
||||
};
|
||||
|
||||
export const requestBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
request: UnknownRecord,
|
||||
): NetworkState["body_shapes"] => {
|
||||
if (!state.input.include_json_body_shapes)
|
||||
return { status: "not_approved", request: null, response: null };
|
||||
const body = stringValue(request.postData);
|
||||
if (!isJsonContentType(recordValue(request.headers)) || body === undefined)
|
||||
return { status: "unavailable", request: null, response: null };
|
||||
const inferred = inferBodyShape(state, body);
|
||||
return {
|
||||
status: inferred.truncated
|
||||
? "truncated"
|
||||
: inferred.shape === null
|
||||
? "unavailable"
|
||||
: "included",
|
||||
request: inferred.shape,
|
||||
response: null,
|
||||
};
|
||||
};
|
||||
|
||||
export const updateResponseBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
requestId: string,
|
||||
response: JsonShape | null,
|
||||
truncated: boolean,
|
||||
): void => {
|
||||
const current = state.network.get(requestId);
|
||||
if (current === undefined) return;
|
||||
const request = current.body_shapes.request;
|
||||
const status =
|
||||
truncated || current.body_shapes.status === "truncated"
|
||||
? "truncated"
|
||||
: response !== null
|
||||
? "included"
|
||||
: request !== null
|
||||
? "partial"
|
||||
: "unavailable";
|
||||
state.network.set(requestId, {
|
||||
...current,
|
||||
body_shapes: { status, request, response },
|
||||
});
|
||||
};
|
||||
|
||||
const inferBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
text: string,
|
||||
): { readonly shape: JsonShape | null; readonly truncated: boolean } => {
|
||||
const bytes = Buffer.byteLength(text);
|
||||
const remaining =
|
||||
state.input.limits.max_total_json_body_bytes - state.jsonBodyBytes;
|
||||
if (bytes > state.input.limits.max_json_body_bytes || bytes > remaining) {
|
||||
state.completeness.truncate("json_body_shapes");
|
||||
return { shape: null, truncated: true };
|
||||
}
|
||||
state.jsonBodyBytes += bytes;
|
||||
const shape = inferJsonShape(text, {
|
||||
maximumBytes: state.input.limits.max_json_body_bytes,
|
||||
maximumNodes: state.input.limits.max_json_shape_nodes,
|
||||
maximumDepth: state.input.limits.max_json_shape_depth,
|
||||
});
|
||||
if (shape?.truncated === true)
|
||||
state.completeness.truncate("json_body_shapes");
|
||||
return { shape, truncated: shape?.truncated === true };
|
||||
};
|
||||
|
||||
const invalidResponseBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
requestId: string,
|
||||
): void => {
|
||||
updateResponseBodyShape(state, requestId, null, false);
|
||||
state.completeness.exclude("json_body_shapes", "invalid_protocol_value");
|
||||
};
|
||||
@@ -0,0 +1,457 @@
|
||||
import type { WebPageInspection } from "../domain/browserObservation.js";
|
||||
import { inferJsonShape } from "../domain/jsonShape.js";
|
||||
import { safeResponseMetadata } from "./CdpSafeMetadata.js";
|
||||
import { boundedSensitiveText } from "./SensitiveTextCapture.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { requestBodyShape } from "./CdpCaptureEventBodyShapes.js";
|
||||
import {
|
||||
consolePrimitive,
|
||||
decodeBase64,
|
||||
exclusionReasonForUrl,
|
||||
executionContextKey,
|
||||
firstCallFrame,
|
||||
initiatorLocation,
|
||||
integerOrNull,
|
||||
} from "./CdpCaptureEventHelpers.js";
|
||||
import type { CdpCaptureEventsState } from "./CdpCaptureEventState.js";
|
||||
import type { CapturedScript } from "./CdpCaptureEventTypes.js";
|
||||
|
||||
export const handleExecutionContextCreated = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const context = recordValue(params.context);
|
||||
const identifier = numberValue(context?.id);
|
||||
const frameId = stringValue(recordValue(context?.auxData)?.frameId);
|
||||
if (
|
||||
identifier === undefined ||
|
||||
!Number.isSafeInteger(identifier) ||
|
||||
frameId === undefined ||
|
||||
frameId.length > 256
|
||||
)
|
||||
return;
|
||||
const key = String(identifier);
|
||||
if (
|
||||
state.executionContextFrames.size >= state.input.limits.max_scripts &&
|
||||
!state.executionContextFrames.has(key)
|
||||
) {
|
||||
state.completeness.truncate("scripts");
|
||||
return;
|
||||
}
|
||||
state.executionContextFrames.set(key, frameId);
|
||||
};
|
||||
|
||||
export const handleExecutionContextDestroyed = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const key = executionContextKey(params.executionContextId);
|
||||
if (key !== null) state.executionContextFrames.delete(key);
|
||||
};
|
||||
|
||||
export const handleScriptParsed = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const scriptId = stringValue(params.scriptId);
|
||||
const rawUrl = stringValue(params.url) ?? "";
|
||||
const sanitized = allowedSanitizedUrl(rawUrl, state.allowedOrigins);
|
||||
if (scriptId === undefined || scriptId.length > 256) {
|
||||
state.completeness.exclude("scripts", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (sanitized === undefined) {
|
||||
state.completeness.exclude("scripts", exclusionReasonForUrl(rawUrl));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
state.scripts.size >= state.input.limits.max_scripts &&
|
||||
!state.scripts.has(scriptId)
|
||||
) {
|
||||
state.completeness.drop("scripts");
|
||||
return;
|
||||
}
|
||||
const sourceMap = sourceMapForScript(params.sourceMapURL, rawUrl, state);
|
||||
const script: CapturedScript = {
|
||||
scriptId,
|
||||
rawUrl,
|
||||
url: sanitized.url,
|
||||
origin: sanitized.origin,
|
||||
hash: (stringValue(params.hash) ?? "").slice(0, 512),
|
||||
length: Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
Math.trunc(numberValue(params.length) ?? 0),
|
||||
),
|
||||
),
|
||||
isModule: params.isModule === true,
|
||||
language: boundedText(params.scriptLanguage, 100),
|
||||
sourceMapUrl: sourceMap.sanitized,
|
||||
sourceMapRawUrl: sourceMap.raw,
|
||||
executionContextKey: executionContextKey(params.executionContextId),
|
||||
};
|
||||
state.scripts.set(scriptId, script);
|
||||
};
|
||||
|
||||
const sourceMapForScript = (
|
||||
value: unknown,
|
||||
scriptUrl: string,
|
||||
state: CdpCaptureEventsState,
|
||||
): { readonly sanitized: string | null; readonly raw: string | null } => {
|
||||
const declaredUrl = stringValue(value);
|
||||
if (declaredUrl === undefined || declaredUrl === "")
|
||||
return { sanitized: null, raw: null };
|
||||
let rawUrl: string;
|
||||
try {
|
||||
rawUrl = new URL(declaredUrl, scriptUrl).href;
|
||||
} catch {
|
||||
state.completeness.exclude("source_maps", "unsupported_url");
|
||||
return { sanitized: null, raw: null };
|
||||
}
|
||||
const sanitized = allowedSanitizedUrl(rawUrl, state.allowedOrigins);
|
||||
if (sanitized !== undefined) return { sanitized: sanitized.url, raw: rawUrl };
|
||||
state.completeness.exclude("source_maps", exclusionReasonForUrl(rawUrl));
|
||||
return { sanitized: null, raw: null };
|
||||
};
|
||||
|
||||
export const handleRequestWillBeSent = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const request = recordValue(params.request);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
state.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (request === undefined) {
|
||||
state.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
state.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
const sanitized = allowedSanitizedUrl(request.url, state.allowedOrigins);
|
||||
if (sanitized === undefined) {
|
||||
state.completeness.exclude(
|
||||
"network_requests",
|
||||
exclusionReasonForUrl(stringValue(request.url)),
|
||||
);
|
||||
state.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
state.network.size >= state.input.limits.max_network_events &&
|
||||
!state.network.has(requestId)
|
||||
) {
|
||||
state.completeness.drop("network_requests");
|
||||
return;
|
||||
}
|
||||
const initiator = recordValue(params.initiator);
|
||||
const initiatorFrame = initiatorLocation(initiator);
|
||||
const rawInitiatorUrl = stringValue(initiatorFrame?.url);
|
||||
const initiatorUrl = allowedSanitizedUrl(
|
||||
rawInitiatorUrl,
|
||||
state.allowedOrigins,
|
||||
);
|
||||
if (rawInitiatorUrl !== undefined && initiatorUrl === undefined)
|
||||
state.completeness.exclude(
|
||||
"network_initiators",
|
||||
exclusionReasonForUrl(rawInitiatorUrl),
|
||||
);
|
||||
state.network.set(requestId, {
|
||||
request_id: requestId,
|
||||
url: sanitized.url,
|
||||
origin: sanitized.origin ?? "",
|
||||
method: (stringValue(request.method) ?? "GET").slice(0, 32),
|
||||
resource_type: boundedText(params.type, 100),
|
||||
status: null,
|
||||
mime_type: null,
|
||||
encoded_data_length: null,
|
||||
initiator: {
|
||||
type: (stringValue(initiator?.type) ?? "other").slice(0, 100),
|
||||
url: initiatorUrl?.url ?? null,
|
||||
line: integerOrNull(initiatorFrame?.lineNumber),
|
||||
column: integerOrNull(initiatorFrame?.columnNumber),
|
||||
},
|
||||
body_shapes: requestBodyShape(state, request),
|
||||
});
|
||||
};
|
||||
|
||||
export const handleResponseReceived = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
state.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
const current = state.network.get(requestId);
|
||||
const response = recordValue(params.response);
|
||||
if (current === undefined) return;
|
||||
const sanitized = allowedSanitizedUrl(response?.url, state.allowedOrigins);
|
||||
if (response === undefined || sanitized === undefined) {
|
||||
state.completeness.exclude(
|
||||
"network_requests",
|
||||
response === undefined
|
||||
? "invalid_protocol_value"
|
||||
: exclusionReasonForUrl(stringValue(response.url)),
|
||||
);
|
||||
state.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
state.network.set(requestId, {
|
||||
...current,
|
||||
status: numberValue(response.status) ?? null,
|
||||
mime_type: boundedText(response.mimeType, 256),
|
||||
});
|
||||
if (state.responseMetadata.length >= state.input.limits.max_network_events) {
|
||||
state.completeness.truncate("metadata");
|
||||
return;
|
||||
}
|
||||
const metadata = safeResponseMetadata(
|
||||
requestId,
|
||||
sanitized.url,
|
||||
response,
|
||||
state.allowedOrigins,
|
||||
);
|
||||
state.responseMetadata.push(metadata.response);
|
||||
state.agentHints.push(...metadata.agentHints);
|
||||
};
|
||||
|
||||
export const handleLoadingFinished = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) return;
|
||||
const current = state.network.get(requestId);
|
||||
if (current === undefined) return;
|
||||
state.network.set(requestId, {
|
||||
...current,
|
||||
encoded_data_length: Math.max(
|
||||
0,
|
||||
numberValue(params.encodedDataLength) ?? 0,
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
export const handleConsoleAPICalled = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const frame = firstCallFrame(recordValue(params.stackTrace));
|
||||
if (frame === undefined) {
|
||||
state.completeness.exclude("console_events", "unattributed_origin");
|
||||
return;
|
||||
}
|
||||
const source = allowedSanitizedUrl(frame.url, state.allowedOrigins);
|
||||
if (source === undefined) {
|
||||
state.completeness.exclude(
|
||||
"console_events",
|
||||
exclusionReasonForUrl(stringValue(frame.url)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (state.console.length >= state.input.limits.max_console_events) {
|
||||
state.completeness.drop("console_events");
|
||||
return;
|
||||
}
|
||||
const arguments_ = recordsValue(params.args);
|
||||
state.console.push({
|
||||
type: (stringValue(params.type) ?? "unknown").slice(0, 100),
|
||||
timestamp: numberValue(params.timestamp) ?? 0,
|
||||
argument_types: arguments_
|
||||
.map((argument) =>
|
||||
(stringValue(argument.type) ?? "unknown").slice(0, 100),
|
||||
)
|
||||
.slice(0, 100),
|
||||
url: source.url,
|
||||
line: integerOrNull(frame.lineNumber),
|
||||
column: integerOrNull(frame.columnNumber),
|
||||
text_capture: captureConsoleText(state, arguments_),
|
||||
});
|
||||
};
|
||||
|
||||
const captureConsoleText = (
|
||||
state: CdpCaptureEventsState,
|
||||
arguments_: readonly UnknownRecord[],
|
||||
): WebPageInspection["console"]["events"][number]["text_capture"] => {
|
||||
if (!state.input.include_console_text)
|
||||
return {
|
||||
status: "not_approved",
|
||||
values: [],
|
||||
retained_bytes: 0,
|
||||
truncated_values: 0,
|
||||
};
|
||||
const values: WebPageInspection["console"]["events"][number]["text_capture"]["values"] =
|
||||
[];
|
||||
let retainedBytes = 0;
|
||||
let truncatedValues = 0;
|
||||
for (const [argumentIndex, argument] of arguments_.entries()) {
|
||||
const primitive = consolePrimitive(argument);
|
||||
if (primitive === undefined) continue;
|
||||
const remaining =
|
||||
state.input.limits.max_total_console_text_bytes - state.consoleTextBytes;
|
||||
if (remaining <= 0) {
|
||||
truncatedValues += 1;
|
||||
continue;
|
||||
}
|
||||
const bounded = boundedSensitiveText(
|
||||
primitive.text,
|
||||
Math.min(state.input.limits.max_console_text_field_bytes, remaining),
|
||||
);
|
||||
values.push({
|
||||
argument_index: argumentIndex,
|
||||
type: primitive.type,
|
||||
text: bounded.text,
|
||||
});
|
||||
retainedBytes += bounded.bytes;
|
||||
state.consoleTextBytes += bounded.bytes;
|
||||
if (bounded.truncated) truncatedValues += 1;
|
||||
}
|
||||
if (truncatedValues > 0) state.completeness.truncate("console_text");
|
||||
return {
|
||||
status: truncatedValues > 0 ? "truncated" : "included",
|
||||
values,
|
||||
retained_bytes: retainedBytes,
|
||||
truncated_values: truncatedValues,
|
||||
};
|
||||
};
|
||||
|
||||
export const handleWebSocketFrame = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
direction: "sent" | "received",
|
||||
): void => {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (
|
||||
requestId === undefined ||
|
||||
requestId.length > 256 ||
|
||||
(!state.network.has(requestId) && !state.allowedWebSockets.has(requestId))
|
||||
)
|
||||
return;
|
||||
if (state.websockets.length >= state.input.limits.max_websocket_events) {
|
||||
state.completeness.drop("websocket_frames");
|
||||
return;
|
||||
}
|
||||
const response = recordValue(params.response);
|
||||
const payload = stringValue(response?.payloadData) ?? "";
|
||||
const opcode = Math.max(0, Math.trunc(numberValue(response?.opcode) ?? 0));
|
||||
const decoded = opcode === 1 ? undefined : decodeBase64(payload);
|
||||
if (opcode !== 1 && decoded === undefined)
|
||||
state.completeness.exclude("websocket_frames", "invalid_protocol_value");
|
||||
state.websockets.push({
|
||||
request_id: requestId,
|
||||
direction,
|
||||
opcode,
|
||||
payload_bytes:
|
||||
opcode === 1 ? Buffer.byteLength(payload) : (decoded?.byteLength ?? 0),
|
||||
payload_shape: captureWebSocketShape(state, payload, opcode),
|
||||
});
|
||||
};
|
||||
|
||||
const captureWebSocketShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
payload: string,
|
||||
opcode: number,
|
||||
): WebPageInspection["network"]["websocket_events"][number]["payload_shape"] => {
|
||||
if (!state.input.include_websocket_shapes) return null;
|
||||
if (opcode !== 1)
|
||||
return { format: "binary", json_shape: null, truncated: false };
|
||||
const bytes = Buffer.byteLength(payload);
|
||||
const remaining =
|
||||
state.input.limits.max_total_websocket_shape_bytes -
|
||||
state.websocketShapeBytes;
|
||||
if (
|
||||
bytes > state.input.limits.max_websocket_shape_bytes ||
|
||||
bytes > remaining
|
||||
) {
|
||||
state.completeness.truncate("websocket_shapes");
|
||||
return { format: "text", json_shape: null, truncated: true };
|
||||
}
|
||||
state.websocketShapeBytes += bytes;
|
||||
const shape = inferJsonShape(payload, {
|
||||
maximumBytes: state.input.limits.max_websocket_shape_bytes,
|
||||
maximumNodes: state.input.limits.max_json_shape_nodes,
|
||||
maximumDepth: state.input.limits.max_json_shape_depth,
|
||||
});
|
||||
if (shape?.truncated === true)
|
||||
state.completeness.truncate("websocket_shapes");
|
||||
return {
|
||||
format: shape === null ? "text" : "json",
|
||||
json_shape: shape,
|
||||
truncated: shape?.truncated === true,
|
||||
};
|
||||
};
|
||||
|
||||
export const handleWebSocketCreated = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const rawUrl = stringValue(params.url);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
state.completeness.exclude(
|
||||
"websocket_connections",
|
||||
"invalid_protocol_value",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (rawUrl === undefined) {
|
||||
state.completeness.exclude(
|
||||
"websocket_connections",
|
||||
"invalid_protocol_value",
|
||||
);
|
||||
return;
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
state.completeness.exclude("websocket_connections", "unsupported_url");
|
||||
return;
|
||||
}
|
||||
if (parsed.protocol === "ws:") parsed.protocol = "http:";
|
||||
else if (parsed.protocol === "wss:") parsed.protocol = "https:";
|
||||
else {
|
||||
state.completeness.exclude("websocket_connections", "unsupported_url");
|
||||
return;
|
||||
}
|
||||
if (!state.allowedOrigins.has(parsed.origin)) {
|
||||
state.completeness.exclude("websocket_connections", "disallowed_origin");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!state.allowedWebSockets.has(requestId) &&
|
||||
state.allowedWebSockets.size >= state.input.limits.max_websocket_events
|
||||
) {
|
||||
state.completeness.drop("websocket_connections");
|
||||
return;
|
||||
}
|
||||
state.allowedWebSockets.add(requestId);
|
||||
};
|
||||
|
||||
export const handleFrameNavigated = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const frame = recordValue(params.frame);
|
||||
if (stringValue(frame?.id) !== state.mainFrameId) return;
|
||||
state.navigationDuringCapture = true;
|
||||
const rawUrl = stringValue(frame?.url);
|
||||
if (
|
||||
isHttpUrl(rawUrl) &&
|
||||
allowedSanitizedUrl(rawUrl, state.allowedOrigins) === undefined
|
||||
)
|
||||
state.originViolation = true;
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
import {
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
export const firstCallFrame = (
|
||||
value: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => recordsValue(value?.callFrames)[0];
|
||||
|
||||
export const initiatorLocation = (
|
||||
initiator: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => {
|
||||
let stack = recordValue(initiator?.stack);
|
||||
for (let depth = 0; depth < 32 && stack !== undefined; depth += 1) {
|
||||
const frame = firstCallFrame(stack);
|
||||
if (frame !== undefined) return frame;
|
||||
stack = recordValue(stack.parent);
|
||||
}
|
||||
return stringValue(initiator?.url) === undefined ? undefined : initiator;
|
||||
};
|
||||
|
||||
export const exclusionReasonForUrl = (
|
||||
value: string | undefined,
|
||||
): "disallowed_origin" | "unsupported_url" | "unattributed_origin" =>
|
||||
value === undefined || value === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(value)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url";
|
||||
|
||||
export const integerOrNull = (value: unknown): number | null => {
|
||||
const number = numberValue(value);
|
||||
return number === undefined ? null : Math.max(0, Math.trunc(number));
|
||||
};
|
||||
|
||||
export const executionContextKey = (value: unknown): string | null => {
|
||||
const identifier = numberValue(value);
|
||||
return identifier !== undefined && Number.isSafeInteger(identifier)
|
||||
? String(identifier)
|
||||
: null;
|
||||
};
|
||||
|
||||
export const isJsonContentType = (
|
||||
headers: UnknownRecord | undefined,
|
||||
): boolean => {
|
||||
if (headers === undefined) return false;
|
||||
for (const [name, value] of Object.entries(headers))
|
||||
if (
|
||||
name.toLowerCase() === "content-type" &&
|
||||
isJsonMediaType(stringValue(value))
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
export const isJsonMediaType = (value: string | null | undefined): boolean => {
|
||||
const mediaType = value?.split(";", 1)[0]?.trim().toLowerCase();
|
||||
return (
|
||||
mediaType === "application/json" || mediaType?.endsWith("+json") === true
|
||||
);
|
||||
};
|
||||
|
||||
export const consolePrimitive = (
|
||||
value: UnknownRecord,
|
||||
): { readonly type: string; readonly text: string } | undefined => {
|
||||
const type = stringValue(value.type);
|
||||
switch (type) {
|
||||
case "string":
|
||||
return typeof value.value === "string"
|
||||
? { type, text: value.value }
|
||||
: undefined;
|
||||
case "boolean":
|
||||
return typeof value.value === "boolean"
|
||||
? { type, text: String(value.value) }
|
||||
: undefined;
|
||||
case "number":
|
||||
return typeof value.value === "number"
|
||||
? { type, text: String(value.value) }
|
||||
: typeof value.unserializableValue === "string"
|
||||
? { type, text: value.unserializableValue }
|
||||
: undefined;
|
||||
case "bigint":
|
||||
return typeof value.unserializableValue === "string"
|
||||
? { type, text: value.unserializableValue }
|
||||
: undefined;
|
||||
case "undefined":
|
||||
return { type, text: "undefined" };
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const BASE64 = /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/u;
|
||||
|
||||
export const decodeBase64 = (value: string): Buffer | undefined =>
|
||||
value.length % 4 === 0 && BASE64.test(value)
|
||||
? Buffer.from(value, "base64")
|
||||
: undefined;
|
||||
@@ -0,0 +1,26 @@
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import type { CapturedScript, NetworkState } from "./CdpCaptureEventTypes.js";
|
||||
|
||||
export interface CdpCaptureEventsState {
|
||||
readonly input: InspectWebPageInput;
|
||||
readonly allowedOrigins: ReadonlySet<string>;
|
||||
readonly scripts: Map<string, CapturedScript>;
|
||||
readonly executionContextFrames: Map<string, string>;
|
||||
readonly network: Map<string, NetworkState>;
|
||||
readonly allowedWebSockets: Set<string>;
|
||||
console: WebPageInspection["console"]["events"];
|
||||
websockets: WebPageInspection["network"]["websocket_events"];
|
||||
responseMetadata: WebPageInspection["metadata"]["responses"];
|
||||
agentHints: WebPageInspection["metadata"]["agent_hints"];
|
||||
readonly completeness: CdpCaptureCompleteness;
|
||||
originViolation: boolean;
|
||||
navigationDuringCapture: boolean;
|
||||
mainFrameId: string | undefined;
|
||||
consoleTextBytes: number;
|
||||
jsonBodyBytes: number;
|
||||
websocketShapeBytes: number;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { WebPageInspection } from "../domain/browserObservation.js";
|
||||
|
||||
export interface CapturedScript {
|
||||
readonly scriptId: string;
|
||||
readonly rawUrl: string;
|
||||
readonly url: string;
|
||||
readonly origin: string | null;
|
||||
readonly hash: string;
|
||||
readonly length: number;
|
||||
readonly isModule: boolean;
|
||||
readonly language: string | null;
|
||||
readonly sourceMapUrl: string | null;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
readonly executionContextKey: string | null;
|
||||
}
|
||||
|
||||
export type NetworkState = WebPageInspection["network"]["requests"][number];
|
||||
+41
-633
@@ -2,48 +2,27 @@ import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import { inferJsonShape, type JsonShape } from "../domain/jsonShape.js";
|
||||
import type { CdpEvent } from "./CdpConnection.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import { safeResponseMetadata } from "./CdpSafeMetadata.js";
|
||||
import { boundedSensitiveText } from "./SensitiveTextCapture.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import * as bodyShapes from "./CdpCaptureEventBodyShapes.js";
|
||||
import type { CdpCaptureEventsState } from "./CdpCaptureEventState.js";
|
||||
import type { CapturedScript, NetworkState } from "./CdpCaptureEventTypes.js";
|
||||
import * as handlers from "./CdpCaptureEventHandlers.js";
|
||||
import { isJsonMediaType } from "./CdpCaptureEventHelpers.js";
|
||||
import { recordValue } from "./CdpCaptureValues.js";
|
||||
|
||||
export interface CapturedScript {
|
||||
readonly scriptId: string;
|
||||
readonly rawUrl: string;
|
||||
readonly url: string;
|
||||
readonly origin: string | null;
|
||||
readonly hash: string;
|
||||
readonly length: number;
|
||||
readonly isModule: boolean;
|
||||
readonly language: string | null;
|
||||
readonly sourceMapUrl: string | null;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
readonly executionContextKey: string | null;
|
||||
}
|
||||
|
||||
type NetworkState = WebPageInspection["network"]["requests"][number];
|
||||
export { type CapturedScript } from "./CdpCaptureEventTypes.js";
|
||||
|
||||
/** Bounded event accumulator that drops payload values at ingestion time. */
|
||||
export class CdpCaptureEvents {
|
||||
export class CdpCaptureEvents implements CdpCaptureEventsState {
|
||||
readonly scripts = new Map<string, CapturedScript>();
|
||||
readonly executionContextFrames = new Map<string, string>();
|
||||
readonly network = new Map<string, NetworkState>();
|
||||
readonly allowedWebSockets = new Set<string>();
|
||||
readonly console: WebPageInspection["console"]["events"] = [];
|
||||
readonly websockets: WebPageInspection["network"]["websocket_events"] = [];
|
||||
readonly responseMetadata: WebPageInspection["metadata"]["responses"] = [];
|
||||
readonly agentHints: WebPageInspection["metadata"]["agent_hints"] = [];
|
||||
console: WebPageInspection["console"]["events"] = [];
|
||||
websockets: WebPageInspection["network"]["websocket_events"] = [];
|
||||
responseMetadata: WebPageInspection["metadata"]["responses"] = [];
|
||||
agentHints: WebPageInspection["metadata"]["agent_hints"] = [];
|
||||
readonly completeness = new CdpCaptureCompleteness([
|
||||
"network_requests",
|
||||
"console_events",
|
||||
@@ -53,18 +32,21 @@ export class CdpCaptureEvents {
|
||||
]);
|
||||
originViolation = false;
|
||||
navigationDuringCapture = false;
|
||||
#mainFrameId: string | undefined;
|
||||
#consoleTextBytes = 0;
|
||||
#jsonBodyBytes = 0;
|
||||
#websocketShapeBytes = 0;
|
||||
mainFrameId: string | undefined = undefined;
|
||||
consoleTextBytes = 0;
|
||||
jsonBodyBytes = 0;
|
||||
websocketShapeBytes = 0;
|
||||
|
||||
constructor(
|
||||
private readonly input: InspectWebPageInput,
|
||||
private readonly allowedOrigins: ReadonlySet<string>,
|
||||
) {}
|
||||
readonly input: InspectWebPageInput;
|
||||
readonly allowedOrigins: ReadonlySet<string>;
|
||||
|
||||
constructor(input: InspectWebPageInput, allowedOrigins: ReadonlySet<string>) {
|
||||
this.input = input;
|
||||
this.allowedOrigins = allowedOrigins;
|
||||
}
|
||||
|
||||
beginAuthorizedFrame(frameId: string): void {
|
||||
this.#mainFrameId = frameId;
|
||||
this.mainFrameId = frameId;
|
||||
this.originViolation = false;
|
||||
this.navigationDuringCapture = false;
|
||||
this.scripts.clear();
|
||||
@@ -75,9 +57,9 @@ export class CdpCaptureEvents {
|
||||
this.websockets.length = 0;
|
||||
this.responseMetadata.length = 0;
|
||||
this.agentHints.length = 0;
|
||||
this.#consoleTextBytes = 0;
|
||||
this.#jsonBodyBytes = 0;
|
||||
this.#websocketShapeBytes = 0;
|
||||
this.consoleTextBytes = 0;
|
||||
this.jsonBodyBytes = 0;
|
||||
this.websocketShapeBytes = 0;
|
||||
this.completeness.reset();
|
||||
if (!this.input.include_console_text)
|
||||
this.completeness.exclude("console_text", "not_approved", null);
|
||||
@@ -88,7 +70,7 @@ export class CdpCaptureEvents {
|
||||
}
|
||||
|
||||
beginFinalCapture(frameId: string): void {
|
||||
this.#mainFrameId = frameId;
|
||||
this.mainFrameId = frameId;
|
||||
this.navigationDuringCapture = false;
|
||||
}
|
||||
|
||||
@@ -97,40 +79,40 @@ export class CdpCaptureEvents {
|
||||
if (params === undefined) return;
|
||||
switch (event.method) {
|
||||
case "Runtime.executionContextCreated":
|
||||
this.#executionContext(params);
|
||||
handlers.handleExecutionContextCreated(this, params);
|
||||
break;
|
||||
case "Runtime.executionContextDestroyed":
|
||||
this.#destroyExecutionContext(params);
|
||||
handlers.handleExecutionContextDestroyed(this, params);
|
||||
break;
|
||||
case "Runtime.executionContextsCleared":
|
||||
this.executionContextFrames.clear();
|
||||
break;
|
||||
case "Debugger.scriptParsed":
|
||||
this.#script(params);
|
||||
handlers.handleScriptParsed(this, params);
|
||||
break;
|
||||
case "Network.requestWillBeSent":
|
||||
this.#request(params);
|
||||
handlers.handleRequestWillBeSent(this, params);
|
||||
break;
|
||||
case "Network.responseReceived":
|
||||
this.#response(params);
|
||||
handlers.handleResponseReceived(this, params);
|
||||
break;
|
||||
case "Network.loadingFinished":
|
||||
this.#finished(params);
|
||||
handlers.handleLoadingFinished(this, params);
|
||||
break;
|
||||
case "Runtime.consoleAPICalled":
|
||||
this.#console(params);
|
||||
handlers.handleConsoleAPICalled(this, params);
|
||||
break;
|
||||
case "Page.frameNavigated":
|
||||
this.#frameNavigated(params);
|
||||
handlers.handleFrameNavigated(this, params);
|
||||
break;
|
||||
case "Network.webSocketCreated":
|
||||
this.#websocketCreated(params);
|
||||
handlers.handleWebSocketCreated(this, params);
|
||||
break;
|
||||
case "Network.webSocketFrameSent":
|
||||
this.#websocket(params, "sent");
|
||||
handlers.handleWebSocketFrame(this, params, "sent");
|
||||
break;
|
||||
case "Network.webSocketFrameReceived":
|
||||
this.#websocket(params, "received");
|
||||
handlers.handleWebSocketFrame(this, params, "received");
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -147,272 +129,6 @@ export class CdpCaptureEvents {
|
||||
: null;
|
||||
}
|
||||
|
||||
#executionContext(params: UnknownRecord): void {
|
||||
const context = recordValue(params.context);
|
||||
const identifier = numberValue(context?.id);
|
||||
const frameId = stringValue(recordValue(context?.auxData)?.frameId);
|
||||
if (
|
||||
identifier === undefined ||
|
||||
!Number.isSafeInteger(identifier) ||
|
||||
frameId === undefined ||
|
||||
frameId.length > 256
|
||||
)
|
||||
return;
|
||||
const key = String(identifier);
|
||||
if (
|
||||
this.executionContextFrames.size >= this.input.limits.max_scripts &&
|
||||
!this.executionContextFrames.has(key)
|
||||
) {
|
||||
this.completeness.truncate("scripts");
|
||||
return;
|
||||
}
|
||||
this.executionContextFrames.set(key, frameId);
|
||||
}
|
||||
|
||||
#destroyExecutionContext(params: UnknownRecord): void {
|
||||
const key = executionContextKey(params.executionContextId);
|
||||
if (key !== null) this.executionContextFrames.delete(key);
|
||||
}
|
||||
|
||||
#script(params: UnknownRecord): void {
|
||||
const scriptId = stringValue(params.scriptId);
|
||||
const rawUrl = stringValue(params.url) ?? "";
|
||||
const sanitized = allowedSanitizedUrl(rawUrl, this.allowedOrigins);
|
||||
if (scriptId === undefined || scriptId.length > 256) {
|
||||
this.completeness.exclude("scripts", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (sanitized === undefined) {
|
||||
this.completeness.exclude("scripts", exclusionReasonForUrl(rawUrl));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.scripts.size >= this.input.limits.max_scripts &&
|
||||
!this.scripts.has(scriptId)
|
||||
) {
|
||||
this.completeness.drop("scripts");
|
||||
return;
|
||||
}
|
||||
const sourceMap = this.#sourceMap(params.sourceMapURL, rawUrl);
|
||||
this.scripts.set(scriptId, {
|
||||
scriptId,
|
||||
rawUrl,
|
||||
url: sanitized.url,
|
||||
origin: sanitized.origin,
|
||||
hash: (stringValue(params.hash) ?? "").slice(0, 512),
|
||||
length: Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
Math.trunc(numberValue(params.length) ?? 0),
|
||||
),
|
||||
),
|
||||
isModule: params.isModule === true,
|
||||
language: boundedText(params.scriptLanguage, 100),
|
||||
sourceMapUrl: sourceMap.sanitized,
|
||||
sourceMapRawUrl: sourceMap.raw,
|
||||
executionContextKey: executionContextKey(params.executionContextId),
|
||||
});
|
||||
}
|
||||
|
||||
#sourceMap(
|
||||
value: unknown,
|
||||
scriptUrl: string,
|
||||
): {
|
||||
readonly sanitized: string | null;
|
||||
readonly raw: string | null;
|
||||
} {
|
||||
const declaredUrl = stringValue(value);
|
||||
if (declaredUrl === undefined || declaredUrl === "")
|
||||
return { sanitized: null, raw: null };
|
||||
let rawUrl: string;
|
||||
try {
|
||||
rawUrl = new URL(declaredUrl, scriptUrl).href;
|
||||
} catch {
|
||||
this.completeness.exclude("source_maps", "unsupported_url");
|
||||
return { sanitized: null, raw: null };
|
||||
}
|
||||
const sanitized = allowedSanitizedUrl(rawUrl, this.allowedOrigins);
|
||||
if (sanitized !== undefined)
|
||||
return { sanitized: sanitized.url, raw: rawUrl };
|
||||
this.completeness.exclude("source_maps", exclusionReasonForUrl(rawUrl));
|
||||
return { sanitized: null, raw: null };
|
||||
}
|
||||
|
||||
#request(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const request = recordValue(params.request);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
this.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (request === undefined) {
|
||||
this.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
this.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
const sanitized = allowedSanitizedUrl(request.url, this.allowedOrigins);
|
||||
if (sanitized === undefined) {
|
||||
this.completeness.exclude(
|
||||
"network_requests",
|
||||
exclusionReasonForUrl(stringValue(request.url)),
|
||||
);
|
||||
this.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.network.size >= this.input.limits.max_network_events &&
|
||||
!this.network.has(requestId)
|
||||
) {
|
||||
this.completeness.drop("network_requests");
|
||||
return;
|
||||
}
|
||||
const initiator = recordValue(params.initiator);
|
||||
const initiatorFrame = initiatorLocation(initiator);
|
||||
const rawInitiatorUrl = stringValue(initiatorFrame?.url);
|
||||
const initiatorUrl = allowedSanitizedUrl(
|
||||
rawInitiatorUrl,
|
||||
this.allowedOrigins,
|
||||
);
|
||||
if (rawInitiatorUrl !== undefined && initiatorUrl === undefined)
|
||||
this.completeness.exclude(
|
||||
"network_initiators",
|
||||
exclusionReasonForUrl(rawInitiatorUrl),
|
||||
);
|
||||
this.network.set(requestId, {
|
||||
request_id: requestId,
|
||||
url: sanitized.url,
|
||||
origin: sanitized.origin ?? "",
|
||||
method: (stringValue(request.method) ?? "GET").slice(0, 32),
|
||||
resource_type: boundedText(params.type, 100),
|
||||
status: null,
|
||||
mime_type: null,
|
||||
encoded_data_length: null,
|
||||
initiator: {
|
||||
type: (stringValue(initiator?.type) ?? "other").slice(0, 100),
|
||||
url: initiatorUrl?.url ?? null,
|
||||
line: integerOrNull(initiatorFrame?.lineNumber),
|
||||
column: integerOrNull(initiatorFrame?.columnNumber),
|
||||
},
|
||||
body_shapes: this.#requestBodyShape(request),
|
||||
});
|
||||
}
|
||||
|
||||
#response(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
this.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
const current = this.network.get(requestId);
|
||||
const response = recordValue(params.response);
|
||||
if (current === undefined) return;
|
||||
const sanitized = allowedSanitizedUrl(response?.url, this.allowedOrigins);
|
||||
if (response === undefined || sanitized === undefined) {
|
||||
this.completeness.exclude(
|
||||
"network_requests",
|
||||
response === undefined
|
||||
? "invalid_protocol_value"
|
||||
: exclusionReasonForUrl(stringValue(response.url)),
|
||||
);
|
||||
this.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
this.network.set(requestId, {
|
||||
...current,
|
||||
status: numberValue(response.status) ?? null,
|
||||
mime_type: boundedText(response.mimeType, 256),
|
||||
});
|
||||
if (this.responseMetadata.length >= this.input.limits.max_network_events) {
|
||||
this.completeness.truncate("metadata");
|
||||
return;
|
||||
}
|
||||
const metadata = safeResponseMetadata(
|
||||
requestId,
|
||||
sanitized.url,
|
||||
response,
|
||||
this.allowedOrigins,
|
||||
);
|
||||
this.responseMetadata.push(metadata.response);
|
||||
this.agentHints.push(...metadata.agentHints);
|
||||
}
|
||||
|
||||
#finished(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) return;
|
||||
const current = this.network.get(requestId);
|
||||
if (current === undefined) return;
|
||||
this.network.set(requestId, {
|
||||
...current,
|
||||
encoded_data_length: Math.max(
|
||||
0,
|
||||
numberValue(params.encodedDataLength) ?? 0,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
#console(params: UnknownRecord): void {
|
||||
const frame = firstCallFrame(recordValue(params.stackTrace));
|
||||
if (frame === undefined) {
|
||||
this.completeness.exclude("console_events", "unattributed_origin");
|
||||
return;
|
||||
}
|
||||
const source = allowedSanitizedUrl(frame.url, this.allowedOrigins);
|
||||
if (source === undefined) {
|
||||
this.completeness.exclude(
|
||||
"console_events",
|
||||
exclusionReasonForUrl(stringValue(frame.url)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (this.console.length >= this.input.limits.max_console_events) {
|
||||
this.completeness.drop("console_events");
|
||||
return;
|
||||
}
|
||||
const arguments_ = recordsValue(params.args);
|
||||
this.console.push({
|
||||
type: (stringValue(params.type) ?? "unknown").slice(0, 100),
|
||||
timestamp: numberValue(params.timestamp) ?? 0,
|
||||
argument_types: arguments_
|
||||
.map((argument) =>
|
||||
(stringValue(argument.type) ?? "unknown").slice(0, 100),
|
||||
)
|
||||
.slice(0, 100),
|
||||
url: source.url,
|
||||
line: integerOrNull(frame.lineNumber),
|
||||
column: integerOrNull(frame.columnNumber),
|
||||
text_capture: this.#consoleText(arguments_),
|
||||
});
|
||||
}
|
||||
|
||||
#websocket(params: UnknownRecord, direction: "sent" | "received"): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (
|
||||
requestId === undefined ||
|
||||
requestId.length > 256 ||
|
||||
(!this.network.has(requestId) && !this.allowedWebSockets.has(requestId))
|
||||
)
|
||||
return;
|
||||
if (this.websockets.length >= this.input.limits.max_websocket_events) {
|
||||
this.completeness.drop("websocket_frames");
|
||||
return;
|
||||
}
|
||||
const response = recordValue(params.response);
|
||||
const payload = stringValue(response?.payloadData) ?? "";
|
||||
const opcode = Math.max(0, Math.trunc(numberValue(response?.opcode) ?? 0));
|
||||
const decoded = opcode === 1 ? undefined : decodeBase64(payload);
|
||||
if (opcode !== 1 && decoded === undefined)
|
||||
this.completeness.exclude("websocket_frames", "invalid_protocol_value");
|
||||
this.websockets.push({
|
||||
request_id: requestId,
|
||||
direction,
|
||||
opcode,
|
||||
payload_bytes:
|
||||
opcode === 1 ? Buffer.byteLength(payload) : (decoded?.byteLength ?? 0),
|
||||
payload_shape: this.#websocketShape(payload, opcode),
|
||||
});
|
||||
}
|
||||
|
||||
responseBodyRequestIds(): readonly string[] {
|
||||
if (!this.input.include_json_body_shapes) return [];
|
||||
return [...this.network.values()]
|
||||
@@ -421,319 +137,11 @@ export class CdpCaptureEvents {
|
||||
}
|
||||
|
||||
responseBodyUnavailable(requestId: string): void {
|
||||
this.#updateResponseShape(requestId, null, false);
|
||||
bodyShapes.updateResponseBodyShape(this, requestId, null, false);
|
||||
this.completeness.unavailable("json_body_shapes");
|
||||
}
|
||||
|
||||
ingestResponseBody(requestId: string, value: unknown): void {
|
||||
const result = recordValue(value);
|
||||
const body = stringValue(result?.body);
|
||||
if (body === undefined) {
|
||||
this.#invalidResponseBody(requestId);
|
||||
return;
|
||||
}
|
||||
const decoded =
|
||||
result?.base64Encoded === true
|
||||
? decodeBase64(body)?.toString("utf8")
|
||||
: body;
|
||||
if (decoded === undefined) {
|
||||
this.#invalidResponseBody(requestId);
|
||||
return;
|
||||
}
|
||||
const inferred = this.#inferBodyShape(decoded);
|
||||
this.#updateResponseShape(requestId, inferred.shape, inferred.truncated);
|
||||
}
|
||||
|
||||
#invalidResponseBody(requestId: string): void {
|
||||
this.#updateResponseShape(requestId, null, false);
|
||||
this.completeness.exclude("json_body_shapes", "invalid_protocol_value");
|
||||
}
|
||||
|
||||
#requestBodyShape(request: UnknownRecord): NetworkState["body_shapes"] {
|
||||
if (!this.input.include_json_body_shapes)
|
||||
return { status: "not_approved", request: null, response: null };
|
||||
const body = stringValue(request.postData);
|
||||
if (!isJsonContentType(recordValue(request.headers)) || body === undefined)
|
||||
return { status: "unavailable", request: null, response: null };
|
||||
const inferred = this.#inferBodyShape(body);
|
||||
return {
|
||||
status: inferred.truncated
|
||||
? "truncated"
|
||||
: inferred.shape === null
|
||||
? "unavailable"
|
||||
: "included",
|
||||
request: inferred.shape,
|
||||
response: null,
|
||||
};
|
||||
}
|
||||
|
||||
#inferBodyShape(text: string): {
|
||||
readonly shape: JsonShape | null;
|
||||
readonly truncated: boolean;
|
||||
} {
|
||||
const bytes = Buffer.byteLength(text);
|
||||
const remaining =
|
||||
this.input.limits.max_total_json_body_bytes - this.#jsonBodyBytes;
|
||||
if (bytes > this.input.limits.max_json_body_bytes || bytes > remaining) {
|
||||
this.completeness.truncate("json_body_shapes");
|
||||
return { shape: null, truncated: true };
|
||||
}
|
||||
this.#jsonBodyBytes += bytes;
|
||||
const shape = inferJsonShape(text, {
|
||||
maximumBytes: this.input.limits.max_json_body_bytes,
|
||||
maximumNodes: this.input.limits.max_json_shape_nodes,
|
||||
maximumDepth: this.input.limits.max_json_shape_depth,
|
||||
});
|
||||
if (shape?.truncated === true)
|
||||
this.completeness.truncate("json_body_shapes");
|
||||
return { shape, truncated: shape?.truncated === true };
|
||||
}
|
||||
|
||||
#updateResponseShape(
|
||||
requestId: string,
|
||||
response: JsonShape | null,
|
||||
truncated: boolean,
|
||||
): void {
|
||||
const current = this.network.get(requestId);
|
||||
if (current === undefined) return;
|
||||
const request = current.body_shapes.request;
|
||||
const status =
|
||||
truncated || current.body_shapes.status === "truncated"
|
||||
? "truncated"
|
||||
: response !== null
|
||||
? "included"
|
||||
: request !== null
|
||||
? "partial"
|
||||
: "unavailable";
|
||||
this.network.set(requestId, {
|
||||
...current,
|
||||
body_shapes: { status, request, response },
|
||||
});
|
||||
}
|
||||
|
||||
#consoleText(
|
||||
arguments_: readonly UnknownRecord[],
|
||||
): WebPageInspection["console"]["events"][number]["text_capture"] {
|
||||
if (!this.input.include_console_text)
|
||||
return {
|
||||
status: "not_approved",
|
||||
values: [],
|
||||
retained_bytes: 0,
|
||||
truncated_values: 0,
|
||||
};
|
||||
const values: WebPageInspection["console"]["events"][number]["text_capture"]["values"] =
|
||||
[];
|
||||
let retainedBytes = 0;
|
||||
let truncatedValues = 0;
|
||||
for (const [argumentIndex, argument] of arguments_.entries()) {
|
||||
const primitive = consolePrimitive(argument);
|
||||
if (primitive === undefined) continue;
|
||||
const remaining =
|
||||
this.input.limits.max_total_console_text_bytes - this.#consoleTextBytes;
|
||||
if (remaining <= 0) {
|
||||
truncatedValues += 1;
|
||||
continue;
|
||||
}
|
||||
const bounded = boundedSensitiveText(
|
||||
primitive.text,
|
||||
Math.min(this.input.limits.max_console_text_field_bytes, remaining),
|
||||
);
|
||||
values.push({
|
||||
argument_index: argumentIndex,
|
||||
type: primitive.type,
|
||||
text: bounded.text,
|
||||
});
|
||||
retainedBytes += bounded.bytes;
|
||||
this.#consoleTextBytes += bounded.bytes;
|
||||
if (bounded.truncated) truncatedValues += 1;
|
||||
}
|
||||
if (truncatedValues > 0) this.completeness.truncate("console_text");
|
||||
return {
|
||||
status: truncatedValues > 0 ? "truncated" : "included",
|
||||
values,
|
||||
retained_bytes: retainedBytes,
|
||||
truncated_values: truncatedValues,
|
||||
};
|
||||
}
|
||||
|
||||
#websocketShape(
|
||||
payload: string,
|
||||
opcode: number,
|
||||
): WebPageInspection["network"]["websocket_events"][number]["payload_shape"] {
|
||||
if (!this.input.include_websocket_shapes) return null;
|
||||
if (opcode !== 1)
|
||||
return { format: "binary", json_shape: null, truncated: false };
|
||||
const bytes = Buffer.byteLength(payload);
|
||||
const remaining =
|
||||
this.input.limits.max_total_websocket_shape_bytes -
|
||||
this.#websocketShapeBytes;
|
||||
if (
|
||||
bytes > this.input.limits.max_websocket_shape_bytes ||
|
||||
bytes > remaining
|
||||
) {
|
||||
this.completeness.truncate("websocket_shapes");
|
||||
return { format: "text", json_shape: null, truncated: true };
|
||||
}
|
||||
this.#websocketShapeBytes += bytes;
|
||||
const shape = inferJsonShape(payload, {
|
||||
maximumBytes: this.input.limits.max_websocket_shape_bytes,
|
||||
maximumNodes: this.input.limits.max_json_shape_nodes,
|
||||
maximumDepth: this.input.limits.max_json_shape_depth,
|
||||
});
|
||||
if (shape?.truncated === true)
|
||||
this.completeness.truncate("websocket_shapes");
|
||||
return {
|
||||
format: shape === null ? "text" : "json",
|
||||
json_shape: shape,
|
||||
truncated: shape?.truncated === true,
|
||||
};
|
||||
}
|
||||
|
||||
#websocketCreated(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const rawUrl = stringValue(params.url);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
this.completeness.exclude(
|
||||
"websocket_connections",
|
||||
"invalid_protocol_value",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (rawUrl === undefined) {
|
||||
this.completeness.exclude(
|
||||
"websocket_connections",
|
||||
"invalid_protocol_value",
|
||||
);
|
||||
return;
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
this.completeness.exclude("websocket_connections", "unsupported_url");
|
||||
return;
|
||||
}
|
||||
if (parsed.protocol === "ws:") parsed.protocol = "http:";
|
||||
else if (parsed.protocol === "wss:") parsed.protocol = "https:";
|
||||
else {
|
||||
this.completeness.exclude("websocket_connections", "unsupported_url");
|
||||
return;
|
||||
}
|
||||
if (!this.allowedOrigins.has(parsed.origin)) {
|
||||
this.completeness.exclude("websocket_connections", "disallowed_origin");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!this.allowedWebSockets.has(requestId) &&
|
||||
this.allowedWebSockets.size >= this.input.limits.max_websocket_events
|
||||
) {
|
||||
this.completeness.drop("websocket_connections");
|
||||
return;
|
||||
}
|
||||
this.allowedWebSockets.add(requestId);
|
||||
}
|
||||
|
||||
#frameNavigated(params: UnknownRecord): void {
|
||||
const frame = recordValue(params.frame);
|
||||
if (stringValue(frame?.id) !== this.#mainFrameId) return;
|
||||
this.navigationDuringCapture = true;
|
||||
const rawUrl = stringValue(frame?.url);
|
||||
if (
|
||||
isHttpUrl(rawUrl) &&
|
||||
allowedSanitizedUrl(rawUrl, this.allowedOrigins) === undefined
|
||||
)
|
||||
this.originViolation = true;
|
||||
bodyShapes.ingestResponseBodyShape(this, requestId, value);
|
||||
}
|
||||
}
|
||||
|
||||
const firstCallFrame = (
|
||||
value: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => recordsValue(value?.callFrames)[0];
|
||||
|
||||
const initiatorLocation = (
|
||||
initiator: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => {
|
||||
let stack = recordValue(initiator?.stack);
|
||||
for (let depth = 0; depth < 32 && stack !== undefined; depth += 1) {
|
||||
const frame = firstCallFrame(stack);
|
||||
if (frame !== undefined) return frame;
|
||||
stack = recordValue(stack.parent);
|
||||
}
|
||||
return stringValue(initiator?.url) === undefined ? undefined : initiator;
|
||||
};
|
||||
|
||||
const exclusionReasonForUrl = (
|
||||
value: string | undefined,
|
||||
): "disallowed_origin" | "unsupported_url" | "unattributed_origin" =>
|
||||
value === undefined || value === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(value)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url";
|
||||
|
||||
const integerOrNull = (value: unknown): number | null => {
|
||||
const number = numberValue(value);
|
||||
return number === undefined ? null : Math.max(0, Math.trunc(number));
|
||||
};
|
||||
|
||||
const executionContextKey = (value: unknown): string | null => {
|
||||
const identifier = numberValue(value);
|
||||
return identifier !== undefined && Number.isSafeInteger(identifier)
|
||||
? String(identifier)
|
||||
: null;
|
||||
};
|
||||
|
||||
const isJsonContentType = (headers: UnknownRecord | undefined): boolean => {
|
||||
if (headers === undefined) return false;
|
||||
for (const [name, value] of Object.entries(headers))
|
||||
if (
|
||||
name.toLowerCase() === "content-type" &&
|
||||
isJsonMediaType(stringValue(value))
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
const isJsonMediaType = (value: string | null | undefined): boolean => {
|
||||
const mediaType = value?.split(";", 1)[0]?.trim().toLowerCase();
|
||||
return (
|
||||
mediaType === "application/json" || mediaType?.endsWith("+json") === true
|
||||
);
|
||||
};
|
||||
|
||||
const consolePrimitive = (
|
||||
value: UnknownRecord,
|
||||
): { readonly type: string; readonly text: string } | undefined => {
|
||||
const type = stringValue(value.type);
|
||||
switch (type) {
|
||||
case "string":
|
||||
return typeof value.value === "string"
|
||||
? { type, text: value.value }
|
||||
: undefined;
|
||||
case "boolean":
|
||||
return typeof value.value === "boolean"
|
||||
? { type, text: String(value.value) }
|
||||
: undefined;
|
||||
case "number":
|
||||
return typeof value.value === "number"
|
||||
? { type, text: String(value.value) }
|
||||
: typeof value.unserializableValue === "string"
|
||||
? { type, text: value.unserializableValue }
|
||||
: undefined;
|
||||
case "bigint":
|
||||
return typeof value.unserializableValue === "string"
|
||||
? { type, text: value.unserializableValue }
|
||||
: undefined;
|
||||
case "undefined":
|
||||
return { type, text: "undefined" };
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const BASE64 = /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/u;
|
||||
|
||||
const decodeBase64 = (value: string): Buffer | undefined =>
|
||||
value.length % 4 === 0 && BASE64.test(value)
|
||||
? Buffer.from(value, "base64")
|
||||
: undefined;
|
||||
|
||||
@@ -34,6 +34,14 @@ interface ObservationContext {
|
||||
type EndReason = WebObservationSession["window"]["end_reason"];
|
||||
type TimelineEvent = WebObservationSession["timeline"][number];
|
||||
|
||||
interface TimelineEntryOptions {
|
||||
readonly type: TimelineEvent["type"];
|
||||
readonly params: UnknownRecord;
|
||||
readonly rawUrl?: string | null;
|
||||
readonly requestId?: string | null;
|
||||
readonly detail?: string | null;
|
||||
}
|
||||
|
||||
/** Observe external user actions without rejecting approved same-origin navigation. */
|
||||
export const observeCdpSession = async (
|
||||
context: ObservationContext,
|
||||
@@ -190,7 +198,13 @@ class TimelineCapture {
|
||||
|
||||
targetTerminated(): void {
|
||||
if (this.#endReason !== undefined) return;
|
||||
this.#add("target_terminated", {}, null, null, "target_terminated");
|
||||
this.#add({
|
||||
type: "target_terminated",
|
||||
params: {},
|
||||
rawUrl: null,
|
||||
requestId: null,
|
||||
detail: "target_terminated",
|
||||
});
|
||||
this.end("target_terminated");
|
||||
}
|
||||
|
||||
@@ -203,13 +217,13 @@ class TimelineCapture {
|
||||
if (stringValue(params.frameId) !== this.mainFrameId) return;
|
||||
const reason = safeDetail(params.reason);
|
||||
this.#pendingReload = reason === "reload";
|
||||
this.#add(
|
||||
"navigation_requested",
|
||||
this.#add({
|
||||
type: "navigation_requested",
|
||||
params,
|
||||
stringValue(params.url),
|
||||
null,
|
||||
reason,
|
||||
);
|
||||
rawUrl: stringValue(params.url) ?? null,
|
||||
requestId: null,
|
||||
detail: reason,
|
||||
});
|
||||
}
|
||||
|
||||
#navigationCommitted(params: UnknownRecord): void {
|
||||
@@ -217,13 +231,13 @@ class TimelineCapture {
|
||||
if (stringValue(frame?.id) !== this.mainFrameId) return;
|
||||
const rawUrl = stringValue(frame?.url);
|
||||
const destination = scopedUrl(rawUrl, this.allowedOrigins);
|
||||
this.#add(
|
||||
this.#pendingReload ? "same_origin_reload" : "navigation_committed",
|
||||
{ ...params, frameId: frame?.id, loaderId: frame?.loaderId },
|
||||
rawUrl,
|
||||
null,
|
||||
safeDetail(frame?.transitionType),
|
||||
);
|
||||
this.#add({
|
||||
type: this.#pendingReload ? "same_origin_reload" : "navigation_committed",
|
||||
params: { ...params, frameId: frame?.id, loaderId: frame?.loaderId },
|
||||
rawUrl: rawUrl ?? null,
|
||||
requestId: null,
|
||||
detail: safeDetail(frame?.transitionType),
|
||||
});
|
||||
this.#pendingReload = false;
|
||||
if (destination.scope === "approved") this.finalUrl = destination.url;
|
||||
else {
|
||||
@@ -237,7 +251,13 @@ class TimelineCapture {
|
||||
if (stringValue(params.frameId) !== this.mainFrameId) return;
|
||||
const rawUrl = stringValue(params.url);
|
||||
const destination = scopedUrl(rawUrl, this.allowedOrigins);
|
||||
this.#add("same_document_navigation", params, rawUrl, null, null);
|
||||
this.#add({
|
||||
type: "same_document_navigation",
|
||||
params,
|
||||
rawUrl: rawUrl ?? null,
|
||||
requestId: null,
|
||||
detail: null,
|
||||
});
|
||||
if (destination.scope === "approved") this.finalUrl = destination.url;
|
||||
else {
|
||||
this.finalUrl = null;
|
||||
@@ -255,13 +275,13 @@ class TimelineCapture {
|
||||
const request = recordValue(params.request);
|
||||
const rawUrl = stringValue(request?.url);
|
||||
const destination = scopedUrl(rawUrl, this.allowedOrigins);
|
||||
this.#add(
|
||||
"redirect",
|
||||
this.#add({
|
||||
type: "redirect",
|
||||
params,
|
||||
rawUrl,
|
||||
stringValue(params.requestId) ?? null,
|
||||
null,
|
||||
);
|
||||
rawUrl: rawUrl ?? null,
|
||||
requestId: stringValue(params.requestId) ?? null,
|
||||
detail: null,
|
||||
});
|
||||
if (destination.scope !== "approved") {
|
||||
this.completeness.exclude("timeline", "out_of_target_scope");
|
||||
this.end("target_left_scope");
|
||||
@@ -271,27 +291,34 @@ class TimelineCapture {
|
||||
#loadingFailed(params: UnknownRecord): void {
|
||||
const frame = stringValue(params.frameId);
|
||||
if (frame !== undefined && frame !== this.mainFrameId) return;
|
||||
this.#add(
|
||||
"load_failed",
|
||||
this.#add({
|
||||
type: "load_failed",
|
||||
params,
|
||||
null,
|
||||
stringValue(params.requestId) ?? null,
|
||||
safeNetworkError(params.errorText),
|
||||
);
|
||||
rawUrl: null,
|
||||
requestId: stringValue(params.requestId) ?? null,
|
||||
detail: safeNetworkError(params.errorText),
|
||||
});
|
||||
}
|
||||
|
||||
#lifecycle(params: UnknownRecord): void {
|
||||
if (stringValue(params.frameId) !== this.mainFrameId) return;
|
||||
this.#add("lifecycle", params, null, null, safeDetail(params.name));
|
||||
this.#add({
|
||||
type: "lifecycle",
|
||||
params,
|
||||
rawUrl: null,
|
||||
requestId: null,
|
||||
detail: safeDetail(params.name),
|
||||
});
|
||||
}
|
||||
|
||||
#add(
|
||||
type: TimelineEvent["type"],
|
||||
params: UnknownRecord,
|
||||
rawUrl: string | null | undefined,
|
||||
requestId: string | null,
|
||||
detail: string | null,
|
||||
): void {
|
||||
#add(options: TimelineEntryOptions): void {
|
||||
const {
|
||||
type,
|
||||
params,
|
||||
rawUrl = null,
|
||||
requestId = null,
|
||||
detail = null,
|
||||
} = options;
|
||||
const destination =
|
||||
rawUrl == null ? null : scopedUrl(rawUrl, this.allowedOrigins);
|
||||
if (this.timeline.length >= this.maximum) {
|
||||
|
||||
+10
-208
@@ -7,11 +7,7 @@ import {
|
||||
BrowserObservationError,
|
||||
type BrowserObservationOperation,
|
||||
} from "../domain/errors.js";
|
||||
import {
|
||||
reconcileCapturedWebScript,
|
||||
stableWebResources,
|
||||
stableWebScriptKey,
|
||||
} from "../domain/webInventory.js";
|
||||
import { stableWebResources } from "../domain/webInventory.js";
|
||||
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
@@ -27,19 +23,14 @@ import {
|
||||
} from "./CdpCaptureDocuments.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
delayWithCancellation,
|
||||
isHttpUrl,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
requiredRecord,
|
||||
sourceExcluded,
|
||||
sourceResult,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { captureScripts } from "./CdpPageCaptureScripts.js";
|
||||
import { captureWorkers } from "./CdpPageCaptureWorkers.js";
|
||||
import type { WebSourceMapRequest } from "./WebSourceMapFetcher.js";
|
||||
|
||||
interface CaptureContext {
|
||||
export interface CaptureContext {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string | undefined;
|
||||
readonly operation: Extract<
|
||||
@@ -77,11 +68,6 @@ export interface CapturedPage {
|
||||
readonly sourceMapRequests: readonly WebSourceMapRequest[];
|
||||
}
|
||||
|
||||
interface CapturedScripts {
|
||||
readonly inventory: WebPageInspection["scripts"];
|
||||
readonly sourceMapRequests: readonly WebSourceMapRequest[];
|
||||
}
|
||||
|
||||
/** Capture and normalize one attached page without evaluating page JavaScript. */
|
||||
export const capturePage = async (
|
||||
context: CaptureContext,
|
||||
@@ -149,15 +135,15 @@ const captureAuthorizedPage = async (
|
||||
const accessibility = await accessibilityForFrames(state, frames);
|
||||
if (accessibility.total > accessibility.nodes.length)
|
||||
state.events.completeness.truncate("accessibility");
|
||||
const scripts = await captureScripts(
|
||||
const scripts = await captureScripts({
|
||||
context,
|
||||
state.events,
|
||||
resourceCapture.items,
|
||||
events: state.events,
|
||||
rawResources: resourceCapture.items,
|
||||
resources,
|
||||
new Set(frames.map((frame) => frame.frame_id)),
|
||||
);
|
||||
frameIds: new Set(frames.map((frame) => frame.frame_id)),
|
||||
});
|
||||
const workerCapture = await captureWorkers(
|
||||
state,
|
||||
{ context, allowedOrigins, limitations, events: state.events },
|
||||
new Set(frames.map((frame) => frame.frame_id)),
|
||||
);
|
||||
if (workerCapture.total > workerCapture.items.length)
|
||||
@@ -403,130 +389,6 @@ const accessibilityForFrames = async (
|
||||
return capture;
|
||||
};
|
||||
|
||||
const captureScripts = async (
|
||||
context: CaptureContext,
|
||||
events: CdpCaptureEvents,
|
||||
rawResources: readonly CapturedResource[],
|
||||
resources: WebPageInspection["resources"],
|
||||
frameIds: ReadonlySet<string>,
|
||||
): Promise<CapturedScripts> => {
|
||||
let totalSourceBytes = 0;
|
||||
const drafts: {
|
||||
readonly item: Omit<
|
||||
WebPageInspection["scripts"]["items"][number],
|
||||
"script_key"
|
||||
>;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
}[] = [];
|
||||
for (const script of events.scripts.values()) {
|
||||
let source: WebPageInspection["scripts"]["items"][number]["source"] =
|
||||
sourceExcluded("source capture was not approved");
|
||||
if (context.input.include_script_sources) {
|
||||
if (script.length > context.input.limits.max_script_source_bytes) {
|
||||
source = sourceExcluded(
|
||||
"declared script length exceeds per-script limit",
|
||||
);
|
||||
events.completeness.truncate("script_sources");
|
||||
} else if (
|
||||
totalSourceBytes + script.length >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
source = sourceExcluded("total script source limit reached");
|
||||
events.completeness.truncate("script_sources");
|
||||
} else {
|
||||
const result = requiredRecord(
|
||||
await context.connection.send(
|
||||
"Debugger.getScriptSource",
|
||||
{ scriptId: script.scriptId },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
),
|
||||
);
|
||||
const content = stringValue(result.scriptSource) ?? "";
|
||||
const bytes = Buffer.byteLength(content);
|
||||
if (
|
||||
bytes > context.input.limits.max_script_source_bytes ||
|
||||
totalSourceBytes + bytes >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
source = sourceExcluded(
|
||||
"actual source exceeds configured byte limits",
|
||||
);
|
||||
events.completeness.truncate("script_sources");
|
||||
} else {
|
||||
source = sourceResult(content);
|
||||
totalSourceBytes += bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
const inventoryScript = {
|
||||
frame_id: events.frameForScript(script, frameIds),
|
||||
url: script.url,
|
||||
cdp_hash: script.hash,
|
||||
length: script.length,
|
||||
is_module: script.isModule,
|
||||
language: script.language,
|
||||
source_map_url: script.sourceMapUrl,
|
||||
};
|
||||
drafts.push({
|
||||
item: {
|
||||
...inventoryScript,
|
||||
origin: script.origin,
|
||||
resource_reconciliation: reconcileCapturedWebScript(
|
||||
{ ...inventoryScript, rawUrl: script.rawUrl },
|
||||
rawResources,
|
||||
resources,
|
||||
),
|
||||
source,
|
||||
},
|
||||
sourceMapRawUrl: script.sourceMapRawUrl,
|
||||
});
|
||||
}
|
||||
if (!context.input.include_script_sources)
|
||||
events.completeness.exclude(
|
||||
"script_sources",
|
||||
"not_approved",
|
||||
events.scripts.size,
|
||||
);
|
||||
const keyed = drafts.map((draft) => ({
|
||||
...draft,
|
||||
base: stableWebScriptKey(draft.item),
|
||||
}));
|
||||
keyed.sort(
|
||||
(left, right) =>
|
||||
left.base.localeCompare(right.base) ||
|
||||
sourceDigest(left.item.source).localeCompare(
|
||||
sourceDigest(right.item.source),
|
||||
) ||
|
||||
(left.item.frame_id ?? "").localeCompare(right.item.frame_id ?? ""),
|
||||
);
|
||||
const totals = new Map<string, number>();
|
||||
for (const { base } of keyed) totals.set(base, (totals.get(base) ?? 0) + 1);
|
||||
const seen = new Map<string, number>();
|
||||
const sourceMapRequests: WebSourceMapRequest[] = [];
|
||||
const items = keyed.map(({ base, item, sourceMapRawUrl }) => {
|
||||
const occurrence = (seen.get(base) ?? 0) + 1;
|
||||
seen.set(base, occurrence);
|
||||
const scriptKey =
|
||||
totals.get(base) === 1 ? base : `${base}_${String(occurrence)}`;
|
||||
if (item.source_map_url !== null && sourceMapRawUrl !== null)
|
||||
sourceMapRequests.push({
|
||||
scriptKey,
|
||||
declaredUrl: item.source_map_url,
|
||||
fetchUrl: sourceMapRawUrl,
|
||||
});
|
||||
return { script_key: scriptKey, ...item };
|
||||
});
|
||||
return {
|
||||
inventory: { total: events.scripts.size, items },
|
||||
sourceMapRequests,
|
||||
};
|
||||
};
|
||||
|
||||
const sourceDigest = (
|
||||
source: WebPageInspection["scripts"]["items"][number]["source"],
|
||||
): string => (source.included ? source.artifact.sha256 : source.reason);
|
||||
|
||||
const publicResource = ({ rawUrl: _rawUrl, ...resource }: CapturedResource) =>
|
||||
resource;
|
||||
|
||||
@@ -542,66 +404,6 @@ const deduplicatedAgentHints = (
|
||||
});
|
||||
};
|
||||
|
||||
const captureWorkers = async (
|
||||
state: CaptureState,
|
||||
frameIds: ReadonlySet<string>,
|
||||
): Promise<{
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["workers"];
|
||||
}> => {
|
||||
const { context, allowedOrigins, limitations, events } = state;
|
||||
const completeness = events.completeness;
|
||||
const result = await optionalCdpCommand(
|
||||
{ ...context, sessionId: undefined },
|
||||
"Target.getTargets",
|
||||
{},
|
||||
limitations,
|
||||
);
|
||||
const items: WebPageInspection["workers"] = [];
|
||||
let total = 0;
|
||||
if (result === undefined) completeness.unavailable("workers");
|
||||
for (const target of recordsValue(recordValue(result)?.targetInfos)) {
|
||||
const type = stringValue(target.type) ?? "";
|
||||
const url = allowedSanitizedUrl(target.url, allowedOrigins);
|
||||
const relatedToPage =
|
||||
stringValue(target.openerId) === context.target.id ||
|
||||
(stringValue(target.parentFrameId) !== undefined &&
|
||||
frameIds.has(stringValue(target.parentFrameId) ?? ""));
|
||||
if (!type.includes("worker")) continue;
|
||||
if (!relatedToPage) {
|
||||
completeness.exclude("workers", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
if (url === undefined) {
|
||||
const rawUrl = stringValue(target.url);
|
||||
completeness.exclude(
|
||||
"workers",
|
||||
rawUrl === undefined || rawUrl === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(rawUrl)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
total += 1;
|
||||
if (items.length >= context.input.limits.max_workers) continue;
|
||||
items.push({
|
||||
target_id: (stringValue(target.targetId) ?? "").slice(0, 256),
|
||||
type: type.slice(0, 100),
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
attached: target.attached === true,
|
||||
opener_target_id: boundedText(target.openerId, 256) ?? null,
|
||||
parent_frame_id: boundedText(target.parentFrameId, 256) ?? null,
|
||||
});
|
||||
}
|
||||
return {
|
||||
total,
|
||||
items,
|
||||
};
|
||||
};
|
||||
|
||||
const normalizedTarget = (
|
||||
target: CdpEndpointTarget,
|
||||
currentUrl: string,
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import type { WebPageInspection } from "../domain/browserObservation.js";
|
||||
import {
|
||||
reconcileCapturedWebScript,
|
||||
stableWebScriptKey,
|
||||
} from "../domain/webInventory.js";
|
||||
import type { CapturedResource } from "./CdpCaptureDocuments.js";
|
||||
import type { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
import type { CapturedScript } from "./CdpCaptureEventTypes.js";
|
||||
import {
|
||||
requiredRecord,
|
||||
sourceExcluded,
|
||||
sourceResult,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import type { CaptureContext } from "./CdpPageCapture.js";
|
||||
import type { WebSourceMapRequest } from "./WebSourceMapFetcher.js";
|
||||
|
||||
export interface CapturedScripts {
|
||||
readonly inventory: WebPageInspection["scripts"];
|
||||
readonly sourceMapRequests: readonly WebSourceMapRequest[];
|
||||
}
|
||||
|
||||
export interface CaptureScriptsOptions {
|
||||
readonly context: CaptureContext;
|
||||
readonly events: CdpCaptureEvents;
|
||||
readonly rawResources: readonly CapturedResource[];
|
||||
readonly resources: WebPageInspection["resources"];
|
||||
readonly frameIds: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
interface ScriptDraftState {
|
||||
readonly context: CaptureContext;
|
||||
readonly events: CdpCaptureEvents;
|
||||
readonly frameIds: ReadonlySet<string>;
|
||||
readonly rawResources: readonly CapturedResource[];
|
||||
readonly resources: WebPageInspection["resources"];
|
||||
totalSourceBytes: number;
|
||||
}
|
||||
|
||||
type ScriptDraftItem = Omit<
|
||||
WebPageInspection["scripts"]["items"][number],
|
||||
"script_key"
|
||||
>;
|
||||
|
||||
export const captureScripts = async (
|
||||
options: CaptureScriptsOptions,
|
||||
): Promise<CapturedScripts> => {
|
||||
const { context, events, rawResources, resources, frameIds } = options;
|
||||
const state: ScriptDraftState = {
|
||||
context,
|
||||
events,
|
||||
frameIds,
|
||||
rawResources,
|
||||
resources,
|
||||
totalSourceBytes: 0,
|
||||
};
|
||||
const drafts: {
|
||||
readonly item: ScriptDraftItem;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
}[] = [];
|
||||
for (const script of events.scripts.values())
|
||||
drafts.push(await buildScriptDraft(script, state));
|
||||
if (!context.input.include_script_sources)
|
||||
events.completeness.exclude(
|
||||
"script_sources",
|
||||
"not_approved",
|
||||
events.scripts.size,
|
||||
);
|
||||
return keyAndBuildInventory(drafts, events.scripts.size);
|
||||
};
|
||||
|
||||
const buildScriptDraft = async (
|
||||
script: CapturedScript,
|
||||
state: ScriptDraftState,
|
||||
): Promise<{
|
||||
readonly item: ScriptDraftItem;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
}> => {
|
||||
let source: WebPageInspection["scripts"]["items"][number]["source"] = state
|
||||
.context.input.include_script_sources
|
||||
? await captureScriptSource(script, state)
|
||||
: sourceExcluded("source capture was not approved");
|
||||
const inventoryScript = {
|
||||
frame_id: state.events.frameForScript(script, state.frameIds),
|
||||
url: script.url,
|
||||
cdp_hash: script.hash,
|
||||
length: script.length,
|
||||
is_module: script.isModule,
|
||||
language: script.language,
|
||||
source_map_url: script.sourceMapUrl,
|
||||
};
|
||||
return {
|
||||
item: {
|
||||
...inventoryScript,
|
||||
origin: script.origin,
|
||||
resource_reconciliation: reconcileCapturedWebScript(
|
||||
{ ...inventoryScript, rawUrl: script.rawUrl },
|
||||
state.rawResources,
|
||||
state.resources,
|
||||
),
|
||||
source,
|
||||
},
|
||||
sourceMapRawUrl: script.sourceMapRawUrl,
|
||||
};
|
||||
};
|
||||
|
||||
const captureScriptSource = async (
|
||||
script: CapturedScript,
|
||||
state: ScriptDraftState,
|
||||
): Promise<WebPageInspection["scripts"]["items"][number]["source"]> => {
|
||||
const { context, events } = state;
|
||||
if (script.length > context.input.limits.max_script_source_bytes) {
|
||||
events.completeness.truncate("script_sources");
|
||||
return sourceExcluded("declared script length exceeds per-script limit");
|
||||
}
|
||||
if (
|
||||
state.totalSourceBytes + script.length >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
events.completeness.truncate("script_sources");
|
||||
return sourceExcluded("total script source limit reached");
|
||||
}
|
||||
const result = requiredRecord(
|
||||
await context.connection.send(
|
||||
"Debugger.getScriptSource",
|
||||
{ scriptId: script.scriptId },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
),
|
||||
);
|
||||
const content = stringValue(result.scriptSource) ?? "";
|
||||
const bytes = Buffer.byteLength(content);
|
||||
if (
|
||||
bytes > context.input.limits.max_script_source_bytes ||
|
||||
state.totalSourceBytes + bytes >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
events.completeness.truncate("script_sources");
|
||||
return sourceExcluded("actual source exceeds configured byte limits");
|
||||
}
|
||||
state.totalSourceBytes += bytes;
|
||||
return sourceResult(content);
|
||||
};
|
||||
|
||||
const keyAndBuildInventory = (
|
||||
drafts: readonly {
|
||||
readonly item: ScriptDraftItem;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
}[],
|
||||
scriptCount: number,
|
||||
): CapturedScripts => {
|
||||
const keyed = drafts.map((draft) => ({
|
||||
...draft,
|
||||
base: stableWebScriptKey(draft.item),
|
||||
}));
|
||||
keyed.sort(
|
||||
(left, right) =>
|
||||
left.base.localeCompare(right.base) ||
|
||||
sourceDigest(left.item.source).localeCompare(
|
||||
sourceDigest(right.item.source),
|
||||
) ||
|
||||
(left.item.frame_id ?? "").localeCompare(right.item.frame_id ?? ""),
|
||||
);
|
||||
const totals = new Map<string, number>();
|
||||
for (const { base } of keyed) totals.set(base, (totals.get(base) ?? 0) + 1);
|
||||
const seen = new Map<string, number>();
|
||||
const sourceMapRequests: WebSourceMapRequest[] = [];
|
||||
const items = keyed.map(({ base, item, sourceMapRawUrl }) => {
|
||||
const occurrence = (seen.get(base) ?? 0) + 1;
|
||||
seen.set(base, occurrence);
|
||||
const scriptKey =
|
||||
totals.get(base) === 1 ? base : `${base}_${String(occurrence)}`;
|
||||
if (item.source_map_url !== null && sourceMapRawUrl !== null)
|
||||
sourceMapRequests.push({
|
||||
scriptKey,
|
||||
declaredUrl: item.source_map_url,
|
||||
fetchUrl: sourceMapRawUrl,
|
||||
});
|
||||
return { script_key: scriptKey, ...item };
|
||||
});
|
||||
return {
|
||||
inventory: { total: scriptCount, items },
|
||||
sourceMapRequests,
|
||||
};
|
||||
};
|
||||
|
||||
const sourceDigest = (
|
||||
source: WebPageInspection["scripts"]["items"][number]["source"],
|
||||
): string => (source.included ? source.artifact.sha256 : source.reason);
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { WebPageInspection } from "../domain/browserObservation.js";
|
||||
import type { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
isHttpUrl,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import type { CaptureContext } from "./CdpPageCapture.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
|
||||
interface CaptureWorkersInput {
|
||||
readonly context: CaptureContext;
|
||||
readonly allowedOrigins: ReadonlySet<string>;
|
||||
readonly limitations: string[];
|
||||
readonly events: CdpCaptureEvents;
|
||||
}
|
||||
|
||||
export const captureWorkers = async (
|
||||
input: CaptureWorkersInput,
|
||||
frameIds: ReadonlySet<string>,
|
||||
): Promise<{
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["workers"];
|
||||
}> => {
|
||||
const { context, allowedOrigins, limitations, events } = input;
|
||||
const completeness = events.completeness;
|
||||
const result = await optionalCdpCommand(
|
||||
{ ...context, sessionId: undefined },
|
||||
"Target.getTargets",
|
||||
{},
|
||||
limitations,
|
||||
);
|
||||
const items: WebPageInspection["workers"] = [];
|
||||
let total = 0;
|
||||
if (result === undefined) completeness.unavailable("workers");
|
||||
for (const target of recordsValue(recordValue(result)?.targetInfos)) {
|
||||
const type = stringValue(target.type) ?? "";
|
||||
const url = allowedSanitizedUrl(target.url, allowedOrigins);
|
||||
const relatedToPage =
|
||||
stringValue(target.openerId) === context.target.id ||
|
||||
(stringValue(target.parentFrameId) !== undefined &&
|
||||
frameIds.has(stringValue(target.parentFrameId) ?? ""));
|
||||
if (!type.includes("worker")) continue;
|
||||
if (!relatedToPage) {
|
||||
completeness.exclude("workers", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
if (url === undefined) {
|
||||
const rawUrl = stringValue(target.url);
|
||||
completeness.exclude(
|
||||
"workers",
|
||||
rawUrl === undefined || rawUrl === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(rawUrl)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
total += 1;
|
||||
if (items.length >= context.input.limits.max_workers) continue;
|
||||
items.push({
|
||||
target_id: (stringValue(target.targetId) ?? "").slice(0, 256),
|
||||
type: type.slice(0, 100),
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
attached: target.attached === true,
|
||||
opener_target_id: boundedText(target.openerId, 256) ?? null,
|
||||
parent_frame_id: boundedText(target.parentFrameId, 256) ?? null,
|
||||
});
|
||||
}
|
||||
return { total, items };
|
||||
};
|
||||
@@ -74,7 +74,13 @@ export const discoverWebMcp = async (
|
||||
const removeListener = context.connection.onEvent((event) => {
|
||||
if (event.sessionId !== context.sessionId) return;
|
||||
if (ingestFrameScopeEvent(event, frameScope)) return;
|
||||
ingestWebMcpEvent(event, context.input, frameUrls, tools, completeness);
|
||||
ingestWebMcpEvent({
|
||||
event,
|
||||
input: context.input,
|
||||
frames: frameUrls,
|
||||
tools,
|
||||
completeness,
|
||||
});
|
||||
});
|
||||
await context.progress?.report({
|
||||
phase: "browser_observation",
|
||||
@@ -100,14 +106,14 @@ export const discoverWebMcp = async (
|
||||
context.signal,
|
||||
);
|
||||
await assertStableAuthorizedFrame(context, initialUrl, origins);
|
||||
return result(
|
||||
return buildWebMcpResult({
|
||||
context,
|
||||
frameTree,
|
||||
tools,
|
||||
completeness,
|
||||
limitations,
|
||||
available,
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
removeListener();
|
||||
await context.progress?.report({
|
||||
@@ -139,20 +145,35 @@ const ingestFrameScopeEvent = (
|
||||
): boolean => {
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return false;
|
||||
if (event.method === "Page.frameDetached") {
|
||||
const frameId = stringValue(params.frameId);
|
||||
if (frameId === undefined || frameId.length > 256)
|
||||
state.completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
else removeFrame(frameId, state.frames, state.tools);
|
||||
switch (event.method) {
|
||||
case "Page.frameDetached":
|
||||
return handleFrameDetached(params, state);
|
||||
case "Page.frameNavigated":
|
||||
return handleFrameUpdate(recordValue(params.frame), state);
|
||||
case "Page.navigatedWithinDocument":
|
||||
return handleFrameUpdate(params, state);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleFrameDetached = (
|
||||
params: UnknownRecord,
|
||||
state: FrameScopeState,
|
||||
): boolean => {
|
||||
const frameId = stringValue(params.frameId);
|
||||
if (frameId === undefined || frameId.length > 256) {
|
||||
state.completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
return true;
|
||||
}
|
||||
const frame =
|
||||
event.method === "Page.frameNavigated" ? recordValue(params.frame) : params;
|
||||
if (
|
||||
event.method !== "Page.frameNavigated" &&
|
||||
event.method !== "Page.navigatedWithinDocument"
|
||||
)
|
||||
return false;
|
||||
removeFrame(frameId, state.frames, state.tools);
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleFrameUpdate = (
|
||||
frame: UnknownRecord | undefined,
|
||||
state: FrameScopeState,
|
||||
): boolean => {
|
||||
const frameId = stringValue(frame?.id) ?? stringValue(frame?.frameId);
|
||||
if (frameId === undefined || frameId.length > 256) {
|
||||
state.completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
@@ -213,16 +234,19 @@ const assertStableAuthorizedFrame = async (
|
||||
throw new BrowserObservationError("inspect_web_page", "target_changed");
|
||||
};
|
||||
|
||||
const ingestWebMcpEvent = (
|
||||
event: CdpEvent,
|
||||
input: DiscoverWebMcpToolsInput,
|
||||
frames: ReadonlyMap<
|
||||
interface WebMcpIngestOptions {
|
||||
readonly event: CdpEvent;
|
||||
readonly input: DiscoverWebMcpToolsInput;
|
||||
readonly frames: ReadonlyMap<
|
||||
string,
|
||||
{ readonly url: string; readonly origin: string | null }
|
||||
>,
|
||||
tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>,
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): void => {
|
||||
>;
|
||||
readonly tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>;
|
||||
readonly completeness: CdpCaptureCompleteness;
|
||||
}
|
||||
|
||||
const ingestWebMcpEvent = (options: WebMcpIngestOptions): void => {
|
||||
const { event, input, frames, tools, completeness } = options;
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return;
|
||||
if (event.method === "WebMCP.toolsRemoved") {
|
||||
@@ -329,14 +353,21 @@ const registrationSource = (
|
||||
};
|
||||
};
|
||||
|
||||
const result = (
|
||||
context: DiscoveryContext,
|
||||
frameTree: unknown,
|
||||
tools: ReadonlyMap<string, WebMcpDiscovery["tools"]["items"][number]>,
|
||||
completeness: CdpCaptureCompleteness,
|
||||
limitations: string[],
|
||||
available: boolean,
|
||||
): WebMcpDiscovery => {
|
||||
interface WebMcpResultOptions {
|
||||
readonly context: DiscoveryContext;
|
||||
readonly frameTree: unknown;
|
||||
readonly tools: ReadonlyMap<
|
||||
string,
|
||||
WebMcpDiscovery["tools"]["items"][number]
|
||||
>;
|
||||
readonly completeness: CdpCaptureCompleteness;
|
||||
readonly limitations: string[];
|
||||
readonly available: boolean;
|
||||
}
|
||||
|
||||
const buildWebMcpResult = (options: WebMcpResultOptions): WebMcpDiscovery => {
|
||||
const { context, frameTree, tools, completeness, limitations, available } =
|
||||
options;
|
||||
const targetUrl = mainFrameUrl(frameTree) ?? context.target.url;
|
||||
const sanitized = allowedSanitizedUrl(
|
||||
targetUrl,
|
||||
|
||||
@@ -153,13 +153,13 @@ const unfilter = (
|
||||
row > 0 && column >= channels
|
||||
? (decoded[outputOffset + column - rowBytes - channels] ?? 0)
|
||||
: 0;
|
||||
decoded[outputOffset + column] = applyFilter(
|
||||
decoded[outputOffset + column] = applyFilter({
|
||||
filter,
|
||||
source,
|
||||
left,
|
||||
above,
|
||||
upperLeft,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
if (channels === 4) return decoded;
|
||||
@@ -177,13 +177,16 @@ const unfilter = (
|
||||
return rgba;
|
||||
};
|
||||
|
||||
const applyFilter = (
|
||||
filter: number,
|
||||
source: number,
|
||||
left: number,
|
||||
above: number,
|
||||
upperLeft: number,
|
||||
): number => {
|
||||
interface ApplyFilterOptions {
|
||||
readonly filter: number;
|
||||
readonly source: number;
|
||||
readonly left: number;
|
||||
readonly above: number;
|
||||
readonly upperLeft: number;
|
||||
}
|
||||
|
||||
const applyFilter = (options: ApplyFilterOptions): number => {
|
||||
const { filter, source, left, above, upperLeft } = options;
|
||||
switch (filter) {
|
||||
case 0:
|
||||
return source;
|
||||
|
||||
+48
-136
@@ -42,14 +42,10 @@ import {
|
||||
type GhidraSessionInfo,
|
||||
} from "./GhidraSessionValues.js";
|
||||
import { createGhidraTargetSnapshot } from "./GhidraTargetSnapshot.js";
|
||||
import {
|
||||
attachGhidraSocket,
|
||||
connectGhidraSocketOnce,
|
||||
} from "./GhidraSocketConnection.js";
|
||||
import {
|
||||
observeGhidraEndpoint,
|
||||
type GhidraEndpoint,
|
||||
} from "./GhidraTransport.js";
|
||||
import { connectGhidraSocket } from "./GhidraSocketConnection.js";
|
||||
import type { GhidraEndpoint } from "./GhidraTransport.js";
|
||||
import { GhidraWire } from "./GhidraClientWire.js";
|
||||
import { completeGhidraStartupHandshake } from "./GhidraClientStartup.js";
|
||||
|
||||
const SHUTDOWN_TIMEOUT_MS = 10_000;
|
||||
const SESSION_ROOT = tmpdir();
|
||||
@@ -75,11 +71,11 @@ export class GhidraClient {
|
||||
>
|
||||
> &
|
||||
GhidraClientOptions;
|
||||
readonly #logger: Logger;
|
||||
readonly #pending = new PendingOperations<
|
||||
number,
|
||||
Result<JsonValue, GhidraSessionError>
|
||||
>();
|
||||
readonly #logger: Logger;
|
||||
#socket: Socket | undefined;
|
||||
#detachSocket: (() => void) | undefined;
|
||||
#launch: GhidraLaunch | undefined;
|
||||
@@ -96,6 +92,7 @@ export class GhidraClient {
|
||||
#startPromise: Promise<GhidraStartResult> | undefined;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
readonly #failure = bindGhidraSessionFailure(() => this.#diagnostics());
|
||||
readonly #wire: GhidraWire;
|
||||
readonly #requestQueue: GhidraRequestQueue;
|
||||
readonly #responseRouter = new GhidraResponseRouter({
|
||||
pending: this.#pending,
|
||||
@@ -122,17 +119,26 @@ export class GhidraClient {
|
||||
};
|
||||
|
||||
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,
|
||||
transport: options.transport ?? "unix-socket",
|
||||
};
|
||||
this.#logger = options.logger ?? silentLogger;
|
||||
this.#wire = new GhidraWire({
|
||||
getSocket: () => this.#socket,
|
||||
getToken: () => this.#token,
|
||||
nextId: () => this.#nextId++,
|
||||
pending: this.#pending,
|
||||
requestTimeoutMs: this.#options.requestTimeoutMs,
|
||||
logger: this.#logger,
|
||||
failure: this.#failure,
|
||||
});
|
||||
this.#requestQueue = new GhidraRequestQueue(
|
||||
GHIDRA_MAX_QUEUED_REQUESTS,
|
||||
(method, parameters, requestOptions) =>
|
||||
this.#request(method, parameters, requestOptions),
|
||||
this.#wire.request(method, parameters, requestOptions),
|
||||
(kind, message, timeoutMs) =>
|
||||
this.#failure(
|
||||
kind,
|
||||
@@ -176,7 +182,7 @@ export class GhidraClient {
|
||||
): Promise<Result<GhidraSessionInfo, GhidraSessionError>> {
|
||||
const started = await this.start(options.signal);
|
||||
if (!started.ok) return started;
|
||||
const result = await this.#request("ping", {}, options);
|
||||
const result = await this.#wire.request("ping", {}, options);
|
||||
if (!result.ok) return result;
|
||||
return this.#parseSessionInfo(result.value);
|
||||
}
|
||||
@@ -306,128 +312,38 @@ export class GhidraClient {
|
||||
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;
|
||||
return completeGhidraStartupHandshake({
|
||||
deadline,
|
||||
request: (method, params, requestOptions) =>
|
||||
this.#wire.request(method, params, requestOptions),
|
||||
parseSessionInfo: (value) => this.#parseSessionInfo(value),
|
||||
cleanup: () => this.#cleanup(),
|
||||
failure: this.#failure,
|
||||
startupTimeoutMs: this.#options.startupTimeoutMs,
|
||||
});
|
||||
}
|
||||
|
||||
async #connect(
|
||||
endpoint: GhidraEndpoint,
|
||||
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"),
|
||||
);
|
||||
const observed = await observeGhidraEndpoint(endpoint);
|
||||
if (!observed.ok) return observed;
|
||||
if (observed.value === null) {
|
||||
if ((await deadline.wait(50)) === "aborted")
|
||||
return err(this.#interruptionFailure(deadline));
|
||||
continue;
|
||||
}
|
||||
const connected = await connectGhidraSocketOnce(
|
||||
observed.value,
|
||||
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: GhidraRequestOptions,
|
||||
): 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 connected = await connectGhidraSocket({
|
||||
endpoint,
|
||||
deadline,
|
||||
failure: this.#failure,
|
||||
isClosed: () => this.#closing,
|
||||
processExited: () => this.#processSnapshot?.exitCode !== undefined,
|
||||
startupTimeoutMs: this.#options.startupTimeoutMs,
|
||||
handlers: {
|
||||
data: this.#onSocketData,
|
||||
error: this.#onSocketError,
|
||||
close: this.#onSocketClose,
|
||||
},
|
||||
);
|
||||
const result = await response;
|
||||
this.#logger[result.ok ? "debug" : "warn"](
|
||||
{ method, status: result.ok ? "ok" : "error" },
|
||||
"Ghidra bridge request completed",
|
||||
);
|
||||
return result;
|
||||
});
|
||||
if (!connected.ok) return connected;
|
||||
this.#socket = connected.value.socket;
|
||||
this.#detachSocket = connected.value.detach;
|
||||
return ok(undefined);
|
||||
}
|
||||
|
||||
#parseSessionInfo(value: JsonValue) {
|
||||
@@ -473,15 +389,11 @@ export class GhidraClient {
|
||||
);
|
||||
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")),
|
||||
);
|
||||
const shutdown = await this.#wire
|
||||
.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" },
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
import type { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
|
||||
import type { GhidraRequestOptions } from "./GhidraClientTypes.js";
|
||||
import type {
|
||||
GhidraSessionError,
|
||||
GhidraSessionErrorOptions,
|
||||
GhidraSessionFailureKind,
|
||||
} from "./GhidraSessionError.js";
|
||||
import type { GhidraSessionInfo } from "./GhidraSessionValues.js";
|
||||
|
||||
/** Inputs needed to complete the post-connection bridge handshake. */
|
||||
export interface GhidraStartupHandshakeOptions {
|
||||
readonly deadline: ProviderStartupDeadline;
|
||||
readonly request: (
|
||||
method: string,
|
||||
params: JsonValue,
|
||||
options: GhidraRequestOptions,
|
||||
) => Promise<Result<JsonValue, GhidraSessionError>>;
|
||||
readonly parseSessionInfo: (
|
||||
value: JsonValue,
|
||||
) => Result<GhidraSessionInfo, GhidraSessionError>;
|
||||
readonly cleanup: () => Promise<void>;
|
||||
readonly failure: (
|
||||
kind: GhidraSessionFailureKind,
|
||||
message: string,
|
||||
cause?: unknown,
|
||||
options?: Pick<GhidraSessionErrorOptions, "timeoutMs" | "remoteCode">,
|
||||
) => GhidraSessionError;
|
||||
readonly startupTimeoutMs: number;
|
||||
}
|
||||
|
||||
/** Ping and validate the bridge after its socket is attached. */
|
||||
export async function completeGhidraStartupHandshake(
|
||||
options: GhidraStartupHandshakeOptions,
|
||||
): Promise<Result<GhidraSessionInfo, GhidraSessionError>> {
|
||||
const ping = await options.request(
|
||||
"ping",
|
||||
{},
|
||||
{
|
||||
signal: options.deadline.signal,
|
||||
timeoutMs: options.deadline.remainingMs(),
|
||||
},
|
||||
);
|
||||
if (!ping.ok) {
|
||||
const failure = options.deadline.signal.aborted
|
||||
? interruptionFailure(options)
|
||||
: ping.error;
|
||||
await options.cleanup();
|
||||
return err(failure);
|
||||
}
|
||||
const parsed = options.parseSessionInfo(ping.value);
|
||||
if (!parsed.ok || parsed.value.analysis_timed_out) {
|
||||
const failure = parsed.ok
|
||||
? options.failure(
|
||||
"analysis_timeout",
|
||||
"Ghidra auto-analysis reached its per-file deadline",
|
||||
)
|
||||
: parsed.error;
|
||||
await options.cleanup();
|
||||
return err(failure);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
const interruptionFailure = (
|
||||
options: GhidraStartupHandshakeOptions,
|
||||
): GhidraSessionError =>
|
||||
options.deadline.cancelled
|
||||
? options.failure("cancelled", "Ghidra startup was cancelled")
|
||||
: options.failure("timeout", "Ghidra startup deadline elapsed", undefined, {
|
||||
timeoutMs: options.startupTimeoutMs,
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { Socket } from "node:net";
|
||||
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { PendingOperations } from "../process/PendingOperations.js";
|
||||
import type { GhidraRequestOptions } from "./GhidraClientTypes.js";
|
||||
import type {
|
||||
GhidraSessionError,
|
||||
GhidraSessionErrorOptions,
|
||||
GhidraSessionFailureKind,
|
||||
} from "./GhidraSessionError.js";
|
||||
|
||||
/** Dependencies needed to write one authenticated line and await its reply. */
|
||||
export interface GhidraWireOptions {
|
||||
readonly getSocket: () => Socket | undefined;
|
||||
readonly getToken: () => string | undefined;
|
||||
readonly nextId: () => number;
|
||||
readonly pending: PendingOperations<
|
||||
number,
|
||||
Result<JsonValue, GhidraSessionError>
|
||||
>;
|
||||
readonly requestTimeoutMs: number;
|
||||
readonly logger: Logger;
|
||||
readonly failure: (
|
||||
kind: GhidraSessionFailureKind,
|
||||
message: string,
|
||||
cause?: unknown,
|
||||
options?: Pick<GhidraSessionErrorOptions, "timeoutMs" | "remoteCode">,
|
||||
) => GhidraSessionError;
|
||||
}
|
||||
|
||||
/** Owns the socket write and pending-reply lifecycle for one bridge session. */
|
||||
export class GhidraWire {
|
||||
readonly #options: GhidraWireOptions;
|
||||
|
||||
constructor(options: GhidraWireOptions) {
|
||||
this.#options = options;
|
||||
}
|
||||
|
||||
/** Write one authenticated request and return its correlated reply. */
|
||||
async request(
|
||||
method: string,
|
||||
params: JsonValue,
|
||||
options: GhidraRequestOptions,
|
||||
): Promise<Result<JsonValue, GhidraSessionError>> {
|
||||
const socket = this.#options.getSocket();
|
||||
const token = this.#options.getToken();
|
||||
if (socket === undefined || socket.destroyed || token === undefined)
|
||||
return err(
|
||||
this.#options.failure("process", "Ghidra bridge is unavailable"),
|
||||
);
|
||||
if (options.signal?.aborted === true)
|
||||
return err(
|
||||
this.#options.failure("cancelled", "Ghidra request was cancelled"),
|
||||
);
|
||||
const id = this.#options.nextId();
|
||||
const timeoutMs = options.timeoutMs ?? this.#options.requestTimeoutMs;
|
||||
if (timeoutMs <= 0)
|
||||
return err(
|
||||
this.#options.failure(
|
||||
"timeout",
|
||||
"Ghidra request deadline elapsed",
|
||||
undefined,
|
||||
{ timeoutMs },
|
||||
),
|
||||
);
|
||||
const response = this.#options.pending.wait(id, {
|
||||
timeoutMs,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
timeoutValue: () =>
|
||||
err(
|
||||
this.#options.failure(
|
||||
"timeout",
|
||||
"Ghidra bridge request timed out",
|
||||
undefined,
|
||||
{ timeoutMs },
|
||||
),
|
||||
),
|
||||
cancelledValue: () =>
|
||||
err(this.#options.failure("cancelled", "Ghidra request was cancelled")),
|
||||
});
|
||||
socket.write(
|
||||
`${JSON.stringify({ id, token, method, params })}\n`,
|
||||
(cause) => {
|
||||
if (cause !== undefined && cause !== null)
|
||||
this.#options.pending.settle(
|
||||
id,
|
||||
err(
|
||||
this.#options.failure(
|
||||
"process",
|
||||
"Ghidra bridge write failed",
|
||||
cause,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
const result = await response;
|
||||
this.#options.logger[result.ok ? "debug" : "warn"](
|
||||
{ method, status: result.ok ? "ok" : "error" },
|
||||
"Ghidra bridge request completed",
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+12
-193
@@ -24,28 +24,20 @@ import {
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import {
|
||||
ENHANCED_TOOL_CONTRACTS,
|
||||
OFFICIAL_TOOL_CONTRACTS,
|
||||
} from "../contracts/toolContracts.js";
|
||||
import { GhidraClient } from "./GhidraClient.js";
|
||||
import type { GhidraClientOptions } from "./GhidraClientTypes.js";
|
||||
import {
|
||||
GHIDRA_ANALYSIS_TIMEOUT_SECONDS,
|
||||
GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS,
|
||||
GHIDRA_DECOMPILE_TIMEOUT_SECONDS,
|
||||
GHIDRA_MAX_LINE_BYTES,
|
||||
GHIDRA_REQUEST_TIMEOUT_MS,
|
||||
GHIDRA_STARTUP_TIMEOUT_MS,
|
||||
} from "./GhidraDefaults.js";
|
||||
import {
|
||||
GHIDRA_FUNCTION_OPERATIONS,
|
||||
isGhidraFunctionOperation,
|
||||
parseGhidraFunctionInput,
|
||||
parseGhidraFunctionResult,
|
||||
} from "./GhidraFunctionValues.js";
|
||||
import {
|
||||
GHIDRA_INVENTORY_OPERATIONS,
|
||||
isGhidraInventoryOperation,
|
||||
parseGhidraInventoryInput,
|
||||
parseGhidraInventoryResult,
|
||||
@@ -59,191 +51,17 @@ import {
|
||||
import { GhidraHeadlessLauncher } from "./GhidraLauncher.js";
|
||||
import { resolveGhidraAnalysisProfile } from "./GhidraAnalysisProfile.js";
|
||||
import type { GhidraSessionError } from "./GhidraSessionError.js";
|
||||
import {
|
||||
CAPABILITIES,
|
||||
WINDOWS_P0_CAPABILITIES,
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS,
|
||||
healthLimitations,
|
||||
windowsP0Limitations,
|
||||
limitationsFor,
|
||||
} from "./GhidraProviderCapabilities.js";
|
||||
|
||||
/** Public identity committed by every Ghidra-backed observation. */
|
||||
export const GHIDRA_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
|
||||
id: "ghidra",
|
||||
name: "Ghidra",
|
||||
version: null,
|
||||
});
|
||||
|
||||
const providerContractByName = new Map(
|
||||
[...OFFICIAL_TOOL_CONTRACTS, ...ENHANCED_TOOL_CONTRACTS].map((contract) => [
|
||||
contract.name,
|
||||
contract,
|
||||
]),
|
||||
);
|
||||
|
||||
/** Provider-neutral read-only contracts implemented by the Ghidra adapter. */
|
||||
export const GHIDRA_PROVIDER_TOOL_CONTRACTS = Object.freeze(
|
||||
[...GHIDRA_INVENTORY_OPERATIONS, ...GHIDRA_FUNCTION_OPERATIONS].map(
|
||||
(operation) => {
|
||||
const contract = providerContractByName.get(operation);
|
||||
if (contract === undefined)
|
||||
throw new TypeError(
|
||||
`Missing provider-neutral contract for ${operation}`,
|
||||
);
|
||||
return contract;
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const PAGINATED_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"list_names",
|
||||
"list_procedures",
|
||||
"list_strings",
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
"procedure_references",
|
||||
"analyze_function",
|
||||
]);
|
||||
const SEARCH_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
]);
|
||||
const DECOMPILE_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"procedure_pseudo_code",
|
||||
"analyze_function",
|
||||
]);
|
||||
const healthLimitations = Object.freeze([
|
||||
"The session serves operations only after default Ghidra auto-analysis completes; an analysis timeout fails the open instead of exposing partial results.",
|
||||
"The imported Program and temporary project are ephemeral, read-only to REA, and deleted on close.",
|
||||
]);
|
||||
const windowsP0Limitations = Object.freeze([
|
||||
"Windows Ghidra P0 accepts approved native x86-64 PE applications only; DLL, managed, hostile, sensitive, and mutable-path targets are unsupported.",
|
||||
"The Windows bridge uses authenticated IPv4 loopback because Node path-based IPC does not expose Java AF_UNIX sockets; the endpoint file contains no bearer token.",
|
||||
"Windows P0 process-tree cleanup uses bounded taskkill termination and does not claim Job Object ownership, private DACL enforcement, or reparse-point-safe path authority.",
|
||||
]);
|
||||
|
||||
const limitationsFor = (operation: string): readonly string[] => {
|
||||
const common = [
|
||||
...healthLimitations,
|
||||
"Default-space addresses use lowercase 0x-prefixed hexadecimal; other address spaces use <percent-encoded-space>:0x<hex>.",
|
||||
];
|
||||
switch (operation) {
|
||||
case "list_documents":
|
||||
return [
|
||||
...common,
|
||||
"A headless Ghidra session contains exactly one imported Program, unlike Hopper's multi-document GUI session.",
|
||||
];
|
||||
case "list_names":
|
||||
return [
|
||||
...common,
|
||||
"The symbol inventory includes memory and external symbols, including dynamic symbols, but excludes variable and no-address namespace records.",
|
||||
];
|
||||
case "list_procedures":
|
||||
case "procedure_address":
|
||||
return [
|
||||
...common,
|
||||
"External functions and local thunks are distinct; procedure metadata identifies both and preserves a thunk target when Ghidra resolves one.",
|
||||
];
|
||||
case "list_strings":
|
||||
return [
|
||||
...common,
|
||||
"Only Ghidra-defined string Data is observed; charset is reported, while a non-missing terminator cannot distinguish a present terminator from a fixed or Pascal layout.",
|
||||
"Returned values are bounded to 1,024 Unicode code points and mark value_truncated instead of silently crossing the wire budget.",
|
||||
];
|
||||
case "list_segments":
|
||||
return [
|
||||
...common,
|
||||
"Memory-block end addresses are exclusive; permissions come from Ghidra MemoryBlock flags rather than inference from section names.",
|
||||
];
|
||||
case "search_procedures":
|
||||
case "search_strings":
|
||||
return [
|
||||
...common,
|
||||
"Literal search enforces 1,000,000 cumulative work units; regex mode also accepts only a conservative finite Java-regex subset with 10,000 static paths and 4,096 UTF-16 code units per candidate.",
|
||||
];
|
||||
case "procedure_pseudo_code":
|
||||
return [
|
||||
...common,
|
||||
"Pseudocode is Ghidra decompiler output, not original source and not text-equivalent to Hopper output; each decompile has a 30-second native deadline.",
|
||||
"External functions and functions without an analyzable body return null; other decompiler failures remain explicit.",
|
||||
];
|
||||
case "procedure_assembly":
|
||||
return [
|
||||
...common,
|
||||
"Assembly is Ghidra Listing text and fails rather than silently truncating when the 100,000-instruction or 1 MiB wire bound is exceeded.",
|
||||
];
|
||||
case "procedure_callers":
|
||||
case "procedure_callees":
|
||||
return [
|
||||
...common,
|
||||
"Only resolved Ghidra call references are returned; unresolved computed or indirect calls remain unknown, while function classifications distinguish thunks and externals.",
|
||||
];
|
||||
case "xrefs":
|
||||
return [
|
||||
...common,
|
||||
"The direct address list projects exact Ghidra references to one address but does not expose their kinds; procedure_references and analyze_function preserve available kind metadata.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
];
|
||||
case "procedure_references":
|
||||
return [
|
||||
...common,
|
||||
"Reference kinds are direct Ghidra ReferenceManager observations; unresolved computed flows without a target are absent and remain unknown.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
"Instruction scans stop at max_instructions; a truncated scan reports an unknown total and no false continuation.",
|
||||
];
|
||||
case "analyze_function":
|
||||
return [
|
||||
...common,
|
||||
"The dossier combines Ghidra FunctionManager, Listing, ReferenceManager, BasicBlockModel, and decompiler observations; provider-specific pseudocode and assembly are not cross-provider text invariants.",
|
||||
"Resolved reference metadata identifies computed, indirect, external, call, jump, and data edges; unresolved targetless flows remain unknown, and function classifications distinguish thunks and externals.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
"The Java bridge serializes one function request per Program through a bounded 32-request queue and applies a 30-second native decompilation deadline.",
|
||||
];
|
||||
default:
|
||||
return common;
|
||||
}
|
||||
};
|
||||
const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS.map((contract) =>
|
||||
Object.freeze({
|
||||
provider: GHIDRA_PROVIDER_IDENTITY,
|
||||
operation: contract.name,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: PAGINATED_OPERATIONS.has(contract.name)
|
||||
? ("offset" as const)
|
||||
: ("none" as const),
|
||||
exhaustive: !PAGINATED_OPERATIONS.has(contract.name),
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: true,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: true,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limits: Object.freeze({
|
||||
maxResults: PAGINATED_OPERATIONS.has(contract.name)
|
||||
? SEARCH_OPERATIONS.has(contract.name)
|
||||
? 100
|
||||
: 500
|
||||
: null,
|
||||
maxPayloadBytes: GHIDRA_MAX_LINE_BYTES,
|
||||
timeoutMs: DECOMPILE_OPERATIONS.has(contract.name)
|
||||
? GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS
|
||||
: GHIDRA_REQUEST_TIMEOUT_MS,
|
||||
}),
|
||||
limitations: Object.freeze(limitationsFor(contract.name)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const WINDOWS_P0_CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
CAPABILITIES.map((capability) =>
|
||||
Object.freeze({
|
||||
...capability,
|
||||
limitations: Object.freeze([
|
||||
...capability.limitations,
|
||||
...windowsP0Limitations,
|
||||
]),
|
||||
}),
|
||||
),
|
||||
);
|
||||
export { GHIDRA_PROVIDER_IDENTITY, GHIDRA_PROVIDER_TOOL_CONTRACTS };
|
||||
|
||||
const SUPPORTED_ARCHITECTURES = new Set(["x86", "x86_64", "arm", "arm64"]);
|
||||
const SUPPORTED_FORMATS = new Set(["elf", "pe", "mach-o"]);
|
||||
@@ -417,7 +235,8 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
if (!input.ok) return input;
|
||||
const called = await client.callTool(operation, input.value, {
|
||||
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(DECOMPILE_OPERATIONS.has(operation)
|
||||
...(operation === "procedure_pseudo_code" ||
|
||||
operation === "analyze_function"
|
||||
? { timeoutMs: GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS }
|
||||
: {}),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import type {
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import {
|
||||
ENHANCED_TOOL_CONTRACTS,
|
||||
OFFICIAL_TOOL_CONTRACTS,
|
||||
} from "../contracts/toolContracts.js";
|
||||
import {
|
||||
GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS,
|
||||
GHIDRA_MAX_LINE_BYTES,
|
||||
GHIDRA_REQUEST_TIMEOUT_MS,
|
||||
} from "./GhidraDefaults.js";
|
||||
import { GHIDRA_FUNCTION_OPERATIONS } from "./GhidraFunctionValues.js";
|
||||
import { GHIDRA_INVENTORY_OPERATIONS } from "./GhidraInventoryValues.js";
|
||||
|
||||
/** Public identity committed by every Ghidra-backed observation. */
|
||||
export const GHIDRA_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
|
||||
id: "ghidra",
|
||||
name: "Ghidra",
|
||||
version: null,
|
||||
});
|
||||
|
||||
const providerContractByName = new Map(
|
||||
[...OFFICIAL_TOOL_CONTRACTS, ...ENHANCED_TOOL_CONTRACTS].map((contract) => [
|
||||
contract.name,
|
||||
contract,
|
||||
]),
|
||||
);
|
||||
|
||||
/** Provider-neutral read-only contracts implemented by the Ghidra adapter. */
|
||||
export const GHIDRA_PROVIDER_TOOL_CONTRACTS = Object.freeze(
|
||||
[...GHIDRA_INVENTORY_OPERATIONS, ...GHIDRA_FUNCTION_OPERATIONS].map(
|
||||
(operation) => {
|
||||
const contract = providerContractByName.get(operation);
|
||||
if (contract === undefined)
|
||||
throw new TypeError(
|
||||
`Missing provider-neutral contract for ${operation}`,
|
||||
);
|
||||
return contract;
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const PAGINATED_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"list_names",
|
||||
"list_procedures",
|
||||
"list_strings",
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
"procedure_references",
|
||||
"analyze_function",
|
||||
]);
|
||||
const SEARCH_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
]);
|
||||
const DECOMPILE_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"procedure_pseudo_code",
|
||||
"analyze_function",
|
||||
]);
|
||||
|
||||
/** Health limitations shared by every Ghidra-backed capability. */
|
||||
export const healthLimitations = Object.freeze([
|
||||
"The session serves operations only after default Ghidra auto-analysis completes; an analysis timeout fails the open instead of exposing partial results.",
|
||||
"The imported Program and temporary project are ephemeral, read-only to REA, and deleted on close.",
|
||||
]);
|
||||
|
||||
/** Additional limitations applied to the experimental Windows x64 P0 boundary. */
|
||||
export const windowsP0Limitations = Object.freeze([
|
||||
"Windows Ghidra P0 accepts approved native x86-64 PE applications only; DLL, managed, hostile, sensitive, and mutable-path targets are unsupported.",
|
||||
"The Windows bridge uses authenticated IPv4 loopback because Node path-based IPC does not expose Java AF_UNIX sockets; the endpoint file contains no bearer token.",
|
||||
"Windows P0 process-tree cleanup uses bounded taskkill termination and does not claim Job Object ownership, private DACL enforcement, or reparse-point-safe path authority.",
|
||||
]);
|
||||
|
||||
/** Limitation text for one admitted operation, including the common base. */
|
||||
export const limitationsFor = (operation: string): readonly string[] => {
|
||||
const common = [
|
||||
...healthLimitations,
|
||||
"Default-space addresses use lowercase 0x-prefixed hexadecimal; other address spaces use <percent-encoded-space>:0x<hex>.",
|
||||
];
|
||||
switch (operation) {
|
||||
case "list_documents":
|
||||
return [
|
||||
...common,
|
||||
"A headless Ghidra session contains exactly one imported Program, unlike Hopper's multi-document GUI session.",
|
||||
];
|
||||
case "list_names":
|
||||
return [
|
||||
...common,
|
||||
"The symbol inventory includes memory and external symbols, including dynamic symbols, but excludes variable and no-address namespace records.",
|
||||
];
|
||||
case "list_procedures":
|
||||
case "procedure_address":
|
||||
return [
|
||||
...common,
|
||||
"External functions and local thunks are distinct; procedure metadata identifies both and preserves a thunk target when Ghidra resolves one.",
|
||||
];
|
||||
case "list_strings":
|
||||
return [
|
||||
...common,
|
||||
"Only Ghidra-defined string Data is observed; charset is reported, while a non-missing terminator cannot distinguish a present terminator from a fixed or Pascal layout.",
|
||||
"Returned values are bounded to 1,024 Unicode code points and mark value_truncated instead of silently crossing the wire budget.",
|
||||
];
|
||||
case "list_segments":
|
||||
return [
|
||||
...common,
|
||||
"Memory-block end addresses are exclusive; permissions come from Ghidra MemoryBlock flags rather than inference from section names.",
|
||||
];
|
||||
case "search_procedures":
|
||||
case "search_strings":
|
||||
return [
|
||||
...common,
|
||||
"Literal search enforces 1,000,000 cumulative work units; regex mode also accepts only a conservative finite Java-regex subset with 10,000 static paths and 4,096 UTF-16 code units per candidate.",
|
||||
];
|
||||
case "procedure_pseudo_code":
|
||||
return [
|
||||
...common,
|
||||
"Pseudocode is Ghidra decompiler output, not original source and not text-equivalent to Hopper output; each decompile has a 30-second native deadline.",
|
||||
"External functions and functions without an analyzable body return null; other decompiler failures remain explicit.",
|
||||
];
|
||||
case "procedure_assembly":
|
||||
return [
|
||||
...common,
|
||||
"Assembly is Ghidra Listing text and fails rather than silently truncating when the 100,000-instruction or 1 MiB wire bound is exceeded.",
|
||||
];
|
||||
case "procedure_callers":
|
||||
case "procedure_callees":
|
||||
return [
|
||||
...common,
|
||||
"Only resolved Ghidra call references are returned; unresolved computed or indirect calls remain unknown, while function classifications distinguish thunks and externals.",
|
||||
];
|
||||
case "xrefs":
|
||||
return [
|
||||
...common,
|
||||
"The direct address list projects exact Ghidra references to one address but does not expose their kinds; procedure_references and analyze_function preserve available kind metadata.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
];
|
||||
case "procedure_references":
|
||||
return [
|
||||
...common,
|
||||
"Reference kinds are direct Ghidra ReferenceManager observations; unresolved computed flows without a target are absent and remain unknown.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
"Instruction scans stop at max_instructions; a truncated scan reports an unknown total and no false continuation.",
|
||||
];
|
||||
case "analyze_function":
|
||||
return [
|
||||
...common,
|
||||
"The dossier combines Ghidra FunctionManager, Listing, ReferenceManager, BasicBlockModel, and decompiler observations; provider-specific pseudocode and assembly are not cross-provider text invariants.",
|
||||
"Resolved reference metadata identifies computed, indirect, external, call, jump, and data edges; unresolved targetless flows remain unknown, and function classifications distinguish thunks and externals.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
"The Java bridge serializes one function request per Program through a bounded 32-request queue and applies a 30-second native decompilation deadline.",
|
||||
];
|
||||
default:
|
||||
return common;
|
||||
}
|
||||
};
|
||||
|
||||
/** Provider-neutral capabilities advertised by every non-Windows Ghidra session. */
|
||||
export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS.map((contract) =>
|
||||
Object.freeze({
|
||||
provider: GHIDRA_PROVIDER_IDENTITY,
|
||||
operation: contract.name,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: PAGINATED_OPERATIONS.has(contract.name)
|
||||
? ("offset" as const)
|
||||
: ("none" as const),
|
||||
exhaustive: !PAGINATED_OPERATIONS.has(contract.name),
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: true,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: true,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limits: Object.freeze({
|
||||
maxResults: PAGINATED_OPERATIONS.has(contract.name)
|
||||
? SEARCH_OPERATIONS.has(contract.name)
|
||||
? 100
|
||||
: 500
|
||||
: null,
|
||||
maxPayloadBytes: GHIDRA_MAX_LINE_BYTES,
|
||||
timeoutMs: DECOMPILE_OPERATIONS.has(contract.name)
|
||||
? GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS
|
||||
: GHIDRA_REQUEST_TIMEOUT_MS,
|
||||
}),
|
||||
limitations: Object.freeze(limitationsFor(contract.name)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
/** Capabilities advertised for the experimental Windows x64 P0 boundary. */
|
||||
export const WINDOWS_P0_CAPABILITIES: readonly CapabilityDescriptor[] =
|
||||
Object.freeze(
|
||||
CAPABILITIES.map((capability) =>
|
||||
Object.freeze({
|
||||
...capability,
|
||||
limitations: Object.freeze([
|
||||
...capability.limitations,
|
||||
...windowsP0Limitations,
|
||||
]),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,8 +1,17 @@
|
||||
import { createConnection, type Socket } from "node:net";
|
||||
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { GhidraSessionError } from "./GhidraSessionError.js";
|
||||
import type { GhidraConnectTarget } from "./GhidraTransport.js";
|
||||
import type { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
|
||||
import {
|
||||
GhidraSessionError,
|
||||
type GhidraSessionErrorOptions,
|
||||
type GhidraSessionFailureKind,
|
||||
} from "./GhidraSessionError.js";
|
||||
import {
|
||||
type GhidraConnectTarget,
|
||||
type GhidraEndpoint,
|
||||
observeGhidraEndpoint,
|
||||
} from "./GhidraTransport.js";
|
||||
|
||||
/** Stable listeners attached for the lifetime of one bridge socket. */
|
||||
export interface GhidraSocketHandlers {
|
||||
@@ -11,6 +20,22 @@ export interface GhidraSocketHandlers {
|
||||
readonly close: () => void;
|
||||
}
|
||||
|
||||
/** Inputs needed to poll and attach one authenticated bridge socket. */
|
||||
export interface GhidraSocketConnectOptions {
|
||||
readonly endpoint: GhidraEndpoint;
|
||||
readonly deadline: ProviderStartupDeadline;
|
||||
readonly failure: (
|
||||
kind: GhidraSessionFailureKind,
|
||||
message: string,
|
||||
cause?: unknown,
|
||||
options?: Pick<GhidraSessionErrorOptions, "timeoutMs" | "remoteCode">,
|
||||
) => GhidraSessionError;
|
||||
readonly isClosed: () => boolean;
|
||||
readonly processExited: () => boolean;
|
||||
readonly startupTimeoutMs: number;
|
||||
readonly handlers: GhidraSocketHandlers;
|
||||
}
|
||||
|
||||
/** Attach decoded bridge listeners and return an idempotent detach callback. */
|
||||
export const attachGhidraSocket = (
|
||||
socket: Socket,
|
||||
@@ -27,6 +52,49 @@ export const attachGhidraSocket = (
|
||||
};
|
||||
};
|
||||
|
||||
/** Poll the endpoint and attach the first ready bridge socket. */
|
||||
export const connectGhidraSocket = async (
|
||||
options: GhidraSocketConnectOptions,
|
||||
): Promise<
|
||||
Result<
|
||||
{ readonly socket: Socket; readonly detach: () => void },
|
||||
GhidraSessionError
|
||||
>
|
||||
> => {
|
||||
while (options.deadline.remainingMs() > 0) {
|
||||
if (options.deadline.signal.aborted)
|
||||
return err(interruptionFailure(options));
|
||||
if (options.isClosed())
|
||||
return err(options.failure("cancelled", "Ghidra startup was closed"));
|
||||
if (options.processExited())
|
||||
return err(
|
||||
options.failure("process", "Ghidra exited before bridge startup"),
|
||||
);
|
||||
const observed = await observeGhidraEndpoint(options.endpoint);
|
||||
if (!observed.ok) return observed;
|
||||
if (observed.value === null) {
|
||||
if ((await options.deadline.wait(50)) === "aborted")
|
||||
return err(interruptionFailure(options));
|
||||
continue;
|
||||
}
|
||||
const connected = await connectGhidraSocketOnce(
|
||||
observed.value,
|
||||
options.deadline.signal,
|
||||
);
|
||||
if (connected.ok) {
|
||||
const detach = attachGhidraSocket(connected.value, options.handlers);
|
||||
return ok({ socket: connected.value, detach });
|
||||
}
|
||||
if ((await options.deadline.wait(50)) === "aborted")
|
||||
return err(interruptionFailure(options));
|
||||
}
|
||||
return err(
|
||||
options.failure("timeout", "Ghidra startup deadline elapsed", undefined, {
|
||||
timeoutMs: options.startupTimeoutMs,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
/** Open one abort-aware connection to an observed local Ghidra endpoint. */
|
||||
export const connectGhidraSocketOnce = (
|
||||
target: GhidraConnectTarget,
|
||||
@@ -76,3 +144,12 @@ export const connectGhidraSocketOnce = (
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal.aborted) onAbort();
|
||||
});
|
||||
|
||||
const interruptionFailure = (
|
||||
options: GhidraSocketConnectOptions,
|
||||
): GhidraSessionError =>
|
||||
options.deadline.cancelled
|
||||
? options.failure("cancelled", "Ghidra startup was cancelled")
|
||||
: options.failure("timeout", "Ghidra startup deadline elapsed", undefined, {
|
||||
timeoutMs: options.startupTimeoutMs,
|
||||
});
|
||||
|
||||
@@ -289,69 +289,103 @@ const normalizeFactorySource = (source: string): string =>
|
||||
? source.replace(/^\s*\d+\s*\(/u, "function(")
|
||||
: source;
|
||||
|
||||
interface ProjectionContext {
|
||||
readonly maximumDepth: number;
|
||||
readonly maximumNodes: number;
|
||||
nodes: number;
|
||||
}
|
||||
|
||||
const projectValue = (
|
||||
value: unknown,
|
||||
maximumDepth: number,
|
||||
maximumNodes: number,
|
||||
): unknown =>
|
||||
projectValueRecursive(value, 0, new Set(), {
|
||||
maximumDepth,
|
||||
maximumNodes,
|
||||
nodes: 0,
|
||||
});
|
||||
|
||||
const projectValueRecursive = (
|
||||
candidate: unknown,
|
||||
depth: number,
|
||||
ancestors: Set<object>,
|
||||
context: ProjectionContext,
|
||||
): unknown => {
|
||||
let nodes = 0;
|
||||
const visit = (
|
||||
candidate: unknown,
|
||||
depth: number,
|
||||
ancestors: Set<object>,
|
||||
): unknown => {
|
||||
nodes += 1;
|
||||
if (nodes > maximumNodes || depth > maximumDepth)
|
||||
throw new RangeError("Replay result projection limit exceeded");
|
||||
if (
|
||||
candidate === null ||
|
||||
typeof candidate === "string" ||
|
||||
typeof candidate === "boolean"
|
||||
)
|
||||
return candidate;
|
||||
if (typeof candidate === "number") {
|
||||
if (!Number.isFinite(candidate))
|
||||
throw new TypeError("Non-finite replay result number");
|
||||
return candidate;
|
||||
}
|
||||
if (typeof candidate !== "object")
|
||||
throw new TypeError(
|
||||
`Unsupported replay result type: ${typeof candidate}`,
|
||||
context.nodes += 1;
|
||||
if (context.nodes > context.maximumNodes || depth > context.maximumDepth)
|
||||
throw new RangeError("Replay result projection limit exceeded");
|
||||
const leaf = projectLeaf(candidate);
|
||||
if (leaf !== undefined) return leaf;
|
||||
if (typeof candidate !== "object" || candidate === null)
|
||||
throw new TypeError(`Unsupported replay result type: ${typeof candidate}`);
|
||||
if (types.isProxy(candidate))
|
||||
throw new TypeError("Proxy replay results are unavailable");
|
||||
if (ancestors.has(candidate)) throw new TypeError("Cyclic replay result");
|
||||
ancestors.add(candidate);
|
||||
try {
|
||||
assertSupportedPrototype(candidate);
|
||||
return projectComplexValue(candidate, depth, ancestors, context);
|
||||
} finally {
|
||||
ancestors.delete(candidate);
|
||||
}
|
||||
};
|
||||
|
||||
const projectLeaf = (candidate: unknown): unknown => {
|
||||
if (
|
||||
candidate === null ||
|
||||
typeof candidate === "string" ||
|
||||
typeof candidate === "boolean"
|
||||
)
|
||||
return candidate;
|
||||
if (typeof candidate === "number") {
|
||||
if (!Number.isFinite(candidate))
|
||||
throw new TypeError("Non-finite replay result number");
|
||||
return candidate;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const assertSupportedPrototype = (candidate: object): void => {
|
||||
if (Array.isArray(candidate)) return;
|
||||
const prototype = Object.getPrototypeOf(candidate) as object | null;
|
||||
if (prototype !== null && Object.getPrototypeOf(prototype) !== null)
|
||||
throw new TypeError("Unsupported replay result prototype");
|
||||
};
|
||||
|
||||
const projectComplexValue = (
|
||||
candidate: object,
|
||||
depth: number,
|
||||
ancestors: Set<object>,
|
||||
context: ProjectionContext,
|
||||
): unknown[] | Record<string, unknown> => {
|
||||
const descriptors = Object.getOwnPropertyDescriptors(candidate);
|
||||
const output: unknown[] | Record<string, unknown> = Array.isArray(candidate)
|
||||
? []
|
||||
: {};
|
||||
for (const [key, descriptor] of Object.entries(descriptors)) {
|
||||
if (key === "length" && Array.isArray(candidate)) continue;
|
||||
if (!("value" in descriptor))
|
||||
throw new TypeError("Replay result accessors are unavailable");
|
||||
if (Array.isArray(output)) {
|
||||
if (!/^\d+$/u.test(key))
|
||||
throw new TypeError("Replay arrays may only contain indexed values");
|
||||
output[Number(key)] = projectValueRecursive(
|
||||
descriptor.value,
|
||||
depth + 1,
|
||||
ancestors,
|
||||
context,
|
||||
);
|
||||
} else {
|
||||
output[key] = projectValueRecursive(
|
||||
descriptor.value,
|
||||
depth + 1,
|
||||
ancestors,
|
||||
context,
|
||||
);
|
||||
if (types.isProxy(candidate))
|
||||
throw new TypeError("Proxy replay results are unavailable");
|
||||
if (ancestors.has(candidate)) throw new TypeError("Cyclic replay result");
|
||||
ancestors.add(candidate);
|
||||
try {
|
||||
const descriptors = Object.getOwnPropertyDescriptors(candidate);
|
||||
const output: unknown[] | Record<string, unknown> = Array.isArray(
|
||||
candidate,
|
||||
)
|
||||
? []
|
||||
: {};
|
||||
if (!Array.isArray(candidate)) {
|
||||
const prototype = Object.getPrototypeOf(candidate) as object | null;
|
||||
if (prototype !== null && Object.getPrototypeOf(prototype) !== null)
|
||||
throw new TypeError("Unsupported replay result prototype");
|
||||
}
|
||||
for (const [key, descriptor] of Object.entries(descriptors)) {
|
||||
if (key === "length" && Array.isArray(candidate)) continue;
|
||||
if (!("value" in descriptor))
|
||||
throw new TypeError("Replay result accessors are unavailable");
|
||||
if (Array.isArray(output)) {
|
||||
if (!/^\d+$/u.test(key))
|
||||
throw new TypeError(
|
||||
"Replay arrays may only contain indexed values",
|
||||
);
|
||||
output[Number(key)] = visit(descriptor.value, depth + 1, ancestors);
|
||||
} else output[key] = visit(descriptor.value, depth + 1, ancestors);
|
||||
}
|
||||
return output;
|
||||
} finally {
|
||||
ancestors.delete(candidate);
|
||||
}
|
||||
};
|
||||
return visit(value, 0, new Set());
|
||||
}
|
||||
return output;
|
||||
};
|
||||
|
||||
const exceptionOutcome = (
|
||||
|
||||
@@ -1,27 +1,37 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { open, readFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import type {
|
||||
JavaScriptReplayPolicy,
|
||||
JavaScriptReplayRunner,
|
||||
PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import {
|
||||
digestBytes,
|
||||
digestJson,
|
||||
type JavaScriptReplayPolicy,
|
||||
type JavaScriptReplayRunner,
|
||||
type PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import type { ReplayExecutionResult } from "../domain/javascriptReplay.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import {
|
||||
buildLinuxX64ReplaySeccomp,
|
||||
linuxX64ReplaySeccompDigest,
|
||||
} from "./LinuxSeccompPolicy.js";
|
||||
import { linuxX64ReplaySeccompDigest } from "./LinuxSeccompPolicy.js";
|
||||
import { resolveLinuxRuntimeClosure } from "./LinuxRuntimeClosure.js";
|
||||
import {
|
||||
assertRuntimeCommitment,
|
||||
systemdArguments,
|
||||
temporaryFilterHandle,
|
||||
type RuntimeFile,
|
||||
} from "./LinuxJavaScriptReplaySandbox.js";
|
||||
import {
|
||||
boundedCollector,
|
||||
killUnit,
|
||||
observeCleanup,
|
||||
observeUnitResult,
|
||||
type CollectedProcess,
|
||||
} from "./ReplayProcessLifecycle.js";
|
||||
import {
|
||||
commitOutcomes,
|
||||
compareOutcomes,
|
||||
terminationResult,
|
||||
workerRequest,
|
||||
} from "./ReplayOutcome.js";
|
||||
import {
|
||||
parseReplayWorkerResponse,
|
||||
type WorkerProtocolOutcome,
|
||||
type WorkerProtocolResponse,
|
||||
} from "./ReplayWorkerProtocol.js";
|
||||
|
||||
@@ -36,544 +46,263 @@ export class LinuxJavaScriptReplayRunner implements JavaScriptReplayRunner {
|
||||
signal?: AbortSignal,
|
||||
): Promise<ReplayExecutionResult> {
|
||||
if (isAborted(signal))
|
||||
return terminationResult(prepared, "", "cancelled", {
|
||||
state: "complete",
|
||||
residual_resources: [],
|
||||
return terminationResult({
|
||||
prepared,
|
||||
stderr: "",
|
||||
termination: "cancelled",
|
||||
cleanup: { state: "complete", residual_resources: [] },
|
||||
});
|
||||
const unit = `rea-replay-${randomBytes(8).toString("hex")}.service`;
|
||||
const workerPath = prepared.publicPlan.runtime.worker.path;
|
||||
const closure = await resolveLinuxRuntimeClosure(policy.nodePath);
|
||||
assertRuntimeCommitment(prepared, closure);
|
||||
if (
|
||||
digestBytes(await readFile(workerPath)) !==
|
||||
prepared.publicPlan.runtime.worker.sha256
|
||||
)
|
||||
throw new TypeError("Replay worker changed after approval");
|
||||
if (
|
||||
linuxX64ReplaySeccompDigest() !==
|
||||
prepared.publicPlan.sandbox.seccomp_sha256
|
||||
)
|
||||
throw new TypeError("Replay seccomp policy changed after approval");
|
||||
const request = workerRequest(prepared);
|
||||
const encoded = Buffer.from(JSON.stringify(request));
|
||||
if (encoded.byteLength > prepared.publicPlan.limits.protocol_bytes)
|
||||
throw new RangeError(
|
||||
"Replay worker protocol input exceeds the committed limit",
|
||||
);
|
||||
const closure = await validateReplayCommitments(prepared, policy);
|
||||
const encoded = buildWorkerPayload(prepared);
|
||||
const filter = await temporaryFilterHandle();
|
||||
const arguments_ = systemdArguments(
|
||||
unit,
|
||||
policy,
|
||||
const replayProcess = launchReplayProcess({
|
||||
prepared,
|
||||
workerPath,
|
||||
policy,
|
||||
encoded,
|
||||
closure,
|
||||
filter.path,
|
||||
);
|
||||
let child: ReturnType<typeof spawn> | undefined;
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
let cancelled = false;
|
||||
let timedOut = false;
|
||||
let terminationRequest: Promise<void> | undefined;
|
||||
const requestTermination = (): void => {
|
||||
terminationRequest ??= killUnit(policy.systemctlPath, unit);
|
||||
child?.kill("SIGKILL");
|
||||
};
|
||||
const terminate = (): void => {
|
||||
cancelled = true;
|
||||
requestTermination();
|
||||
};
|
||||
filterPath: filter.path,
|
||||
unit,
|
||||
signal,
|
||||
});
|
||||
try {
|
||||
const completion = new Promise<CollectedProcess>((resolve, reject) => {
|
||||
child = spawn(policy.systemdRunPath, arguments_, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: {
|
||||
PATH: "/usr/bin:/bin",
|
||||
LANG: "C",
|
||||
LC_ALL: "C",
|
||||
TZ: "UTC",
|
||||
...(process.env.XDG_RUNTIME_DIR === undefined
|
||||
? {}
|
||||
: { XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR }),
|
||||
...(process.env.DBUS_SESSION_BUS_ADDRESS === undefined
|
||||
? {}
|
||||
: {
|
||||
DBUS_SESSION_BUS_ADDRESS:
|
||||
process.env.DBUS_SESSION_BUS_ADDRESS,
|
||||
}),
|
||||
},
|
||||
});
|
||||
const output = boundedCollector(
|
||||
prepared.publicPlan.limits.output_bytes,
|
||||
);
|
||||
const diagnostics = boundedCollector(
|
||||
prepared.publicPlan.limits.stderr_bytes,
|
||||
);
|
||||
child.stdout?.on("data", output.append);
|
||||
child.stderr?.on("data", diagnostics.append);
|
||||
child.once("error", reject);
|
||||
child.once("close", (code, signalName) =>
|
||||
resolve({
|
||||
code,
|
||||
signal: signalName,
|
||||
stdout: output.value(),
|
||||
stderr: diagnostics.value(),
|
||||
outputExceeded: output.exceeded(),
|
||||
}),
|
||||
);
|
||||
child.stdin?.end(encoded);
|
||||
});
|
||||
signal?.addEventListener("abort", terminate, { once: true });
|
||||
if (isAborted(signal)) terminate();
|
||||
timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
requestTermination();
|
||||
}, prepared.publicPlan.limits.wall_time_ms);
|
||||
timeout.unref();
|
||||
const collected = await completion;
|
||||
if (terminationRequest !== undefined) await terminationRequest;
|
||||
const collected = await replayProcess.completion;
|
||||
if (replayProcess.terminationRequest !== undefined)
|
||||
await replayProcess.terminationRequest;
|
||||
const unitResult = await observeUnitResult(policy.systemctlPath, unit);
|
||||
const cleanup = await observeCleanup(policy.systemctlPath, unit);
|
||||
if (cancelled || timedOut)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
cancelled ? "cancelled" : "timeout",
|
||||
cleanup,
|
||||
);
|
||||
if (collected.outputExceeded)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
"protocol_error",
|
||||
cleanup,
|
||||
"Worker stdout exceeded the committed bound",
|
||||
);
|
||||
if (collected.code !== 0)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
collected.code === 137 || unitResult === "oom-kill" ? "oom" : "crash",
|
||||
cleanup,
|
||||
);
|
||||
let response: WorkerProtocolResponse;
|
||||
try {
|
||||
response = parseReplayWorkerResponse(
|
||||
JSON.parse(collected.stdout),
|
||||
prepared.publicPlan.cases,
|
||||
prepared.publicPlan.right !== undefined,
|
||||
);
|
||||
} catch {
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
"protocol_error",
|
||||
cleanup,
|
||||
);
|
||||
}
|
||||
const outcomes = commitOutcomes(response.left);
|
||||
const right =
|
||||
response.right === undefined
|
||||
? undefined
|
||||
: commitOutcomes(response.right);
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [...outcomes, ...(right ?? [])],
|
||||
...(right === undefined
|
||||
? {}
|
||||
: { comparison: compareOutcomes(outcomes, right) }),
|
||||
stderr: collected.stderr,
|
||||
termination: "completed",
|
||||
return resolveReplayResult({
|
||||
prepared,
|
||||
collected,
|
||||
unitResult,
|
||||
cleanup,
|
||||
limitations: [
|
||||
"Controlled replay observes the isolated extracted modules, not the original application runtime.",
|
||||
"Network and host filesystem access were unavailable; unsupported dependencies may change behavior.",
|
||||
],
|
||||
reproducer: null,
|
||||
};
|
||||
cancelled: replayProcess.cancelled,
|
||||
timedOut: replayProcess.timedOut,
|
||||
});
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", terminate);
|
||||
if (timeout !== undefined) clearTimeout(timeout);
|
||||
if (child !== undefined && child.exitCode === null) {
|
||||
requestTermination();
|
||||
await terminationRequest;
|
||||
signal?.removeEventListener("abort", replayProcess.terminate);
|
||||
if (replayProcess.timeout !== undefined)
|
||||
clearTimeout(replayProcess.timeout);
|
||||
if (
|
||||
replayProcess.child !== undefined &&
|
||||
replayProcess.child.exitCode === null
|
||||
) {
|
||||
replayProcess.requestTermination();
|
||||
await replayProcess.terminationRequest;
|
||||
}
|
||||
await filter.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const workerRequest = (prepared: PreparedReplayPlan) => ({
|
||||
schemaVersion: 1,
|
||||
left: workerSide(prepared.publicPlan.left, prepared.leftSources),
|
||||
...(prepared.publicPlan.right === undefined ||
|
||||
prepared.rightSources === undefined
|
||||
? {}
|
||||
: { right: workerSide(prepared.publicPlan.right, prepared.rightSources) }),
|
||||
cases: prepared.publicPlan.cases.map((item) => ({
|
||||
caseId: item.case_id,
|
||||
arguments: item.arguments,
|
||||
inputSha256: item.sha256,
|
||||
})),
|
||||
determinism: {
|
||||
clockIso: prepared.publicPlan.determinism.clock_iso,
|
||||
randomSeed: prepared.publicPlan.determinism.random_seed,
|
||||
},
|
||||
limits: {
|
||||
resultDepth: prepared.publicPlan.limits.result_depth,
|
||||
resultNodes: prepared.publicPlan.limits.result_nodes,
|
||||
exceptionBytes: Math.min(
|
||||
64 * 1024,
|
||||
prepared.publicPlan.limits.output_bytes,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
const workerSide = (
|
||||
side: PreparedReplayPlan["publicPlan"]["left"],
|
||||
sources: Readonly<Record<string, string>>,
|
||||
) => ({
|
||||
modules: side.modules.map((module) => ({
|
||||
alias: module.alias,
|
||||
format: module.format,
|
||||
dependencies: module.dependencies,
|
||||
source: sources[module.alias] ?? "",
|
||||
})),
|
||||
entryAlias: side.entry_alias,
|
||||
entryExport: side.entry_export,
|
||||
});
|
||||
|
||||
const systemdArguments = (
|
||||
unit: string,
|
||||
const validateReplayCommitments = async (
|
||||
prepared: PreparedReplayPlan,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
prepared: PreparedReplayPlan,
|
||||
workerPath: string,
|
||||
closure: readonly RuntimeFile[],
|
||||
filterPath: string,
|
||||
): string[] => {
|
||||
const limits = prepared.publicPlan.limits;
|
||||
const descriptorPaths = [
|
||||
filterPath,
|
||||
...closure.map(({ sourcePath }) => sourcePath),
|
||||
workerPath,
|
||||
];
|
||||
const workerFd = descriptorPaths.length + 2;
|
||||
const wrapper = descriptorPaths
|
||||
.map((_, index) => `exec ${String(index + 3)}<"$1"; shift`)
|
||||
.concat('exec "$@"')
|
||||
.join("\n");
|
||||
return [
|
||||
"--user",
|
||||
"--pipe",
|
||||
"--wait",
|
||||
"--service-type=exec",
|
||||
"--quiet",
|
||||
`--unit=${unit}`,
|
||||
`--property=MemoryMax=${String(limits.memory_bytes)}`,
|
||||
"--property=MemorySwapMax=0",
|
||||
`--property=TasksMax=${String(limits.tasks)}`,
|
||||
`--property=CPUQuota=${String(limits.cpu_quota_percent)}%`,
|
||||
"--property=KillMode=control-group",
|
||||
"--property=SendSIGKILL=yes",
|
||||
"--",
|
||||
policy.shellPath,
|
||||
"-c",
|
||||
wrapper,
|
||||
"rea-replay-wrapper",
|
||||
...descriptorPaths,
|
||||
policy.bubblewrapPath,
|
||||
"--unshare-all",
|
||||
"--unshare-user",
|
||||
"--disable-userns",
|
||||
"--new-session",
|
||||
"--die-with-parent",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/work",
|
||||
"--setenv",
|
||||
"TMPDIR",
|
||||
"/tmp",
|
||||
"--setenv",
|
||||
"TZ",
|
||||
"UTC",
|
||||
"--setenv",
|
||||
"LANG",
|
||||
"C",
|
||||
"--setenv",
|
||||
"LC_ALL",
|
||||
"C",
|
||||
"--tmpfs",
|
||||
"/",
|
||||
"--dir",
|
||||
"/runtime",
|
||||
"--dir",
|
||||
"/work",
|
||||
"--size",
|
||||
String(limits.tmpfs_bytes),
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
...bindArguments(closure),
|
||||
"--ro-bind-fd",
|
||||
String(workerFd),
|
||||
"/runtime/worker.js",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--remount-ro",
|
||||
"/",
|
||||
"--chdir",
|
||||
"/work",
|
||||
"--seccomp",
|
||||
"3",
|
||||
"--",
|
||||
"/runtime/node",
|
||||
`--max-old-space-size=${String(Math.max(8, Math.floor(limits.memory_bytes / 1024 / 1024 / 2)))}`,
|
||||
"--experimental-vm-modules",
|
||||
"--permission",
|
||||
"--allow-fs-read=/runtime/worker.js",
|
||||
"/runtime/worker.js",
|
||||
];
|
||||
};
|
||||
|
||||
const bindArguments = (closure: readonly RuntimeFile[]): string[] => {
|
||||
const arguments_: string[] = [];
|
||||
const directories = new Set<string>();
|
||||
for (const [index, item] of closure.entries()) {
|
||||
const destination = item.destinationPath;
|
||||
let parent = dirname(destination);
|
||||
const chain: string[] = [];
|
||||
while (parent !== "/" && !directories.has(parent)) {
|
||||
chain.push(parent);
|
||||
parent = dirname(parent);
|
||||
}
|
||||
for (const directory of chain.reverse()) {
|
||||
directories.add(directory);
|
||||
arguments_.push("--dir", directory);
|
||||
}
|
||||
arguments_.push("--ro-bind-fd", String(index + 4), destination);
|
||||
}
|
||||
return arguments_;
|
||||
};
|
||||
|
||||
type RuntimeFile = Awaited<
|
||||
ReturnType<typeof resolveLinuxRuntimeClosure>
|
||||
>[number];
|
||||
|
||||
const assertRuntimeCommitment = (
|
||||
prepared: PreparedReplayPlan,
|
||||
closure: readonly RuntimeFile[],
|
||||
): void => {
|
||||
const observed = closure.map((item) => ({
|
||||
source_path: item.sourcePath,
|
||||
destination_path: item.destinationPath,
|
||||
sha256: item.sha256,
|
||||
}));
|
||||
): Promise<readonly RuntimeFile[]> => {
|
||||
const closure = await resolveLinuxRuntimeClosure(policy.nodePath);
|
||||
assertRuntimeCommitment(prepared, closure);
|
||||
const workerPath = prepared.publicPlan.runtime.worker.path;
|
||||
if (
|
||||
digestJson(observed) !==
|
||||
digestJson(prepared.publicPlan.runtime.read_only_files)
|
||||
digestBytes(await readFile(workerPath)) !==
|
||||
prepared.publicPlan.runtime.worker.sha256
|
||||
)
|
||||
throw new TypeError("Replay runtime closure changed after approval");
|
||||
throw new TypeError("Replay worker changed after approval");
|
||||
if (
|
||||
linuxX64ReplaySeccompDigest() !== prepared.publicPlan.sandbox.seccomp_sha256
|
||||
)
|
||||
throw new TypeError("Replay seccomp policy changed after approval");
|
||||
return closure;
|
||||
};
|
||||
|
||||
const temporaryFilterHandle = async () => {
|
||||
const { mkdtemp, writeFile, rm } = await import("node:fs/promises");
|
||||
const { tmpdir } = await import("node:os");
|
||||
const { join } = await import("node:path");
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-replay-filter-"));
|
||||
const path = join(directory, "seccomp.bpf");
|
||||
await writeFile(path, buildLinuxX64ReplaySeccomp(), { mode: 0o600 });
|
||||
const handle = await open(path, "r");
|
||||
return {
|
||||
path,
|
||||
handle,
|
||||
close: async () => {
|
||||
await handle.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
const buildWorkerPayload = (prepared: PreparedReplayPlan): Buffer => {
|
||||
const request = workerRequest(prepared);
|
||||
const encoded = Buffer.from(JSON.stringify(request));
|
||||
if (encoded.byteLength > prepared.publicPlan.limits.protocol_bytes)
|
||||
throw new RangeError(
|
||||
"Replay worker protocol input exceeds the committed limit",
|
||||
);
|
||||
return encoded;
|
||||
};
|
||||
|
||||
interface CollectedProcess {
|
||||
readonly code: number | null;
|
||||
readonly signal: NodeJS.Signals | null;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly outputExceeded: boolean;
|
||||
interface LaunchReplayProcessOptions {
|
||||
readonly prepared: PreparedReplayPlan;
|
||||
readonly policy: JavaScriptReplayPolicy;
|
||||
readonly encoded: Buffer;
|
||||
readonly closure: readonly RuntimeFile[];
|
||||
readonly filterPath: string;
|
||||
readonly unit: string;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
}
|
||||
|
||||
const boundedCollector = (maximum: number) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
let overflow = false;
|
||||
interface ReplayProcess {
|
||||
readonly child: ReturnType<typeof spawn>;
|
||||
readonly completion: Promise<CollectedProcess>;
|
||||
readonly timeout: NodeJS.Timeout;
|
||||
readonly terminate: () => void;
|
||||
readonly requestTermination: () => void;
|
||||
readonly terminationRequest: Promise<void> | undefined;
|
||||
readonly cancelled: boolean;
|
||||
readonly timedOut: boolean;
|
||||
}
|
||||
|
||||
const launchReplayProcess = (
|
||||
options: LaunchReplayProcessOptions,
|
||||
): ReplayProcess => {
|
||||
const { prepared, policy, encoded, closure, filterPath, unit, signal } =
|
||||
options;
|
||||
const arguments_ = systemdArguments({
|
||||
unit,
|
||||
policy,
|
||||
prepared,
|
||||
workerPath: prepared.publicPlan.runtime.worker.path,
|
||||
closure,
|
||||
filterPath,
|
||||
});
|
||||
let child: ReturnType<typeof spawn> | undefined;
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
let cancelled = false;
|
||||
let timedOut = false;
|
||||
let terminationRequest: Promise<void> | undefined;
|
||||
const requestTermination = (): void => {
|
||||
terminationRequest ??= killUnit(policy.systemctlPath, unit);
|
||||
child?.kill("SIGKILL");
|
||||
};
|
||||
const terminate = (): void => {
|
||||
cancelled = true;
|
||||
requestTermination();
|
||||
};
|
||||
const completion = new Promise<CollectedProcess>((resolve, reject) => {
|
||||
child = spawn(policy.systemdRunPath, arguments_, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: replayProcessEnvironment(),
|
||||
});
|
||||
const output = boundedCollector(prepared.publicPlan.limits.output_bytes);
|
||||
const diagnostics = boundedCollector(
|
||||
prepared.publicPlan.limits.stderr_bytes,
|
||||
);
|
||||
child.stdout?.on("data", output.append);
|
||||
child.stderr?.on("data", diagnostics.append);
|
||||
child.once("error", reject);
|
||||
child.once("close", (code, signalName) =>
|
||||
resolve({
|
||||
code,
|
||||
signal: signalName,
|
||||
stdout: output.value(),
|
||||
stderr: diagnostics.value(),
|
||||
outputExceeded: output.exceeded(),
|
||||
}),
|
||||
);
|
||||
child.stdin?.end(encoded);
|
||||
});
|
||||
signal?.addEventListener("abort", terminate, { once: true });
|
||||
if (isAborted(signal)) terminate();
|
||||
timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
requestTermination();
|
||||
}, prepared.publicPlan.limits.wall_time_ms);
|
||||
timeout.unref();
|
||||
if (child === undefined || timeout === undefined)
|
||||
throw new TypeError("Replay process was not launched");
|
||||
return {
|
||||
append: (chunk: Buffer) => {
|
||||
const retained = chunk.subarray(0, Math.max(0, maximum - bytes));
|
||||
if (retained.byteLength > 0) chunks.push(retained);
|
||||
bytes += retained.byteLength;
|
||||
if (retained.byteLength < chunk.byteLength) overflow = true;
|
||||
child,
|
||||
completion,
|
||||
timeout,
|
||||
terminate,
|
||||
requestTermination,
|
||||
get terminationRequest() {
|
||||
return terminationRequest;
|
||||
},
|
||||
get cancelled() {
|
||||
return cancelled;
|
||||
},
|
||||
get timedOut() {
|
||||
return timedOut;
|
||||
},
|
||||
value: () => Buffer.concat(chunks).toString("utf8"),
|
||||
exceeded: () => overflow,
|
||||
};
|
||||
};
|
||||
|
||||
const collect = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
maximum: number,
|
||||
) =>
|
||||
new Promise<{ code: number | null; stdout: string; stderr: string }>(
|
||||
(resolve, reject) => {
|
||||
const child = spawn(executable, [...arguments_], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const stdout = boundedCollector(maximum);
|
||||
const stderr = boundedCollector(maximum);
|
||||
const timeout = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
||||
timeout.unref();
|
||||
child.stdout?.on("data", stdout.append);
|
||||
child.stderr?.on("data", stderr.append);
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
resolve({ code, stdout: stdout.value(), stderr: stderr.value() });
|
||||
});
|
||||
},
|
||||
);
|
||||
const replayProcessEnvironment = (): NodeJS.ProcessEnv => ({
|
||||
PATH: "/usr/bin:/bin",
|
||||
LANG: "C",
|
||||
LC_ALL: "C",
|
||||
TZ: "UTC",
|
||||
...(process.env.XDG_RUNTIME_DIR === undefined
|
||||
? {}
|
||||
: { XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR }),
|
||||
...(process.env.DBUS_SESSION_BUS_ADDRESS === undefined
|
||||
? {}
|
||||
: { DBUS_SESSION_BUS_ADDRESS: process.env.DBUS_SESSION_BUS_ADDRESS }),
|
||||
});
|
||||
|
||||
const killUnit = async (systemctl: string, unit: string): Promise<void> => {
|
||||
try {
|
||||
await collect(
|
||||
systemctl,
|
||||
["--user", "kill", "--kill-whom=all", "--signal=SIGKILL", unit],
|
||||
4096,
|
||||
);
|
||||
} catch {
|
||||
/* cleanup continues */
|
||||
}
|
||||
};
|
||||
interface ResolveReplayResultOptions {
|
||||
readonly prepared: PreparedReplayPlan;
|
||||
readonly collected: CollectedProcess;
|
||||
readonly unitResult: string;
|
||||
readonly cleanup: ReplayExecutionResult["cleanup"];
|
||||
readonly cancelled: boolean;
|
||||
readonly timedOut: boolean;
|
||||
}
|
||||
|
||||
const observeCleanup = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<ReplayExecutionResult["cleanup"]> => {
|
||||
try {
|
||||
const state = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=ActiveState", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
if (
|
||||
state.code !== 0 ||
|
||||
state.stdout.trim() === "inactive" ||
|
||||
state.stdout.trim() === "failed" ||
|
||||
state.stdout.trim().length === 0
|
||||
) {
|
||||
await collect(systemctl, ["--user", "reset-failed", unit], 4096);
|
||||
return { state: "complete", residual_resources: [] };
|
||||
}
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
} catch {
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
}
|
||||
};
|
||||
|
||||
const observeUnitResult = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<string> => {
|
||||
try {
|
||||
const result = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=Result", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
return result.stdout.trim();
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
};
|
||||
|
||||
const commitOutcomes = (
|
||||
outcomes: readonly WorkerProtocolOutcome[],
|
||||
): ReplayExecutionResult["outcomes"] =>
|
||||
outcomes.map((outcome) => {
|
||||
const semantic =
|
||||
outcome.value === undefined ? (outcome.exception ?? null) : outcome.value;
|
||||
return {
|
||||
case_id: outcome.case_id,
|
||||
outcome: outcome.outcome,
|
||||
...(outcome.value === undefined
|
||||
? {}
|
||||
: { value: jsonValueSchema.parse(outcome.value) }),
|
||||
...(outcome.exception === undefined
|
||||
? {}
|
||||
: { exception: outcome.exception }),
|
||||
input_sha256: outcome.input_sha256,
|
||||
output_sha256: digestJson(semantic),
|
||||
truncated: false,
|
||||
};
|
||||
});
|
||||
|
||||
const compareOutcomes = (
|
||||
left: ReplayExecutionResult["outcomes"],
|
||||
right: ReplayExecutionResult["outcomes"],
|
||||
): NonNullable<ReplayExecutionResult["comparison"]> =>
|
||||
left.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status:
|
||||
right[index] === undefined
|
||||
? "unknown"
|
||||
: item.outcome === right[index].outcome &&
|
||||
item.output_sha256 === right[index].output_sha256
|
||||
? "equal"
|
||||
: "changed",
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
}));
|
||||
|
||||
const terminationResult = (
|
||||
prepared: PreparedReplayPlan,
|
||||
stderr: string,
|
||||
termination: "timeout" | "oom" | "crash" | "cancelled" | "protocol_error",
|
||||
cleanup: ReplayExecutionResult["cleanup"],
|
||||
limitation?: string,
|
||||
const resolveReplayResult = (
|
||||
options: ResolveReplayResultOptions,
|
||||
): ReplayExecutionResult => {
|
||||
const outcomes = prepared.publicPlan.cases.map((item) => ({
|
||||
case_id: item.case_id,
|
||||
outcome: termination,
|
||||
input_sha256: item.sha256,
|
||||
output_sha256: null,
|
||||
truncated: termination === "protocol_error",
|
||||
}));
|
||||
const differential = prepared.publicPlan.right !== undefined;
|
||||
const { prepared, collected, unitResult, cleanup, cancelled, timedOut } =
|
||||
options;
|
||||
if (cancelled || timedOut)
|
||||
return terminationResult({
|
||||
prepared,
|
||||
stderr: collected.stderr,
|
||||
termination: cancelled ? "cancelled" : "timeout",
|
||||
cleanup,
|
||||
});
|
||||
if (collected.outputExceeded)
|
||||
return terminationResult({
|
||||
prepared,
|
||||
stderr: collected.stderr,
|
||||
termination: "protocol_error",
|
||||
cleanup,
|
||||
limitation: "Worker stdout exceeded the committed bound",
|
||||
});
|
||||
if (collected.code !== 0)
|
||||
return terminationResult({
|
||||
prepared,
|
||||
stderr: collected.stderr,
|
||||
termination:
|
||||
collected.code === 137 || unitResult === "oom-kill" ? "oom" : "crash",
|
||||
cleanup,
|
||||
});
|
||||
let response: WorkerProtocolResponse;
|
||||
try {
|
||||
const rawResponse: unknown = JSON.parse(collected.stdout);
|
||||
response = parseReplayWorkerResponse(
|
||||
rawResponse,
|
||||
prepared.publicPlan.cases,
|
||||
prepared.publicPlan.right !== undefined,
|
||||
);
|
||||
} catch {
|
||||
return terminationResult({
|
||||
prepared,
|
||||
stderr: collected.stderr,
|
||||
termination: "protocol_error",
|
||||
cleanup,
|
||||
});
|
||||
}
|
||||
const outcomes = commitOutcomes(response.left);
|
||||
const right =
|
||||
response.right === undefined ? undefined : commitOutcomes(response.right);
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [...outcomes, ...(differential ? outcomes : [])],
|
||||
...(differential
|
||||
? {
|
||||
comparison: outcomes.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status: "unknown" as const,
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
stderr,
|
||||
termination,
|
||||
outcomes: [...outcomes, ...(right ?? [])],
|
||||
...(right === undefined
|
||||
? {}
|
||||
: { comparison: compareOutcomes(outcomes, right) }),
|
||||
stderr: collected.stderr,
|
||||
termination: "completed",
|
||||
cleanup,
|
||||
limitations: [
|
||||
limitation ??
|
||||
`Replay terminated with ${termination}; the requested functional result remains unknown.`,
|
||||
"Controlled replay observes the isolated extracted modules, not the original application runtime.",
|
||||
"Network and host filesystem access were unavailable; unsupported dependencies may change behavior.",
|
||||
],
|
||||
reproducer: null,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { open } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import {
|
||||
digestJson,
|
||||
type JavaScriptReplayPolicy,
|
||||
type PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import { buildLinuxX64ReplaySeccomp } from "./LinuxSeccompPolicy.js";
|
||||
import { resolveLinuxRuntimeClosure } from "./LinuxRuntimeClosure.js";
|
||||
|
||||
export type RuntimeFile = Awaited<
|
||||
ReturnType<typeof resolveLinuxRuntimeClosure>
|
||||
>[number];
|
||||
|
||||
export interface SandboxArgumentsOptions {
|
||||
readonly unit: string;
|
||||
readonly policy: JavaScriptReplayPolicy;
|
||||
readonly prepared: PreparedReplayPlan;
|
||||
readonly workerPath: string;
|
||||
readonly closure: readonly RuntimeFile[];
|
||||
readonly filterPath: string;
|
||||
}
|
||||
|
||||
export const assertRuntimeCommitment = (
|
||||
prepared: PreparedReplayPlan,
|
||||
closure: readonly RuntimeFile[],
|
||||
): void => {
|
||||
const observed = closure.map((item) => ({
|
||||
source_path: item.sourcePath,
|
||||
destination_path: item.destinationPath,
|
||||
sha256: item.sha256,
|
||||
}));
|
||||
if (
|
||||
digestJson(observed) !==
|
||||
digestJson(prepared.publicPlan.runtime.read_only_files)
|
||||
)
|
||||
throw new TypeError("Replay runtime closure changed after approval");
|
||||
};
|
||||
|
||||
export const temporaryFilterHandle = async () => {
|
||||
const { mkdtemp, writeFile, rm } = await import("node:fs/promises");
|
||||
const { tmpdir } = await import("node:os");
|
||||
const { join } = await import("node:path");
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-replay-filter-"));
|
||||
const path = join(directory, "seccomp.bpf");
|
||||
await writeFile(path, buildLinuxX64ReplaySeccomp(), { mode: 0o600 });
|
||||
const handle = await open(path, "r");
|
||||
return {
|
||||
path,
|
||||
handle,
|
||||
close: async () => {
|
||||
await handle.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const systemdArguments = (
|
||||
options: SandboxArgumentsOptions,
|
||||
): string[] => {
|
||||
const { unit, policy, prepared, workerPath, closure, filterPath } = options;
|
||||
const limits = prepared.publicPlan.limits;
|
||||
const descriptorPaths = [
|
||||
filterPath,
|
||||
...closure.map(({ sourcePath }) => sourcePath),
|
||||
workerPath,
|
||||
];
|
||||
const workerFd = descriptorPaths.length + 2;
|
||||
const wrapper = descriptorPaths
|
||||
.map((_, index) => `exec ${String(index + 3)}<"$1"; shift`)
|
||||
.concat('exec "$@"')
|
||||
.join("\n");
|
||||
return [
|
||||
"--user",
|
||||
"--pipe",
|
||||
"--wait",
|
||||
"--service-type=exec",
|
||||
"--quiet",
|
||||
`--unit=${unit}`,
|
||||
`--property=MemoryMax=${String(limits.memory_bytes)}`,
|
||||
"--property=MemorySwapMax=0",
|
||||
`--property=TasksMax=${String(limits.tasks)}`,
|
||||
`--property=CPUQuota=${String(limits.cpu_quota_percent)}%`,
|
||||
"--property=KillMode=control-group",
|
||||
"--property=SendSIGKILL=yes",
|
||||
"--",
|
||||
policy.shellPath,
|
||||
"-c",
|
||||
wrapper,
|
||||
"rea-replay-wrapper",
|
||||
...descriptorPaths,
|
||||
policy.bubblewrapPath,
|
||||
"--unshare-all",
|
||||
"--unshare-user",
|
||||
"--disable-userns",
|
||||
"--new-session",
|
||||
"--die-with-parent",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/work",
|
||||
"--setenv",
|
||||
"TMPDIR",
|
||||
"/tmp",
|
||||
"--setenv",
|
||||
"TZ",
|
||||
"UTC",
|
||||
"--setenv",
|
||||
"LANG",
|
||||
"C",
|
||||
"--setenv",
|
||||
"LC_ALL",
|
||||
"C",
|
||||
"--tmpfs",
|
||||
"/",
|
||||
"--dir",
|
||||
"/runtime",
|
||||
"--dir",
|
||||
"/work",
|
||||
"--size",
|
||||
String(limits.tmpfs_bytes),
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
...bindArguments(closure),
|
||||
"--ro-bind-fd",
|
||||
String(workerFd),
|
||||
"/runtime/worker.js",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--remount-ro",
|
||||
"/",
|
||||
"--chdir",
|
||||
"/work",
|
||||
"--seccomp",
|
||||
"3",
|
||||
"--",
|
||||
"/runtime/node",
|
||||
`--max-old-space-size=${String(
|
||||
Math.max(8, Math.floor(limits.memory_bytes / 1024 / 1024 / 2)),
|
||||
)}`,
|
||||
"--experimental-vm-modules",
|
||||
"--permission",
|
||||
"--allow-fs-read=/runtime/worker.js",
|
||||
"/runtime/worker.js",
|
||||
];
|
||||
};
|
||||
|
||||
const bindArguments = (closure: readonly RuntimeFile[]): string[] => {
|
||||
const arguments_: string[] = [];
|
||||
const directories = new Set<string>();
|
||||
for (const [index, item] of closure.entries()) {
|
||||
const destination = item.destinationPath;
|
||||
let parent = dirname(destination);
|
||||
const chain: string[] = [];
|
||||
while (parent !== "/" && !directories.has(parent)) {
|
||||
chain.push(parent);
|
||||
parent = dirname(parent);
|
||||
}
|
||||
for (const directory of chain.reverse()) {
|
||||
directories.add(directory);
|
||||
arguments_.push("--dir", directory);
|
||||
}
|
||||
arguments_.push("--ro-bind-fd", String(index + 4), destination);
|
||||
}
|
||||
return arguments_;
|
||||
};
|
||||
@@ -0,0 +1,135 @@
|
||||
import {
|
||||
digestJson,
|
||||
type PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import type { ReplayExecutionResult } from "../domain/javascriptReplay.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import type { WorkerProtocolOutcome } from "./ReplayWorkerProtocol.js";
|
||||
|
||||
export const workerRequest = (prepared: PreparedReplayPlan) => ({
|
||||
schemaVersion: 1,
|
||||
left: workerSide(prepared.publicPlan.left, prepared.leftSources),
|
||||
...(prepared.publicPlan.right === undefined ||
|
||||
prepared.rightSources === undefined
|
||||
? {}
|
||||
: { right: workerSide(prepared.publicPlan.right, prepared.rightSources) }),
|
||||
cases: prepared.publicPlan.cases.map((item) => ({
|
||||
caseId: item.case_id,
|
||||
arguments: item.arguments,
|
||||
inputSha256: item.sha256,
|
||||
})),
|
||||
determinism: {
|
||||
clockIso: prepared.publicPlan.determinism.clock_iso,
|
||||
randomSeed: prepared.publicPlan.determinism.random_seed,
|
||||
},
|
||||
limits: {
|
||||
resultDepth: prepared.publicPlan.limits.result_depth,
|
||||
resultNodes: prepared.publicPlan.limits.result_nodes,
|
||||
exceptionBytes: Math.min(
|
||||
64 * 1024,
|
||||
prepared.publicPlan.limits.output_bytes,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
const workerSide = (
|
||||
side: PreparedReplayPlan["publicPlan"]["left"],
|
||||
sources: Readonly<Record<string, string>>,
|
||||
) => ({
|
||||
modules: side.modules.map((module) => ({
|
||||
alias: module.alias,
|
||||
format: module.format,
|
||||
dependencies: module.dependencies,
|
||||
source: sources[module.alias] ?? "",
|
||||
})),
|
||||
entryAlias: side.entry_alias,
|
||||
entryExport: side.entry_export,
|
||||
});
|
||||
|
||||
export const commitOutcomes = (
|
||||
outcomes: readonly WorkerProtocolOutcome[],
|
||||
): ReplayExecutionResult["outcomes"] =>
|
||||
outcomes.map((outcome) => {
|
||||
const semantic =
|
||||
outcome.value === undefined ? (outcome.exception ?? null) : outcome.value;
|
||||
return {
|
||||
case_id: outcome.case_id,
|
||||
outcome: outcome.outcome,
|
||||
...(outcome.value === undefined
|
||||
? {}
|
||||
: { value: jsonValueSchema.parse(outcome.value) }),
|
||||
...(outcome.exception === undefined
|
||||
? {}
|
||||
: { exception: outcome.exception }),
|
||||
input_sha256: outcome.input_sha256,
|
||||
output_sha256: digestJson(semantic),
|
||||
truncated: false,
|
||||
};
|
||||
});
|
||||
|
||||
export const compareOutcomes = (
|
||||
left: ReplayExecutionResult["outcomes"],
|
||||
right: ReplayExecutionResult["outcomes"],
|
||||
): NonNullable<ReplayExecutionResult["comparison"]> =>
|
||||
left.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status:
|
||||
right[index] === undefined
|
||||
? "unknown"
|
||||
: item.outcome === right[index].outcome &&
|
||||
item.output_sha256 === right[index].output_sha256
|
||||
? "equal"
|
||||
: "changed",
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
}));
|
||||
|
||||
export interface TerminationResultOptions {
|
||||
readonly prepared: PreparedReplayPlan;
|
||||
readonly stderr: string;
|
||||
readonly termination:
|
||||
| "timeout"
|
||||
| "oom"
|
||||
| "crash"
|
||||
| "cancelled"
|
||||
| "protocol_error";
|
||||
readonly cleanup: ReplayExecutionResult["cleanup"];
|
||||
readonly limitation?: string;
|
||||
}
|
||||
|
||||
export const terminationResult = (
|
||||
options: TerminationResultOptions,
|
||||
): ReplayExecutionResult => {
|
||||
const { prepared, stderr, termination, cleanup, limitation } = options;
|
||||
const outcomes = prepared.publicPlan.cases.map((item) => ({
|
||||
case_id: item.case_id,
|
||||
outcome: termination,
|
||||
input_sha256: item.sha256,
|
||||
output_sha256: null,
|
||||
truncated: termination === "protocol_error",
|
||||
}));
|
||||
const differential = prepared.publicPlan.right !== undefined;
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [...outcomes, ...(differential ? outcomes : [])],
|
||||
...(differential
|
||||
? {
|
||||
comparison: outcomes.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status: "unknown" as const,
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
stderr,
|
||||
termination,
|
||||
cleanup,
|
||||
limitations: [
|
||||
limitation ??
|
||||
`Replay terminated with ${termination}; the requested functional result remains unknown.`,
|
||||
],
|
||||
reproducer: null,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import type { ReplayExecutionResult } from "../domain/javascriptReplay.js";
|
||||
|
||||
export interface CollectedProcess {
|
||||
readonly code: number | null;
|
||||
readonly signal: NodeJS.Signals | null;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly outputExceeded: boolean;
|
||||
}
|
||||
|
||||
export const boundedCollector = (maximum: number) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
let overflow = false;
|
||||
return {
|
||||
append: (chunk: Buffer) => {
|
||||
const retained = chunk.subarray(0, Math.max(0, maximum - bytes));
|
||||
if (retained.byteLength > 0) chunks.push(retained);
|
||||
bytes += retained.byteLength;
|
||||
if (retained.byteLength < chunk.byteLength) overflow = true;
|
||||
},
|
||||
value: () => Buffer.concat(chunks).toString("utf8"),
|
||||
exceeded: () => overflow,
|
||||
};
|
||||
};
|
||||
|
||||
export const collect = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
maximum: number,
|
||||
) =>
|
||||
new Promise<{ code: number | null; stdout: string; stderr: string }>(
|
||||
(resolve, reject) => {
|
||||
const child = spawn(executable, [...arguments_], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const stdout = boundedCollector(maximum);
|
||||
const stderr = boundedCollector(maximum);
|
||||
const timeout = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
||||
timeout.unref();
|
||||
child.stdout?.on("data", stdout.append);
|
||||
child.stderr?.on("data", stderr.append);
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
resolve({ code, stdout: stdout.value(), stderr: stderr.value() });
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const killUnit = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<void> => {
|
||||
try {
|
||||
await collect(
|
||||
systemctl,
|
||||
["--user", "kill", "--kill-whom=all", "--signal=SIGKILL", unit],
|
||||
4096,
|
||||
);
|
||||
} catch {
|
||||
/* cleanup continues */
|
||||
}
|
||||
};
|
||||
|
||||
export const observeCleanup = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<ReplayExecutionResult["cleanup"]> => {
|
||||
try {
|
||||
const state = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=ActiveState", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
const activeState = state.stdout.trim();
|
||||
if (
|
||||
state.code !== 0 ||
|
||||
activeState === "inactive" ||
|
||||
activeState === "failed" ||
|
||||
activeState.length === 0
|
||||
) {
|
||||
await collect(systemctl, ["--user", "reset-failed", unit], 4096);
|
||||
return { state: "complete", residual_resources: [] };
|
||||
}
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
} catch {
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
}
|
||||
};
|
||||
|
||||
export const observeUnitResult = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<string> => {
|
||||
try {
|
||||
const result = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=Result", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
return result.stdout.trim();
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
};
|
||||
Vendored
+227
-178
@@ -364,83 +364,118 @@ const resultFor = (
|
||||
): Readonly<Record<string, unknown>> => {
|
||||
switch (command.method) {
|
||||
case "Target.attachToTarget":
|
||||
return { sessionId: options.invalidAttachedSession ? "" : "session-1" };
|
||||
return attachToTargetResult(options);
|
||||
case "Page.getFrameTree":
|
||||
return frameTree(
|
||||
port,
|
||||
frameTreeReads > 1 && options.frameUrlAfterFirstRead !== undefined
|
||||
? options.frameUrlAfterFirstRead
|
||||
: frameTreeReads <= (options.transitionalFrameReads ?? 0)
|
||||
? ":"
|
||||
: (options.electronFileUrl ?? options.attachedFrameUrl),
|
||||
options.extraCollections === true,
|
||||
);
|
||||
return frameTreeResult(port, options, frameTreeReads);
|
||||
case "Page.getResourceTree":
|
||||
return resourceTree(
|
||||
port,
|
||||
options.extraCollections === true,
|
||||
options.electronFileUrl,
|
||||
options.duplicateElectronInventory === true,
|
||||
);
|
||||
return resourceTreeResult(port, options);
|
||||
case "DOMSnapshot.captureSnapshot":
|
||||
return domSnapshot(
|
||||
port,
|
||||
options.electronFileUrl,
|
||||
options.extraCollections === true,
|
||||
);
|
||||
return domSnapshotResult(port, options);
|
||||
case "Accessibility.getFullAXTree":
|
||||
return accessibilityTree(options.extraCollections === true);
|
||||
return accessibilityTreeResult(options);
|
||||
case "Debugger.getScriptSource":
|
||||
return { scriptSource: "export const observed = 'source-secret';" };
|
||||
return scriptSourceResult();
|
||||
case "Network.getResponseBody":
|
||||
return options.invalidResponseBodyBase64 === true
|
||||
? { body: "%%%not-base64%%%", base64Encoded: true }
|
||||
: {
|
||||
body: JSON.stringify({
|
||||
result: { ok: true, token: "response-body-secret" },
|
||||
items: [{ id: 1 }, { id: 2 }],
|
||||
}),
|
||||
base64Encoded: false,
|
||||
};
|
||||
return responseBodyResult(options);
|
||||
case "Page.captureScreenshot":
|
||||
return {
|
||||
data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PzWvWQAAAABJRU5ErkJggg==",
|
||||
};
|
||||
return screenshotResult();
|
||||
case "Target.getTargets":
|
||||
return { targetInfos: targets(port, options).map(endpointTargetToInfo) };
|
||||
case "Storage.getUsageAndQuota":
|
||||
return { usage: 42, quota: 1_024, usageBreakdown: [] };
|
||||
return storageUsageResult();
|
||||
case "DOMStorage.getDOMStorageItems":
|
||||
return {
|
||||
entries:
|
||||
options.extraCollections === true
|
||||
? [
|
||||
["public-key", "storage-secret"],
|
||||
["second-key", "second-secret"],
|
||||
]
|
||||
: [["public-key", "storage-secret"]],
|
||||
};
|
||||
return domStorageResult(options);
|
||||
case "IndexedDB.requestDatabaseNames":
|
||||
return {
|
||||
databaseNames:
|
||||
options.extraCollections === true
|
||||
? ["app-db", "second-db"]
|
||||
: ["app-db"],
|
||||
};
|
||||
return indexedDbResult(options);
|
||||
case "CacheStorage.requestCacheNames":
|
||||
return {
|
||||
caches: [
|
||||
{ cacheName: "assets-v1", cacheId: "secret-id" },
|
||||
...(options.extraCollections === true
|
||||
? [{ cacheName: "assets-v2", cacheId: "second-secret-id" }]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
return cacheStorageResult(options);
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
const attachToTargetResult = (options: FakeOptions) => ({
|
||||
sessionId: options.invalidAttachedSession ? "" : "session-1",
|
||||
});
|
||||
|
||||
const frameTreeResult = (
|
||||
port: number,
|
||||
options: FakeOptions,
|
||||
frameTreeReads: number,
|
||||
) =>
|
||||
frameTree(
|
||||
port,
|
||||
frameTreeReads > 1 && options.frameUrlAfterFirstRead !== undefined
|
||||
? options.frameUrlAfterFirstRead
|
||||
: frameTreeReads <= (options.transitionalFrameReads ?? 0)
|
||||
? ":"
|
||||
: (options.electronFileUrl ?? options.attachedFrameUrl),
|
||||
options.extraCollections === true,
|
||||
);
|
||||
|
||||
const resourceTreeResult = (port: number, options: FakeOptions) =>
|
||||
resourceTree(
|
||||
port,
|
||||
options.extraCollections === true,
|
||||
options.electronFileUrl,
|
||||
options.duplicateElectronInventory === true,
|
||||
);
|
||||
|
||||
const domSnapshotResult = (port: number, options: FakeOptions) =>
|
||||
domSnapshot(port, options.electronFileUrl, options.extraCollections === true);
|
||||
|
||||
const accessibilityTreeResult = (options: FakeOptions) =>
|
||||
accessibilityTree(options.extraCollections === true);
|
||||
|
||||
const scriptSourceResult = () => ({
|
||||
scriptSource: "export const observed = 'source-secret';",
|
||||
});
|
||||
|
||||
const responseBodyResult = (options: FakeOptions) =>
|
||||
options.invalidResponseBodyBase64 === true
|
||||
? { body: "%%%not-base64%%%", base64Encoded: true }
|
||||
: {
|
||||
body: JSON.stringify({
|
||||
result: { ok: true, token: "response-body-secret" },
|
||||
items: [{ id: 1 }, { id: 2 }],
|
||||
}),
|
||||
base64Encoded: false,
|
||||
};
|
||||
|
||||
const screenshotResult = () => ({
|
||||
data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PzWvWQAAAABJRU5ErkJggg==",
|
||||
});
|
||||
|
||||
const storageUsageResult = () => ({
|
||||
usage: 42,
|
||||
quota: 1_024,
|
||||
usageBreakdown: [],
|
||||
});
|
||||
|
||||
const domStorageResult = (options: FakeOptions) => ({
|
||||
entries:
|
||||
options.extraCollections === true
|
||||
? [
|
||||
["public-key", "storage-secret"],
|
||||
["second-key", "second-secret"],
|
||||
]
|
||||
: [["public-key", "storage-secret"]],
|
||||
});
|
||||
|
||||
const indexedDbResult = (options: FakeOptions) => ({
|
||||
databaseNames:
|
||||
options.extraCollections === true ? ["app-db", "second-db"] : ["app-db"],
|
||||
});
|
||||
|
||||
const cacheStorageResult = (options: FakeOptions) => ({
|
||||
caches: [
|
||||
{ cacheName: "assets-v1", cacheId: "secret-id" },
|
||||
...(options.extraCollections === true
|
||||
? [{ cacheName: "assets-v2", cacheId: "second-secret-id" }]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
|
||||
const versionTargetId = (options: FakeOptions): string =>
|
||||
options.electronFileUrl === undefined ? "allowed-page" : "electron-page";
|
||||
|
||||
@@ -642,56 +677,7 @@ const emitEvents = (
|
||||
port: number,
|
||||
options: FakeOptions,
|
||||
): void => {
|
||||
if (command.method === "Debugger.enable") {
|
||||
if (options.foreignSessionEvents === true)
|
||||
event(socket, "Debugger.scriptParsed", "foreign-session", {
|
||||
scriptId: "script-foreign",
|
||||
url: `http://127.0.0.1:${String(port)}/foreign.js`,
|
||||
hash: "foreign-hash",
|
||||
length: 20,
|
||||
isModule: false,
|
||||
});
|
||||
event(socket, "Debugger.scriptParsed", command.sessionId, {
|
||||
scriptId: "script-allowed",
|
||||
url:
|
||||
options.electronFileUrl === undefined
|
||||
? `http://127.0.0.1:${String(port)}/app.js?token=script-secret`
|
||||
: new URL("app.js", options.electronFileUrl).href,
|
||||
hash: "cdp-hash",
|
||||
length: 40,
|
||||
isModule: true,
|
||||
executionContextId: 1,
|
||||
scriptLanguage: "JavaScript",
|
||||
sourceMapURL: "/app.js.map?token=map-secret",
|
||||
});
|
||||
if (
|
||||
options.electronFileUrl !== undefined &&
|
||||
options.duplicateElectronInventory === true
|
||||
)
|
||||
event(socket, "Debugger.scriptParsed", command.sessionId, {
|
||||
scriptId: "script-allowed-duplicate",
|
||||
url: new URL("app.js", options.electronFileUrl).href,
|
||||
hash: "cdp-hash",
|
||||
length: 40,
|
||||
isModule: true,
|
||||
executionContextId: 1,
|
||||
scriptLanguage: "JavaScript",
|
||||
});
|
||||
event(socket, "Debugger.scriptParsed", command.sessionId, {
|
||||
scriptId: "script-private",
|
||||
url: "https://private.example.test/private.js?secret=forbidden",
|
||||
hash: "private-hash",
|
||||
length: 100,
|
||||
isModule: false,
|
||||
});
|
||||
event(socket, "Debugger.scriptParsed", command.sessionId, {
|
||||
scriptId: "script-inline",
|
||||
url: "",
|
||||
hash: "inline-secret",
|
||||
length: 100,
|
||||
isModule: false,
|
||||
});
|
||||
}
|
||||
emitDebuggerEvents(socket, command, port, options);
|
||||
if (command.method === "Network.enable") {
|
||||
if (options.navigateDuringObservationUrl !== undefined)
|
||||
event(socket, "Page.frameNavigated", command.sessionId, {
|
||||
@@ -794,55 +780,7 @@ const emitEvents = (
|
||||
},
|
||||
});
|
||||
}
|
||||
if (command.method === "Runtime.enable") {
|
||||
event(socket, "Runtime.executionContextCreated", command.sessionId, {
|
||||
context: {
|
||||
id: 1,
|
||||
origin:
|
||||
options.electronFileUrl === undefined
|
||||
? `http://127.0.0.1:${String(port)}`
|
||||
: "file://",
|
||||
auxData: { frameId: "frame-main", isDefault: true },
|
||||
},
|
||||
});
|
||||
event(socket, "Runtime.consoleAPICalled", command.sessionId, {
|
||||
type: "log",
|
||||
timestamp: 123,
|
||||
args: [
|
||||
{
|
||||
type: "string",
|
||||
value:
|
||||
options.sensitiveShapes === true
|
||||
? "authorization=Bearer console-secret"
|
||||
: "console-secret",
|
||||
},
|
||||
...(options.sensitiveShapes === true
|
||||
? [
|
||||
{ type: "number", value: 42 },
|
||||
{
|
||||
type: "object",
|
||||
objectId: "must-not-be-expanded",
|
||||
description: "object-secret",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
stackTrace: {
|
||||
callFrames: [
|
||||
{
|
||||
url: `http://127.0.0.1:${String(port)}/app.js?secret=console-url`,
|
||||
lineNumber: 7,
|
||||
columnNumber: 9,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
event(socket, "Runtime.consoleAPICalled", command.sessionId, {
|
||||
type: "unknown-origin-console-secret",
|
||||
timestamp: 124,
|
||||
args: [{ type: "string", value: "unknown-console-value-secret" }],
|
||||
});
|
||||
}
|
||||
emitRuntimeEvents(socket, command, port, options);
|
||||
if (command.method === "WebMCP.enable" && options.webMcpTools === true) {
|
||||
event(socket, "WebMCP.toolsAdded", command.sessionId, {
|
||||
tools: [
|
||||
@@ -922,26 +860,7 @@ const emitEvents = (
|
||||
});
|
||||
}
|
||||
}
|
||||
if (
|
||||
command.method === "DOMSnapshot.captureSnapshot" &&
|
||||
options.navigateDuringCaptureUrl !== undefined
|
||||
)
|
||||
event(socket, "Page.frameNavigated", command.sessionId, {
|
||||
frame: {
|
||||
id: "frame-main",
|
||||
url: options.navigateDuringCaptureUrl,
|
||||
},
|
||||
});
|
||||
if (
|
||||
command.method === "Page.captureScreenshot" &&
|
||||
options.navigateDuringScreenshotUrl !== undefined
|
||||
)
|
||||
event(socket, "Page.frameNavigated", command.sessionId, {
|
||||
frame: {
|
||||
id: "frame-main",
|
||||
url: options.navigateDuringScreenshotUrl,
|
||||
},
|
||||
});
|
||||
emitCaptureNavigation(socket, command, options);
|
||||
if (
|
||||
command.method === "Page.setLifecycleEventsEnabled" &&
|
||||
options.sessionTimeline !== undefined
|
||||
@@ -1001,6 +920,136 @@ const emitEvents = (
|
||||
}
|
||||
};
|
||||
|
||||
const emitDebuggerEvents = (
|
||||
socket: WebSocket,
|
||||
command: FakeCdpCommand,
|
||||
port: number,
|
||||
options: FakeOptions,
|
||||
): void => {
|
||||
if (command.method !== "Debugger.enable") return;
|
||||
if (options.foreignSessionEvents === true)
|
||||
event(socket, "Debugger.scriptParsed", "foreign-session", {
|
||||
scriptId: "script-foreign",
|
||||
url: `http://127.0.0.1:${String(port)}/foreign.js`,
|
||||
hash: "foreign-hash",
|
||||
length: 20,
|
||||
isModule: false,
|
||||
});
|
||||
event(socket, "Debugger.scriptParsed", command.sessionId, {
|
||||
scriptId: "script-allowed",
|
||||
url:
|
||||
options.electronFileUrl === undefined
|
||||
? `http://127.0.0.1:${String(port)}/app.js?token=script-secret`
|
||||
: new URL("app.js", options.electronFileUrl).href,
|
||||
hash: "cdp-hash",
|
||||
length: 40,
|
||||
isModule: true,
|
||||
executionContextId: 1,
|
||||
scriptLanguage: "JavaScript",
|
||||
sourceMapURL: "/app.js.map?token=map-secret",
|
||||
});
|
||||
if (
|
||||
options.electronFileUrl !== undefined &&
|
||||
options.duplicateElectronInventory === true
|
||||
)
|
||||
event(socket, "Debugger.scriptParsed", command.sessionId, {
|
||||
scriptId: "script-allowed-duplicate",
|
||||
url: new URL("app.js", options.electronFileUrl).href,
|
||||
hash: "cdp-hash",
|
||||
length: 40,
|
||||
isModule: true,
|
||||
executionContextId: 1,
|
||||
scriptLanguage: "JavaScript",
|
||||
});
|
||||
event(socket, "Debugger.scriptParsed", command.sessionId, {
|
||||
scriptId: "script-private",
|
||||
url: "https://private.example.test/private.js?secret=forbidden",
|
||||
hash: "private-hash",
|
||||
length: 100,
|
||||
isModule: false,
|
||||
});
|
||||
event(socket, "Debugger.scriptParsed", command.sessionId, {
|
||||
scriptId: "script-inline",
|
||||
url: "",
|
||||
hash: "inline-secret",
|
||||
length: 100,
|
||||
isModule: false,
|
||||
});
|
||||
};
|
||||
|
||||
const emitRuntimeEvents = (
|
||||
socket: WebSocket,
|
||||
command: FakeCdpCommand,
|
||||
port: number,
|
||||
options: FakeOptions,
|
||||
): void => {
|
||||
if (command.method !== "Runtime.enable") return;
|
||||
event(socket, "Runtime.executionContextCreated", command.sessionId, {
|
||||
context: {
|
||||
id: 1,
|
||||
origin:
|
||||
options.electronFileUrl === undefined
|
||||
? `http://127.0.0.1:${String(port)}`
|
||||
: "file://",
|
||||
auxData: { frameId: "frame-main", isDefault: true },
|
||||
},
|
||||
});
|
||||
event(socket, "Runtime.consoleAPICalled", command.sessionId, {
|
||||
type: "log",
|
||||
timestamp: 123,
|
||||
args: [
|
||||
{
|
||||
type: "string",
|
||||
value:
|
||||
options.sensitiveShapes === true
|
||||
? "authorization=Bearer console-secret"
|
||||
: "console-secret",
|
||||
},
|
||||
...(options.sensitiveShapes === true
|
||||
? [
|
||||
{ type: "number", value: 42 },
|
||||
{
|
||||
type: "object",
|
||||
objectId: "must-not-be-expanded",
|
||||
description: "object-secret",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
stackTrace: {
|
||||
callFrames: [
|
||||
{
|
||||
url: `http://127.0.0.1:${String(port)}/app.js?secret=console-url`,
|
||||
lineNumber: 7,
|
||||
columnNumber: 9,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
event(socket, "Runtime.consoleAPICalled", command.sessionId, {
|
||||
type: "unknown-origin-console-secret",
|
||||
timestamp: 124,
|
||||
args: [{ type: "string", value: "unknown-console-value-secret" }],
|
||||
});
|
||||
};
|
||||
|
||||
const emitCaptureNavigation = (
|
||||
socket: WebSocket,
|
||||
command: FakeCdpCommand,
|
||||
options: FakeOptions,
|
||||
): void => {
|
||||
const navigationUrl =
|
||||
command.method === "DOMSnapshot.captureSnapshot"
|
||||
? options.navigateDuringCaptureUrl
|
||||
: command.method === "Page.captureScreenshot"
|
||||
? options.navigateDuringScreenshotUrl
|
||||
: undefined;
|
||||
if (navigationUrl !== undefined)
|
||||
event(socket, "Page.frameNavigated", command.sessionId, {
|
||||
frame: { id: "frame-main", url: navigationUrl },
|
||||
});
|
||||
};
|
||||
|
||||
const event = (
|
||||
socket: WebSocket,
|
||||
method: string,
|
||||
|
||||
Vendored
+208
-187
@@ -30,105 +30,17 @@ else {
|
||||
await rm(endpointPath, { force: true });
|
||||
const server = createServer((socket) => {
|
||||
socket.setEncoding("utf8");
|
||||
let buffer = "";
|
||||
let pings = 0;
|
||||
socket.on("data", (chunk) => {
|
||||
buffer += chunk;
|
||||
let newline = buffer.indexOf("\n");
|
||||
while (newline >= 0) {
|
||||
const line = buffer.slice(0, newline);
|
||||
buffer = buffer.slice(newline + 1);
|
||||
newline = buffer.indexOf("\n");
|
||||
const request = JSON.parse(line);
|
||||
if (request.token !== token) {
|
||||
socket.end(
|
||||
`${JSON.stringify({
|
||||
id: request.id,
|
||||
ok: false,
|
||||
error: { code: "auth", message: "Authentication failed" },
|
||||
})}\n`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (request.method === "ping") {
|
||||
pings += 1;
|
||||
if (mode === "malformed") {
|
||||
socket.write("{invalid\n");
|
||||
continue;
|
||||
}
|
||||
if (mode === "contradictory") {
|
||||
socket.write(
|
||||
`${JSON.stringify({
|
||||
id: request.id,
|
||||
ok: false,
|
||||
result: { unexpected: true },
|
||||
error: { code: "failure", message: "Failed" },
|
||||
})}\n`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (mode === "oversized_whitespace") {
|
||||
socket.write(`${" ".repeat(1024 * 1024 + 1)}\n`);
|
||||
continue;
|
||||
}
|
||||
if (mode === "future_id") {
|
||||
socket.write(
|
||||
`${JSON.stringify({ id: request.id + 10, ok: true, result: null })}\n`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (mode === "hang_after_start" && pings > 1) continue;
|
||||
const result = sessionInfo({
|
||||
runId,
|
||||
providerVersion:
|
||||
mode === "wrong_identity" ? "0.0.0" : providerVersion,
|
||||
profileDigest,
|
||||
targetSha256,
|
||||
timedOut: mode === "analysis_timeout",
|
||||
});
|
||||
const response = `${JSON.stringify({ id: request.id, ok: true, result })}\n`;
|
||||
if (mode === "fragmented") {
|
||||
const split = Math.floor(response.length / 2);
|
||||
socket.write(response.slice(0, split));
|
||||
setTimeout(() => socket.write(response.slice(split)), 5);
|
||||
} else socket.write(response);
|
||||
continue;
|
||||
}
|
||||
if (mode === "remote_error" && request.method === "list_procedures") {
|
||||
socket.write(
|
||||
`${JSON.stringify({
|
||||
id: request.id,
|
||||
ok: false,
|
||||
error: {
|
||||
code: "not_found",
|
||||
message: "Unknown Ghidra procedure name",
|
||||
},
|
||||
})}\n`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (mode === "exit_tools" && request.method !== "shutdown")
|
||||
process.exit(74);
|
||||
if (mode === "hang_tools" && request.method !== "shutdown") continue;
|
||||
const inventory = inventoryResult(request.method);
|
||||
if (inventory !== undefined) {
|
||||
socket.write(
|
||||
`${JSON.stringify({ id: request.id, ok: true, result: inventory })}\n`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (request.method === "shutdown") {
|
||||
socket.end(
|
||||
`${JSON.stringify({
|
||||
id: request.id,
|
||||
ok: true,
|
||||
result: { shutdown: true, project_ephemeral: true },
|
||||
})}\n`,
|
||||
);
|
||||
server.close(() => process.exit(0));
|
||||
}
|
||||
}
|
||||
});
|
||||
const state = {
|
||||
buffer: { value: "" },
|
||||
pings: { value: 0 },
|
||||
mode,
|
||||
token,
|
||||
runId,
|
||||
providerVersion,
|
||||
profileDigest,
|
||||
targetSha256,
|
||||
};
|
||||
socket.on("data", (chunk) => onSocketData(socket, server, chunk, state));
|
||||
});
|
||||
if (transport === "unix-socket") server.listen(endpointPath);
|
||||
else {
|
||||
@@ -150,6 +62,112 @@ else {
|
||||
}
|
||||
}
|
||||
|
||||
const onSocketData = (socket, server, chunk, state) => {
|
||||
state.buffer.value += chunk;
|
||||
let newline = state.buffer.value.indexOf("\n");
|
||||
while (newline >= 0) {
|
||||
const line = state.buffer.value.slice(0, newline);
|
||||
state.buffer.value = state.buffer.value.slice(newline + 1);
|
||||
newline = state.buffer.value.indexOf("\n");
|
||||
const request = JSON.parse(line);
|
||||
if (request.token !== state.token) {
|
||||
socket.end(
|
||||
`${JSON.stringify({
|
||||
id: request.id,
|
||||
ok: false,
|
||||
error: { code: "auth", message: "Authentication failed" },
|
||||
})}\n`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
handleRequest(socket, server, request, state);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRequest = (socket, server, request, state) => {
|
||||
if (request.method === "ping") {
|
||||
handlePing(socket, request, state);
|
||||
return;
|
||||
}
|
||||
if (state.mode === "remote_error" && request.method === "list_procedures") {
|
||||
socket.write(
|
||||
`${JSON.stringify({
|
||||
id: request.id,
|
||||
ok: false,
|
||||
error: {
|
||||
code: "not_found",
|
||||
message: "Unknown Ghidra procedure name",
|
||||
},
|
||||
})}\n`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (state.mode === "exit_tools" && request.method !== "shutdown")
|
||||
process.exit(74);
|
||||
if (state.mode === "hang_tools" && request.method !== "shutdown") return;
|
||||
const inventory = inventoryResultFor(request.method);
|
||||
if (inventory !== undefined) {
|
||||
socket.write(
|
||||
`${JSON.stringify({ id: request.id, ok: true, result: inventory })}\n`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (request.method === "shutdown") {
|
||||
socket.end(
|
||||
`${JSON.stringify({
|
||||
id: request.id,
|
||||
ok: true,
|
||||
result: { shutdown: true, project_ephemeral: true },
|
||||
})}\n`,
|
||||
);
|
||||
server.close(() => process.exit(0));
|
||||
}
|
||||
};
|
||||
|
||||
const handlePing = (socket, request, state) => {
|
||||
state.pings.value += 1;
|
||||
if (state.mode === "malformed") {
|
||||
socket.write("{invalid\n");
|
||||
return;
|
||||
}
|
||||
if (state.mode === "contradictory") {
|
||||
socket.write(
|
||||
`${JSON.stringify({
|
||||
id: request.id,
|
||||
ok: false,
|
||||
result: { unexpected: true },
|
||||
error: { code: "failure", message: "Failed" },
|
||||
})}\n`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (state.mode === "oversized_whitespace") {
|
||||
socket.write(`${" ".repeat(1024 * 1024 + 1)}\n`);
|
||||
return;
|
||||
}
|
||||
if (state.mode === "future_id") {
|
||||
socket.write(
|
||||
`${JSON.stringify({ id: request.id + 10, ok: true, result: null })}\n`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (state.mode === "hang_after_start" && state.pings.value > 1) return;
|
||||
const result = sessionInfo({
|
||||
runId: state.runId,
|
||||
providerVersion:
|
||||
state.mode === "wrong_identity" ? "0.0.0" : state.providerVersion,
|
||||
profileDigest: state.profileDigest,
|
||||
targetSha256: state.targetSha256,
|
||||
timedOut: state.mode === "analysis_timeout",
|
||||
});
|
||||
const response = `${JSON.stringify({ id: request.id, ok: true, result })}\n`;
|
||||
if (state.mode === "fragmented") {
|
||||
const split = Math.floor(response.length / 2);
|
||||
socket.write(response.slice(0, split));
|
||||
setTimeout(() => socket.write(response.slice(split)), 5);
|
||||
} else socket.write(response);
|
||||
};
|
||||
|
||||
const sessionInfo = ({
|
||||
runId: sessionRunId,
|
||||
providerVersion: version,
|
||||
@@ -197,109 +215,112 @@ const sessionInfo = ({
|
||||
},
|
||||
});
|
||||
|
||||
const inventoryResult = (method) => {
|
||||
const page = (items) => ({
|
||||
items,
|
||||
offset: 0,
|
||||
limit: method.startsWith("search_") ? 100 : 500,
|
||||
total: items.length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
const inventoryResultFor = (method) => {
|
||||
switch (method) {
|
||||
case "address_name":
|
||||
return "fixture_main";
|
||||
case "list_documents":
|
||||
return ["fixture"];
|
||||
case "list_names":
|
||||
return page([
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: false,
|
||||
type: "function",
|
||||
source: "analysis",
|
||||
},
|
||||
},
|
||||
]);
|
||||
return page(method, [nameItem()]);
|
||||
case "list_procedures":
|
||||
return page([
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
procedure: { external: false, thunk: false, thunk_target: null },
|
||||
},
|
||||
]);
|
||||
return page(method, [procedureItem()]);
|
||||
case "list_segments":
|
||||
return [
|
||||
{
|
||||
name: ".text",
|
||||
start: "0x1000",
|
||||
end: "0x1100",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
permissions: { available: true, source: "ghidra-memory-block" },
|
||||
provenance: "ghidra-memory-block",
|
||||
address_space: "ram",
|
||||
image_base: "0x1000",
|
||||
initialized: true,
|
||||
overlay: false,
|
||||
sections: [],
|
||||
},
|
||||
];
|
||||
return [segmentItem()];
|
||||
case "list_strings":
|
||||
return page([
|
||||
{
|
||||
address: "0x2000",
|
||||
value: "fixture value",
|
||||
value_truncated: false,
|
||||
string: {
|
||||
encoding: "UTF-8",
|
||||
termination: "present_or_not_required",
|
||||
byte_length: 14,
|
||||
},
|
||||
},
|
||||
]);
|
||||
return page(method, [stringItem("0x2000", "fixture value")]);
|
||||
case "procedure_address":
|
||||
return "0x1000";
|
||||
case "resolve_containing_procedure":
|
||||
return {
|
||||
query_address: "0x1001",
|
||||
found: true,
|
||||
procedure: {
|
||||
address: "0x1000",
|
||||
name: "fixture_main",
|
||||
classification: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
provenance: "ghidra-function-manager",
|
||||
},
|
||||
},
|
||||
};
|
||||
return containingProcedureResult();
|
||||
case "search_procedures":
|
||||
return page([
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
},
|
||||
]);
|
||||
return page(method, [procedureSearchItem()]);
|
||||
case "search_strings":
|
||||
return page([
|
||||
{
|
||||
address: "0x2000",
|
||||
value: "fixture value",
|
||||
value_truncated: false,
|
||||
},
|
||||
]);
|
||||
return page(method, [stringSearchItem()]);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const page = (method, items) => ({
|
||||
items,
|
||||
offset: 0,
|
||||
limit: method.startsWith("search_") ? 100 : 500,
|
||||
total: items.length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
|
||||
const nameItem = () => ({
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: false,
|
||||
type: "function",
|
||||
source: "analysis",
|
||||
},
|
||||
});
|
||||
|
||||
const procedureItem = () => ({
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
procedure: { external: false, thunk: false, thunk_target: null },
|
||||
});
|
||||
|
||||
const segmentItem = () => ({
|
||||
name: ".text",
|
||||
start: "0x1000",
|
||||
end: "0x1100",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
permissions: { available: true, source: "ghidra-memory-block" },
|
||||
provenance: "ghidra-memory-block",
|
||||
address_space: "ram",
|
||||
image_base: "0x1000",
|
||||
initialized: true,
|
||||
overlay: false,
|
||||
sections: [],
|
||||
});
|
||||
|
||||
const stringItem = (address, value) => ({
|
||||
address,
|
||||
value,
|
||||
value_truncated: false,
|
||||
string: {
|
||||
encoding: "UTF-8",
|
||||
termination: "present_or_not_required",
|
||||
byte_length: value.length + 1,
|
||||
},
|
||||
});
|
||||
|
||||
const containingProcedureResult = () => ({
|
||||
query_address: "0x1001",
|
||||
found: true,
|
||||
procedure: {
|
||||
address: "0x1000",
|
||||
name: "fixture_main",
|
||||
classification: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
provenance: "ghidra-function-manager",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const procedureSearchItem = () => ({
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
});
|
||||
|
||||
const stringSearchItem = () => ({
|
||||
address: "0x2000",
|
||||
value: "fixture value",
|
||||
value_truncated: false,
|
||||
});
|
||||
|
||||
+98
-77
@@ -324,16 +324,17 @@ const sessionInfo = (profileDigest: string, targetSha256: string) => ({
|
||||
},
|
||||
});
|
||||
|
||||
const resultFor = (
|
||||
operation: GhidraOperation,
|
||||
type GhidraResultBuilder = (
|
||||
input: Readonly<Record<string, JsonValue>>,
|
||||
): JsonValue => {
|
||||
const limit = typeof input.limit === "number" ? input.limit : 100;
|
||||
switch (operation) {
|
||||
case "list_documents":
|
||||
return ["fixture"];
|
||||
case "list_procedures":
|
||||
return page(
|
||||
limit: number,
|
||||
) => JsonValue;
|
||||
|
||||
const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
|
||||
["list_documents", () => ["fixture"]],
|
||||
[
|
||||
"list_procedures",
|
||||
(_input, limit) =>
|
||||
page(
|
||||
[
|
||||
{
|
||||
address: "0x401000",
|
||||
@@ -347,35 +348,43 @@ const resultFor = (
|
||||
},
|
||||
],
|
||||
limit,
|
||||
);
|
||||
case "list_strings":
|
||||
return page(
|
||||
),
|
||||
],
|
||||
[
|
||||
"list_strings",
|
||||
(_input, limit) =>
|
||||
page(
|
||||
[
|
||||
stringItem("0x402000", "inventory fixture"),
|
||||
stringItem("0x402020", "external fixture"),
|
||||
],
|
||||
limit,
|
||||
);
|
||||
case "list_segments":
|
||||
return [
|
||||
{
|
||||
name: ".text",
|
||||
start: "0x401000",
|
||||
end: "0x401100",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
permissions: { available: true, source: "ghidra-memory-block" },
|
||||
provenance: "ghidra-memory-block",
|
||||
address_space: "ram",
|
||||
image_base: "0x400000",
|
||||
initialized: true,
|
||||
overlay: false,
|
||||
sections: [],
|
||||
},
|
||||
];
|
||||
case "list_names":
|
||||
return page(
|
||||
),
|
||||
],
|
||||
[
|
||||
"list_segments",
|
||||
() => [
|
||||
{
|
||||
name: ".text",
|
||||
start: "0x401000",
|
||||
end: "0x401100",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
permissions: { available: true, source: "ghidra-memory-block" },
|
||||
provenance: "ghidra-memory-block",
|
||||
address_space: "ram",
|
||||
image_base: "0x400000",
|
||||
initialized: true,
|
||||
overlay: false,
|
||||
sections: [],
|
||||
},
|
||||
],
|
||||
],
|
||||
[
|
||||
"list_names",
|
||||
(_input, limit) =>
|
||||
page(
|
||||
[
|
||||
{
|
||||
address: "0x401000",
|
||||
@@ -391,50 +400,62 @@ const resultFor = (
|
||||
},
|
||||
],
|
||||
limit,
|
||||
);
|
||||
case "search_procedures":
|
||||
case "search_strings":
|
||||
return page([], limit);
|
||||
case "address_name":
|
||||
return "fixture_main";
|
||||
case "procedure_address":
|
||||
return "0x401000";
|
||||
case "resolve_containing_procedure":
|
||||
return {
|
||||
query_address: "0x401001",
|
||||
found: true,
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
};
|
||||
case "procedure_assembly":
|
||||
return "0x401000: CALL 0x401020\n0x401005: RET";
|
||||
case "procedure_callees":
|
||||
case "procedure_callers":
|
||||
return [];
|
||||
case "procedure_info":
|
||||
return {
|
||||
name: "fixture_main",
|
||||
entrypoint: "0x401000",
|
||||
basicblock_count: 1,
|
||||
length: 6,
|
||||
signature: "int fixture_main(void)",
|
||||
locals: [],
|
||||
classification: ghidraFunctionClassification(),
|
||||
};
|
||||
case "procedure_pseudo_code":
|
||||
return "int fixture_main(void) { return 42; }";
|
||||
case "procedure_references":
|
||||
return {
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: input.direction ?? "outgoing",
|
||||
references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
instructions_scanned: 2,
|
||||
instruction_scan_truncated: false,
|
||||
};
|
||||
case "xrefs":
|
||||
return ["0x401001"];
|
||||
case "analyze_function":
|
||||
return ghidraFunctionDossier(input.include_assembly === true);
|
||||
}
|
||||
),
|
||||
],
|
||||
["search_procedures", (_input, limit) => page([], limit)],
|
||||
["search_strings", (_input, limit) => page([], limit)],
|
||||
["address_name", () => "fixture_main"],
|
||||
["procedure_address", () => "0x401000"],
|
||||
[
|
||||
"resolve_containing_procedure",
|
||||
() => ({
|
||||
query_address: "0x401001",
|
||||
found: true,
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
}),
|
||||
],
|
||||
["procedure_assembly", () => "0x401000: CALL 0x401020\n0x401005: RET"],
|
||||
["procedure_callees", () => []],
|
||||
["procedure_callers", () => []],
|
||||
[
|
||||
"procedure_info",
|
||||
() => ({
|
||||
name: "fixture_main",
|
||||
entrypoint: "0x401000",
|
||||
basicblock_count: 1,
|
||||
length: 6,
|
||||
signature: "int fixture_main(void)",
|
||||
locals: [],
|
||||
classification: ghidraFunctionClassification(),
|
||||
}),
|
||||
],
|
||||
["procedure_pseudo_code", () => "int fixture_main(void) { return 42; }"],
|
||||
[
|
||||
"procedure_references",
|
||||
(input, _limit) => ({
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: input.direction ?? "outgoing",
|
||||
references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
instructions_scanned: 2,
|
||||
instruction_scan_truncated: false,
|
||||
}),
|
||||
],
|
||||
["xrefs", () => ["0x401001"]],
|
||||
[
|
||||
"analyze_function",
|
||||
(input, _limit) => ghidraFunctionDossier(input.include_assembly === true),
|
||||
],
|
||||
]);
|
||||
|
||||
const resultFor = (
|
||||
operation: GhidraOperation,
|
||||
input: Readonly<Record<string, JsonValue>>,
|
||||
): JsonValue => {
|
||||
const limit = typeof input.limit === "number" ? input.limit : 100;
|
||||
const builder = resultBuilders.get(operation);
|
||||
if (builder === undefined)
|
||||
throw new TypeError(`Unexpected Ghidra operation: ${operation}`);
|
||||
return builder(input, limit);
|
||||
};
|
||||
|
||||
const page = (items: readonly JsonValue[], limit: number): JsonValue => ({
|
||||
|
||||
Reference in New Issue
Block a user