feat(electron): reconcile static artifacts with passive runtime

This commit is contained in:
N0zoM1z0
2026-07-16 09:55:21 +09:00
committed by N0zoM1z0
parent 3fa2304bc7
commit 8c67dbd49e
258 changed files with 7609 additions and 650 deletions
+59
View File
@@ -29,6 +29,7 @@ export interface CapturedScript {
readonly language: string | null;
readonly sourceMapUrl: string | null;
readonly sourceMapRawUrl: string | null;
readonly executionContextKey: string | null;
}
type NetworkState = WebPageInspection["network"]["requests"][number];
@@ -36,6 +37,7 @@ type NetworkState = WebPageInspection["network"]["requests"][number];
/** Bounded event accumulator that drops payload values at ingestion time. */
export class CdpCaptureEvents {
readonly scripts = new Map<string, CapturedScript>();
readonly executionContextFrames = new Map<string, string>();
readonly network = new Map<string, NetworkState>();
readonly allowedWebSockets = new Set<string>();
readonly console: WebPageInspection["console"]["events"] = [];
@@ -66,6 +68,7 @@ export class CdpCaptureEvents {
this.originViolation = false;
this.navigationDuringCapture = false;
this.scripts.clear();
this.executionContextFrames.clear();
this.network.clear();
this.allowedWebSockets.clear();
this.console.length = 0;
@@ -93,6 +96,15 @@ export class CdpCaptureEvents {
const params = recordValue(event.params);
if (params === undefined) return;
switch (event.method) {
case "Runtime.executionContextCreated":
this.#executionContext(params);
break;
case "Runtime.executionContextDestroyed":
this.#destroyExecutionContext(params);
break;
case "Runtime.executionContextsCleared":
this.executionContextFrames.clear();
break;
case "Debugger.scriptParsed":
this.#script(params);
break;
@@ -123,6 +135,45 @@ export class CdpCaptureEvents {
}
}
/** Resolve a transient execution context to one already authorized frame. */
frameForScript(
script: CapturedScript,
allowedFrameIds: ReadonlySet<string>,
): string | null {
if (script.executionContextKey === null) return null;
const frameId = this.executionContextFrames.get(script.executionContextKey);
return frameId !== undefined && allowedFrameIds.has(frameId)
? frameId
: null;
}
#executionContext(params: UnknownRecord): void {
const context = recordValue(params.context);
const identifier = numberValue(context?.id);
const frameId = stringValue(recordValue(context?.auxData)?.frameId);
if (
identifier === undefined ||
!Number.isSafeInteger(identifier) ||
frameId === undefined ||
frameId.length > 256
)
return;
const key = String(identifier);
if (
this.executionContextFrames.size >= this.input.limits.max_scripts &&
!this.executionContextFrames.has(key)
) {
this.completeness.truncate("scripts");
return;
}
this.executionContextFrames.set(key, frameId);
}
#destroyExecutionContext(params: UnknownRecord): void {
const key = executionContextKey(params.executionContextId);
if (key !== null) this.executionContextFrames.delete(key);
}
#script(params: UnknownRecord): void {
const scriptId = stringValue(params.scriptId);
const rawUrl = stringValue(params.url) ?? "";
@@ -160,6 +211,7 @@ export class CdpCaptureEvents {
language: boundedText(params.scriptLanguage, 100),
sourceMapUrl: sourceMap.sanitized,
sourceMapRawUrl: sourceMap.raw,
executionContextKey: executionContextKey(params.executionContextId),
});
}
@@ -624,6 +676,13 @@ const integerOrNull = (value: unknown): number | null => {
return number === undefined ? null : Math.max(0, Math.trunc(number));
};
const executionContextKey = (value: unknown): string | null => {
const identifier = numberValue(value);
return identifier !== undefined && Number.isSafeInteger(identifier)
? String(identifier)
: null;
};
const isJsonContentType = (headers: UnknownRecord | undefined): boolean => {
if (headers === undefined) return false;
for (const [name, value] of Object.entries(headers))
+182 -229
View File
@@ -8,12 +8,10 @@ import type {
InspectElectronPageInput,
} from "../domain/electronObservation.js";
import { BrowserObservationError } from "../domain/errors.js";
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
import type { CdpConnection, CdpEvent } from "./CdpConnection.js";
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import {
boundedText,
delayWithCancellation,
numberValue,
recordValue,
@@ -22,6 +20,12 @@ import {
stringValue,
type UnknownRecord,
} from "./CdpCaptureValues.js";
import {
ingestElectronScriptEvent,
type ElectronScriptDraft,
} from "./CdpElectronScriptEvents.js";
import { captureElectronScripts } from "./CdpElectronScripts.js";
import { captureElectronWorkers } from "./CdpElectronWorkers.js";
import {
authorizedElectronFile,
canonicalElectronRoots,
@@ -37,124 +41,199 @@ interface ElectronContext {
readonly progress?: ProgressReporter;
}
interface ScriptDraft {
readonly scriptId: string;
readonly rawUrl: string;
readonly hash: string;
readonly length: number;
readonly isModule: boolean;
readonly language: string | null;
interface ElectronInspectionState {
readonly roots: readonly string[];
readonly completeness: CdpCaptureCompleteness;
readonly scripts: ElectronScriptDraft[];
readonly executionContextFrames: Map<string, string>;
readonly limitations: string[];
mainFrameId: string | undefined;
navigationDuringCapture: boolean;
}
/** Passively inspect one root-confined Electron file page. */
export const inspectCdpElectronPage = async (
context: ElectronContext,
): Promise<ElectronPageInspection> => {
const roots = await canonicalElectronRoots(context.input.allowed_file_roots);
const completeness = new CdpCaptureCompleteness();
const scripts: ScriptDraft[] = [];
let mainFrameId: string | undefined;
let navigationDuringCapture = false;
const state: ElectronInspectionState = {
roots: await canonicalElectronRoots(context.input.allowed_file_roots),
completeness: new CdpCaptureCompleteness(),
scripts: [],
executionContextFrames: new Map(),
limitations: [
"Only canonical file paths contained by an approved root are retained.",
"REA does not evaluate renderer JavaScript, invoke Electron APIs, navigate, click, or close the page.",
"Script contents require separate source-capture approval and remain byte bounded.",
],
mainFrameId: undefined,
navigationDuringCapture: false,
};
const removeListener = context.connection.onEvent((event) => {
if (event.sessionId !== context.sessionId) return;
ingestScript(event, scripts, completeness);
if (mainFrameId !== undefined && navigatedFrameId(event) === mainFrameId)
navigationDuringCapture = true;
ingestElectronScriptEvent({
event,
scripts: state.scripts,
executionContextFrames: state.executionContextFrames,
completeness: state.completeness,
});
if (
state.mainFrameId !== undefined &&
navigatedFrameId(event) === state.mainFrameId
)
state.navigationDuringCapture = true;
});
const startedAt = new Date().toISOString();
try {
await report(context.progress, 1, "Authorizing Electron file frames");
await context.connection.send(
"Page.enable",
{},
context.sessionId,
context.signal,
);
const before = await context.connection.send(
"Page.getFrameTree",
{},
context.sessionId,
context.signal,
);
const frames = await captureFrames(
before,
roots,
context.input.limits.max_frames,
completeness,
);
const main = frames[0];
if (main === undefined)
throw new BrowserObservationError(
"inspect_web_page",
"target_not_allowed",
);
mainFrameId = main.frame_id;
await context.connection.send(
"Debugger.enable",
{ maxScriptsCacheSize: 4 * 1_024 * 1_024 },
context.sessionId,
context.signal,
);
await delayWithCancellation(
context.input.observation_ms,
"inspect_electron_page",
context.signal,
);
await report(context.progress, 2, "Capturing Electron structure");
const resources = await captureResources(context, roots, completeness);
const dom = await captureDom(context, roots, completeness);
const normalizedScripts = await captureScripts(
return await runElectronInspection(
context,
roots,
scripts,
completeness,
state,
new Date().toISOString(),
);
const after = await context.connection.send(
"Page.getFrameTree",
{},
context.sessionId,
context.signal,
);
const afterMain = await mainFilePath(after, roots);
if (afterMain === undefined)
throw new BrowserObservationError(
"inspect_web_page",
"target_not_allowed",
);
if (navigationDuringCapture || afterMain !== main.file_path)
throw new BrowserObservationError("inspect_web_page", "target_changed");
await report(context.progress, 3, "Electron inspection complete");
return {
schema_version: 1,
browser: context.discovery.version,
target: {
target_id: context.target.id,
type: context.target.type,
title: context.target.title.slice(0, 16_384),
file_path: main.file_path,
attached: context.target.attached,
},
capture_window: {
started_at: startedAt,
ended_at: new Date().toISOString(),
observation_ms: context.input.observation_ms,
},
completeness: completeness.snapshot(),
frames,
dom,
scripts: normalizedScripts,
resources,
limitations: [
"Only canonical file paths contained by an approved root are retained.",
"REA does not evaluate renderer JavaScript, invoke Electron APIs, navigate, click, or close the page.",
"Script contents require separate source-capture approval and remain byte bounded.",
],
};
} finally {
removeListener();
}
};
const runElectronInspection = async (
context: ElectronContext,
state: ElectronInspectionState,
startedAt: string,
): Promise<ElectronPageInspection> => {
const frames = await authorizeInitialFrames(context, state);
const main = frames[0]!;
state.mainFrameId = main.frame_id;
await enableElectronCapture(context);
await delayWithCancellation(
context.input.observation_ms,
"inspect_electron_page",
context.signal,
);
const captured = await captureElectronContent(context, state, frames);
await assertStableMainFrame(context, state, main.file_path);
await report(context.progress, 3, "Electron inspection complete");
return {
schema_version: 1,
browser: context.discovery.version,
target: {
target_id: context.target.id,
type: context.target.type,
title: context.target.title.slice(0, 16_384),
file_path: main.file_path,
attached: context.target.attached,
},
capture_window: {
started_at: startedAt,
ended_at: new Date().toISOString(),
observation_ms: context.input.observation_ms,
},
completeness: state.completeness.snapshot(),
frames,
...captured,
limitations: state.limitations,
};
};
const authorizeInitialFrames = async (
context: ElectronContext,
state: ElectronInspectionState,
): Promise<ElectronPageInspection["frames"]> => {
await report(context.progress, 1, "Authorizing Electron file frames");
await context.connection.send(
"Page.enable",
{},
context.sessionId,
context.signal,
);
const result = await context.connection.send(
"Page.getFrameTree",
{},
context.sessionId,
context.signal,
);
const frames = await captureFrames(
result,
state.roots,
context.input.limits.max_frames,
state.completeness,
);
if (frames[0] === undefined)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
return frames;
};
const enableElectronCapture = async (
context: ElectronContext,
): Promise<void> => {
await context.connection.send(
"Runtime.enable",
{},
context.sessionId,
context.signal,
);
await context.connection.send(
"Debugger.enable",
{ maxScriptsCacheSize: 4 * 1_024 * 1_024 },
context.sessionId,
context.signal,
);
};
const captureElectronContent = async (
context: ElectronContext,
state: ElectronInspectionState,
frames: ElectronPageInspection["frames"],
): Promise<
Pick<ElectronPageInspection, "dom" | "scripts" | "resources" | "workers">
> => {
await report(context.progress, 2, "Capturing Electron structure");
const frameIds = new Set(frames.map((frame) => frame.frame_id));
const resources = await captureResources(
context,
state.roots,
state.completeness,
);
const dom = await captureDom(context, state.roots, state.completeness);
const scripts = await captureElectronScripts({
connection: context.connection,
sessionId: context.sessionId,
...(context.signal === undefined ? {} : { signal: context.signal }),
request: context.input,
roots: state.roots,
scripts: state.scripts,
executionContextFrames: state.executionContextFrames,
frameIds,
completeness: state.completeness,
});
const workers = await captureElectronWorkers({
connection: context.connection,
...(context.signal === undefined ? {} : { signal: context.signal }),
target: context.target,
request: context.input,
roots: state.roots,
frameIds,
completeness: state.completeness,
limitations: state.limitations,
});
return { dom, scripts, resources, workers };
};
const assertStableMainFrame = async (
context: ElectronContext,
state: ElectronInspectionState,
expectedPath: string,
): Promise<void> => {
const result = await context.connection.send(
"Page.getFrameTree",
{},
context.sessionId,
context.signal,
);
const afterPath = await mainFilePath(result, state.roots);
if (afterPath === undefined)
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
if (state.navigationDuringCapture || afterPath !== expectedPath)
throw new BrowserObservationError("inspect_web_page", "target_changed");
};
const navigatedFrameId = (event: CdpEvent): string | undefined => {
const params = recordValue(event.params);
if (params === undefined) return undefined;
@@ -165,37 +244,6 @@ const navigatedFrameId = (event: CdpEvent): string | undefined => {
return undefined;
};
const ingestScript = (
event: CdpEvent,
scripts: ScriptDraft[],
completeness: CdpCaptureCompleteness,
): void => {
if (event.method !== "Debugger.scriptParsed") return;
const value = recordValue(event.params);
const scriptId = stringValue(value?.scriptId);
const rawUrl = stringValue(value?.url);
if (scriptId === undefined || scriptId.length > 256) {
completeness.exclude("scripts", "invalid_protocol_value");
return;
}
if (rawUrl === undefined || rawUrl === "") {
completeness.exclude("scripts", "unattributed_origin");
return;
}
if (scripts.length >= 2_000) {
completeness.drop("scripts");
return;
}
scripts.push({
scriptId,
rawUrl,
hash: (stringValue(value?.hash) ?? "").slice(0, 512),
length: nonnegativeInteger(value?.length),
isModule: value?.isModule === true,
language: boundedText(value?.scriptLanguage, 100),
});
};
const captureFrames = async (
result: unknown,
roots: readonly string[],
@@ -350,98 +398,6 @@ const captureDom = async (
return { total_nodes: total, nodes };
};
const captureScripts = async (
context: ElectronContext,
roots: readonly string[],
scripts: readonly ScriptDraft[],
completeness: CdpCaptureCompleteness,
): Promise<ElectronPageInspection["scripts"]> => {
let total = 0;
let sourceBytes = 0;
const items: ElectronPageInspection["scripts"]["items"] = [];
const seen = new Set<string>();
for (const script of scripts) {
const path = await authorizedElectronFile(script.rawUrl, roots);
if (path === undefined) {
completeness.exclude("scripts", "out_of_target_scope");
continue;
}
const identity = {
file_path: path,
cdp_hash: script.hash,
length: script.length,
is_module: script.isModule,
language: script.language,
};
const scriptKey = `electron_script_${digest(identity)}`;
if (seen.has(scriptKey)) continue;
seen.add(scriptKey);
total += 1;
if (items.length >= context.input.limits.max_scripts) {
completeness.drop("scripts");
continue;
}
let source: ElectronPageInspection["scripts"]["items"][number]["source"] = {
included: false,
reason: "source capture was not approved",
};
if (context.input.include_script_sources) {
if (
script.length > context.input.limits.max_script_source_bytes ||
sourceBytes + script.length >
context.input.limits.max_total_script_source_bytes
) {
source = {
included: false,
reason: "script source byte limit reached",
};
completeness.truncate("script_sources");
} else {
const result = requiredRecord(
await context.connection.send(
"Debugger.getScriptSource",
{ scriptId: script.scriptId },
context.sessionId,
context.signal,
),
);
const text = stringValue(result.scriptSource) ?? "";
const bytes = Buffer.byteLength(text);
if (
bytes > context.input.limits.max_script_source_bytes ||
sourceBytes + bytes >
context.input.limits.max_total_script_source_bytes
) {
source = {
included: false,
reason: "script source byte limit reached",
};
completeness.truncate("script_sources");
} else {
source = {
included: true,
artifact: createWebTextArtifact(text, "text/javascript"),
};
sourceBytes += bytes;
}
}
}
items.push({
script_key: scriptKey,
...identity,
source,
});
}
if (!context.input.include_script_sources)
completeness.exclude("script_sources", "not_approved", total);
return {
total,
items: items.sort((left, right) =>
left.script_key.localeCompare(right.script_key),
),
};
};
const mainFilePath = async (
result: unknown,
roots: readonly string[],
@@ -462,9 +418,6 @@ const integer = (value: unknown, fallback: number): number => {
return number === undefined ? fallback : Math.trunc(number);
};
const nonnegativeInteger = (value: unknown): number =>
Math.max(0, integer(value, 0));
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined) throw new TypeError("Expected canonical JSON");
+5 -1
View File
@@ -166,7 +166,11 @@ export class CdpElectronProvider implements ElectronObservationPort {
return err(providerError(cause, "inspect_electron_page"));
} finally {
if (targetSession !== undefined)
await closeCdpTargetSession(targetSession, ["Debugger", "Page"]);
await closeCdpTargetSession(targetSession, [
"Debugger",
"Runtime",
"Page",
]);
}
}
}
+100
View File
@@ -0,0 +1,100 @@
import type { CdpEvent } from "./CdpConnection.js";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import {
boundedText,
numberValue,
recordValue,
stringValue,
} from "./CdpCaptureValues.js";
export interface ElectronScriptDraft {
readonly scriptId: string;
readonly rawUrl: string;
readonly hash: string;
readonly length: number;
readonly isModule: boolean;
readonly language: string | null;
readonly executionContextKey: string | null;
}
/** Retain only bounded script/frame metadata from passive Electron events. */
export const ingestElectronScriptEvent = (input: {
readonly event: CdpEvent;
readonly scripts: ElectronScriptDraft[];
readonly executionContextFrames: Map<string, string>;
readonly completeness: CdpCaptureCompleteness;
}): void => {
if (input.event.method === "Runtime.executionContextsCleared") {
input.executionContextFrames.clear();
return;
}
if (input.event.method === "Runtime.executionContextDestroyed") {
const parameters = recordValue(input.event.params);
const key = executionContextKey(parameters?.executionContextId);
if (key !== null) input.executionContextFrames.delete(key);
return;
}
if (input.event.method === "Runtime.executionContextCreated") {
retainExecutionContext(
input.event,
input.executionContextFrames,
input.completeness,
);
return;
}
if (input.event.method !== "Debugger.scriptParsed") return;
const value = recordValue(input.event.params);
const scriptId = stringValue(value?.scriptId);
const rawUrl = stringValue(value?.url);
if (scriptId === undefined || scriptId.length > 256) {
input.completeness.exclude("scripts", "invalid_protocol_value");
return;
}
if (rawUrl === undefined || rawUrl === "") {
input.completeness.exclude("scripts", "unattributed_origin");
return;
}
if (input.scripts.length >= 2_000) {
input.completeness.drop("scripts");
return;
}
input.scripts.push({
scriptId,
rawUrl,
hash: (stringValue(value?.hash) ?? "").slice(0, 512),
length: nonnegativeInteger(value?.length),
isModule: value?.isModule === true,
language: boundedText(value?.scriptLanguage, 100),
executionContextKey: executionContextKey(value?.executionContextId),
});
};
const retainExecutionContext = (
event: CdpEvent,
frames: Map<string, string>,
completeness: CdpCaptureCompleteness,
): void => {
const parameters = recordValue(event.params);
const runtimeContext = recordValue(parameters?.context);
const contextKey = executionContextKey(runtimeContext?.id);
const frameId = stringValue(recordValue(runtimeContext?.auxData)?.frameId);
if (contextKey === null || frameId === undefined || frameId.length > 256)
return;
if (frames.size >= 2_000 && !frames.has(contextKey)) {
completeness.truncate("scripts");
return;
}
frames.set(contextKey, frameId);
};
const nonnegativeInteger = (value: unknown): number => {
const number = numberValue(value);
return number === undefined ? 0 : Math.max(0, Math.trunc(number));
};
const executionContextKey = (value: unknown): string | null => {
const identifier = numberValue(value);
return identifier !== undefined && Number.isSafeInteger(identifier)
? String(identifier)
: null;
};
+151
View File
@@ -0,0 +1,151 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import type {
ElectronPageInspection,
InspectElectronPageInput,
} from "../domain/electronObservation.js";
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
import type { CdpConnection } from "./CdpConnection.js";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import { requiredRecord, stringValue } from "./CdpCaptureValues.js";
import type { ElectronScriptDraft } from "./CdpElectronScriptEvents.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
interface ElectronScriptCaptureInput {
readonly connection: CdpConnection;
readonly sessionId: string | undefined;
readonly signal?: AbortSignal;
readonly request: InspectElectronPageInput;
readonly roots: readonly string[];
readonly scripts: readonly ElectronScriptDraft[];
readonly executionContextFrames: ReadonlyMap<string, string>;
readonly frameIds: ReadonlySet<string>;
readonly completeness: CdpCaptureCompleteness;
}
/** Normalize root-confined script metadata and optionally approved source. */
export const captureElectronScripts = async (
input: ElectronScriptCaptureInput,
): Promise<ElectronPageInspection["scripts"]> => {
let total = 0;
let sourceBytes = 0;
const items: ElectronPageInspection["scripts"]["items"] = [];
const seen = new Set<string>();
for (const script of input.scripts) {
const path = await authorizedElectronFile(script.rawUrl, input.roots);
if (path === undefined) {
input.completeness.exclude("scripts", "out_of_target_scope");
continue;
}
const mappedFrame =
script.executionContextKey === null
? undefined
: input.executionContextFrames.get(script.executionContextKey);
const identity = {
frame_id:
mappedFrame !== undefined && input.frameIds.has(mappedFrame)
? mappedFrame
: null,
file_path: path,
cdp_hash: script.hash,
length: script.length,
is_module: script.isModule,
language: script.language,
};
const scriptKey = `electron_script_${digest(identity)}`;
if (seen.has(scriptKey)) continue;
seen.add(scriptKey);
total += 1;
if (items.length >= input.request.limits.max_scripts) {
input.completeness.drop("scripts");
continue;
}
const capturedSource = await captureScriptSource(
input,
script,
sourceBytes,
);
sourceBytes += capturedSource.bytes;
items.push({
script_key: scriptKey,
...identity,
source: capturedSource.source,
});
}
if (!input.request.include_script_sources)
input.completeness.exclude("script_sources", "not_approved", total);
return {
total,
items: items.sort((left, right) =>
left.script_key.localeCompare(right.script_key),
),
};
};
type ElectronScriptSource =
ElectronPageInspection["scripts"]["items"][number]["source"];
const captureScriptSource = async (
input: ElectronScriptCaptureInput,
script: ElectronScriptDraft,
sourceBytes: number,
): Promise<{
readonly source: ElectronScriptSource;
readonly bytes: number;
}> => {
if (!input.request.include_script_sources)
return {
source: {
included: false,
reason: "source capture was not approved",
},
bytes: 0,
};
if (sourceLimitReached(input.request.limits, script.length, sourceBytes))
return sourceLimitResult(input.completeness);
const result = requiredRecord(
await input.connection.send(
"Debugger.getScriptSource",
{ scriptId: script.scriptId },
input.sessionId,
input.signal,
),
);
const text = stringValue(result.scriptSource) ?? "";
const bytes = Buffer.byteLength(text);
if (sourceLimitReached(input.request.limits, bytes, sourceBytes))
return sourceLimitResult(input.completeness);
return {
source: {
included: true,
artifact: createWebTextArtifact(text, "text/javascript"),
},
bytes,
};
};
const sourceLimitReached = (
limits: InspectElectronPageInput["limits"],
bytes: number,
previousBytes: number,
): boolean =>
bytes > limits.max_script_source_bytes ||
previousBytes + bytes > limits.max_total_script_source_bytes;
const sourceLimitResult = (
completeness: CdpCaptureCompleteness,
): { readonly source: ElectronScriptSource; readonly bytes: 0 } => {
completeness.truncate("script_sources");
return {
source: { included: false, reason: "script source byte limit reached" },
bytes: 0,
};
};
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined) throw new TypeError("Expected canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
+89
View File
@@ -0,0 +1,89 @@
import type {
ElectronPageInspection,
InspectElectronPageInput,
} from "../domain/electronObservation.js";
import type { CdpConnection } from "./CdpConnection.js";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import {
boundedText,
recordValue,
recordsValue,
stringValue,
} from "./CdpCaptureValues.js";
import type { CdpEndpointTarget } from "./CdpEndpoint.js";
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
/** Inventory root-confined worker targets without attaching to them. */
export const captureElectronWorkers = async (input: {
readonly connection: CdpConnection;
readonly signal?: AbortSignal;
readonly target: CdpEndpointTarget;
readonly request: InspectElectronPageInput;
readonly roots: readonly string[];
readonly frameIds: ReadonlySet<string>;
readonly completeness: CdpCaptureCompleteness;
readonly limitations: string[];
}): Promise<ElectronPageInspection["workers"]> => {
const result = await optionalCdpCommand(
{
connection: input.connection,
sessionId: undefined,
...(input.signal === undefined ? {} : { signal: input.signal }),
},
"Target.getTargets",
{},
input.limitations,
);
if (result === undefined) {
input.completeness.unavailable("workers");
return [];
}
const workers: ElectronPageInspection["workers"] = [];
for (const target of recordsValue(recordValue(result)?.targetInfos)) {
const type = stringValue(target.type) ?? "";
if (!type.includes("worker")) continue;
const openerTargetId = boundedTargetField(target.openerId);
const parentFrameId = boundedTargetField(target.parentFrameId);
if (
openerTargetId !== input.target.id &&
(parentFrameId === null || !input.frameIds.has(parentFrameId))
) {
input.completeness.exclude("workers", "out_of_target_scope");
continue;
}
const path = await authorizedElectronFile(
stringValue(target.url) ?? "",
input.roots,
);
if (path === undefined) {
input.completeness.exclude("workers", "out_of_target_scope");
continue;
}
if (workers.length >= input.request.limits.max_workers) {
input.completeness.truncate("workers");
continue;
}
const targetId = boundedTargetField(target.targetId);
if (targetId === null) {
input.completeness.exclude("workers", "invalid_protocol_value");
continue;
}
workers.push({
target_id: targetId,
type: type.slice(0, 100),
file_path: path,
attached: target.attached === true,
opener_target_id: openerTargetId,
parent_frame_id: parentFrameId,
});
}
return workers.sort((left, right) =>
left.target_id.localeCompare(right.target_id),
);
};
const boundedTargetField = (value: unknown): string | null => {
const field = boundedText(value, 256);
return field === null || field === "" ? null : field;
};
+8 -1
View File
@@ -27,6 +27,7 @@ import {
} from "./CdpCaptureDocuments.js";
import {
allowedSanitizedUrl,
boundedText,
delayWithCancellation,
isHttpUrl,
recordValue,
@@ -153,6 +154,7 @@ const captureAuthorizedPage = async (
state.events,
resourceCapture.items,
resources,
new Set(frames.map((frame) => frame.frame_id)),
);
const workerCapture = await captureWorkers(
state,
@@ -406,6 +408,7 @@ const captureScripts = async (
events: CdpCaptureEvents,
rawResources: readonly CapturedResource[],
resources: WebPageInspection["resources"],
frameIds: ReadonlySet<string>,
): Promise<CapturedScripts> => {
let totalSourceBytes = 0;
const drafts: {
@@ -457,6 +460,7 @@ const captureScripts = async (
}
}
const inventoryScript = {
frame_id: events.frameForScript(script, frameIds),
url: script.url,
cdp_hash: script.hash,
length: script.length,
@@ -493,7 +497,8 @@ const captureScripts = async (
left.base.localeCompare(right.base) ||
sourceDigest(left.item.source).localeCompare(
sourceDigest(right.item.source),
),
) ||
(left.item.frame_id ?? "").localeCompare(right.item.frame_id ?? ""),
);
const totals = new Map<string, number>();
for (const { base } of keyed) totals.set(base, (totals.get(base) ?? 0) + 1);
@@ -587,6 +592,8 @@ const captureWorkers = async (
url: url.url,
origin: url.origin,
attached: target.attached === true,
opener_target_id: boundedText(target.openerId, 256) ?? null,
parent_frame_id: boundedText(target.parentFrameId, 256) ?? null,
});
}
return {