diff --git a/docs/electron-observation.md b/docs/electron-observation.md index 60ab80deb..62ade7095 100644 --- a/docs/electron-observation.md +++ b/docs/electron-observation.md @@ -86,9 +86,18 @@ rea capture-electron-scenario scenario.json --json The result records action status and targets, correlated app/window/WebContents, preload, session, navigation, shell, permission, popup, download, protocol, -native-addon, process, and IPC timeline events. IPC channels are capped at -1,024 characters and argument-shape metadata at 32 entries; values are never -retained. Renderer crash/restart and deep-link actions are synthetic +native-addon, process, and IPC timeline events. Event retention has a 16 MiB +accounting budget for full channel strings, argument-shape arrays, and an +estimated object-graph cost. Admission computes an exact JSON byte length +incrementally, then charges twice that size plus 256 bytes per event and 8 bytes +per argument shape. The doubled JSON charge covers the timeline and IPC views; +the additional charge estimates their in-process object and array storage. This +is a resource estimate, not an exact V8 heap measurement. An event that does not +fit is dropped whole. The result reports the estimate, serialized-byte upper +bound, dropped event families, and +observed/dropped totals for IPC and runtime events. Retained sequence numbers +keep their original capture identities. Payload values are never retained. +Renderer crash/restart and deep-link actions are synthetic scenario controls; their attempted and observed outcomes remain in the timeline. The active hook blocks and records external shell/navigation, permission, download, popup, updater, and OS-integration effects. The timeline diff --git a/scripts/electron-active-hook-boundaries.cjs b/scripts/electron-active-hook-boundaries.cjs index a312ae2b4..81d199a18 100644 --- a/scripts/electron-active-hook-boundaries.cjs +++ b/scripts/electron-active-hook-boundaries.cjs @@ -61,7 +61,7 @@ const createElectronActiveBoundaryPatches = ({ const target = typeof args[0] === "string" ? args[0] : null; recordRuntime("preload", "context-bridge-exposure", "attempted", { target, - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, process_type: processType(), }); try { @@ -110,7 +110,7 @@ const createElectronActiveBoundaryPatches = ({ event === "will-download" ? "blocked" : "observed", { target: identity(args[0], "webContents"), - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, error: event === "will-download", }, ); @@ -124,7 +124,7 @@ const createElectronActiveBoundaryPatches = ({ (webContents, permission, callback) => { recordRuntime("permission", "permission-request", "blocked", { target: identity(webContents, "webContents"), - argument_shapes: [shape(permission)], + argument_shape_values: [permission], error: true, }); if (typeof callback === "function") callback(false); @@ -137,7 +137,7 @@ const createElectronActiveBoundaryPatches = ({ return originalPermissionCheck.call(this, (webContents, permission) => { recordRuntime("permission", "permission-check", "blocked", { target: identity(webContents, "webContents"), - argument_shapes: [shape(permission)], + argument_shape_values: [permission], error: true, }); return false; @@ -148,7 +148,7 @@ const createElectronActiveBoundaryPatches = ({ session.setCertificateVerifyProc = function blockedCertificate() { return originalCertificate.call(this, (request, callback) => { recordRuntime("permission", "certificate-error", "blocked", { - argument_shapes: [shape(request)], + argument_shape_values: [request], error: true, }); if (typeof callback === "function") callback(-2); @@ -168,14 +168,14 @@ const createElectronActiveBoundaryPatches = ({ } catch { recordRuntime("popup-attempt", "window-open-handler", "failed", { target: contentsId, - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, error: true, }); return { action: "deny" }; } recordRuntime("popup-attempt", "window-open-handler", "blocked", { target: contentsId, - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, error: true, }); return { action: "deny" }; @@ -223,7 +223,7 @@ const createElectronActiveBoundaryPatches = ({ method === "relaunch" ? "updater" : "protocol", method, "blocked", - { argument_shapes: args.map((value) => shape(value)), error: true }, + { argument_shape_values: args, error: true }, ); return method === "setAsDefaultProtocolClient" ? false : undefined; }; @@ -250,11 +250,7 @@ const createElectronActiveBoundaryPatches = ({ recordRuntime("native-addon", "dlopen", "attempted", { artifact_path: typeof filename === "string" ? filename : null, artifact_sha256: digest, - argument_shapes: [ - shape(module), - shape(filename), - ...args.map((value) => shape(value)), - ], + argument_shape_value_groups: [[module, filename], args], }); try { const result = original.call(this, module, filename, ...args); @@ -280,7 +276,7 @@ const createElectronActiveBoundaryPatches = ({ if (typeof original !== "function") return; utilityProcess.fork = function patchedFork(...args) { recordRuntime("process-lifecycle", "utility-process-fork", "attempted", { - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, process_type: "main", }); const child = original.apply(this, args); @@ -304,7 +300,7 @@ const createElectronActiveBoundaryPatches = ({ recordRuntime("process-lifecycle", `utility.${event}`, "observed", { target: childId, process_type: "utility", - argument_shapes: eventArgs.map((value) => shape(value)), + argument_shape_values: eventArgs, }); }); if (child && typeof child.postMessage === "function") { @@ -344,7 +340,7 @@ const createElectronActiveBoundaryPatches = ({ if (typeof original !== "function") continue; shell[method] = function blockedShellCall(...args) { recordRuntime("shell-attempt", method, "blocked", { - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, error: true, }); return Promise.reject(new Error("External shell effects are blocked")); @@ -359,7 +355,7 @@ const createElectronActiveBoundaryPatches = ({ if (typeof original !== "function") continue; childProcess[method] = function patchedChildProcess(...args) { recordRuntime("process-lifecycle", `child.${method}`, "attempted", { - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, }); const child = original.apply(this, args); const childId = identity(child, "child"); @@ -369,7 +365,7 @@ const createElectronActiveBoundaryPatches = ({ patchEmitter(child, (event, eventArgs) => recordRuntime("process-lifecycle", `child.${event}`, "observed", { target: childId, - argument_shapes: eventArgs.map((value) => shape(value)), + argument_shape_values: eventArgs, }), ); return child; diff --git a/scripts/electron-active-hook.cjs b/scripts/electron-active-hook.cjs index 4185ffc78..8d7766c95 100644 --- a/scripts/electron-active-hook.cjs +++ b/scripts/electron-active-hook.cjs @@ -16,9 +16,19 @@ const ipcEventKinds = new Set([ "ipc-renderer-post-message", ]); const events = []; +// Budget serialized data and estimated retained object/array storage together. +const retentionBudgetBytes = 16 * 1024 * 1024; +const snapshotEnvelopeReserveBytes = 1024; +let estimatedRetainedBytes = 0; +let serializedBytes = 0; let observed = 0; let observedIpc = 0; let observedRuntime = 0; +let dropped = 0; +let droppedIpc = 0; +let droppedRuntime = 0; +const droppedFamilies = new Map(); +const droppedRoles = new Map(); let sequence = 0; let correlationSequence = 0; @@ -43,6 +53,73 @@ const shape = (value, depth = 0) => { } }; +// Measure JSON strings without allocating an encoded copy of a caller value. +const jsonStringBytes = (value) => { + let bytes = 2; + for (let index = 0; index < value.length; index += 1) { + const code = value.charCodeAt(index); + if (code === 0x22 || code === 0x5c) bytes += 2; + else if ( + code === 0x08 || + code === 0x09 || + code === 0x0a || + code === 0x0c || + code === 0x0d + ) + bytes += 2; + else if (code <= 0x1f) bytes += 6; + else if (code >= 0xd800 && code <= 0xdbff) { + const next = value.charCodeAt(index + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + bytes += 4; + index += 1; + } else bytes += 6; + } else if (code >= 0xdc00 && code <= 0xdfff) bytes += 6; + else if (code <= 0x7f) bytes += 1; + else if (code <= 0x7ff) bytes += 2; + else bytes += 3; + if (bytes > retentionBudgetBytes) return bytes; + } + return bytes; +}; + +const jsonScalarBytes = (value) => { + if (value === null) return 4; + if (typeof value === "string") return jsonStringBytes(value); + if (typeof value === "boolean") return value ? 4 : 5; + return String(value).length; +}; + +const eventFamily = (kind, processTypeValue) => { + if (kind === "preload" && processTypeValue === "main") + return "preload-configuration"; + if (kind.startsWith("ipc-renderer")) + return processTypeValue === "renderer" ? "renderer-ipc" : "ipc"; + return ipcEventKinds.has(kind) ? "ipc" : kind; +}; + +const noteDropped = (kind, processTypeValue, isIpc) => { + dropped += 1; + if (isIpc) droppedIpc += 1; + else droppedRuntime += 1; + const family = eventFamily(kind, processTypeValue); + droppedFamilies.set(family, (droppedFamilies.get(family) ?? 0) + 1); + if (typeof processTypeValue === "string") + droppedRoles.set( + processTypeValue, + (droppedRoles.get(processTypeValue) ?? 0) + 1, + ); + if (kind === "window-lifecycle") + droppedRoles.set("window", (droppedRoles.get("window") ?? 0) + 1); + if (kind === "web-contents-lifecycle" || kind === "navigation") + droppedRoles.set( + "web_contents", + (droppedRoles.get("web_contents") ?? 0) + 1, + ); + if (kind === "preload" && processTypeValue === "preload") + droppedRoles.set("preload", (droppedRoles.get("preload") ?? 0) + 1); +}; + const isAllowedNavigation = (value) => { if (typeof value !== "string") return true; try { @@ -83,7 +160,8 @@ const frameIdentity = (event) => { const record = (event) => { observed += 1; - if (ipcEventKinds.has(event.kind)) observedIpc += 1; + const isIpc = ipcEventKinds.has(event.kind); + if (isIpc) observedIpc += 1; else observedRuntime += 1; const raw = { sequence: ++sequence, @@ -109,10 +187,15 @@ const record = (event) => { error: false, ...event, }; - const argumentShapes = Array.isArray(raw.argument_shapes) + const shapeGroups = Array.isArray(raw.argument_shape_value_groups) + ? raw.argument_shape_value_groups.filter(Array.isArray) + : Array.isArray(raw.argument_shape_values) + ? [raw.argument_shape_values] + : []; + const existingShapes = Array.isArray(raw.argument_shapes) ? raw.argument_shapes : []; - events.push({ + const retainedEvent = { ...raw, correlation_id: raw.correlation_id, event: typeof raw.event === "string" ? raw.event : null, @@ -121,9 +204,7 @@ const record = (event) => { receiver: typeof raw.receiver === "string" ? raw.receiver : null, frame: typeof raw.frame === "string" ? raw.frame : null, target: typeof raw.target === "string" ? raw.target : null, - argument_shapes: argumentShapes.map((value) => - typeof value === "string" ? value : "unknown", - ), + argument_shapes: [], result_shape: typeof raw.result_shape === "string" ? raw.result_shape : null, process_type: @@ -132,8 +213,91 @@ const record = (event) => { typeof raw.artifact_path === "string" ? raw.artifact_path : null, artifact_sha256: typeof raw.artifact_sha256 === "string" ? raw.artifact_sha256 : null, - }); - return events.at(-1); + }; + delete retainedEvent.argument_shape_values; + delete retainedEvent.argument_shape_value_groups; + + // All event values are JSON scalars except argument_shapes. Measure them + // incrementally so large channels, paths, or shape lists never require a + // full JSON.stringify temporary allocation before the budget decision. + let eventBytes = 2; + let argumentShapeCount = 0; + const eventKeys = Object.keys(retainedEvent); + for (let index = 0; index < eventKeys.length; index += 1) { + const key = eventKeys[index]; + const value = retainedEvent[key]; + if (index > 0) eventBytes += 1; + eventBytes += jsonStringBytes(key) + 1; + if (key === "argument_shapes") { + eventBytes += 2; + let shapeOverflow = false; + const countShape = (argument) => { + const encodedShapeBytes = jsonStringBytes(shape(argument)); + eventBytes += encodedShapeBytes + (argumentShapeCount === 0 ? 0 : 1); + argumentShapeCount += 1; + shapeOverflow = + eventBytes + estimatedRetainedBytes + snapshotEnvelopeReserveBytes > + retentionBudgetBytes; + }; + for (const group of shapeGroups) + for (const argument of group) { + countShape(argument); + if (shapeOverflow) break; + } + if (shapeOverflow) { + noteDropped(raw.kind, retainedEvent.process_type, isIpc); + return null; + } + for (const valueShape of existingShapes) + if (!shapeOverflow) { + eventBytes += + jsonStringBytes( + typeof valueShape === "string" ? valueShape : "unknown", + ) + (argumentShapeCount++ === 0 ? 0 : 1); + shapeOverflow = + eventBytes + estimatedRetainedBytes + snapshotEnvelopeReserveBytes > + retentionBudgetBytes; + } + if (shapeOverflow) { + noteDropped(raw.kind, retainedEvent.process_type, isIpc); + return null; + } + } else eventBytes += jsonScalarBytes(value); + if ( + eventBytes + estimatedRetainedBytes + snapshotEnvelopeReserveBytes > + retentionBudgetBytes + ) { + noteDropped(raw.kind, retainedEvent.process_type, isIpc); + return null; + } + } + // Reserve room for the only fields mutated after recording: result_shape and + // error. The shape vocabulary's longest value is "undefined". + const reservedMutationBytes = retainedEvent.result_shape === null ? 7 : 0; + // Include one byte for the event-array separator and reserve space for the + // snapshot's counters and JSON delimiters. + // One retained event, one defensive snapshot copy, and up to two serialized + // result views (timeline plus IPC), with per-object and per-array-slot costs. + const eventEstimateBytes = eventBytes * 3 + 512 + argumentShapeCount * 16; + const retainedEventBytes = eventEstimateBytes + reservedMutationBytes + 1; + if ( + estimatedRetainedBytes + retainedEventBytes + snapshotEnvelopeReserveBytes > + retentionBudgetBytes + ) { + noteDropped(raw.kind, retainedEvent.process_type, isIpc); + return null; + } + for (const group of shapeGroups) + for (const argument of group) + retainedEvent.argument_shapes.push(shape(argument)); + for (const valueShape of existingShapes) + retainedEvent.argument_shapes.push( + typeof valueShape === "string" ? valueShape : "unknown", + ); + events.push(retainedEvent); + estimatedRetainedBytes += retainedEventBytes; + serializedBytes += eventBytes + reservedMutationBytes + 1; + return retainedEvent; }; const recordRuntime = (kind, event, phase, details = {}) => @@ -145,7 +309,7 @@ const recordIpc = (kind, channel, args, details = {}) => return record({ kind, channel: typeof channel === "string" ? channel : null, - argument_shapes: values.map((value) => shape(value)), + argument_shape_values: values, ...details, }); })(); @@ -222,7 +386,7 @@ const patchNavigationMethods = (webContents, contentsId) => { webContents[method] = function patchedNavigation(...args) { recordRuntime("navigation", method, "attempted", { target: contentsId, - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, }); if (method === "loadURL" && !isAllowedNavigation(args[0])) { recordRuntime("navigation", method, "blocked", { @@ -354,7 +518,7 @@ const patchWebContents = (webContents, windowId) => { recordRuntime("navigation", event, "blocked", { target: contentsId, sender: windowId, - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, error: true, }); return; @@ -363,7 +527,7 @@ const patchWebContents = (webContents, windowId) => { recordRuntime(kind, event, "observed", { target: contentsId, sender: windowId, - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, error: kind === "error", }); if (event === "did-create-window") { @@ -388,7 +552,7 @@ const patchBrowserWindow = (electron) => { const targetId = identity(window, "window"); recordRuntime("window-lifecycle", "created", "completed", { target: targetId, - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, }); const preload = args[0]?.webPreferences?.preload; if (typeof preload === "string") @@ -427,7 +591,7 @@ try { "observed", { target: "app", - argument_shapes: args.map((value) => shape(value)), + argument_shape_values: args, process_type: "main", }, ), @@ -444,14 +608,14 @@ try { boundaries.patchChildProcess(); process.once("uncaughtException", (cause, origin) => { recordRuntime("process-lifecycle", "uncaught-exception", "observed", { - argument_shapes: [shape(cause), shape(origin)], + argument_shape_values: [cause, origin], error: true, }); throw cause; }); process.once("unhandledRejection", (reason, promise) => { recordRuntime("process-lifecycle", "unhandled-rejection", "observed", { - argument_shapes: [shape(reason), shape(promise)], + argument_shape_values: [reason, promise], error: true, }); throw reason; @@ -461,7 +625,25 @@ try { } globalThis.__reaElectronActiveSnapshot = () => ({ - events: events.slice(), + events: events.map((event) => ({ + ...event, + argument_shapes: [...event.argument_shapes], + })), + retention_budget_bytes: retentionBudgetBytes, + estimated_retained_bytes: estimatedRetainedBytes, + event_serialized_byte_upper_bound: serializedBytes, + retained: events.length, + dropped, + dropped_ipc: droppedIpc, + dropped_runtime: droppedRuntime, + dropped_event_families: [...droppedFamilies].map(([family, count]) => ({ + family, + count, + })), + dropped_event_roles: [...droppedRoles].map(([role, count]) => ({ + role, + count, + })), observed, observed_ipc: observedIpc, observed_runtime: observedRuntime, diff --git a/src/browser/PlaywrightElectronActiveActions.test.ts b/src/browser/PlaywrightElectronActiveActions.test.ts index c8890cd45..5f78a29b8 100644 --- a/src/browser/PlaywrightElectronActiveActions.test.ts +++ b/src/browser/PlaywrightElectronActiveActions.test.ts @@ -9,6 +9,19 @@ import { import { createElectronActiveObservationFixtureResult } from "../domain/javascript/electronActiveObservation.fixture.js"; import { runElectronActions } from "./PlaywrightElectronActiveActions.js"; +it("keeps legacy Electron results explicit about unavailable retention data", () => { + const { retention: _retention, ...legacyResult } = + createElectronActiveObservationFixtureResult("/opt/app"); + const parsed = electronActiveObservationResultSchema.parse({ + ...legacyResult, + ipc: { ...legacyResult.ipc, dropped: undefined }, + timeline: { ...legacyResult.timeline, dropped: undefined }, + }); + expect(parsed.retention).toBeNull(); + expect(parsed.ipc.dropped).toBeNull(); + expect(parsed.timeline.dropped).toBeNull(); +}); + it("parses window, renderer, and deep-link actions for agents", () => { const input = electronActiveObservationInputSchema.parse({ executable_path: "/opt/electron", diff --git a/src/browser/PlaywrightElectronActiveActions.ts b/src/browser/PlaywrightElectronActiveActions.ts index 2c4a71183..bb1469e46 100644 --- a/src/browser/PlaywrightElectronActiveActions.ts +++ b/src/browser/PlaywrightElectronActiveActions.ts @@ -68,6 +68,25 @@ const hookEventSchema = z.strictObject({ const hookSnapshotSchema = z.strictObject({ events: z.array(hookEventSchema), + retention_budget_bytes: z.number().int().min(0), + estimated_retained_bytes: z.number().int().min(0), + event_serialized_byte_upper_bound: z.number().int().min(0), + retained: z.number().int().min(0), + dropped: z.number().int().min(0), + dropped_ipc: z.number().int().min(0), + dropped_runtime: z.number().int().min(0), + dropped_event_families: z.array( + z.strictObject({ + family: z.string().min(1), + count: z.number().int().min(1), + }), + ), + dropped_event_roles: z.array( + z.strictObject({ + role: z.string().min(1), + count: z.number().int().min(1), + }), + ), observed: z.number().int().min(0), observed_ipc: z.number().int().min(0), observed_runtime: z.number().int().min(0), @@ -357,6 +376,15 @@ export const readApplicationState = async ( ? candidate() : { events: [], + retention_budget_bytes: 0, + estimated_retained_bytes: 0, + event_serialized_byte_upper_bound: 0, + retained: 0, + dropped: 0, + dropped_ipc: 0, + dropped_runtime: 0, + dropped_event_families: [], + dropped_event_roles: [], observed: 0, observed_ipc: 0, observed_runtime: 0, diff --git a/src/browser/PlaywrightElectronActiveProjection.test.ts b/src/browser/PlaywrightElectronActiveProjection.test.ts new file mode 100644 index 000000000..baec9b219 --- /dev/null +++ b/src/browser/PlaywrightElectronActiveProjection.test.ts @@ -0,0 +1,129 @@ +import { expect, it } from "vitest"; + +import { projectElectronActiveCapture } from "./PlaywrightElectronActiveProjection.js"; + +it("projects hook retention and dropped event families through the result schema", () => { + const event = { + sequence: 1, + correlation_id: "capture:123:1", + kind: "main-handler-invocation" as const, + event: null, + phase: "observed" as const, + channel: "readiness:echo", + direction: "renderer-to-main" as const, + sender: null, + receiver: "main", + frame: null, + target: null, + argument_shapes: [], + result_shape: null, + process_type: "main", + source: "electron-active-hook", + capture_method: "api-wrapper" as const, + artifact_path: null, + artifact_sha256: null, + error: false, + }; + const result = projectElectronActiveCapture( + { + executable: "/opt/electron", + application: "/opt/app/main.js", + }, + [], + { + windows: [], + metrics: [], + electronVersion: "test-electron", + hookSnapshot: { + events: [event], + retention_budget_bytes: 16 * 1024 * 1024, + estimated_retained_bytes: 1_024, + event_serialized_byte_upper_bound: 512, + retained: 1, + dropped: 1, + dropped_ipc: 0, + dropped_runtime: 1, + dropped_event_families: [{ family: "renderer-ipc", count: 1 }], + dropped_event_roles: [{ role: "renderer", count: 1 }], + observed: 2, + observed_ipc: 1, + observed_runtime: 1, + hook_error: false, + }, + }, + ); + + expect(result.retention).toMatchObject({ + budget_bytes: 16 * 1024 * 1024, + estimated_retained_bytes: 1_024, + event_serialized_byte_upper_bound: 512, + retained: 1, + dropped: 1, + dropped_event_families: [{ family: "renderer-ipc", count: 1 }], + dropped_event_roles: [{ role: "renderer", count: 1 }], + }); + expect(result.ipc).toMatchObject({ observed: 1, dropped: 0 }); + expect(result.timeline).toMatchObject({ observed: 2, dropped: 1 }); + expect(result.coverage.observed_event_families).toContain("renderer-ipc"); + expect(result.coverage.unavailable_event_families).not.toContain( + "renderer-ipc", + ); + expect(result.coverage.observed_roles).toContain("renderer"); + expect(result.coverage.unavailable_event_families).toContain("preload"); +}); + +it("keeps renderer coverage unavailable when only the main process was observed", () => { + const result = projectElectronActiveCapture( + { + executable: "/opt/electron", + application: "/opt/app/main.js", + }, + [], + { + windows: [], + metrics: [], + electronVersion: "test-electron", + hookSnapshot: { + events: [ + { + sequence: 1, + correlation_id: "capture:123:1", + kind: "app-lifecycle", + event: "ready", + phase: "observed", + channel: null, + direction: null, + sender: null, + receiver: null, + frame: null, + target: "app", + argument_shapes: [], + result_shape: null, + process_type: "main", + source: "electron-active-hook", + capture_method: "event-emitter", + artifact_path: null, + artifact_sha256: null, + error: false, + }, + ], + retention_budget_bytes: 16 * 1024 * 1024, + estimated_retained_bytes: 0, + event_serialized_byte_upper_bound: 0, + retained: 1, + dropped: 0, + dropped_ipc: 0, + dropped_runtime: 0, + dropped_event_families: [], + dropped_event_roles: [], + observed: 1, + observed_ipc: 0, + observed_runtime: 1, + hook_error: false, + }, + }, + ); + + expect(result.coverage.observed_roles).not.toContain("renderer"); + expect(result.coverage.unavailable_event_families).toContain("renderer-ipc"); +}); diff --git a/src/browser/PlaywrightElectronActiveProjection.ts b/src/browser/PlaywrightElectronActiveProjection.ts new file mode 100644 index 000000000..d105d5606 --- /dev/null +++ b/src/browser/PlaywrightElectronActiveProjection.ts @@ -0,0 +1,178 @@ +import { + electronActiveObservationResultSchema, + type ElectronActiveObservationResult, +} from "../domain/javascript/electronActiveObservation.js"; +import type { + ElectronHookEvent, + ElectronHookSnapshot, + ElectronMetrics, +} from "./PlaywrightElectronActiveActions.js"; + +type ElectronCapturePaths = { + readonly executable: string; + readonly application: string; +}; + +type ElectronCaptureState = { + readonly windows: ReadonlyArray< + ElectronActiveObservationResult["windows"][number] + >; + readonly metrics: ElectronMetrics; + readonly electronVersion: string; + readonly hookSnapshot: ElectronHookSnapshot; +}; + +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([ + "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 eventFamily = ( + kind: ElectronHookEvent["kind"], + processType: string | null, +): string => { + if (kind === "preload" && processType === "main") + return "preload-configuration"; + if (kind.startsWith("ipc-renderer")) + return processType === "renderer" ? "renderer-ipc" : "ipc"; + return ipcEventKinds.has(kind) ? "ipc" : kind; +}; + +const createCoverage = (hookSnapshot: ElectronHookSnapshot) => { + const observedEventFamilies: string[] = [ + ...new Set([ + ...hookSnapshot.events.map(({ kind, process_type }) => + eventFamily(kind, process_type), + ), + ...hookSnapshot.dropped_event_families.map(({ family }) => family), + ]), + ].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"] + : []), + ]), + ...hookSnapshot.dropped_event_roles.map(({ role }) => role), + ]), + ].sort(); + if (!observedRoles.includes("preload")) + unavailableEventFamilies.add("preload"); + if (!observedRoles.includes("renderer")) + unavailableEventFamilies.add("renderer-ipc"); + return { + status: hookSnapshot.hook_error ? "hook_conflict" : "partial_attach", + observed_event_families: observedEventFamilies, + unavailable_event_families: [...unavailableEventFamilies].sort(), + observed_roles: observedRoles, + pre_capture_activity: "unavailable", + } as const; +}; + +/** Project one provider hook snapshot into the canonical public result. */ +export const projectElectronActiveCapture = ( + paths: ElectronCapturePaths, + actions: ElectronActiveObservationResult["actions"], + state: ElectronCaptureState, +): ElectronActiveObservationResult => { + const { hookSnapshot } = state; + const ipcEvents = hookSnapshot.events.filter(({ kind }) => + ipcEventKinds.has(kind), + ); + return electronActiveObservationResultSchema.parse({ + 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, + processes: { + items: state.metrics, + }, + ipc: { + events: ipcEvents, + observed: hookSnapshot.observed_ipc, + dropped: hookSnapshot.dropped_ipc, + }, + timeline: { + events: hookSnapshot.events, + observed: hookSnapshot.observed, + dropped: hookSnapshot.dropped, + }, + retention: { + budget_bytes: hookSnapshot.retention_budget_bytes, + estimated_retained_bytes: hookSnapshot.estimated_retained_bytes, + event_serialized_byte_upper_bound: + hookSnapshot.event_serialized_byte_upper_bound, + retained: hookSnapshot.retained, + dropped: hookSnapshot.dropped, + dropped_event_families: hookSnapshot.dropped_event_families, + dropped_event_roles: hookSnapshot.dropped_event_roles, + observed_ipc: hookSnapshot.observed_ipc, + dropped_ipc: hookSnapshot.dropped_ipc, + observed_runtime: hookSnapshot.observed_runtime, + dropped_runtime: hookSnapshot.dropped_runtime, + }, + coverage: createCoverage(hookSnapshot), + limitations: [ + "IPC payloads are represented by value shapes; payload values are never retained.", + "IPC direction and sender/receiver identifiers are observed only where Electron exposes them at the hooked boundary.", + "The runtime timeline records 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.", + ...(hookSnapshot.dropped > 0 + ? [ + `The active hook retained ${hookSnapshot.retained} of ${hookSnapshot.observed} observed events within a ${hookSnapshot.retention_budget_bytes}-byte retained-data budget; ${hookSnapshot.dropped} events were dropped (${hookSnapshot.dropped_ipc} IPC, ${hookSnapshot.dropped_runtime} runtime).`, + ] + : []), + "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.", + ...(hookSnapshot.hook_error + ? ["The active IPC hook could not be installed."] + : []), + ], + }); +}; diff --git a/src/browser/PlaywrightElectronActiveProvider.ts b/src/browser/PlaywrightElectronActiveProvider.ts index 5aa0ef88c..590376955 100644 --- a/src/browser/PlaywrightElectronActiveProvider.ts +++ b/src/browser/PlaywrightElectronActiveProvider.ts @@ -10,10 +10,9 @@ import type { ProviderIdentity, } from "../application/AnalysisProvider.js"; import type { ElectronActiveObservationPort } from "../application/javascript/ElectronActiveObservationPort.js"; -import { - electronActiveObservationResultSchema, - type ElectronActiveObservationInput, - type ElectronActiveObservationResult, +import type { + ElectronActiveObservationInput, + ElectronActiveObservationResult, } from "../domain/javascript/electronActiveObservation.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { BrowserObservationError } from "../domain/browserObservationError.js"; @@ -38,10 +37,8 @@ import { runElectronActions, readApplicationState, runWithExecutionLimits, - type ElectronHookEvent, - type ElectronHookSnapshot, - type ElectronMetrics, } from "./PlaywrightElectronActiveActions.js"; +import { projectElectronActiveCapture } from "./PlaywrightElectronActiveProjection.js"; const OPERATION = "capture_electron_scenario" as const; const STARTUP_TIMEOUT_MS = 60_000; @@ -61,89 +58,6 @@ type ElectronPaths = { 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([ - "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" : "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 { @@ -200,7 +114,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati readApplicationState(application), options.signal, ); - outcome = ok(createResult(paths, input, actions, state)); + outcome = ok(projectElectronActiveCapture(paths, actions, state)); } catch (cause: unknown) { outcome = err( options.signal?.aborted === true && @@ -339,64 +253,6 @@ const cleanupElectronProcesses = async ( }; }; -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 metrics: ElectronMetrics; - readonly electronVersion: string; - readonly hookSnapshot: ElectronHookSnapshot; - }, -): ElectronActiveObservationResult => { - const { hookSnapshot } = state; - const ipcEvents = hookSnapshot.events.filter(({ kind }) => - ipcEventKinds.has(kind), - ); - return electronActiveObservationResultSchema.parse({ - 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, - processes: { - items: state.metrics, - }, - ipc: { - events: ipcEvents, - observed: hookSnapshot.observed_ipc, - }, - timeline: { - events: hookSnapshot.events, - observed: hookSnapshot.observed, - }, - coverage: createCoverage(hookSnapshot), - limitations: [ - "IPC payloads are represented by value shapes; payload values are never retained.", - "IPC direction and sender/receiver identifiers are observed only where Electron exposes them at the hooked boundary.", - "The runtime timeline records 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.", - ...(hookSnapshot.hook_error - ? ["The active IPC hook could not be installed."] - : []), - ], - }); -}; - const canonicalPaths = async ( input: ElectronActiveObservationInput, ): Promise => { diff --git a/src/domain/javascript/electronActiveObservation.fixture.ts b/src/domain/javascript/electronActiveObservation.fixture.ts index 144dccca8..aa217b57a 100644 --- a/src/domain/javascript/electronActiveObservation.fixture.ts +++ b/src/domain/javascript/electronActiveObservation.fixture.ts @@ -49,6 +49,20 @@ export const createElectronActiveObservationFixtureResult = ( }, ], observed: 1, + dropped: 0, + }, + retention: { + budget_bytes: 16 * 1024 * 1024, + estimated_retained_bytes: 768, + event_serialized_byte_upper_bound: 512, + retained: 1, + dropped: 0, + dropped_event_families: [], + dropped_event_roles: [], + observed_ipc: 1, + dropped_ipc: 0, + observed_runtime: 0, + dropped_runtime: 0, }, limitations: [ "IPC payloads are represented by value shapes; payload values are never retained.", diff --git a/src/domain/javascript/electronActiveObservation.ts b/src/domain/javascript/electronActiveObservation.ts index 6c1391266..7a3fd9af6 100644 --- a/src/domain/javascript/electronActiveObservation.ts +++ b/src/domain/javascript/electronActiveObservation.ts @@ -262,13 +262,41 @@ export const electronActiveObservationResultSchema = z.strictObject({ ipc: z.strictObject({ events: z.array(ipcEventSchema), observed: z.number().int().min(0), + dropped: z.number().int().min(0).nullable().default(null), }), timeline: z .strictObject({ events: z.array(timelineEventSchema), observed: z.number().int().min(0), + dropped: z.number().int().min(0).nullable().default(null), }) - .default({ events: [], observed: 0 }), + .default({ events: [], observed: 0, dropped: null }), + retention: z + .strictObject({ + budget_bytes: z.number().int().min(0), + estimated_retained_bytes: z.number().int().min(0), + event_serialized_byte_upper_bound: z.number().int().min(0), + retained: z.number().int().min(0), + dropped: z.number().int().min(0), + dropped_event_families: z.array( + z.strictObject({ + family: z.string().min(1), + count: z.number().int().min(1), + }), + ), + dropped_event_roles: z.array( + z.strictObject({ + role: z.string().min(1), + count: z.number().int().min(1), + }), + ), + observed_ipc: z.number().int().min(0), + dropped_ipc: z.number().int().min(0), + observed_runtime: z.number().int().min(0), + dropped_runtime: z.number().int().min(0), + }) + .nullable() + .default(null), coverage: coverageSchema.default({ status: "partial_attach", observed_event_families: [], diff --git a/tests/boundary/browser/electronActiveHook.test.ts b/tests/boundary/browser/electronActiveHook.test.ts index 2afaebc7a..f4cd1e19f 100644 --- a/tests/boundary/browser/electronActiveHook.test.ts +++ b/tests/boundary/browser/electronActiveHook.test.ts @@ -102,8 +102,17 @@ electron.app.relaunch(); electron.contextBridge.exposeInMainWorld("api", { value: true }); window.webContents.loadURL("https://example.invalid").catch(() => undefined); for (let index = 0; index < 6000; index++) electron.app.relaunch(); +electron.ipcRenderer.send("x".repeat(9 * 1024 * 1024)); +electron.app.emit("r".repeat(9 * 1024 * 1024)); +const manyArguments = Array(30_000).fill(true); +for (let index = 0; index < 8; index++) electron.ipcRenderer.send("shape-budget", ...manyArguments); try { process.dlopen({}, "/missing/native.node"); } catch {} -process.stdout.write(JSON.stringify({ snapshot: globalThis.__reaElectronActiveSnapshot(), default_popup_decision: defaultPopupDecision, popup_decision: popupDecision }) + "\\n"); +const firstSnapshot = globalThis.__reaElectronActiveSnapshot(); +const firstIpc = firstSnapshot.events.find((event) => event.kind === "main-handler-invocation"); +if (firstIpc) { firstIpc.channel = "mutated"; firstIpc.argument_shapes.push("mutated"); } +firstSnapshot.events.length = 0; +const snapshot = globalThis.__reaElectronActiveSnapshot(); +process.stdout.write(JSON.stringify({ snapshot, default_popup_decision: defaultPopupDecision, popup_decision: popupDecision }) + "\\n"); })(); `; @@ -115,7 +124,7 @@ afterEach(async () => { ); }); -it("retains active hook lifecycle and IPC evidence without a count ceiling", async () => { +it("retains active hook evidence within its event-retention budget", async () => { const root = await createTestTempDirectory("rea-electron-hook-"); temporary.push(root); await writeFile(join(root, "electron.js"), electronModuleSource); @@ -123,7 +132,7 @@ it("retains active hook lifecycle and IPC evidence without a count ceiling", asy await writeFile(script, activeCaptureSource); const hook = join(process.cwd(), "scripts/electron-active-hook.cjs"); const execution = await runNode(hook, script, root, root); - expect(execution.code).toBe(0); + expect(execution.code, execution.stderr).toBe(0); const result = JSON.parse( execution.stdout.trim().split("\n").at(-1) ?? "null", ) as { @@ -133,13 +142,37 @@ it("retains active hook lifecycle and IPC evidence without a count ceiling", asy readonly hook_error: boolean; readonly events: readonly Record[]; readonly observed: number; + readonly retained: number; + readonly dropped: number; + readonly dropped_ipc: number; + readonly dropped_runtime: number; + readonly retention_budget_bytes: number; }; }; const { snapshot } = result; expect(snapshot.hook_error).toBe(false); - expect(snapshot.events).toHaveLength(snapshot.observed); + expect(snapshot.events).toHaveLength(snapshot.retained); + expect(snapshot.observed).toBe(snapshot.retained + snapshot.dropped); expect(snapshot.observed).toBeGreaterThan(5_000); + expect(snapshot.dropped_ipc).toBeGreaterThanOrEqual(2); + expect(snapshot.dropped_runtime).toBe(1); + expect(snapshot.dropped).toBe( + snapshot.dropped_ipc + snapshot.dropped_runtime, + ); + expect( + snapshot.events.some( + (event) => + event.kind === "ipc-renderer-send" && + Array.isArray(event.argument_shapes) && + event.argument_shapes.length === 30_000, + ), + ).toBe(true); + expect( + Buffer.byteLength(JSON.stringify(snapshot), "utf8"), + ).toBeLessThanOrEqual(snapshot.retention_budget_bytes); + const sequences = snapshot.events.map((event) => event.sequence as number); + expect(sequences).toEqual([...sequences].sort((left, right) => left - right)); expect(snapshot.events).toEqual( expect.arrayContaining([ expect.objectContaining({ kind: "window-lifecycle", event: "created" }),