feat(electron): map static process and IPC boundaries

This commit is contained in:
N0zoM1z0
2026-07-16 07:56:13 +09:00
committed by N0zoM1z0
parent 3988a866f1
commit 3fa2304bc7
279 changed files with 7481 additions and 775 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ describe("browser MCP tools", () => {
const connected = await connectBrowser(browser);
const tools = await connected.client.listTools();
expect(tools.tools).toHaveLength(78);
expect(tools.tools).toHaveLength(79);
expect(tools.tools.map(({ name }) => name)).toEqual(
expect.arrayContaining([
"list_browser_targets",
+3 -3
View File
@@ -58,7 +58,7 @@ describe("tool contract surface", () => {
...BROWSER_TOOL_CONTRACTS,
...ELECTRON_TOOL_CONTRACTS,
];
expect(contracts).toHaveLength(60);
expect(contracts).toHaveLength(61);
for (const contract of contracts) {
const inputSchema = contractJsonSchema(contract.inputSchema);
const outputSchema = contractJsonSchema(contract.outputSchema);
@@ -148,7 +148,7 @@ describe("tool contract surface", () => {
}
});
it("publishes no unconstrained output-schema holes across all 78 tools", () => {
it("publishes no unconstrained output-schema holes across all 79 tools", () => {
const contracts = [
...OFFICIAL_TOOL_CONTRACTS,
...ENHANCED_TOOL_CONTRACTS,
@@ -158,7 +158,7 @@ describe("tool contract surface", () => {
...ELECTRON_TOOL_CONTRACTS,
...SESSION_TOOL_CONTRACTS,
];
expect(contracts).toHaveLength(78);
expect(contracts).toHaveLength(79);
for (const contract of contracts) {
const schema = contractJsonSchema(contract.outputSchema);
expect(emptySchemaPaths(schema), contract.name).toEqual([]);
+281
View File
@@ -0,0 +1,281 @@
import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { analyzeJavaScriptApplication } from "../src/application/JavaScriptApplicationService.js";
import { PermissionAuthority } from "../src/application/PermissionAuthority.js";
import { reconstructJavaScriptArtifact } from "../src/application/JavaScriptArtifactReconstruction.js";
import { parseEvidence } from "../src/domain/evidence.js";
import { parseJavaScriptApplicationGraph } from "../src/domain/javascriptApplicationGraph.js";
import { analyzeJavaScriptApplicationInputSchema } from "../src/domain/javascriptApplicationAnalysis.js";
import { createPermissionPolicy } from "../src/domain/permissionPolicy.js";
import { writeElectronBoundaryFixture } from "./fixtures/electronBoundaryApplication.js";
describe("static Electron application analysis", () => {
it("requires explicit approval, an absolute path, and graph-safe combined bounds", () => {
expect(
analyzeJavaScriptApplicationInputSchema.safeParse({
input_path: "relative/app.asar",
approved: true,
}).success,
).toBe(false);
expect(
analyzeJavaScriptApplicationInputSchema.safeParse({
input_path: "/tmp/app.asar",
}).success,
).toBe(false);
expect(
analyzeJavaScriptApplicationInputSchema.safeParse({
input_path: "/tmp/app.asar",
approved: true,
limits: {
max_entries: 100_000,
max_findings: 200_000,
},
}).success,
).toBe(false);
expect(
analyzeJavaScriptApplicationInputSchema.parse({
input_path: "/tmp/app.asar",
approved: true,
}),
).toMatchObject({
format: "auto",
source_map_read_approved: false,
limits: { max_findings: 8_000 },
});
});
it("maps windows, preload, contextBridge, IPC, validations, utility, and native boundaries without execution", async () => {
const root = await fixtureDirectory();
Reflect.deleteProperty(globalThis, "__rea_electron_fixture_executed");
const first = await reconstructJavaScriptArtifact({ input_path: root });
const second = await reconstructJavaScriptArtifact({ input_path: root });
const graph = parseJavaScriptApplicationGraph(first.graph);
expect(
Reflect.get(globalThis, "__rea_electron_fixture_executed"),
).toBeUndefined();
expect(first.graph).toEqual(second.graph);
expect(first.electron_summary).toMatchObject({
browser_windows: 3,
explicit_web_preferences: 8,
preload_entrypoints: 1,
context_bridge_apis: 2,
exposed_api_members: 5,
ipc: {
literal_channels: 5,
dynamic_channel_operations: 2,
paired_renderer_transmissions: 4,
ambiguous_renderer_transmissions: 1,
unpaired_literal_renderer_transmissions: 1,
},
sender_validation_observations: 2,
utility_processes: 1,
resolved_utility_entrypoints: 1,
native_addon_bindings: 4,
resolved_native_addon_bindings: 4,
});
expect(graph.nodes.map(({ kind }) => kind)).toEqual(
expect.arrayContaining([
"browser-window",
"electron-preload",
"context-bridge-api",
"ipc-channel",
"ipc-handler",
"electron-utility",
"native-addon",
"native-export",
]),
);
expect(graph.nodes).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "browser-window",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
preload_path: "preload.js",
absence_means_default: false,
web_preferences: expect.arrayContaining([
expect.objectContaining({
name: "nodeIntegration",
value: expect.objectContaining({
status: "literal",
value: true,
}),
}),
]),
}),
}),
]),
}),
expect.objectContaining({
kind: "browser-window",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
web_preferences: expect.arrayContaining([
expect.objectContaining({
name: "nodeIntegration",
value: expect.objectContaining({
status: "literal",
value: false,
}),
}),
expect.objectContaining({
name: "contextIsolation",
value: expect.objectContaining({
status: "literal",
value: true,
}),
}),
]),
}),
}),
]),
}),
expect.objectContaining({
kind: "context-bridge-api",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
api_key: "reaApi",
members: expect.arrayContaining([
"nested",
"nested.write",
"read",
]),
}),
}),
]),
}),
expect.objectContaining({
kind: "ipc-handler",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
fact_kind: "sender-validation-candidate",
enforcement: "unknown",
}),
}),
]),
}),
expect.objectContaining({
kind: "native-export",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
native_export_verification: "not-performed",
}),
}),
]),
}),
]),
);
const pairingEdges = graph.edges.filter(
({ properties }) =>
properties.pairing_basis === "unique-exact-literal-channel",
);
expect(pairingEdges).toHaveLength(4);
expect(
pairingEdges.some(
({ properties }) => properties.channel === "rea:ambiguous",
),
).toBe(false);
expect(graph.limitations.join(" ")).toMatch(/dynamic IPC|ambiguous/iu);
});
it("returns Evidence v2 only after exact investigation-input authorization", async () => {
const root = await fixtureDirectory();
const authority = permissionAuthority(root);
const result = await analyzeJavaScriptApplication(authority, {
input_path: root,
approved: true,
});
if (!result.ok) throw result.error;
const evidence = parseEvidence(result.value);
expect(evidence).toMatchObject({
operation: "analyze_javascript_application",
predicate_type: "rea.javascript-application-analysis/v1",
provider: { id: "rea-javascript-application" },
authority: "shipped-artifact",
confidence: "derived",
subject: { local_path: root, format: "directory" },
normalized_result: {
schema_version: 1,
input_path: root,
summary: { browser_windows: 3 },
},
});
const denied = await analyzeJavaScriptApplication(
permissionAuthority(root),
{
input_path: join(root, ".."),
approved: true,
},
);
expect(denied).toMatchObject({
ok: false,
error: { _tag: "PermissionRequiredError" },
});
});
it("returns a tagged cancellation without executing application code", async () => {
const root = await fixtureDirectory();
const controller = new AbortController();
controller.abort();
Reflect.deleteProperty(globalThis, "__rea_electron_fixture_executed");
const result = await analyzeJavaScriptApplication(
permissionAuthority(root),
{ input_path: root, approved: true },
{ signal: controller.signal },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "cancelled" },
});
expect(
Reflect.get(globalThis, "__rea_electron_fixture_executed"),
).toBeUndefined();
});
});
const fixtureDirectory = async (): Promise<string> => {
const root = await mkdtemp(join(tmpdir(), "rea-electron-boundaries-"));
await writeElectronBoundaryFixture(root);
return root;
};
const permissionAuthority = (root: string): PermissionAuthority =>
new PermissionAuthority(
createPermissionPolicy(
[scope(root)],
[
{
...scope(root),
grant_id: "test:investigation-input",
lifetime: "session",
operation_identity: null,
expires_at: null,
},
],
),
);
const scope = (root: string) => ({
capability: "investigation_input" as const,
roots: [root],
executables: [],
environment_names: [],
network: "none" as const,
mount: false,
});
+33
View File
@@ -11,6 +11,7 @@ import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "./fixtures/fakeCdpBrowser.js";
import { writeElectronBoundaryFixture } from "./fixtures/electronBoundaryApplication.js";
const execute = promisify(execFile);
const INTEGRATION_TEST_TIMEOUT_MS = 20_000;
@@ -82,6 +83,38 @@ describe("Electron CLI parity", () => {
},
INTEGRATION_TEST_TIMEOUT_MS,
);
it(
"returns the static JavaScript application Evidence contract",
async () => {
const root = await mkdtemp(join(tmpdir(), "rea-electron-static-cli-"));
temporary.push(root);
await writeElectronBoundaryFixture(root);
const environment = {
...process.env,
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
};
const analyzed = await runCli(
["analyze-javascript-application", root, "--approved", "--json"],
environment,
);
expect(analyzed).toMatchObject({
operation: "analyze_javascript_application",
provider: { id: "rea-javascript-application" },
normalized_result: {
input_path: root,
summary: {
browser_windows: 3,
context_bridge_apis: 2,
ipc: { paired_renderer_transmissions: 4 },
},
},
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
});
const runCli = async (
+54
View File
@@ -16,6 +16,7 @@ import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "./fixtures/fakeCdpBrowser.js";
import { writeElectronBoundaryFixture } from "./fixtures/electronBoundaryApplication.js";
describe("Electron MCP tools", () => {
const browsers: FakeCdpBrowser[] = [];
@@ -128,4 +129,57 @@ describe("Electron MCP tools", () => {
});
expect(browser.commands).toHaveLength(commandsBeforeDenial);
});
it("exposes the target-free static JavaScript application workflow", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-electron-static-mcp-"));
temporary.push(root);
await writeElectronBoundaryFixture(root);
const config = parseConfig({
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) throw authority.error;
const session = new BinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
permissionAuthority: authority.value,
availabilityPolicy: () => ({
processCaptureEnabled: false,
evidenceFileRoots: 0,
}),
});
const client = new Client({
name: "electron-static-mcp-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const analyzed = await client.callTool({
name: "analyze_javascript_application",
arguments: { input_path: root, approved: true },
});
expect(analyzed.isError).not.toBe(true);
expect(analyzed.structuredContent).toMatchObject({
operation: "analyze_javascript_application",
provider: { id: "rea-javascript-application" },
normalized_result: {
schema_version: 1,
input_path: root,
summary: {
browser_windows: 3,
context_bridge_apis: 2,
ipc: { paired_renderer_transmissions: 4 },
},
graph: { schema: "JavaScriptApplicationGraph", schema_version: 1 },
},
});
});
});
+107
View File
@@ -0,0 +1,107 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
/** Write a source-owned Electron boundary fixture; none of its code is executed. */
export const writeElectronBoundaryFixture = async (
root: string,
): Promise<void> => {
await Promise.all([
mkdir(join(root, "renderer"), { recursive: true }),
mkdir(join(root, "utility"), { recursive: true }),
mkdir(join(root, "native"), { recursive: true }),
]);
await Promise.all([
writeFile(
join(root, "package.json"),
JSON.stringify({
name: "rea-electron-boundary-fixture",
version: "1.0.0",
main: "main.js",
renderer: "renderer/index.html",
}),
),
writeFile(join(root, "main.js"), MAIN_SOURCE),
writeFile(join(root, "preload.js"), PRELOAD_SOURCE),
writeFile(join(root, "renderer", "renderer.js"), RENDERER_SOURCE),
writeFile(
join(root, "renderer", "index.html"),
"<script src='./renderer.js'></script>",
),
writeFile(join(root, "utility", "worker.js"), UTILITY_SOURCE),
writeFile(join(root, "native", "addon.node"), Buffer.from([0, 1, 2, 3])),
]);
};
const MAIN_SOURCE = String.raw`
const path = require("node:path");
const { BrowserWindow, ipcMain, utilityProcess } = require("electron");
const { read, write: nativeWrite } = require("./native/addon.node");
new BrowserWindow({
width: 900,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: true,
contextIsolation: false,
sandbox: false,
webSecurity: false,
},
});
new BrowserWindow({
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
},
});
new BrowserWindow(windowOptions);
ipcMain.handle("rea:read", async (event, key) => {
if (!event.senderFrame.url.startsWith("file://")) throw new Error("denied");
return read(key);
});
ipcMain.on("rea:write", (event, value) => {
if (event.sender.getURL() !== "file://fixture/index.html") return;
nativeWrite(value);
});
ipcMain.handle("rea:ambiguous", async () => 1);
ipcMain.handle("rea:ambiguous", async () => 2);
ipcMain.handle(dynamicChannel, dynamicHandler);
utilityProcess.fork("./utility/worker.js", [], { serviceName: "fixture-db" });
module.exports.nativeRead = require("./native/addon.node").read;
globalThis.__rea_electron_fixture_executed = true;
throw new Error("Electron boundary fixture must never execute");
`;
const PRELOAD_SOURCE = String.raw`
const { contextBridge, ipcRenderer } = require("electron");
const { read, write } = require("./native/addon.node");
contextBridge.exposeInMainWorld("reaApi", {
read: (key) => ipcRenderer.invoke("rea:read", key),
nested: {
write: (value) => ipcRenderer.send("rea:write", value),
},
nativeRead: read,
nativeWrite: write,
});
contextBridge.exposeInMainWorld(dynamicApiKey, dynamicApi);
ipcRenderer.on("rea:event", (_event, value) => console.log(value));
ipcRenderer.invoke("rea:ambiguous");
ipcRenderer.invoke("rea:missing");
ipcRenderer.invoke(dynamicChannel);
`;
const RENDERER_SOURCE = String.raw`
const { ipcRenderer } = require("electron");
ipcRenderer.invoke("rea:read", "renderer-key");
ipcRenderer.send("rea:write", "renderer-value");
ipcRenderer.on("rea:event", (_event, value) => console.log(value));
`;
const UTILITY_SOURCE = String.raw`
const addon = require("../native/addon.node");
module.exports = addon;
`;
+2 -2
View File
@@ -131,7 +131,7 @@ describe("full MCP integration with multi-tool sequences", () => {
});
});
it("preserves the complete 78-tool inventory with a session", async () => {
it("preserves the complete 79-tool inventory with a session", async () => {
const session = new BinarySession(
(_path) =>
({
@@ -154,7 +154,7 @@ describe("full MCP integration with multi-tool sequences", () => {
await client.connect(clientTransport);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(78);
expect(listed.tools).toHaveLength(79);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("open_binary");
expect(names).toContain("close_binary");
+16 -2
View File
@@ -7,7 +7,10 @@ import { afterEach, describe, expect, it } from "vitest";
import { z } from "zod";
import { SUPPORTED_CLIENT_DEFINITIONS } from "../src/application/SupportedClients.js";
import { ARTIFACT_GRAPH_PROVIDER } from "../src/application/InvestigationProviders.js";
import {
ARTIFACT_GRAPH_PROVIDER,
JAVASCRIPT_APPLICATION_PROVIDER,
} from "../src/application/InvestigationProviders.js";
import { CDP_BROWSER_PROVIDER_IDENTITY } from "../src/browser/CdpBrowserProvider.js";
import { CDP_ELECTRON_PROVIDER_IDENTITY } from "../src/browser/CdpElectronProvider.js";
import { CLI_COMMAND_NAMES } from "../src/cliCommandNames.js";
@@ -66,6 +69,7 @@ describe("canonical product catalog", () => {
ARTIFACT_GRAPH_PROVIDER,
CDP_BROWSER_PROVIDER_IDENTITY,
CDP_ELECTRON_PROVIDER_IDENTITY,
JAVASCRIPT_APPLICATION_PROVIDER,
]
.map(({ id }) => id)
.sort(),
@@ -78,6 +82,16 @@ describe("canonical product catalog", () => {
catalog.providers.find(({ id }) => id === GHIDRA_PROVIDER_IDENTITY.id)
?.capabilities,
).toEqual(GHIDRA_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name).sort());
expect(
catalog.providers.find(
({ id }) => id === CDP_ELECTRON_PROVIDER_IDENTITY.id,
)?.capabilities,
).toEqual(["inspect_electron_page", "list_electron_targets"]);
expect(
catalog.providers.find(
({ id }) => id === JAVASCRIPT_APPLICATION_PROVIDER.id,
)?.capabilities,
).toEqual(["analyze_javascript_application"]);
expect(
z.toJSONSchema(analysisSnapshotSchema).properties?.snapshot_version,
).toMatchObject({
@@ -147,7 +161,7 @@ describe("canonical product catalog", () => {
),
};
const issues = await documentationFactIssues(root, drifted);
expect(issues.some((issue) => issue.includes("79-tool"))).toBe(true);
expect(issues.some((issue) => issue.includes("80-tool"))).toBe(true);
expect(issues.some((issue) => issue.includes("Future Client"))).toBe(true);
expect(issues.some((issue) => issue.includes("Process Capture v5"))).toBe(
true,
+1 -1
View File
@@ -54,7 +54,7 @@ describe("guided prompts over MCP", () => {
),
);
}
expect((await client.listTools()).tools).toHaveLength(78);
expect((await client.listTools()).tools).toHaveLength(79);
const result = await client.getPrompt({
name: "investigate_feature",
arguments: {
+3 -3
View File
@@ -10,7 +10,7 @@ const fixturePath = fileURLToPath(
);
describe("production stdio runtime", () => {
it("starts the built entrypoint, lists 78 tools, calls one, and shuts down", async () => {
it("starts the built entrypoint, lists 79 tools, calls one, and shuts down", async () => {
const transport = new StdioClientTransport({
command: process.execPath,
args: [mainPath],
@@ -32,7 +32,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
const tools = await client.listTools();
expect(tools.tools).toHaveLength(78);
expect(tools.tools).toHaveLength(79);
const result = await client.callTool({
name: "current_document",
arguments: {},
@@ -78,7 +78,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
expect((await client.listTools()).tools).toHaveLength(78);
expect((await client.listTools()).tools).toHaveLength(79);
} finally {
await client.close();
await transport.close();
+5 -5
View File
@@ -24,11 +24,11 @@ describe("server and catalog identity", () => {
});
expect(PRODUCT_IDENTITY.packageVersion).toBe(packageJson.version);
expect(SDK_IDENTITY.server).toBe("2.0.0-beta.4");
expect(CLI_COMMAND_NAMES).toHaveLength(38);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(38);
expect(CLI_COMMAND_NAMES).toHaveLength(39);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(39);
expect(CATALOG_IDENTITY.counts).toEqual({
cli_commands: 38,
mcp_tools: 78,
cli_commands: 39,
mcp_tools: 79,
mcp_prompts: 6,
mcp_resources: 2,
mcp_resource_templates: 7,
@@ -162,7 +162,7 @@ describe("server and catalog identity", () => {
expect(status.structuredContent).toMatchObject({
result: {
server_identity: {
catalog: { counts: { mcp_tools: 78, cli_commands: 38 } },
catalog: { counts: { mcp_tools: 79, cli_commands: 39 } },
alignment: { state: "mcp_server_restart_required" },
},
tool_availability: expect.arrayContaining([
+1 -1
View File
@@ -142,7 +142,7 @@ describe("target-free MCP lifecycle", () => {
expect(text(before)).toBe(
"No app is open. Ask the user which app to investigate, then call open_binary with its local path.",
);
expect((await mcp.listTools()).tools).toHaveLength(78);
expect((await mcp.listTools()).tools).toHaveLength(79);
const deniedCapture = await mcp.callTool({
name: "capture_process_scenario",
arguments: {
+1 -1
View File
@@ -31,7 +31,7 @@ describe("canonical skill transaction", () => {
expect(await readFile(`${destination}.rea.backup`, "utf8")).toBe(
"stale managed skill\n",
);
expect(await readFile(destination, "utf8")).toContain('version: "14"');
expect(await readFile(destination, "utf8")).toContain('version: "15"');
expect(await readFile(destination, "utf8")).toContain(
`tool_count: ${String(TOOL_CONTRACTS.length)}`,
);
+4 -3
View File
@@ -12,7 +12,7 @@ import { BROWSER_TOOL_CONTRACTS } from "../src/contracts/browserToolContracts.js
import { ELECTRON_TOOL_CONTRACTS } from "../src/contracts/electronToolContracts.js";
describe("tool contract inventory", () => {
it("publishes 60 analysis contracts and eighteen session tools", () => {
it("publishes 61 analysis contracts and eighteen session tools", () => {
expect(OFFICIAL_TOOL_CONTRACTS).toHaveLength(33);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(10);
expect(NATIVE_TOOL_CONTRACTS).toHaveLength(5);
@@ -30,6 +30,7 @@ describe("tool contract inventory", () => {
expect(ELECTRON_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"list_electron_targets",
"inspect_electron_page",
"analyze_javascript_application",
]);
expect(SESSION_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"open_binary",
@@ -51,8 +52,8 @@ describe("tool contract inventory", () => {
"update_unknown",
"verify_unknown_resolution",
]);
expect(TOOL_CONTRACTS).toHaveLength(78);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(78);
expect(TOOL_CONTRACTS).toHaveLength(79);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(79);
});
it("retains documented enhanced-tool limits at the input boundary", () => {