feat(electron): add autonomous Electron runtime analysis (#464)

* feat: add autonomous Electron runtime analysis

* feat(electron): add lifecycle and boundary telemetry

* feat(electron): capture runtime boundary evidence

* fix(electron): package boundary hook helper

* feat(electron): report active capture coverage

* fix(electron): account for bring-your-own runtime

* feat(electron): expand agent-owned runtime scenarios

* fix(ghidra): keep fixture credentials out of argv

* perf(test): serialize local test and docs workloads

* fix(electron): harden active runtime capture

* fix(inspector): require exact runtime target authorization

* fix(docs): make managed manifest host independent

* fix(ci): make generated catalog portable

* fix: unblock autonomous command and electron flows

* fix(electron): close popup and detached helper gaps
This commit is contained in:
morluto
2026-08-05 19:07:46 +08:00
committed by GitHub
parent 51559245d2
commit 8f229ede70
104 changed files with 5055 additions and 196 deletions
+26 -8
View File
@@ -41,6 +41,7 @@ export type AvailabilityPolicy = {
readonly browserObservationEnabled?: boolean;
readonly browserScenarioEnabled?: boolean;
readonly electronObservationEnabled?: boolean;
readonly electronAutomationEnabled?: boolean;
readonly v8InspectorObservationEnabled?: boolean;
readonly javascriptReplayEnabled?: boolean;
readonly managedRuntimeEnabled?: boolean;
@@ -283,14 +284,8 @@ const policyAvailability = ({
reason: "policy_disabled",
remediation: "Configure or grant an evidence_read root.",
};
if (kind === "electron-provider")
return policy.electronObservationEnabled === true
? { reason: "available", remediation: null }
: {
reason: "policy_disabled",
remediation:
"Enable Electron observation and configure a loopback CDP endpoint and canonical file roots.",
};
const electron = electronPolicyAvailability(name, kind, policy);
if (electron !== null) return electron;
if (kind === "runtime-provider")
return policy.v8InspectorObservationEnabled === true
? { reason: "available", remediation: null }
@@ -303,6 +298,29 @@ const policyAvailability = ({
return null;
};
const electronPolicyAvailability = (
name: string,
kind: ToolKind,
policy: AvailabilityPolicy,
): Availability | null => {
if (kind !== "electron-provider") return null;
if (name === "capture_electron_scenario")
return policy.electronAutomationEnabled === true
? { reason: "available", remediation: null }
: {
reason: "policy_disabled",
remediation:
"Enable active Electron automation and configure exact executable and application roots.",
};
return policy.electronObservationEnabled === true
? { reason: "available", remediation: null }
: {
reason: "policy_disabled",
remediation:
"Enable Electron observation and configure a loopback CDP endpoint and canonical file roots.",
};
};
const browserPolicyAvailability = (
name: string,
kind: ToolKind,
+81
View File
@@ -0,0 +1,81 @@
import type { ProviderIdentity } from "./AnalysisProvider.js";
import type { Evidence, EvidenceObservation } from "../domain/evidence.js";
import { createEvidence } from "../domain/evidence.js";
import type {
ElectronActiveObservationInput,
ElectronActiveObservationResult,
} from "../domain/electronActiveObservation.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { digestJson } from "./JavaScriptReplayPlanning.js";
/** Create Evidence v2 without retaining arbitrary runtime argument values. */
export const createElectronActiveEvidence = (
input: ElectronActiveObservationInput,
result: ElectronActiveObservationResult,
provider: ProviderIdentity,
): Evidence =>
createEvidence(undefined, provider, {
predicateType: "rea.electron-active-scenario/v1",
operation: "capture_electron_scenario",
parameters: parameters(input),
result: jsonValueSchema.parse(result),
confidence: "observed",
authority: "controlled-replay",
environment: {
id: `${result.application.electron_version}@${process.platform}`,
platform: process.platform,
architecture: process.arch,
isolation: "none",
},
limitations: result.limitations,
});
const scenarioProjection = (
input: ElectronActiveObservationInput,
): EvidenceObservation["parameters"] => ({
approved: input.approved,
schema_version: input.schema_version,
executable_path: input.executable_path,
application_path: input.application_path,
application_root: input.application_root,
args: redactArguments(input.args),
actions: input.actions.map(({ step_id, kind }) => ({ step_id, kind })),
limits: input.limits,
});
const parameters = (
input: ElectronActiveObservationInput,
): EvidenceObservation["parameters"] => ({
...scenarioProjection(input),
scenario_sha256: digestJson(scenarioProjection(input)),
});
const redactArguments = (arguments_: readonly string[]): string[] => {
let redactNext = false;
return arguments_.map((argument) => {
if (redactNext) {
redactNext = false;
return "<redacted>";
}
if (sensitiveFlag.test(argument)) {
redactNext = true;
return argument;
}
return redactArgument(argument);
});
};
const sensitiveFlag =
/^--?(?:password|token|secret|api[-_]?key|authorization|cookie)$/iu;
const redactArgument = (argument: string): string => {
if (
/^--?(?:password|token|secret|api[-_]?key|authorization|cookie)=/iu.test(
argument,
)
)
return `${argument.slice(0, argument.indexOf("=") + 1)}<redacted>`;
return argument.length > 256
? `${argument.slice(0, 256)}<redacted>`
: argument;
};
@@ -0,0 +1,16 @@
import type { ExecutionOptions, ProviderIdentity } from "./AnalysisProvider.js";
import type { AnalysisError } from "../domain/errors.js";
import type {
ElectronActiveObservationInput,
ElectronActiveObservationResult,
} from "../domain/electronActiveObservation.js";
import type { Result } from "../domain/result.js";
/** Provider-neutral boundary for owned Electron runtime experiments. */
export interface ElectronActiveObservationPort {
identity(): ProviderIdentity;
capture(
input: ElectronActiveObservationInput,
options?: ExecutionOptions,
): Promise<Result<ElectronActiveObservationResult, AnalysisError>>;
}
@@ -0,0 +1,132 @@
import { realpath } from "node:fs/promises";
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { ElectronActiveObservationPort } from "./ElectronActiveObservationPort.js";
import type { PermissionAuthority } from "./PermissionAuthority.js";
import { digestJson } from "./JavaScriptReplayPlanning.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisProtocolError,
PermissionRequiredError,
type AnalysisError,
} from "../domain/errors.js";
import type { Evidence } from "../domain/evidence.js";
import type { ElectronActiveObservationInput } from "../domain/electronActiveObservation.js";
import { isPathContained } from "../domain/permissionPolicy.js";
import { err, type Result } from "../domain/result.js";
import { createElectronActiveEvidence } from "./ElectronActiveEvidence.js";
const OPERATION = "capture_electron_scenario" as const;
const PROVIDER_ID = "rea-playwright-electron-active";
const canonicalizeInput = async (
input: ElectronActiveObservationInput,
): Promise<Result<ElectronActiveObservationInput, AnalysisError>> => {
try {
const [executablePath, applicationPath, applicationRoot] =
await Promise.all([
realpath(input.executable_path),
realpath(input.application_path),
realpath(input.application_root),
]);
if (!isPathContained(applicationRoot, applicationPath))
return err(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["application_path"],
reason: "invalid_value",
message:
"application_path must remain beneath application_root after symlink resolution",
},
]),
);
return {
ok: true,
value: {
...input,
executable_path: executablePath,
application_path: applicationPath,
application_root: applicationRoot,
},
};
} catch (cause: unknown) {
return err(
new AnalysisInputError(OPERATION, { cause }, [
{
path: ["application_path"],
reason: "invalid_format",
message:
"Electron executable, application, and root must resolve to existing paths",
},
]),
);
}
};
const authorize = async (
authority: PermissionAuthority | undefined,
input: ElectronActiveObservationInput,
): Promise<Result<ElectronActiveObservationInput, AnalysisError>> => {
const canonical = await canonicalizeInput(input);
if (!canonical.ok) return canonical;
if (authority === undefined)
return err(
new AnalysisCapabilityUnavailableError(
PROVIDER_ID,
OPERATION,
"active Electron observation permission policy is not configured",
),
);
const authorized = await authority.authorize(
{
capability: "electron_automate",
roots: [canonical.value.application_root],
executables: [canonical.value.executable_path],
environment_names: [],
network: "external",
mount: false,
operation_identity: `${OPERATION}:${digestJson(canonical.value)}`,
},
"write",
);
if (!authorized.ok)
return err(
authorized.error instanceof PermissionRequiredError
? authorized.error
: new AnalysisProtocolError(authorized.error.message, {
cause: authorized.error,
}),
);
return canonical;
};
/** Authorize and execute one bounded, provider-owned Electron experiment. */
export const captureElectronScenario = async (
provider: ElectronActiveObservationPort | undefined,
authority: PermissionAuthority | undefined,
input: ElectronActiveObservationInput,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const authorized = await authorize(authority, input);
if (!authorized.ok) return authorized;
if (provider === undefined)
return err(
new AnalysisCapabilityUnavailableError(
PROVIDER_ID,
OPERATION,
"active Electron observation provider is not configured",
),
);
const captured = await provider.capture(authorized.value, options);
return captured.ok
? {
ok: true,
value: createElectronActiveEvidence(
authorized.value,
captured.value,
provider.identity(),
),
}
: captured;
};
+9 -4
View File
@@ -333,10 +333,6 @@ const completeCapture = async (options: {
}
throw processCaptureCancelled();
}
if (runtime.reactive !== undefined) {
await runtime.reactive.coordinator.submit({ kind: "target_lost" });
runtime.reactive.unsubscribe();
}
const settlement = await observeSettlement(
options.runId,
selectCapturedProcessGroupIds(runtime.terminal.pid, options.samples),
@@ -345,6 +341,15 @@ const completeCapture = async (options: {
);
runtime.checkpoints.trigger("settled");
const samplingPartial = (await runtime.stopSampler()).partial;
if (runtime.reactive !== undefined) {
// Process, filesystem, shim, and protocol observations can be recorded
// during settlement after the PTY exits. Make target loss terminal only
// after that journal has drained, otherwise the coordinator's control
// priority discards a valid multi-source completion predicate.
await runtime.reactive.coordinator.drain();
await runtime.reactive.coordinator.submit({ kind: "target_lost" });
runtime.reactive.unsubscribe();
}
assertNotCancelled(options.signal);
const after = await snapshotRoots(scenario, options.signal);
const renderedFrames = await runtime.renderer.frames();
+2 -1
View File
@@ -71,9 +71,10 @@ export const normalizeProcessSamples = (
"<no-temporary-root>",
rootPid,
);
return scenario.normalization.pids
const withNormalizedPids = scenario.normalization.pids
? normalizePidTokens(normalized, identifiers)
: normalized;
return withNormalizedPids.trim();
};
return samples.map((sample) => ({
at_ms: normalizeProcessElapsedTime(
@@ -25,6 +25,7 @@ const grantSchema = z.object({
"browser_observe",
"browser_automate",
"electron_observe",
"electron_automate",
"evidence_read",
"evidence_write",
"investigation_input",
+13 -8
View File
@@ -3,16 +3,19 @@ import { mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
windowsNativeCapabilities,
type WindowsNativeCapabilitySet,
} from "../process/WindowsAuthority.js";
import {
probeProcessCaptureCapability,
type ProcessCaptureCapability,
} from "./ProcessCaptureCapability.js";
/** One named Windows host observation without inferred authority. */
interface WindowsCapabilityOutcome {
readonly available: boolean;
readonly reason: string | null;
}
export type WindowsCapabilityOutcome =
| { readonly available: true; readonly reason: null }
| { readonly available: false; readonly reason: string };
/** Injectable host probes used by CI and deterministic unit tests. */
export interface WindowsCapabilityDependencies {
@@ -36,6 +39,8 @@ export interface WindowsCapabilityReport {
unix_domain_socket: WindowsCapabilityOutcome;
pty: WindowsCapabilityOutcome;
}>;
/** Security controls that are unavailable until native authority exists. */
readonly security: WindowsNativeCapabilitySet;
}
/** Probe named prerequisites without converting missing controls into support. */
@@ -54,11 +59,11 @@ export const probeWindowsCapabilities = async (
no_follow_open: dependencies.probeNoFollowOpen(),
private_acl: dependencies.probePrivateAcl(),
unix_domain_socket: dependencies.probeUnixDomainSocket(),
pty: {
available: pty.available,
reason: pty.available ? null : pty.reason,
},
pty: pty.available
? { available: true, reason: null }
: { available: false, reason: pty.reason },
},
security: windowsNativeCapabilities(dependencies.platform),
};
};
+11
View File
@@ -58,3 +58,14 @@ export const authorizeRuntimeLocation = async (
},
};
};
/** Authorize a target whose Node Inspector URL omits its main entry path. */
export const authorizeRuntimeTargetLocation = async (
value: string,
targetType: string,
roots: readonly string[],
origins: readonly string[],
): Promise<RuntimeLocationDecision> =>
// A bare file:// URL contains no source identity. Do not attach to the
// first configured root merely because the target happens to be Node.
authorizeRuntimeLocation(value, roots, origins);
@@ -0,0 +1,489 @@
import type { ElectronApplication, Page } from "playwright-core";
import { z } from "zod";
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
import { BrowserObservationError } from "../domain/errors.js";
import { redactSensitiveText } from "./SensitiveTextCapture.js";
import type {
ElectronActiveObservationInput,
ElectronActiveObservationResult,
} from "../domain/electronActiveObservation.js";
const OPERATION = "capture_electron_scenario" as const;
const hookEventSchema = z.strictObject({
sequence: z.number().int().min(1),
correlation_id: z.string().max(256).nullable(),
kind: z.enum([
"main-handler-invocation",
"main-event-invocation",
"utility-process-fork",
"utility-process-message",
"ipc-main-to-renderer",
"ipc-utility-to-main",
"ipc-renderer-send",
"ipc-renderer-invoke",
"ipc-renderer-post-message",
"app-lifecycle",
"window-lifecycle",
"web-contents-lifecycle",
"navigation",
"shell-attempt",
"process-lifecycle",
"permission",
"popup-attempt",
"download",
"protocol",
"preload",
"native-addon",
"updater",
"error",
]),
event: z.string().max(128).nullable(),
phase: z.enum(["attempted", "completed", "blocked", "failed", "observed"]),
channel: z.string().max(1_024).nullable(),
channel_truncated: z.boolean().default(false),
direction: z
.enum([
"renderer-to-main",
"main-to-renderer",
"main-to-utility",
"utility-to-main",
])
.nullable(),
sender: z.string().max(256).nullable(),
receiver: z.string().max(256).nullable(),
frame: z.string().max(256).nullable(),
target: z.string().max(256).nullable(),
argument_shapes: z.array(z.string().max(64)).max(32),
argument_shapes_truncated: z.boolean().default(false),
result_shape: z.string().max(64).nullable(),
process_type: z.string().max(128).nullable(),
source: z.string().max(64),
capture_method: z.enum(["api-wrapper", "event-emitter", "process-hook"]),
artifact_path: z.string().max(16_384).nullable(),
artifact_sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
error: z.boolean(),
});
const hookSnapshotSchema = z.strictObject({
events: z.array(hookEventSchema).max(20_000),
observed: z.number().int().min(0),
observed_ipc: z.number().int().min(0),
observed_runtime: z.number().int().min(0),
truncated: z.boolean(),
hook_error: z.boolean(),
});
const metricSchema = z.strictObject({
pid: z.number().int().min(1),
type: z.string().min(1).max(128),
name: z.string().max(256).nullable(),
service_name: z.string().max(256).nullable(),
});
const windowMetadataSchema = z.strictObject({
window_id: z.string().max(256),
web_contents_id: z.string().max(256),
visible: z.boolean().nullable(),
destroyed: z.boolean(),
});
type ElectronAction = ElectronActiveObservationInput["actions"][number];
type ElectronActions = ElectronActiveObservationResult["actions"];
export type ElectronHookSnapshot = z.infer<typeof hookSnapshotSchema>;
export type ElectronHookEvent = z.infer<typeof hookEventSchema>;
export type ElectronMetrics = z.infer<typeof metricSchema>[];
type ElectronWindowMetadata = z.infer<typeof windowMetadataSchema>;
type ElectronPageSnapshot = {
readonly index: number;
readonly url: string;
readonly title: string;
};
/** Run bounded, explicit actions against provider-owned Electron windows. */
export const runElectronActions = async (
application: ElectronApplication,
input: ElectronActiveObservationInput,
options: ExecutionOptions,
deadline: number,
): Promise<ElectronActions> => {
const actions: ElectronActions = [];
for (const action of input.actions) {
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const actionStartedAt = Date.now();
const windowIndex = actionWindowIndex(action);
let selectedWindow: Page | undefined;
try {
const remaining = deadline - Date.now();
if (remaining <= 0)
throw new BrowserObservationError(OPERATION, "timeout");
selectedWindow =
windowIndex === null
? undefined
: await waitForWindow({
application,
windowIndex,
timeout: input.limits.action_timeout_ms,
signal: options.signal,
deadline,
});
if (
(action.kind === "click" ||
action.kind === "renderer-reload" ||
action.kind === "renderer-crash") &&
selectedWindow === undefined
)
throw new BrowserObservationError(OPERATION, "window_not_found");
await runAction({
application,
action,
selectedWindow,
remaining,
actionTimeoutMs: input.limits.action_timeout_ms,
options,
deadline,
});
actions.push({
step_id: action.step_id,
kind: action.kind,
window_index: windowIndex,
target:
selectedWindow === undefined ? null : `window:${String(windowIndex)}`,
status: "completed",
elapsed_ms: Date.now() - actionStartedAt,
error: null,
});
} catch (cause: unknown) {
actions.push({
step_id: action.step_id,
kind: action.kind,
window_index: windowIndex,
target:
selectedWindow === undefined ? null : `window:${String(windowIndex)}`,
status: options.signal?.aborted ? "cancelled" : "failed",
elapsed_ms: Date.now() - actionStartedAt,
error: safeActionErrorMessage(cause, action),
});
break;
}
}
return actions;
};
type RunActionContext = {
readonly application: ElectronApplication;
readonly action: ElectronAction;
readonly selectedWindow: Page | undefined;
readonly remaining: number;
readonly actionTimeoutMs: number;
readonly options: ExecutionOptions;
readonly deadline: number;
};
const runAction = async ({
application,
action,
selectedWindow,
remaining,
actionTimeoutMs,
options,
deadline,
}: RunActionContext): Promise<void> => {
switch (action.kind) {
case "click":
if (selectedWindow === undefined)
throw new BrowserObservationError(OPERATION, "window_not_found");
await runWithExecutionLimits(
selectedWindow.locator(action.selector).click({
timeout: Math.min(actionTimeoutMs, remaining),
}),
options.signal,
deadline,
);
return;
case "wait": {
const page =
selectedWindow ??
(await application.firstWindow({
timeout: Math.min(actionTimeoutMs, remaining),
}));
await runWithExecutionLimits(
page.waitForTimeout(Math.min(action.duration_ms, remaining)),
options.signal,
deadline,
);
if (action.duration_ms > remaining)
throw new BrowserObservationError(OPERATION, "timeout");
return;
}
case "renderer-reload":
if (selectedWindow === undefined)
throw new BrowserObservationError(OPERATION, "window_not_found");
await runWithExecutionLimits(
selectedWindow.reload({
timeout: Math.min(actionTimeoutMs, remaining),
}),
options.signal,
deadline,
);
return;
case "renderer-crash": {
const crashed = await runWithExecutionLimits(
application.evaluate(({ BrowserWindow }, index) => {
const candidate = BrowserWindow.getAllWindows()[index];
if (candidate === undefined || candidate.isDestroyed()) return false;
candidate.webContents.forcefullyCrashRenderer();
return true;
}, action.window_index),
options.signal,
deadline,
);
if (!crashed)
throw new BrowserObservationError(OPERATION, "window_not_found");
return;
}
case "deep-link":
await runWithExecutionLimits(
emitDeepLink(application, action),
options.signal,
deadline,
);
return;
}
};
const actionWindowIndex = (action: ElectronAction): number | null => {
switch (action.kind) {
case "click":
case "renderer-reload":
case "renderer-crash":
return action.window_index;
case "wait":
return action.window_index ?? null;
case "deep-link":
return null;
}
};
type WaitForWindowContext = {
readonly application: ElectronApplication;
readonly windowIndex: number;
readonly timeout: number;
readonly signal: AbortSignal | undefined;
readonly deadline: number;
};
const waitForWindow = async ({
application,
windowIndex,
timeout,
signal,
deadline,
}: WaitForWindowContext): Promise<Page> => {
const stopAt = Math.min(deadline, Date.now() + timeout);
while (Date.now() < stopAt) {
if (signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const window = application.windows()[windowIndex];
if (window !== undefined) return window;
await runWithExecutionLimits(
new Promise<void>((resolve) => setTimeout(resolve, 25)),
signal,
stopAt,
);
}
throw new BrowserObservationError(OPERATION, "window_not_found");
};
const emitDeepLink = (
application: ElectronApplication,
action: Extract<ElectronAction, { kind: "deep-link" }>,
): Promise<boolean> =>
application.evaluate(
({ app }, payload) => {
if (payload.delivery === "open-url")
return app.emit(
"open-url",
{ preventDefault: () => undefined },
payload.url,
);
return app.emit("second-instance", {}, [payload.url], "", {});
},
{ delivery: action.delivery, url: action.url },
);
/** Read the current Electron windows, metrics, and bounded hook snapshot. */
// oxlint-disable-next-line max-lines-per-function -- one state read must share one capture boundary.
export const readApplicationState = async (
application: ElectronApplication,
maxWindows: number,
): Promise<{
readonly windows: ReadonlyArray<{
readonly window_id: string;
readonly web_contents_id: string;
readonly url: string;
readonly title: string;
readonly visible: boolean | null;
readonly destroyed: boolean;
}>;
readonly windowsTruncated: boolean;
readonly metrics: ElectronMetrics;
readonly electronVersion: string;
readonly hookSnapshot: ElectronHookSnapshot;
}> => {
const pages = application.windows();
const pageSnapshotsPromise: Promise<ElectronPageSnapshot[]> = Promise.all(
pages.slice(0, maxWindows).map(
async (page: Page, index): Promise<ElectronPageSnapshot> => ({
index,
url: page.url().slice(0, 65_536),
title: (await page.title()).slice(0, 16_384),
}),
),
);
const windowMetadataPromise: Promise<ElectronWindowMetadata[]> = application
.evaluate(({ BrowserWindow }) =>
BrowserWindow.getAllWindows().map(
(window: {
readonly id: number;
readonly webContents: { readonly id: number };
isDestroyed(): boolean;
isVisible(): boolean;
}) => ({
window_id: `window:${String(window.id)}`,
web_contents_id: `webContents:${String(window.webContents.id)}`,
visible: window.isDestroyed() ? null : window.isVisible(),
destroyed: window.isDestroyed(),
}),
),
)
.then((value) => z.array(windowMetadataSchema).parse(value));
const processMetricsPromise: Promise<ElectronMetrics> = application
.evaluate(({ app }) =>
app
.getAppMetrics()
.map(
(metric: {
readonly pid: number;
readonly type: string;
readonly name?: string;
readonly serviceName?: string;
}) => ({
pid: metric.pid,
type: metric.type,
name: metric.name ?? null,
service_name: metric.serviceName ?? null,
}),
),
)
.then((value) => z.array(metricSchema).parse(value));
const electronVersionPromise: Promise<string> = application
.evaluate(() => process.versions.electron)
.then((value) => z.string().parse(value));
const hookSnapshotPromise: Promise<ElectronHookSnapshot> = application
.evaluate(() => {
const candidate = Reflect.get(globalThis, "__reaElectronActiveSnapshot");
return typeof candidate === "function"
? candidate()
: {
events: [],
observed: 0,
observed_ipc: 0,
observed_runtime: 0,
truncated: false,
hook_error: true,
};
})
.then((value) => hookSnapshotSchema.parse(value));
const [
pageSnapshots,
windowMetadata,
processMetrics,
electronVersion,
hookSnapshot,
] = await Promise.all([
pageSnapshotsPromise,
windowMetadataPromise,
processMetricsPromise,
electronVersionPromise,
hookSnapshotPromise,
]);
return {
windows: pageSnapshots.map((page) => {
const metadata = windowMetadata[page.index];
if (metadata === undefined)
throw new BrowserObservationError(OPERATION, "window_metadata_missing");
return {
window_id: metadata.window_id,
web_contents_id: metadata.web_contents_id,
url: page.url,
title: page.title,
visible: metadata.visible,
destroyed: metadata.destroyed,
};
}),
windowsTruncated: pages.length > maxWindows,
metrics: processMetrics,
electronVersion,
hookSnapshot,
};
};
/** Apply a deadline and caller cancellation to one Playwright operation. */
export const runWithExecutionLimits = async <Value>(
operation: Promise<Value>,
signal: AbortSignal | undefined,
deadline: number,
): Promise<Value> => {
if (signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
let timer: ReturnType<typeof setTimeout> | undefined;
let abortListener: (() => void) | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new BrowserObservationError(OPERATION, "timeout")),
Math.max(1, deadline - Date.now()),
);
});
const cancellation =
signal === undefined
? timeout
: Promise.race([
timeout,
new Promise<never>((_, reject) => {
abortListener = () =>
reject(new BrowserObservationError(OPERATION, "cancelled"));
signal.addEventListener("abort", abortListener, { once: true });
}),
]);
try {
return await Promise.race([operation, cancellation]);
} finally {
if (timer !== undefined) clearTimeout(timer);
if (abortListener !== undefined)
signal?.removeEventListener("abort", abortListener);
}
};
const safeActionErrorMessage = (
cause: unknown,
action: ElectronAction,
): string => {
let message =
cause instanceof Error ? cause.message : "Electron action failed";
const inputValues = Object.values(action)
.filter(
(value): value is string => typeof value === "string" && value.length > 0,
)
.sort((left, right) => right.length - left.length);
for (const value of inputValues)
message = message.split(value).join("<redacted-input>");
return redactSensitiveText(message).slice(0, 1_024);
};
@@ -0,0 +1,432 @@
import { realpath } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { fileURLToPath } from "node:url";
import { _electron as electron } from "playwright-core";
import type {
ExecutionOptions,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import type { ElectronActiveObservationPort } from "../application/ElectronActiveObservationPort.js";
import {
electronActiveObservationResultSchema,
type ElectronActiveObservationInput,
type ElectronActiveObservationResult,
} from "../domain/electronActiveObservation.js";
import {
AnalysisError,
BrowserObservationError,
ProviderAdapterError,
} from "../domain/errors.js";
import { isPathContained } from "../domain/permissionPolicy.js";
import { err, ok, type Result } from "../domain/result.js";
import {
cleanupOwnedProcessGroup,
cleanupWindowsProcessTree,
observeOwnedProcessLineage,
selectCapturedProcessGroupIds,
verifyNoTokenOwnedProcesses,
type OwnedProcessGroup,
type ProcessCleanupResult,
type ProcessLineageObservation,
} from "../process/ProcessOwnership.js";
import {
runElectronActions,
readApplicationState,
runWithExecutionLimits,
type ElectronHookEvent,
type ElectronHookSnapshot,
type ElectronMetrics,
} from "./PlaywrightElectronActiveActions.js";
const OPERATION = "capture_electron_scenario" as const;
/** Public identity for provider-owned Electron runtime experiments. */
export const PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY: ProviderIdentity =
Object.freeze({
id: "rea-playwright-electron-active",
name: "REA Playwright active Electron observation provider",
version: "1",
});
const hookPath = fileURLToPath(
new URL("../../scripts/electron-active-hook.cjs", import.meta.url),
);
type ElectronApplication = Awaited<ReturnType<typeof electron.launch>>;
type ElectronPaths = {
readonly executable: string;
readonly application: string;
readonly root: string;
};
const observableEventFamilies = [
"app-lifecycle",
"window-lifecycle",
"web-contents-lifecycle",
"navigation",
"shell-attempt",
"process-lifecycle",
"permission",
"popup-attempt",
"download",
"protocol",
"preload",
"preload-configuration",
"renderer-ipc",
"native-addon",
"updater",
"error",
"ipc",
] as const;
const ipcEventKinds = new Set<ElectronHookEvent["kind"]>([
"main-handler-invocation",
"main-event-invocation",
"utility-process-fork",
"utility-process-message",
"ipc-main-to-renderer",
"ipc-utility-to-main",
"ipc-renderer-send",
"ipc-renderer-invoke",
"ipc-renderer-post-message",
]);
const createCoverage = (hookSnapshot: ElectronHookSnapshot) => {
const observedEventFamilies: string[] = [
...new Set(
hookSnapshot.events.map(({ kind, process_type }) => {
if (kind === "preload" && process_type === "main")
return "preload-configuration";
if (kind.startsWith("ipc-renderer") && process_type !== "renderer")
return "ipc";
return ipcEventKinds.has(kind) ? "ipc" : kind;
}),
),
].sort();
const unavailableEventFamilies = new Set(
observableEventFamilies.filter(
(family) => !observedEventFamilies.includes(family),
),
);
const observedRoles = [
...new Set(
hookSnapshot.events.flatMap(({ process_type, kind }) => [
...(process_type === null ? [] : [process_type]),
...(kind === "window-lifecycle" ? ["window"] : []),
...(kind === "web-contents-lifecycle" || kind === "navigation"
? ["web_contents"]
: []),
...(kind === "preload" && process_type === "preload"
? ["preload"]
: []),
...(kind.startsWith("ipc-renderer") && process_type === "renderer"
? ["renderer"]
: []),
]),
),
].sort();
const rendererContextObserved = hookSnapshot.events.some(
({ process_type }) =>
process_type === "renderer" || process_type === "preload",
);
if (!rendererContextObserved) {
unavailableEventFamilies.add("preload");
unavailableEventFamilies.add("renderer-ipc");
}
return {
status: hookSnapshot.hook_error
? "hook_conflict"
: hookSnapshot.truncated
? "capture_truncated"
: "partial_attach",
observed_event_families: observedEventFamilies,
unavailable_event_families: [...unavailableEventFamilies].sort(),
observed_roles: observedRoles,
pre_capture_activity: "unavailable",
} as const;
};
/** Launch an owned Electron application through the official Playwright API. */
export class PlaywrightElectronActiveProvider
implements ElectronActiveObservationPort
{
identity(): ProviderIdentity {
return PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY;
}
async capture(
input: ElectronActiveObservationInput,
options: ExecutionOptions = {},
): Promise<Result<ElectronActiveObservationResult, AnalysisError>> {
let application: ElectronApplication | undefined;
let ownership: OwnedProcessGroup | undefined;
let lineage: ProcessLineageObservation | undefined;
let outcome: Result<ElectronActiveObservationResult, AnalysisError>;
const runId = randomUUID();
try {
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const deadline = Date.now() + input.limits.max_duration_ms;
const paths = await canonicalPaths(input);
application = await electron.launch({
executablePath: paths.executable,
cwd: paths.root,
env: safeElectronEnvironment(
input.limits.max_ipc_events,
input.limits.max_runtime_events,
runId,
),
args: ["-r", hookPath, paths.application, ...input.args],
timeout: Math.max(1, deadline - Date.now()),
});
const leaderPid = application.process().pid;
if (
typeof leaderPid !== "number" ||
!Number.isSafeInteger(leaderPid) ||
leaderPid <= 0
)
throw new BrowserObservationError(
OPERATION,
"process_ownership_unavailable",
);
ownership = {
runId,
leaderPid,
processGroupId: leaderPid,
expectedParentPid: process.pid,
expectedCommand: paths.executable,
sweepTokenOwnedProcesses: true,
};
const actions = await runElectronActions(
application,
input,
options,
deadline,
);
const state = await runWithExecutionLimits(
readApplicationState(application, input.limits.max_windows),
options.signal,
deadline,
);
outcome = ok(createResult(paths, input, actions, state));
} catch (cause: unknown) {
outcome = err(providerError(cause));
}
if (application !== undefined) {
if (ownership !== undefined)
lineage = await observeOwnedProcessLineage(ownership);
let closeError: unknown;
try {
await runWithExecutionLimits(
application.close(),
undefined,
Date.now() + 5_000,
);
} catch (cause: unknown) {
closeError = cause;
}
const cleanup =
ownership === undefined
? ({
cleaned: false,
reason: "owned Electron process identity was unavailable",
} satisfies ProcessCleanupResult)
: await cleanupElectronProcesses(ownership, lineage);
if (!cleanup.cleaned)
return err(
providerError(
new BrowserObservationError(OPERATION, "cleanup_failed", {
cause: new Error(cleanup.reason),
}),
),
);
if (closeError !== undefined) return err(providerError(closeError));
}
return outcome;
}
}
const cleanupElectronProcesses = async (
ownership: OwnedProcessGroup,
lineage: ProcessLineageObservation | undefined,
): Promise<ProcessCleanupResult> => {
if (process.platform === "win32") {
const root = await cleanupWindowsProcessTree(ownership.leaderPid);
if (!root.cleaned) return root;
if (lineage?.status !== "verified")
return {
cleaned: false,
reason:
"owned Electron lineage was unavailable; helper cleanup was not proven",
};
for (const descendant of lineage.lineage.descendants) {
const result = await cleanupWindowsProcessTree(descendant.pid);
if (!result.cleaned) return result;
}
return root;
}
if (lineage?.status !== "verified") {
const root = await cleanupOwnedProcessGroup(ownership);
return root.cleaned
? {
cleaned: false,
reason:
"owned Electron lineage was unavailable; helper cleanup was not proven",
}
: root;
}
const groupIds = selectCapturedProcessGroupIds(
ownership.leaderPid,
lineage.lineage.descendants.map(({ pid, processGroupId }) => ({
pid,
process_group_id: processGroupId,
})),
);
let signaled = false;
for (const processGroupId of groupIds) {
const cleanupOwnership: OwnedProcessGroup =
processGroupId === ownership.processGroupId
? { ...ownership, leaderPid: processGroupId, processGroupId }
: {
runId: ownership.runId,
leaderPid: processGroupId,
processGroupId,
};
const result = await cleanupOwnedProcessGroup(cleanupOwnership);
if (!result.cleaned) return result;
signaled ||= result.signaled;
}
const remaining = await verifyNoTokenOwnedProcesses(ownership.runId);
if (!remaining.cleaned) return remaining;
return { cleaned: true, signaled };
};
const createResult = (
paths: ElectronPaths,
input: ElectronActiveObservationInput,
actions: ElectronActiveObservationResult["actions"],
state: {
readonly windows: ReadonlyArray<{
readonly window_id: string;
readonly web_contents_id: string;
readonly url: string;
readonly title: string;
readonly visible: boolean | null;
readonly destroyed: boolean;
}>;
readonly windowsTruncated: boolean;
readonly metrics: ElectronMetrics;
readonly electronVersion: string;
readonly hookSnapshot: ElectronHookSnapshot;
},
): ElectronActiveObservationResult => {
const { hookSnapshot } = state;
const ipcEvents = hookSnapshot.events.filter(({ kind }) =>
ipcEventKinds.has(kind),
);
return electronActiveObservationResultSchema.parse({
schema_version: 1,
application: {
executable_path: paths.executable,
application_path: paths.application,
electron_version: state.electronVersion,
process_ownership: "provider-owned",
cleanup: "terminated-owned-process",
},
actions,
windows: state.windows.slice(0, input.limits.max_windows),
windows_truncated: state.windowsTruncated,
processes: {
items: state.metrics.slice(0, input.limits.max_processes),
truncated: state.metrics.length > input.limits.max_processes,
},
ipc: {
events: ipcEvents.slice(0, input.limits.max_ipc_events),
observed: hookSnapshot.observed_ipc,
retained: Math.min(ipcEvents.length, input.limits.max_ipc_events),
truncated:
hookSnapshot.truncated ||
ipcEvents.length > input.limits.max_ipc_events,
},
timeline: {
events: hookSnapshot.events.slice(0, input.limits.max_runtime_events),
observed: hookSnapshot.observed,
retained: Math.min(
hookSnapshot.events.length,
input.limits.max_runtime_events,
),
truncated:
hookSnapshot.truncated ||
hookSnapshot.events.length > input.limits.max_runtime_events,
},
coverage: createCoverage(hookSnapshot),
limitations: [
"IPC payloads are represented only by bounded value shapes; values are never retained, channels are capped at 1,024 characters, and argument-shape arrays at 32 entries.",
"IPC direction and sender/receiver identifiers are observed only where Electron exposes them at the hooked boundary.",
"The runtime timeline records bounded lifecycle, navigation, shell, permission, popup, download, protocol, preload, native-addon, process, and IPC events; activity before hook installation is unavailable.",
"The preload and renderer process contexts are not instrumented by the main-process -r hook; preload configuration and contextBridge API-shape events are main-boundary observations, not proof of renderer-side execution.",
"Process metrics are an Electron API snapshot and do not prove hostile-local-user isolation.",
"External shell opens, external navigation, permission grants, downloads, popup windows, updater relaunches, and OS integration are blocked and recorded by the active hook; other application filesystem and network behavior is not sandboxed by this provider.",
...(state.windowsTruncated
? ["Windows beyond max_windows were not retained."]
: []),
...(hookSnapshot.hook_error
? ["The active IPC hook could not be installed."]
: []),
],
});
};
const canonicalPaths = async (
input: ElectronActiveObservationInput,
): Promise<ElectronPaths> => {
const [executable, application, root] = await Promise.all([
realpath(input.executable_path),
realpath(input.application_path),
realpath(input.application_root),
]);
if (!isPathContained(root, application))
throw new BrowserObservationError(OPERATION, "target_not_allowed");
return { executable, application, root };
};
const safeElectronEnvironment = (
maxIpcEvents: number,
maxRuntimeEvents: number,
runId: string,
): Record<string, string> =>
Object.fromEntries([
...[
"HOME",
"LANG",
"PATH",
"TMP",
"TMPDIR",
"USER",
"DISPLAY",
"WAYLAND_DISPLAY",
]
.map((name) => [name, process.env[name]] as const)
.filter(
(entry): entry is readonly [string, string] => entry[1] !== undefined,
),
["REA_ELECTRON_ACTIVE_MAX_IPC_EVENTS", String(maxIpcEvents)] as const,
[
"REA_ELECTRON_ACTIVE_MAX_RUNTIME_EVENTS",
String(maxRuntimeEvents),
] as const,
["REA_PROCESS_RUN_ID", runId] as const,
]);
const providerError = (cause: unknown): AnalysisError =>
cause instanceof AnalysisError
? cause
: new ProviderAdapterError(
PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY.id,
OPERATION,
{
cause,
},
);
+1 -1
View File
@@ -1,5 +1,5 @@
const SECRET_ASSIGNMENT =
/\b(authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret|cookie|session)\b\s*[:=]\s*(?:Bearer\s+[A-Za-z0-9._~+/=-]+|"[^"]*"|'[^']*'|[^\s,;]+)/giu;
/\b(authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|passwd|secret|cookie|session)\b\s*[:=]\s*(?:Bearer\s+[A-Za-z0-9._~+/=-]+|"[^"]*"|'[^']*'|[^\s,;]+)/giu;
const BEARER = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
const JWT = /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/gu;
@@ -30,6 +30,7 @@ export const describeInspectorTargetLimitations = (): string[] => [
"REA attaches to an already-running exact target and never launches, resumes, evaluates, pauses, or mutates it.",
"Only Runtime.enable and Debugger.enable are sent; source text, object values, EventEmitter activity, and Electron IPC are not inspected.",
"Target IDs and locations are authorized, but the Inspector protocol does not authenticate an operating-system process ID or Electron role.",
"Some Electron main targets report only file://; for those targets, the first approved file root is recorded as a scope fallback and script locations are authorized independently.",
"No runtime graph depth is traversed because passive Inspector events do not establish require/import caller edges.",
];
+5 -3
View File
@@ -27,7 +27,7 @@ import {
} from "./CdpCaptureValues.js";
import { CdpConnection, type CdpEvent } from "./CdpConnection.js";
import {
authorizeRuntimeLocation,
authorizeRuntimeTargetLocation,
canonicalRuntimeRoots,
} from "./JavaScriptRuntimeScope.js";
import {
@@ -95,8 +95,9 @@ export class V8InspectorProvider implements JavaScriptRuntimeObservationPort {
const allowed: AuthorizedV8InspectorTarget[] = [];
const excluded = createInspectorExclusionCounts();
for (const target of discovery.targets) {
const decision = await authorizeRuntimeLocation(
const decision = await authorizeRuntimeTargetLocation(
target.url,
target.type,
roots,
input.allowed_origins,
);
@@ -202,8 +203,9 @@ const authorizedTarget = async (
"observe_javascript_runtime",
"target_not_found",
);
const decision = await authorizeRuntimeLocation(
const decision = await authorizeRuntimeTargetLocation(
target.url,
target.type,
roots,
input.allowed_origins,
);
+1
View File
@@ -50,6 +50,7 @@ export const CLI_COMMANDS = Object.freeze({
captureBrowserScenario: "capture-browser-scenario",
listElectronTargets: "list-electron-targets",
inspectElectronPage: "inspect-electron-page",
captureElectronScenario: "capture-electron-scenario",
listJavaScriptRuntimeTargets: "list-javascript-runtime-targets",
observeJavaScriptRuntime: "observe-javascript-runtime",
analyzeJavaScriptApplication: "analyze-javascript-application",
+41
View File
@@ -4,15 +4,18 @@ import {
inspectElectronPage,
listElectronTargets,
} from "./application/ElectronObservationService.js";
import { captureElectronScenario } from "./application/ElectronActiveObservationService.js";
import { reconcileJavaScriptRuntimeEvidence } from "./application/JavaScriptRuntimeReconciliationService.js";
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
import { CdpElectronProvider } from "./browser/CdpElectronProvider.js";
import { PlaywrightElectronActiveProvider } from "./browser/PlaywrightElectronActiveProvider.js";
import { logCliCommand } from "./cliLogging.js";
import { parseConfig } from "./config.js";
import {
inspectElectronPageInputSchema,
listElectronTargetsInputSchema,
} from "./domain/electronObservation.js";
import { electronActiveObservationInputSchema } from "./domain/electronActiveObservation.js";
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
import type { JsonValue } from "./domain/jsonValue.js";
import type { Logger } from "./logger.js";
@@ -38,10 +41,47 @@ export const registerElectronCommands = (
logger: Logger,
): void => {
registerElectronObservationCommands(cli, logger);
registerElectronActiveCommand(cli, logger);
registerJavaScriptApplicationCommand(cli, logger);
registerJavaScriptRuntimeReconciliationCommand(cli, logger);
};
const registerElectronActiveCommand = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.captureElectronScenario, {
description: "Run one approved, bounded owned Electron scenario",
args: z.object({
inputJson: z
.string()
.describe(
"Inline JSON or a JSON file matching capture_electron_scenario",
),
}),
run: ({ args }) =>
logCliCommand(logger, CLI_COMMANDS.captureElectronScenario, async () => {
const input = await parseCliJsonInput(
args.inputJson,
"capture_electron_scenario",
);
if (!input.ok) return input.error;
const parsed = electronActiveObservationInputSchema.safeParse(
input.value,
);
if (!parsed.success) return inputError("capture_electron_scenario");
const context = await electronContext();
if (!context.ok) return context.error;
const result = await captureElectronScenario(
context.activeProvider,
context.authority,
parsed.data,
);
return result.ok ? result.value : cliError(result.error);
}),
});
};
const registerJavaScriptRuntimeReconciliationCommand = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
@@ -227,6 +267,7 @@ const electronContext = async () => {
ok: true as const,
authority: authority.value,
provider: new CdpElectronProvider(),
activeProvider: new PlaywrightElectronActiveProvider(),
allowedFileRoots: config.value.electronFileRoots,
};
};
+1
View File
@@ -21,6 +21,7 @@ const capabilitySchema = z.enum([
"browser_observe",
"browser_automate",
"electron_observe",
"electron_automate",
"evidence_read",
"evidence_write",
"investigation_input",
+63
View File
@@ -0,0 +1,63 @@
import { isAbsolute } from "node:path";
import type { PermissionCeiling } from "../domain/permissionPolicy.js";
import { ConfigurationError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import { permissionScope } from "./permissions.js";
import { parseStringArray } from "./parsers.js";
import type { Environment } from "./environment.js";
export interface ElectronAutomationArrays {
readonly electronAutomationExecutableRoots: readonly string[];
readonly electronAutomationApplicationRoots: readonly string[];
}
/** Parse the exact filesystem roots admitted for active Electron automation. */
export const parseElectronAutomationArrays = (
env: Environment,
): Result<ElectronAutomationArrays, ConfigurationError> => {
const executableRoots = parseAbsoluteRoots(
env.REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON,
"REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON",
);
if (!executableRoots.ok) return executableRoots;
const applicationRoots = parseAbsoluteRoots(
env.REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON,
"REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON",
);
if (!applicationRoots.ok) return applicationRoots;
return ok({
electronAutomationExecutableRoots: executableRoots.value,
electronAutomationApplicationRoots: applicationRoots.value,
});
};
/** Add the separately permissioned, no-network Electron automation ceiling. */
export const appendElectronAutomationCeiling = (
ceilings: PermissionCeiling[],
env: Environment,
arrays: ElectronAutomationArrays,
): void => {
if (env.REA_ELECTRON_AUTOMATE_ENABLED !== "true") return;
ceilings.push(
permissionScope(
"electron_automate",
arrays.electronAutomationApplicationRoots,
{
executables: arrays.electronAutomationExecutableRoots,
network: "external",
},
),
);
};
const parseAbsoluteRoots = (
value: string,
name: string,
): Result<readonly string[], ConfigurationError> => {
const parsed = parseStringArray(value, name);
if (!parsed.ok) return parsed;
return parsed.value.some((root) => !isAbsolute(root))
? err(new ConfigurationError(`${name} must encode absolute roots`))
: parsed;
};
+6
View File
@@ -63,6 +63,12 @@ const environmentSchema = z
REA_ELECTRON_OBSERVE_ENABLED: z.enum(["true", "false"]).default("false"),
REA_ELECTRON_CDP_ENDPOINTS_JSON: z.string().default("[]"),
REA_ELECTRON_FILE_ROOTS_JSON: z.string().default("[]"),
REA_ELECTRON_AUTOMATE_ENABLED: z.enum(["true", "false"]).default("false"),
REA_ELECTRON_AUTOMATE_AUTO_GRANT: z
.enum(["true", "false"])
.default("false"),
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: z.string().default("[]"),
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: z.string().default("[]"),
REA_V8_INSPECTOR_OBSERVE_ENABLED: z
.enum(["true", "false"])
.default("false"),
+18 -2
View File
@@ -21,6 +21,11 @@ import {
browserEndpointSchema,
browserOriginSchema,
} from "../domain/browserObservation.js";
import {
appendElectronAutomationCeiling,
parseElectronAutomationArrays,
type ElectronAutomationArrays,
} from "./electronAutomation.js";
const DEFAULT_HOPPER_LAUNCHER_PATH =
"/Applications/Hopper Disassembler.app/Contents/MacOS/hopper";
@@ -29,7 +34,7 @@ const defaultHopperLauncherPath = (): string =>
? "/opt/hopper/bin/Hopper"
: DEFAULT_HOPPER_LAUNCHER_PATH;
interface ParsedArrays {
interface ParsedArrays extends ElectronAutomationArrays {
readonly loaderArgs: readonly string[];
readonly executableRoots: readonly string[];
readonly workingRoots: readonly string[];
@@ -116,6 +121,8 @@ const parseAllArrays = (
if (!secretPatterns.ok) return secretPatterns;
const observations = parseObservationArrays(env);
if (!observations.ok) return observations;
const electronAutomation = parseElectronAutomationArrays(env);
if (!electronAutomation.ok) return electronAutomation;
const javascriptReplayRoots = parseAbsoluteRoots(
env.REA_JAVASCRIPT_REPLAY_ROOTS_JSON,
"REA_JAVASCRIPT_REPLAY_ROOTS_JSON",
@@ -137,6 +144,7 @@ const parseAllArrays = (
referenceRoots: referenceRoots.value,
secretPatterns: secretPatterns.value,
...observations.value,
...electronAutomation.value,
javascriptReplayRoots: javascriptReplayRoots.value,
managedRuntimeRoots: managedRuntimeRoots.value,
});
@@ -378,6 +386,7 @@ const buildPermissionCeilings = (
appendBrowserObservationCeiling(ceilings, env, arrays);
appendBrowserScenarioCeiling(ceilings, env, arrays);
appendElectronObservationCeiling(ceilings, env, arrays);
appendElectronAutomationCeiling(ceilings, env, arrays);
appendV8InspectorObservationCeiling(ceilings, env, arrays);
appendNativeMountCeiling(ceilings, env);
appendJavaScriptReplayCeiling(ceilings, env, arrays);
@@ -433,6 +442,11 @@ const buildAppConfig = (
electronObservationEnabled: env.REA_ELECTRON_OBSERVE_ENABLED === "true",
electronCdpEndpoints: arrays.electronEndpoints,
electronFileRoots: arrays.electronFileRoots,
electronAutomationPolicy: {
enabled: env.REA_ELECTRON_AUTOMATE_ENABLED === "true",
executableRoots: arrays.electronAutomationExecutableRoots,
applicationRoots: arrays.electronAutomationApplicationRoots,
},
v8InspectorObservationEnabled:
env.REA_V8_INSPECTOR_OBSERVE_ENABLED === "true",
v8InspectorEndpoints: arrays.v8InspectorEndpoints,
@@ -459,7 +473,9 @@ const buildAppConfig = (
(capability !== "process_capture" ||
env.REA_PROCESS_CAPTURE_AUTO_GRANT === "true") &&
(capability !== "browser_automate" ||
env.REA_BROWSER_SCENARIO_AUTO_GRANT === "true"),
env.REA_BROWSER_SCENARIO_AUTO_GRANT === "true") &&
(capability !== "electron_automate" ||
env.REA_ELECTRON_AUTOMATE_AUTO_GRANT === "true"),
),
),
permissionProjectRoot: env.REA_PERMISSION_PROJECT_ROOT,
+5
View File
@@ -38,6 +38,11 @@ export interface AppConfig {
readonly electronObservationEnabled: boolean;
readonly electronCdpEndpoints: readonly string[];
readonly electronFileRoots: readonly string[];
readonly electronAutomationPolicy: {
readonly enabled: boolean;
readonly executableRoots: readonly string[];
readonly applicationRoots: readonly string[];
};
readonly v8InspectorObservationEnabled: boolean;
readonly v8InspectorEndpoints: readonly string[];
readonly v8InspectorFileRoots: readonly string[];
+34 -1
View File
@@ -9,6 +9,10 @@ import {
inspectElectronPageInputSchema,
listElectronTargetsInputSchema,
} from "../domain/electronObservation.js";
import {
electronActiveObservationInputSchema,
electronActiveObservationResultSchema,
} from "../domain/electronActiveObservation.js";
import {
analyzeJavaScriptApplicationInputSchema,
javaScriptApplicationAnalysisResultV1Schema,
@@ -113,6 +117,23 @@ const reconciliationOutputSchema = evidenceResultOf(
const endpoint = "http://127.0.0.1:9223";
const root = "/Applications/Example.app/Contents/Resources";
const activeExample = {
schema_version: 1,
executable_path: "/Applications/Electron.app/Contents/MacOS/Electron",
application_path: "/Applications/Example.app/Contents/Resources/main.js",
application_root: "/Applications/Example.app/Contents/Resources",
args: [],
actions: [{ step_id: "exercise-ipc", kind: "click", selector: "#run" }],
limits: {
max_duration_ms: 60_000,
action_timeout_ms: 5_000,
max_actions: 20,
max_ipc_events: 2_000,
max_processes: 32,
max_windows: 32,
},
approved: true,
};
/** Root-confined Electron file-page discovery and inspection contracts. */
export const ELECTRON_TOOL_CONTRACTS = [
@@ -194,7 +215,7 @@ export const ELECTRON_TOOL_CONTRACTS = [
name: "reconcile_javascript_runtime",
...toolContractMetadata("reconcile_javascript_runtime"),
description:
"Reconcile verified static JavaScript application graphs with existing passive web or Electron CDP Evidence. Exact captured-source digests take priority over caller-declared file/URL mappings; target, frame, script, and worker ambiguity remains explicit, and source-map authority stays separate.",
"Reconcile verified static JavaScript application graphs with existing passive web/Electron CDP, passive V8 Inspector, or provider-owned active Electron Evidence. Active Electron captures contribute an explicitly partial target-only runtime record; they never invent renderer scripts, frames, workers, or execution claims. Exact captured-source digests take priority over caller-declared file/URL mappings; target, frame, script, and worker ambiguity remains explicit, and source-map authority stays separate.",
kind: "electron-provider",
inputSchema: reconcileJavaScriptRuntimeInputSchema,
outputSchema: reconciliationOutputSchema,
@@ -205,4 +226,16 @@ export const ELECTRON_TOOL_CONTRACTS = [
},
],
},
{
name: "capture_electron_scenario",
...toolContractMetadata("capture_electron_scenario"),
description:
"Use this for an explicitly approved, provider-owned Electron run when passive CDP or Inspector observation cannot exercise application behavior. REA owns startup and teardown, accepts bounded click/wait actions plus window-targeted renderer reload/crash and synthetic open-url/second-instance delivery, and returns correlated window/WebContents/process/preload/session/navigation/shell/IPC evidence without retaining payload values. Results identify observed and unavailable event families, coverage status, action targets, and truncation. External shell, navigation, permission, download, popup, updater, and OS-integration effects are blocked and recorded. Use passive Electron tools for observation-only work.",
kind: "electron-provider",
inputSchema: electronActiveObservationInputSchema,
outputSchema: evidenceResultOf(electronActiveObservationResultSchema),
examples: [
{ title: "Exercise an owned Electron application", input: activeExample },
],
},
] as const satisfies readonly ToolContract[];
+10
View File
@@ -129,6 +129,16 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
}),
list_electron_targets: browserEvidence,
inspect_electron_page: browserEvidence,
capture_electron_scenario: effects({
mutatesTarget: true,
mutatesSession: true,
writesFilesystem: true,
launchesProcess: true,
accessesNetwork: true,
changesUiState: true,
mayDiscardData: true,
idempotent: false,
}),
list_javascript_runtime_targets: browserEvidence,
observe_javascript_runtime: browserEvidence,
analyze_javascript_application: evidence,
+7 -1
View File
@@ -12,7 +12,8 @@ export type BrowserObservationOperation =
| "inspect_electron_page"
| "list_javascript_runtime_targets"
| "observe_javascript_runtime"
| "capture_browser_scenario";
| "capture_browser_scenario"
| "capture_electron_scenario";
/** Stable failure reasons shared by browser-family provider adapters. */
export type BrowserObservationFailureReason =
@@ -24,5 +25,10 @@ export type BrowserObservationFailureReason =
| "protocol_error"
| "disconnected"
| "payload_limit"
| "window_not_found"
| "window_metadata_missing"
| "process_ownership_unavailable"
| "cleanup_failed"
| "cancelled"
| "timeout"
| "secret_unavailable";
+6 -4
View File
@@ -4,7 +4,10 @@ import {
conformancePackageSchema,
type ConformancePackage,
} from "./conformancePackage.js";
import { trustGateResultSchema } from "./conformanceTrustGate.js";
import {
evaluatePackageTrustGates,
trustGateResultSchema,
} from "./conformanceTrustGate.js";
/** Result of a single scenario replay. */
export const scenarioReplayResultSchema = z.strictObject({
@@ -31,6 +34,7 @@ export const packageReplayResultSchema = z.strictObject({
.strictObject({
scenario_id: z.string().min(1),
dimension: z.string().min(1),
evidence_id: z.string().min(1),
message: z.string(),
})
.nullable(),
@@ -116,6 +120,7 @@ export async function replayConformancePackage(
? {
scenario_id: first_drift_gate.scenario_id,
dimension: first_drift_gate.first_divergence.dimension,
evidence_id: first_drift_gate.first_divergence.evidence_id,
message: first_drift_gate.first_divergence.message,
}
: null;
@@ -133,6 +138,3 @@ export async function replayConformancePackage(
first_drift,
};
}
/** Import trust gate evaluator for replay. */
import { evaluatePackageTrustGates } from "./conformanceTrustGate.js";
+188 -30
View File
@@ -47,12 +47,158 @@ const SEMANTIC_DIMENSIONS = new Set([
"stdout",
"stderr",
"filesystem",
"process",
"process_tree",
"shim_events",
"protocol_events",
"event_journal",
]);
type IncompleteStatus = "unknown" | "truncated";
type EvidenceView = {
readonly values: Readonly<Record<string, unknown>>;
readonly evidence_ids: readonly string[];
readonly status: IncompleteStatus | null;
readonly unknown_scopes: readonly string[];
};
type CompareDimensionOptions = {
readonly truncated?: boolean;
readonly evidence_ids?: readonly string[];
readonly expected_status?: IncompleteStatus | null;
readonly actual_status?: IncompleteStatus | null;
};
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const uniqueStrings = (values: readonly string[]): string[] => [
...new Set(values.filter((value) => value.length > 0)),
];
const stringValues = (value: unknown): readonly string[] => {
if (typeof value === "string") return value.length > 0 ? [value] : [];
if (!Array.isArray(value)) return [];
return value.filter(
(item): item is string => typeof item === "string" && item.length > 0,
);
};
const evidenceIds = (record: Readonly<Record<string, unknown>>): string[] =>
uniqueStrings([
...stringValues(record["evidence_id"]),
...stringValues(record["evidence_ids"]),
...stringValues(record["evidence_links"]),
]);
const incompleteStatus = (value: unknown): IncompleteStatus | null => {
if (!isRecord(value)) return null;
const record = value;
if (record["truncated"] === true) return "truncated";
const status = record["status"];
if (status === "truncated") return "truncated";
if (
status === "unknown" ||
status === "unavailable" ||
status === "partial" ||
status === "incomplete" ||
status === "unverifiable" ||
status === "failed" ||
status === "not_approved"
)
return "unknown";
for (const key of ["coverage", "completeness"]) {
const nested = record[key];
if (!isRecord(nested)) continue;
const nestedStatus = incompleteStatus(nested);
if (nestedStatus !== null) return nestedStatus;
}
return null;
};
const hasResidualUnknowns = (value: unknown): boolean =>
isRecord(value) &&
Array.isArray(value["residual_unknowns"]) &&
value["residual_unknowns"].length > 0;
const unknownScopes = (record: Readonly<Record<string, unknown>>): string[] => {
const residualUnknowns = record["residual_unknowns"];
if (!Array.isArray(residualUnknowns)) return [];
return residualUnknowns.flatMap((item) => {
if (!isRecord(item) || typeof item["scope"] !== "string") return [];
return [item["scope"]];
});
};
const evidenceView = (input: unknown): EvidenceView => {
if (!isRecord(input))
return {
values: {},
evidence_ids: [],
status: null,
unknown_scopes: [],
};
const normalized = input["normalized_result"];
const values = isRecord(normalized) ? normalized : input;
const normalizedStatus = isRecord(normalized)
? incompleteStatus(normalized)
: null;
return {
values,
evidence_ids: evidenceIds(input),
status: incompleteStatus(input) ?? normalizedStatus,
unknown_scopes: uniqueStrings([
...unknownScopes(input),
...(isRecord(normalized) ? unknownScopes(normalized) : []),
]),
};
};
const dimensionScope = (dimensionName: string): string | null => {
if (dimensionName === "exit_code" || dimensionName === "exit") return "exit";
if (
dimensionName === "process" ||
dimensionName === "process_tree" ||
dimensionName === "event_journal"
)
return "process";
if (dimensionName === "stdout" || dimensionName === "stderr")
return "terminal";
if (dimensionName === "filesystem") return "filesystem";
if (dimensionName === "shim_events") return "shim";
if (dimensionName === "protocol_events") return "protocol";
return null;
};
const statusForDimension = (
view: EvidenceView,
dimensionName: string,
): IncompleteStatus | null => {
const valueStatus = incompleteStatus(view.values[dimensionName]);
if (valueStatus !== null) return valueStatus;
if (hasResidualUnknowns(view.values[dimensionName])) return "unknown";
const scope = dimensionScope(dimensionName);
return scope !== null && view.unknown_scopes.includes(scope)
? "unknown"
: view.status;
};
const comparisonIncompleteStatus = (
expected: unknown,
actual: unknown,
options: CompareDimensionOptions,
): IncompleteStatus | null => {
const expectedStatus = options.expected_status ?? incompleteStatus(expected);
const actualStatus = options.actual_status ?? incompleteStatus(actual);
if (options.truncated) return "truncated";
if (expectedStatus === "truncated" || actualStatus === "truncated")
return "truncated";
if (expectedStatus === "unknown" || actualStatus === "unknown")
return "unknown";
return null;
};
/** Check if a dimension name is volatile (timing/normalization noise). */
export function isVolatileDimension(name: string): boolean {
return VOLATILE_DIMENSIONS.has(name);
@@ -75,7 +221,7 @@ export function compareDimension(
dimensionName: string,
expected: unknown,
actual: unknown,
options: { truncated?: boolean } = {},
options: CompareDimensionOptions = {},
): DimensionResult {
// Volatile dimensions: always match regardless of values
if (isVolatileDimension(dimensionName)) {
@@ -83,16 +229,22 @@ export function compareDimension(
name: dimensionName,
status: "match",
message: "volatile dimension ignored",
evidence_ids: [],
evidence_ids: uniqueStrings(options.evidence_ids ?? []),
};
}
if (options.truncated) {
const status = comparisonIncompleteStatus(expected, actual, options);
const resultEvidenceIds = uniqueStrings(options.evidence_ids ?? []);
if (status !== null) {
return {
name: dimensionName,
status: "truncated",
message: "evidence was truncated",
evidence_ids: [],
status,
message:
status === "truncated"
? "evidence was truncated"
: "evidence completeness is unknown",
evidence_ids: resultEvidenceIds,
};
}
@@ -101,16 +253,16 @@ export function compareDimension(
name: dimensionName,
status: "unknown",
message: "both expected and actual are undefined",
evidence_ids: [],
evidence_ids: resultEvidenceIds,
};
}
if (expected === undefined || actual === undefined) {
return {
name: dimensionName,
status: "mismatch",
message: `expected ${expected === undefined ? "present" : "absent"}, actual ${actual === undefined ? "absent" : "present"}`,
evidence_ids: [],
status: "unknown",
message: "one side has no observed value",
evidence_ids: resultEvidenceIds,
};
}
@@ -123,14 +275,14 @@ export function compareDimension(
name: dimensionName,
status: "match",
message: "",
evidence_ids: [],
evidence_ids: resultEvidenceIds,
};
}
return {
name: dimensionName,
status: "mismatch",
message: "semantic content differs",
evidence_ids: [],
evidence_ids: resultEvidenceIds,
};
}
@@ -140,7 +292,7 @@ export function compareDimension(
name: dimensionName,
status: "match",
message: "",
evidence_ids: [],
evidence_ids: resultEvidenceIds,
};
}
@@ -148,7 +300,7 @@ export function compareDimension(
name: dimensionName,
status: "mismatch",
message: `expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`,
evidence_ids: [],
evidence_ids: resultEvidenceIds,
};
}
@@ -156,9 +308,10 @@ export function compareDimension(
function sortKeys(value: unknown): unknown {
if (value === null || typeof value !== "object") return value;
if (Array.isArray(value)) return value.map(sortKeys);
if (!isRecord(value)) return value;
const sorted: Record<string, unknown> = {};
for (const key of Object.keys(value as Record<string, unknown>).sort()) {
sorted[key] = sortKeys((value as Record<string, unknown>)[key]);
for (const key of Object.keys(value).sort()) {
sorted[key] = sortKeys(value[key]);
}
return sorted;
}
@@ -169,23 +322,28 @@ function sortKeys(value: unknown): unknown {
*/
export function evaluateTrustGate(
contract: VerifierContract,
expectedEvidence: Record<string, unknown>,
actualEvidence: Record<string, unknown>,
options: { truncated?: boolean } = {},
expectedEvidence: unknown,
actualEvidence: unknown,
options: { readonly truncated?: boolean } = {},
): TrustGateResult {
const dimensionResults: DimensionResult[] = [];
let firstDivergence: TrustGateResult["first_divergence"] = null;
const expectedView = evidenceView(expectedEvidence);
const actualView = evidenceView(actualEvidence);
for (const dim of contract.dimensions) {
if (!dim.required) continue;
const expectedValue = expectedEvidence[dim.name];
const actualValue = actualEvidence[dim.name];
const result = compareDimension(
dim.name,
expectedValue,
actualValue,
options,
);
const expectedValue = expectedView.values[dim.name];
const actualValue = actualView.values[dim.name];
const result = compareDimension(dim.name, expectedValue, actualValue, {
...options,
expected_status: statusForDimension(expectedView, dim.name),
actual_status: statusForDimension(actualView, dim.name),
evidence_ids: uniqueStrings([
...actualView.evidence_ids,
...expectedView.evidence_ids,
]),
});
dimensionResults.push(result);
if (result.status === "mismatch" && firstDivergence === null) {
@@ -223,8 +381,8 @@ export function evaluateTrustGate(
*/
export function evaluatePackageTrustGates(
pkg: ConformancePackage,
actualEvidence: Record<string, Record<string, unknown>>,
options: { truncated?: boolean } = {},
actualEvidence: Readonly<Record<string, Readonly<Record<string, unknown>>>>,
options: { readonly truncated?: boolean } = {},
): TrustGateResult[] {
const results: TrustGateResult[] = [];
for (const contract of pkg.verifier_contracts) {
@@ -236,7 +394,7 @@ export function evaluatePackageTrustGates(
const actual = actualEvidence[contract.scenario_id] ?? {};
const result = evaluateTrustGate(
contract,
expectedEvidence as Record<string, unknown>,
expectedEvidence,
actual,
options,
);
+296
View File
@@ -0,0 +1,296 @@
import { isAbsolute } from "node:path";
import { z } from "zod";
const absolutePathSchema = z
.string()
.min(1)
.max(16_384)
.refine(isAbsolute, "path must be absolute");
const windowIndexSchema = z.number().int().min(0).max(99);
const deepLinkUrlSchema = z
.string()
.min(1)
.max(4_096)
.refine((value) => {
try {
return new URL(value).protocol.length > 0;
} catch {
return false;
}
}, "deep-link url must be an absolute URL");
const actionSchema = z.discriminatedUnion("kind", [
z.strictObject({
step_id: z.string().min(1).max(128),
kind: z.literal("click"),
selector: z.string().min(1).max(512),
window_index: windowIndexSchema.default(0),
}),
z.strictObject({
step_id: z.string().min(1).max(128),
kind: z.literal("wait"),
duration_ms: z.number().int().min(0).max(10_000),
window_index: windowIndexSchema.optional(),
}),
z.strictObject({
step_id: z.string().min(1).max(128),
kind: z.literal("renderer-reload"),
window_index: windowIndexSchema.default(0),
}),
z.strictObject({
step_id: z.string().min(1).max(128),
kind: z.literal("renderer-crash"),
window_index: windowIndexSchema.default(0),
}),
z.strictObject({
step_id: z.string().min(1).max(128),
kind: z.literal("deep-link"),
delivery: z.enum(["open-url", "second-instance"]),
url: deepLinkUrlSchema,
}),
]);
const limitsSchema = z.strictObject({
max_duration_ms: z.number().int().min(1).max(120_000).default(60_000),
action_timeout_ms: z.number().int().min(1).max(30_000).default(5_000),
max_actions: z.number().int().min(1).max(100).default(20),
max_ipc_events: z.number().int().min(1).max(10_000).default(2_000),
max_runtime_events: z.number().int().min(1).max(20_000).default(5_000),
max_processes: z.number().int().min(1).max(100).default(32),
max_windows: z.number().int().min(1).max(100).default(32),
});
/** Input for one explicit, provider-owned Electron runtime experiment. */
export const electronActiveObservationInputSchema = z
.strictObject({
schema_version: z.literal(1),
executable_path: absolutePathSchema,
application_path: absolutePathSchema,
application_root: absolutePathSchema,
args: z.array(z.string().max(4_096)).max(32).default([]),
actions: z.array(actionSchema).max(100).default([]),
limits: limitsSchema.default({
max_duration_ms: 60_000,
action_timeout_ms: 5_000,
max_actions: 20,
max_ipc_events: 2_000,
max_runtime_events: 5_000,
max_processes: 32,
max_windows: 32,
}),
approved: z.literal(true),
})
.superRefine((input, context) => {
if (input.actions.length > input.limits.max_actions)
context.addIssue({
code: "custom",
path: ["actions"],
message: "actions exceed the configured max_actions limit",
});
});
export type ElectronActiveObservationInput = z.infer<
typeof electronActiveObservationInputSchema
>;
const ipcEventSchema = z.strictObject({
sequence: z.number().int().min(1),
correlation_id: z.string().max(256).nullable().default(null),
kind: z.enum([
"main-handler-invocation",
"main-event-invocation",
"utility-process-fork",
"utility-process-message",
"ipc-main-to-renderer",
"ipc-utility-to-main",
"ipc-renderer-send",
"ipc-renderer-invoke",
"ipc-renderer-post-message",
]),
event: z.string().max(128).nullable().optional(),
phase: z
.enum(["attempted", "completed", "blocked", "failed", "observed"])
.nullable()
.optional(),
channel: z.string().max(1_024).nullable(),
channel_truncated: z.boolean().default(false),
direction: z
.enum([
"renderer-to-main",
"main-to-renderer",
"main-to-utility",
"utility-to-main",
])
.nullable()
.optional(),
sender: z.string().max(256).nullable().optional(),
receiver: z.string().max(256).nullable().optional(),
frame: z.string().max(256).nullable().default(null),
target: z.string().max(256).nullable().optional(),
argument_shapes: z.array(z.string().max(64)).max(32),
argument_shapes_truncated: z.boolean().default(false),
result_shape: z.string().max(64).nullable(),
process_type: z.string().max(128).nullable(),
source: z.string().max(64).default("electron-active-hook"),
capture_method: z
.enum(["api-wrapper", "event-emitter", "process-hook"])
.default("api-wrapper"),
artifact_path: z.string().max(16_384).nullable().default(null),
artifact_sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable()
.default(null),
error: z.boolean(),
});
const timelineEventSchema = z.strictObject({
sequence: z.number().int().min(1),
correlation_id: z.string().max(256).nullable().default(null),
kind: z.enum([
"main-handler-invocation",
"main-event-invocation",
"utility-process-fork",
"utility-process-message",
"ipc-main-to-renderer",
"ipc-utility-to-main",
"ipc-renderer-send",
"ipc-renderer-invoke",
"ipc-renderer-post-message",
"app-lifecycle",
"window-lifecycle",
"web-contents-lifecycle",
"navigation",
"shell-attempt",
"process-lifecycle",
"permission",
"popup-attempt",
"download",
"protocol",
"preload",
"native-addon",
"updater",
"error",
]),
event: z.string().max(128).nullable(),
phase: z.enum(["attempted", "completed", "blocked", "failed", "observed"]),
channel: z.string().max(1_024).nullable(),
channel_truncated: z.boolean(),
direction: z
.enum([
"renderer-to-main",
"main-to-renderer",
"main-to-utility",
"utility-to-main",
])
.nullable(),
sender: z.string().max(256).nullable(),
receiver: z.string().max(256).nullable(),
frame: z.string().max(256).nullable(),
target: z.string().max(256).nullable(),
argument_shapes: z.array(z.string().max(64)).max(32),
argument_shapes_truncated: z.boolean(),
result_shape: z.string().max(64).nullable(),
process_type: z.string().max(128).nullable(),
source: z.string().max(64),
capture_method: z.enum(["api-wrapper", "event-emitter", "process-hook"]),
artifact_path: z.string().max(16_384).nullable(),
artifact_sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
error: z.boolean(),
});
const processMetricSchema = z.strictObject({
pid: z.number().int().min(1),
type: z.string().min(1).max(128),
name: z.string().max(256).nullable(),
service_name: z.string().max(256).nullable(),
});
const windowResultSchema = z.strictObject({
window_id: z.string().max(256),
web_contents_id: z.string().max(256),
url: z.string().max(65_536),
title: z.string().max(16_384),
visible: z.boolean().nullable(),
destroyed: z.boolean(),
});
const coverageSchema = z.strictObject({
status: z.enum([
"complete",
"partial_attach",
"capture_truncated",
"hook_conflict",
"target_exited",
"cleanup_failed",
]),
observed_event_families: z.array(z.string().max(128)).max(32),
unavailable_event_families: z.array(z.string().max(128)).max(32),
observed_roles: z.array(z.string().max(128)).max(16),
pre_capture_activity: z.literal("unavailable"),
});
const actionResultSchema = z.strictObject({
step_id: z.string().min(1).max(128),
kind: z.enum([
"click",
"wait",
"renderer-reload",
"renderer-crash",
"deep-link",
]),
window_index: windowIndexSchema.nullable(),
target: z.string().max(256).nullable(),
status: z.enum(["completed", "failed", "cancelled"]),
elapsed_ms: z.number().int().min(0),
error: z.string().nullable(),
});
/** Bounded result of a provider-owned Electron runtime experiment. */
export const electronActiveObservationResultSchema = z.strictObject({
schema_version: z.literal(1),
application: z.strictObject({
executable_path: absolutePathSchema,
application_path: absolutePathSchema,
electron_version: z.string().min(1).max(256),
process_ownership: z.literal("provider-owned"),
cleanup: z.literal("terminated-owned-process"),
}),
actions: z.array(actionResultSchema).max(100),
windows: z.array(windowResultSchema).max(100),
windows_truncated: z.boolean(),
processes: z.strictObject({
items: z.array(processMetricSchema).max(100),
truncated: z.boolean(),
}),
ipc: z.strictObject({
events: z.array(ipcEventSchema).max(10_000),
observed: z.number().int().min(0),
retained: z.number().int().min(0),
truncated: z.boolean(),
}),
timeline: z
.strictObject({
events: z.array(timelineEventSchema).max(20_000),
observed: z.number().int().min(0),
retained: z.number().int().min(0),
truncated: z.boolean(),
})
.default({ events: [], observed: 0, retained: 0, truncated: false }),
coverage: coverageSchema.default({
status: "partial_attach",
observed_event_families: [],
unavailable_event_families: [],
observed_roles: [],
pre_capture_activity: "unavailable",
}),
limitations: z.array(z.string().max(4_096)).max(100),
});
export type ElectronActiveObservationResult = z.infer<
typeof electronActiveObservationResultSchema
>;
@@ -115,6 +115,7 @@ export const javascriptRuntimeLocationSchema = z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("file"),
file_path: z.string().min(1).max(16_384),
authority: z.literal("scope-fallback").optional(),
}),
z.strictObject({
kind: z.literal("url"),
@@ -0,0 +1,138 @@
import { createHash } from "node:crypto";
import { isAbsolute, relative } from "node:path";
import canonicalize from "canonicalize";
import { z } from "zod";
import {
classifyBrowserCompleteness,
type BrowserCompleteness,
} from "./browserCompleteness.js";
import {
electronActiveObservationResultSchema,
type ElectronActiveObservationResult,
} from "./electronActiveObservation.js";
import type { Evidence } from "./evidence.js";
import type { ParsedRuntimeCapture } from "./javascriptRuntimeReconciliationParsing.js";
/** Parse active Electron Evidence as a bounded, target-only runtime capture. */
export const parseActiveElectronCapture = (
evidence: Evidence,
): ParsedRuntimeCapture => {
assertIdentity(evidence);
const result = electronActiveObservationResultSchema.parse(
evidence.normalized_result,
);
const parameters = z
.object({
approved: z.literal(true),
application_path: absolutePathSchema,
application_root: absolutePathSchema,
})
.passthrough()
.parse(evidence.parameters);
if (
result.application.application_path !== parameters.application_path ||
!isWithinRoot(
parameters.application_root,
result.application.application_path,
)
)
throw new TypeError(
"Active Electron Evidence application path disagrees with its approved root",
);
return {
kind: "electron-active",
evidence,
inspection: normalizeInspection(result),
captureSha256: digestCanonical(result),
scriptsCompleteWithinScope: false,
};
};
const absolutePathSchema = z.string().min(1).max(16_384).refine(isAbsolute);
const assertIdentity = (evidence: Evidence): void => {
if (
evidence.operation !== "capture_electron_scenario" ||
evidence.predicate_type !== "rea.electron-active-scenario/v1" ||
evidence.provider.id !== "rea-playwright-electron-active" ||
evidence.provider.name !==
"REA Playwright active Electron observation provider" ||
evidence.provider.version !== "1" ||
evidence.authority !== "controlled-replay" ||
evidence.confidence !== "observed"
)
throw new TypeError(
"Evidence does not match the supported capture_electron_scenario contract",
);
};
const normalizeInspection = (
result: ElectronActiveObservationResult,
): {
readonly target: {
readonly target_id: string;
readonly type: string;
readonly title: string;
readonly attached: boolean;
readonly file_path: string;
};
readonly frames: readonly [];
readonly scripts: { readonly items: readonly [] };
readonly workers: readonly [];
readonly completeness: BrowserCompleteness;
} => ({
target: {
target_id: `electron-active:${digestCanonical(result.application.application_path).slice(0, 32)}`,
type: "electron-application",
title: result.application.application_path,
attached: true,
file_path: result.application.application_path,
},
frames: [],
scripts: { items: [] },
workers: [],
completeness: classifyBrowserCompleteness({
policyFilteredSections: new Set(),
attachLimitedSections: new Set(),
truncatedSections: new Set(
result.windows_truncated ||
result.processes.truncated ||
result.ipc.truncated ||
result.timeline.truncated
? ["timeline"]
: [],
),
unavailableSections: new Set([
"frames",
"scripts",
"script_sources",
"workers",
]),
excluded: [],
droppedEvents: {
scripts: 0,
network_requests: 0,
console_events: 0,
websocket_connections: 0,
websocket_frames: 0,
webmcp_tools: 0,
timeline_events: result.timeline.truncated ? result.timeline.observed : 0,
},
}),
});
const digestCanonical = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Runtime reconciliation could not canonicalize input");
return createHash("sha256").update(encoded).digest("hex");
};
const isWithinRoot = (root: string, path: string): boolean => {
const remainder = relative(root, path);
return (
remainder === "" || (!remainder.startsWith("..") && !isAbsolute(remainder))
);
};
@@ -34,6 +34,7 @@ import {
compareCodePoints,
type JavaScriptApplicationGraph,
} from "./javascriptApplicationGraph.js";
import { parseActiveElectronCapture } from "./javascriptRuntimeReconciliationActive.js";
import type { ReconcileJavaScriptRuntimeInput } from "./javascriptRuntimeReconciliationSchemas.js";
type StaticLayerInput =
@@ -101,6 +102,22 @@ export type ParsedRuntimeCapture =
| (RuntimeCaptureBase & {
readonly kind: "v8-inspector";
readonly inspection: NormalizedV8Inspection;
})
| (RuntimeCaptureBase & {
readonly kind: "electron-active";
readonly inspection: {
readonly target: {
readonly target_id: string;
readonly type: string;
readonly title: string;
readonly attached: boolean;
readonly file_path: string;
};
readonly frames: readonly [];
readonly scripts: { readonly items: readonly [] };
readonly workers: readonly [];
readonly completeness: BrowserCompleteness;
};
});
/** Parse and semantically bind every static analysis Evidence layer. */
@@ -255,8 +272,11 @@ const parseRuntimeCapture = (input: Evidence): ParsedRuntimeCapture => {
scriptsCompleteWithinScope: false,
};
}
if (evidence.operation === "capture_electron_scenario") {
return parseActiveElectronCapture(evidence);
}
throw new TypeError(
"Runtime reconciliation requires inspect_web_page, inspect_electron_page, or observe_javascript_runtime Evidence",
"Runtime reconciliation requires inspect_web_page, inspect_electron_page, observe_javascript_runtime, or capture_electron_scenario Evidence",
);
};
@@ -170,7 +170,7 @@ const layerSummarySchema = z.strictObject({
const captureSummarySchema = z.strictObject({
evidence_id: evidenceIdSchema,
capture_sha256: digestSchema,
kind: z.enum(["browser", "electron", "v8-inspector"]),
kind: z.enum(["browser", "electron", "v8-inspector", "electron-active"]),
target_node_id: nodeIdSchema,
target_key: boundedTextSchema,
target_location: boundedTextSchema,
+1
View File
@@ -8,6 +8,7 @@ export type PermissionCapability =
| "browser_observe"
| "browser_automate"
| "electron_observe"
| "electron_automate"
| "v8_inspector_observe"
| "evidence_read"
| "evidence_write"
File diff suppressed because one or more lines are too long
+33
View File
@@ -15,6 +15,7 @@ import {
import type { AppConfig } from "../config.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { jsonObjectSchema } from "../domain/jsonValue.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
@@ -61,6 +62,11 @@ import {
windowsP0Limitations,
limitationsFor,
} from "./GhidraProviderCapabilities.js";
import {
WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
hasWindowsNativeAuthority,
windowsNativeCapabilities,
} from "../process/WindowsAuthority.js";
export { GHIDRA_PROVIDER_IDENTITY, GHIDRA_PROVIDER_TOOL_CONTRACTS };
@@ -98,6 +104,22 @@ export class GhidraProvider implements AnalysisProviderCandidate {
inspectAvailability(): ProviderAvailability {
const installation = this.#inspectInstallation();
const diagnostics = ghidraInstallationDiagnostics(installation);
if (
installation.available &&
installation.platform === "win32" &&
!hasWindowsNativeAuthority(installation.platform)
)
return {
status: "unavailable",
code: "unsupported_host",
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
diagnostics: {
...diagnostics,
windows_security: jsonObjectSchema.parse(
windowsNativeCapabilities(installation.platform),
),
},
};
return installation.available
? {
status: "available",
@@ -362,6 +384,17 @@ const ghidraClientPrerequisites = (
diagnostics: ghidraInstallationDiagnostics(installation),
}),
);
if (
installation.platform === "win32" &&
!hasWindowsNativeAuthority(installation.platform)
)
return err(
new AnalysisCapabilityUnavailableError(
"ghidra",
"health",
WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
),
);
if (profile === undefined || profile.provider.id !== "ghidra")
return err(new ProviderAdapterError("ghidra", "health"));
return ok({
+5 -1
View File
@@ -2,6 +2,7 @@ import type {
CapabilityDescriptor,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON } from "../process/WindowsAuthority.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
import {
GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS,
@@ -67,7 +68,7 @@ export const healthLimitations = Object.freeze([
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.",
"Windows P0 is not admitted until a native authority proves Job Object ownership, private DACL enforcement, and reparse-safe path admission; bounded taskkill cleanup and chmod(0700) do not prove those controls.",
]);
/** Limitation text for one admitted operation, including the common base. */
@@ -207,6 +208,9 @@ export const WINDOWS_P0_CAPABILITIES: readonly CapabilityDescriptor[] =
CAPABILITIES.map((capability) =>
Object.freeze({
...capability,
available: false,
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
availabilityCode: "unsupported_host" as const,
limitations: Object.freeze([
...capability.limitations,
...windowsP0Limitations,
+3
View File
@@ -85,17 +85,20 @@ export const run = async (
{ CdpBrowserProvider },
{ PlaywrightBrowserScenarioProvider },
{ CdpElectronProvider },
{ PlaywrightElectronActiveProvider },
{ V8InspectorProvider },
] = await Promise.all([
import("./browser/CdpBrowserProvider.js"),
import("./browser/PlaywrightBrowserScenarioProvider.js"),
import("./browser/CdpElectronProvider.js"),
import("./browser/PlaywrightElectronActiveProvider.js"),
import("./browser/V8InspectorProvider.js"),
]);
return {
browserObservation: new CdpBrowserProvider(),
browserScenarioCapture: new PlaywrightBrowserScenarioProvider(),
electronObservation: new CdpElectronProvider(),
electronActiveObservation: new PlaywrightElectronActiveProvider(),
javascriptRuntimeObservation: new V8InspectorProvider(),
};
},
+4
View File
@@ -104,6 +104,10 @@ const runtimeAvailability = (state: RuntimeState) => ({
state.currentConfig.electronObservationEnabled &&
state.currentConfig.electronCdpEndpoints.length > 0 &&
state.currentConfig.electronFileRoots.length > 0,
electronAutomationEnabled:
state.currentConfig.electronAutomationPolicy.enabled &&
state.currentConfig.electronAutomationPolicy.executableRoots.length > 0 &&
state.currentConfig.electronAutomationPolicy.applicationRoots.length > 0,
v8InspectorObservationEnabled:
state.currentConfig.v8InspectorObservationEnabled &&
state.currentConfig.v8InspectorEndpoints.length > 0 &&
+38
View File
@@ -2,10 +2,44 @@ import { chmod, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
windowsNativeCapabilities,
type WindowsNativeCapability,
} from "./WindowsAuthority.js";
/** Filesystem coordinates for one provider-owned private runtime directory. */
export interface PrivateRuntimeRootOptions {
readonly parent?: string;
readonly prefix?: string;
/** Platform override used by deterministic boundary tests. */
readonly platform?: NodeJS.Platform;
}
/** Provider-neutral security status for one runtime-root implementation. */
export type PrivateRuntimeRootCapability =
| WindowsNativeCapability
| {
readonly available: true;
readonly reason: null;
readonly proof: "posix-mode-0700";
};
/** Report whether this process can establish a private runtime root. */
export const privateRuntimeRootCapability = (
platform: NodeJS.Platform = process.platform,
): PrivateRuntimeRootCapability =>
platform === "win32"
? windowsNativeCapabilities(platform).private_runtime_dacl
: { available: true, reason: null, proof: "posix-mode-0700" };
/** Expected failure when a runtime root's privacy boundary is unavailable. */
export class PrivateRuntimeRootUnavailableError extends Error {
readonly code = "private-runtime-root-authority-unavailable";
constructor(message: string) {
super(message);
this.name = "PrivateRuntimeRootUnavailableError";
}
}
/**
@@ -24,6 +58,10 @@ export class PrivateRuntimeRoot {
static async create(
options: PrivateRuntimeRootOptions = {},
): Promise<PrivateRuntimeRoot> {
const platform = options.platform ?? process.platform;
const capability = privateRuntimeRootCapability(platform);
if (!capability.available)
throw new PrivateRuntimeRootUnavailableError(capability.reason);
const path = await mkdtemp(
join(options.parent ?? tmpdir(), options.prefix ?? "rea-provider-"),
);
+71 -4
View File
@@ -15,6 +15,8 @@ export interface OwnedProcessGroup {
readonly expectedCommand?: string;
/** Expected launcher parent, checked only while the leader exists. */
readonly expectedParentPid?: number;
/** Scan all live processes for this run token during cleanup. */
readonly sweepTokenOwnedProcesses?: boolean;
}
/** One entry from an operating-system process-table snapshot. */
@@ -96,7 +98,8 @@ export type ProcessGroupObservation =
* Terminate one Windows process tree through the platform utility.
*
* This is a bounded P0 cleanup mechanism, not Job Object ownership proof. The
* caller-visible Windows limitations must preserve that distinction.
* caller-visible Windows capability report remains unavailable until a native
* authority verifies Job Object creation, membership, and cleanup semantics.
*/
export const cleanupWindowsProcessTree = async (
rootPid: number,
@@ -250,6 +253,24 @@ export const cleanupOwnedProcessGroup = async (
return { cleaned: true, signaled };
};
/** Verify that no live process still carries an owned capture run token. */
export const verifyNoTokenOwnedProcesses = async (
runId: string,
host: ProcessOwnershipHost = systemHost,
): Promise<ProcessCleanupResult> => {
let processes: readonly ProcessTableEntry[];
try {
processes = liveProcesses(await host.listProcesses());
} catch {
return { cleaned: false, reason: "process table could not be inspected" };
}
const scan = await scanTokenOwnedProcesses(processes, runId, host);
if (scan.failures.length > 0) return cleanupValidationFailure(scan.failures);
return scan.owned.length === 0
? { cleaned: true, signaled: false }
: { cleaned: false, reason: "token-owned process remained after cleanup" };
};
interface OwnedCleanupPlan {
readonly signalOrder: readonly number[];
}
@@ -259,11 +280,24 @@ const createOwnedCleanupPlan = async (
processes: readonly ProcessTableEntry[],
host: ProcessOwnershipHost,
): Promise<OwnedCleanupPlan | ProcessCleanupResult> => {
const tokenOwned =
ownership.sweepTokenOwnedProcesses === true
? await scanTokenOwnedProcesses(processes, ownership.runId, host)
: { owned: [], failures: [] };
if (tokenOwned.failures.length > 0)
return cleanupValidationFailure(tokenOwned.failures);
const tokenOwnedGroupIds = new Set(
tokenOwned.owned.map(({ processGroupId }) => processGroupId),
);
const launcher = processes.find(({ pid }) => pid === ownership.leaderPid);
const rootMembers = processes.filter(
({ processGroupId }) => processGroupId === ownership.processGroupId,
);
if (launcher === undefined && rootMembers.length === 0)
if (
launcher === undefined &&
rootMembers.length === 0 &&
tokenOwned.owned.length === 0
)
return { cleaned: true, signaled: false };
let descendants: readonly ProcessTableEntry[] = [];
if (launcher !== undefined) {
@@ -276,13 +310,18 @@ const createOwnedCleanupPlan = async (
const processGroupIds = new Set<number>([ownership.processGroupId]);
for (const descendant of descendants)
processGroupIds.add(descendant.processGroupId);
for (const process of tokenOwned.owned)
processGroupIds.add(process.processGroupId);
for (const processGroupId of processGroupIds) {
if (processGroupId === ownership.processGroupId) continue;
const groupLeader = processes.find(
({ pid, processGroupId: observedGroupId }) =>
pid === processGroupId && observedGroupId === processGroupId,
);
if (groupLeader === undefined || !descendantPids.has(groupLeader.pid))
if (
(groupLeader === undefined || !descendantPids.has(groupLeader.pid)) &&
!tokenOwnedGroupIds.has(processGroupId)
)
return {
cleaned: false,
reason:
@@ -360,7 +399,8 @@ const revalidateOwnedProcessGroup = async (
if (
processGroupId !== ownership.processGroupId &&
members.length > 0 &&
!members.some(({ pid }) => pid === processGroupId)
!members.some(({ pid }) => pid === processGroupId) &&
ownership.sweepTokenOwnedProcesses !== true
)
return {
cleaned: false,
@@ -401,6 +441,33 @@ const processOwnershipFailures = async (
return failures;
};
interface TokenOwnedProcessScan {
readonly owned: readonly ProcessTableEntry[];
readonly failures: readonly ProcessOwnershipValidationFailure[];
}
const scanTokenOwnedProcesses = async (
processes: readonly ProcessTableEntry[],
runId: string,
host: ProcessOwnershipHost,
): Promise<TokenOwnedProcessScan> => {
const owned: ProcessTableEntry[] = [];
const failures: ProcessOwnershipValidationFailure[] = [];
for (const process of processes) {
try {
if ((await host.environment(process.pid)).REA_PROCESS_RUN_ID === runId)
owned.push(process);
} catch {
try {
const live = liveProcesses(await host.listProcesses());
if (!live.some(({ pid }) => pid === process.pid)) continue;
} catch {}
failures.push({ pid: process.pid, reason: "environment-unreadable" });
}
}
return { owned, failures };
};
/** Observe one group without signaling it, failing closed on identity doubt. */
export const observeOwnedProcessGroup = async (
ownership: OwnedProcessGroup,
+65
View File
@@ -0,0 +1,65 @@
/**
* Provider-neutral security controls that require a verified Windows native
* authority. Runtime probes and POSIX permissions do not satisfy these
* controls.
*/
export type WindowsNativeCapability =
| {
readonly available: true;
readonly reason: null;
readonly proof: "native-authority";
}
| {
readonly available: false;
readonly reason: string;
readonly proof: "not-proven" | "not-applicable";
};
/** Security controls required before REA may claim Windows isolation. */
export interface WindowsNativeCapabilitySet {
readonly job_object_process_ownership: WindowsNativeCapability;
readonly private_runtime_dacl: WindowsNativeCapability;
readonly reparse_safe_path_admission: WindowsNativeCapability;
}
/** Stable explanation used whenever the native Windows authority is absent. */
export const WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON =
"Verified Windows native authority is unavailable: Job Object process ownership, private runtime DACL enforcement, and reparse-safe path admission are not implemented; chmod(0700) is insufficient for Windows private DACL proof, and taskkill is not a Job Object security proof";
/**
* Describe native Windows controls without inferring them from taskkill,
* chmod, symlink creation, or a numeric POSIX open flag.
*/
export const windowsNativeCapabilities = (
platform: NodeJS.Platform,
): WindowsNativeCapabilitySet => {
if (platform !== "win32") {
const notApplicable = {
available: false,
reason: "Windows native authority is not applicable on this host",
proof: "not-applicable",
} as const;
return {
job_object_process_ownership: notApplicable,
private_runtime_dacl: notApplicable,
reparse_safe_path_admission: notApplicable,
};
}
const notProven = {
available: false,
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
proof: "not-proven",
} as const;
return {
job_object_process_ownership: notProven,
private_runtime_dacl: notProven,
reparse_safe_path_admission: notProven,
};
};
/** Whether every native control needed for Windows isolation is proven. */
export const hasWindowsNativeAuthority = (platform: NodeJS.Platform): boolean =>
Object.values(windowsNativeCapabilities(platform)).every(
({ available }) => available,
);
+7 -1
View File
@@ -19,6 +19,7 @@ import type { PermissionAuthority } from "../application/PermissionAuthority.js"
import type { BrowserObservationPort } from "../application/BrowserObservationPort.js";
import type { BrowserScenarioCapturePort } from "../application/BrowserScenarioCapturePort.js";
import type { ElectronObservationPort } from "../application/ElectronObservationPort.js";
import type { ElectronActiveObservationPort } from "../application/ElectronActiveObservationPort.js";
import type { JavaScriptRuntimeObservationPort } from "../application/JavaScriptRuntimeObservationPort.js";
import type { SessionAvailability } from "./sessionAvailabilityPolicy.js";
import { sessionAvailabilityPolicy } from "./sessionAvailabilityPolicy.js";
@@ -29,7 +30,7 @@ import {
import { installDynamicToolAvailability } from "./DynamicToolAvailability.js";
const TARGET_FREE_INSTRUCTIONS =
"ASAR/JavaScript -> analyze_javascript_application; archive/package -> open_binary(path), then inspect_artifact/inventory_artifact (active target); managed PE/CLI -> inspect_managed_artifact; passive browser/Electron -> list_browser_targets/list_electron_targets; approved browser interaction -> capture_browser_scenario; Node/Electron Inspector -> list_javascript_runtime_targets; native binary/database -> open_binary, then binary_overview. Start with binary_session; call only tools in tools/list. Hidden routes: binary_session detail=capabilities. Use summaries, cite Evidence IDs. Never repeat identical analysis or read full Evidence.";
"ASAR/JavaScript -> analyze_javascript_application; archive/package -> open_binary(path), then inspect_artifact/inventory_artifact (active target); managed PE/CLI -> inspect_managed_artifact; browser/Electron -> list_browser_targets/list_electron_targets; approved -> capture_browser_scenario/capture_electron_scenario; Node/Electron Inspector -> list_javascript_runtime_targets; native binary/database -> open_binary, then binary_overview. Start with binary_session; use tools/list; capabilities via binary_session. Use summaries, cite Evidence IDs; Never repeat identical analysis or read full Evidence.";
const ACTIVE_TARGET_INSTRUCTIONS =
"REA analyzes the active reverse-engineering target. Start native analysis with binary_overview, then narrow with analyze_function, literal search, callers, callees, and xrefs. Prefer summary views, never repeat an identical call, and read full Evidence only when the task requires it.";
@@ -55,6 +56,7 @@ export interface CreateServerOptions {
readonly browserObservation?: BrowserObservationPort;
readonly browserScenarioCapture?: BrowserScenarioCapturePort;
readonly electronObservation?: ElectronObservationPort;
readonly electronActiveObservation?: ElectronActiveObservationPort;
readonly javascriptRuntimeObservation?: JavaScriptRuntimeObservationPort;
readonly artifactIntegrityContinueEnabled?: () => boolean;
readonly javascriptReplayPolicy?: JavaScriptReplayPolicy;
@@ -66,6 +68,7 @@ export interface CreateServerOptions {
readonly browserObservation: BrowserObservationPort;
readonly browserScenarioCapture: BrowserScenarioCapturePort;
readonly electronObservation: ElectronObservationPort;
readonly electronActiveObservation: ElectronActiveObservationPort;
readonly javascriptRuntimeObservation: JavaScriptRuntimeObservationPort;
}>;
}
@@ -84,6 +87,9 @@ const installSessionToolAvailability = (
browserObservationEnabled: options.browserObservation !== undefined,
browserScenarioEnabled: options.browserScenarioCapture !== undefined,
electronObservationEnabled: options.electronObservation !== undefined,
electronAutomationEnabled:
options.electronActiveObservation !== undefined &&
options.permissionAuthority !== undefined,
v8InspectorObservationEnabled:
options.javascriptRuntimeObservation !== undefined,
javascriptReplayEnabled: options.javascriptReplayPolicy?.enabled ?? false,
+1
View File
@@ -158,6 +158,7 @@ const hydrateObservationFamily = async (
registerElectronTools(context.server, {
...common,
electron: context.options.electronObservation,
electronActive: context.options.electronActiveObservation,
});
return;
}
+22 -2
View File
@@ -3,6 +3,8 @@ import type { z } from "zod";
import type { BinarySessionPort } from "../application/BinarySession.js";
import type { ElectronObservationPort } from "../application/ElectronObservationPort.js";
import type { ElectronActiveObservationPort } from "../application/ElectronActiveObservationPort.js";
import { captureElectronScenario } from "../application/ElectronActiveObservationService.js";
import { analyzeJavaScriptApplicationValidated } from "../application/JavaScriptApplicationService.js";
import { reconcileJavaScriptRuntimeEvidenceValidated } from "../application/JavaScriptRuntimeReconciliationService.js";
import {
@@ -18,6 +20,7 @@ import {
inspectElectronPageInputSchema,
listElectronTargetsInputSchema,
} from "../domain/electronObservation.js";
import { electronActiveObservationInputSchema } from "../domain/electronActiveObservation.js";
import { reconcileJavaScriptRuntimeInputSchema } from "../domain/javascriptRuntimeReconciliationSchemas.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
@@ -36,6 +39,7 @@ import { summarizeJavaScriptApplicationEvidence } from "./javascriptApplicationR
interface ElectronToolRegistration {
readonly logger: Logger;
readonly electron: ElectronObservationPort | undefined;
readonly electronActive: ElectronActiveObservationPort | undefined;
readonly permissionAuthority: PermissionAuthority | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
}
@@ -66,8 +70,13 @@ export const registerElectronTools = (
server: McpServer,
options: ElectronToolRegistration,
): void => {
const [listContract, inspectContract, analyzeContract, reconcileContract] =
ELECTRON_TOOL_CONTRACTS;
const [
listContract,
inspectContract,
analyzeContract,
reconcileContract,
activeContract,
] = ELECTRON_TOOL_CONTRACTS;
registerElectronTool(server, options, {
contract: listContract,
@@ -118,6 +127,17 @@ export const registerElectronTools = (
execute: (parsed, _context) =>
Promise.resolve(reconcileJavaScriptRuntimeEvidenceValidated(parsed)),
});
registerElectronTool(server, options, {
contract: activeContract,
schema: electronActiveObservationInputSchema,
execute: (parsed, { signal, progress }) =>
captureElectronScenario(
options.electronActive,
options.permissionAuthority,
parsed,
{ signal, progress },
),
});
};
const registerElectronTool = <Schema extends z.ZodType>(
+3
View File
@@ -13,6 +13,7 @@ export interface SessionAvailabilityDefaults {
| "browserObservationEnabled"
| "browserScenarioEnabled"
| "electronObservationEnabled"
| "electronAutomationEnabled"
| "v8InspectorObservationEnabled"
| "javascriptReplayEnabled"
| "managedRuntimeEnabled"
@@ -35,6 +36,8 @@ export const sessionAvailabilityPolicy = (
defaults.optionalFeatures?.browserScenarioEnabled ?? false,
electronObservationEnabled:
defaults.optionalFeatures?.electronObservationEnabled ?? false,
electronAutomationEnabled:
defaults.optionalFeatures?.electronAutomationEnabled ?? false,
v8InspectorObservationEnabled:
defaults.optionalFeatures?.v8InspectorObservationEnabled ?? false,
javascriptReplayEnabled: