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:
@@ -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,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.",
|
||||
];
|
||||
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user