Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(browser): keep malformed Electron CDP inventories incomplete (#3901)
Kaoru08226fcfc5b5e0c0
diff --git a/src/browser/CdpCaptureDocuments.ts b/src/browser/CdpCaptureDocuments.tsindex 4d3645f1d..5dcbfd4a4 100644--- a/src/browser/CdpCaptureDocuments.ts+++ b/src/browser/CdpCaptureDocuments.ts@@ -99,51 +99,62 @@ export const captureResources = (return { items: [] };}const items: CapturedResource[] = [];- for (const tree of walkFrameTrees(root, (omittedCount) =>- completeness?.exclude("resources", "invalid_protocol_value", omittedCount),+ for (const resource of frameTreeResources(root, (count) =>+ completeness?.exclude("resources", "invalid_protocol_value", count),)) {+ const url = allowedSanitizedUrl(resource.url, allowedOrigins);+ if (url === undefined || url.origin === null) {+ completeness?.exclude(+ "resources",+ exclusionReasonForUrl(cdpStringValue(resource.url)),+ );+ continue;+ }+ const type = cdpStringValue(resource.type);+ const mimeType = cdpStringValue(resource.mimeType);+ if (type === undefined || type.length === 0 || mimeType === undefined) {+ completeness?.exclude("resources", "invalid_protocol_value");+ continue;+ }+ const rawContentSize = numberValue(resource.contentSize);+ const contentSize =+ rawContentSize !== undefined && rawContentSize >= 0+ ? rawContentSize+ : null;+ if (resource.contentSize !== undefined && contentSize === null)+ completeness?.exclude("resources", "invalid_protocol_value");+ items.push({+ rawUrl: cdpStringValue(resource.url) ?? "",+ url: url.url,+ origin: url.origin,+ type,+ mime_type: mimeType,+ content_size: contentSize,+ });+ }+ return { items };+};++/**+ * Yield resource records from every frame of a resource tree. A missing or+ * non-array `resources` list, or a non-record entry, is reported as invalid+ * rather than read as an empty frame.+ */+export const frameTreeResources = function* (+ root: UnknownRecord,+ onInvalid: (count: number | null) => void,+): Generator<UnknownRecord> {+ for (const tree of walkFrameTrees(root, onInvalid)) {if (!Array.isArray(tree.resources)) {- completeness?.exclude("resources", "invalid_protocol_value", null);+ onInvalid(null);continue;}for (const entry of tree.resources) {const resource = recordValue(entry);- if (resource === undefined) {- completeness?.exclude("resources", "invalid_protocol_value");- continue;- }- const url = allowedSanitizedUrl(resource.url, allowedOrigins);- if (url === undefined || url.origin === null) {- completeness?.exclude(- "resources",- exclusionReasonForUrl(cdpStringValue(resource.url)),- );- continue;- }- const type = cdpStringValue(resource.type);- const mimeType = cdpStringValue(resource.mimeType);- if (type === undefined || type.length === 0 || mimeType === undefined) {- completeness?.exclude("resources", "invalid_protocol_value");- continue;- }- const rawContentSize = numberValue(resource.contentSize);- const contentSize =- rawContentSize !== undefined && rawContentSize >= 0- ? rawContentSize- : null;- if (resource.contentSize !== undefined && contentSize === null)- completeness?.exclude("resources", "invalid_protocol_value");- items.push({- rawUrl: cdpStringValue(resource.url) ?? "",- url: url.url,- origin: url.origin,- type,- mime_type: mimeType,- content_size: contentSize,- });+ if (resource === undefined) onInvalid(1);+ else yield resource;}}- return { items };};export const walkFrameTrees = function* (@@ -217,7 +228,9 @@ export function* captureDom(let unresolvedSvgNodes = 0;if (!Array.isArray(root.strings))excludeDocumentEvidence(completeness, "invalid_protocol_value", null);- for (const document of snapshotDocuments(root.documents, completeness)) {+ for (const document of snapshotDocuments(root.documents, (count) =>+ excludeDocumentEvidence(completeness, "invalid_protocol_value", count),+ )) {const documentUrl = cdpSnapshotString(strings, document.documentURL);if (documentUrl === undefined) {excludeDocumentEvidence(completeness, "invalid_protocol_value");@@ -236,40 +249,25 @@ export function* captureDom(continue;}const baseUrl = baseUrlValue || documentUrl;- const documentNodes = recordValue(document.nodes);+ const documentNodes = snapshotDocumentNodes(document.nodes);if (documentNodes === undefined) {excludeDocumentEvidence(completeness, "invalid_protocol_value");continue;}- const rawNodeTypes = numberArray(documentNodes.nodeType);- const rawNodeNames = numberArray(documentNodes.nodeName);- const rawNodeValues = numberArray(documentNodes.nodeValue);- const rawParents = numberArray(documentNodes.parentIndex);- const rawAttributes = Array.isArray(documentNodes.attributes)- ? documentNodes.attributes- : undefined;- if (- rawNodeTypes === undefined ||- rawNodeNames === undefined ||- rawNodeValues === undefined ||- rawParents === undefined ||- rawAttributes === undefined ||- rawNodeNames.length !== rawNodeTypes.length ||- rawNodeValues.length !== rawNodeTypes.length ||- rawParents.length !== rawNodeTypes.length- ) {- excludeDocumentEvidence(completeness, "invalid_protocol_value");- continue;- }- if (rawAttributes.length > rawNodeTypes.length)+ const {+ nodeTypes: rawNodeTypes,+ nodeNames: rawNodeNames,+ nodeValues: rawNodeValues,+ parents: rawParents,+ attributes: rawAttributes,+ backendNodeIds,+ } = documentNodes;+ if (documentNodes.excessAttributes > 0)excludeDocumentEvidence(completeness,"invalid_protocol_value",- rawAttributes.length - rawNodeTypes.length,+ documentNodes.excessAttributes,);- const backendNodeIds = Array.isArray(documentNodes.backendNodeId)- ? documentNodes.backendNodeId- : [];const baseIndex = total;total += rawNodeTypes.length;const ancestry = createDocumentSvgAncestry({@@ -389,22 +387,74 @@ const excludeDocumentEvidence = (completeness?.exclude("metadata", reason, count);};-const snapshotDocuments = (+/**+ * Read DOMSnapshot documents. A snapshot always describes at least one+ * document, so a missing or empty list is invalid rather than an empty DOM.+ */+export const snapshotDocuments = (value: unknown,- completeness: CdpCaptureCompleteness | undefined,+ onInvalid: (count: number | null) => void,): readonly UnknownRecord[] => {if (!Array.isArray(value) || value.length === 0) {- excludeDocumentEvidence(completeness, "invalid_protocol_value", null);+ onInvalid(null);return [];}return value.flatMap((item) => {const document = recordValue(item);- if (document === undefined)- excludeDocumentEvidence(completeness, "invalid_protocol_value");+ if (document === undefined) onInvalid(1);return document === undefined ? [] : [document];});};+/** One snapshot document's parallel node arrays, validated for every consumer. */+export interface SnapshotDocumentNodes {+ readonly nodeTypes: readonly (number | undefined)[];+ readonly nodeNames: readonly (number | undefined)[];+ readonly nodeValues: readonly (number | undefined)[];+ readonly parents: readonly (number | undefined)[];+ readonly attributes: readonly unknown[];+ readonly backendNodeIds: readonly unknown[];+ /** Attribute rows beyond the node count describe no node. */+ readonly excessAttributes: number;+}++/** Missing or misaligned node arrays make the document's nodes unknown. */+export const snapshotDocumentNodes = (+ value: unknown,+): SnapshotDocumentNodes | undefined => {+ const nodes = recordValue(value);+ if (nodes === undefined) return undefined;+ const nodeTypes = numberArray(nodes.nodeType);+ const nodeNames = numberArray(nodes.nodeName);+ const nodeValues = numberArray(nodes.nodeValue);+ const parents = numberArray(nodes.parentIndex);+ const attributes = Array.isArray(nodes.attributes)+ ? nodes.attributes+ : undefined;+ if (+ nodeTypes === undefined ||+ nodeNames === undefined ||+ nodeValues === undefined ||+ parents === undefined ||+ attributes === undefined ||+ nodeNames.length !== nodeTypes.length ||+ nodeValues.length !== nodeTypes.length ||+ parents.length !== nodeTypes.length+ )+ return undefined;+ return {+ nodeTypes,+ nodeNames,+ nodeValues,+ parents,+ attributes,+ backendNodeIds: Array.isArray(nodes.backendNodeId)+ ? nodes.backendNodeId+ : [],+ excessAttributes: Math.max(0, attributes.length - nodeTypes.length),+ };+};+function* captureDomMetadata(pending: readonly PendingDomMetadata[],completeness: CdpCaptureCompleteness | undefined,diff --git a/src/browser/CdpElectronInspection.ts b/src/browser/CdpElectronInspection.tsindex cf6613f77..43e208428 100644--- a/src/browser/CdpElectronInspection.ts+++ b/src/browser/CdpElectronInspection.ts@@ -12,11 +12,15 @@ import {delayWithCancellation,numberValue,recordValue,- recordsValue,requiredRecord,cdpStringValue,} from "./CdpCaptureValues.js";-import { walkFrameTrees } from "./CdpCaptureDocuments.js";+import {+ frameTreeResources,+ snapshotDocumentNodes,+ snapshotDocuments,+ walkFrameTrees,+} from "./CdpCaptureDocuments.js";import {ingestElectronScriptEvent,type ElectronScriptDraft,@@ -276,38 +280,34 @@ const captureResources = async (const root = recordValue(requiredRecord(result).frameTree);if (root === undefined)throw new BrowserObservationError("inspect_web_page", "protocol_error");- const pending = [root];const resources: ElectronPageInspection["resources"] = [];const seen = new Set<string>();- while (pending.length > 0) {- const tree = pending.shift();- if (tree === undefined) break;- for (const resource of recordsValue(tree.resources)) {- const path = await authorizedElectronFile(- cdpStringValue(resource.url) ?? "",- );- if (path === undefined) {- completeness.exclude("resources", "out_of_target_scope");- continue;- }- const item = {- file_path: path,- type: cdpStringValue(resource.type) ?? "Other",- mime_type: cdpStringValue(resource.mimeType) ?? "",- content_size:- numberValue(resource.contentSize) === undefined- ? null- : Math.max(0, numberValue(resource.contentSize) ?? 0),- };- const resourceKey = `electron_resource_${digestCanonicalValue(item, "CDP capture")}`;- if (seen.has(resourceKey)) continue;- seen.add(resourceKey);- resources.push({- resource_key: resourceKey,- ...item,- });+ for (const resource of frameTreeResources(root, (count) =>+ completeness.exclude("resources", "invalid_protocol_value", count),+ )) {+ const path = await authorizedElectronFile(+ cdpStringValue(resource.url) ?? "",+ );+ if (path === undefined) {+ completeness.exclude("resources", "out_of_target_scope");+ continue;}- pending.push(...recordsValue(tree.childFrames));+ const item = {+ file_path: path,+ type: cdpStringValue(resource.type) ?? "Other",+ mime_type: cdpStringValue(resource.mimeType) ?? "",+ content_size:+ numberValue(resource.contentSize) === undefined+ ? null+ : Math.max(0, numberValue(resource.contentSize) ?? 0),+ };+ const resourceKey = `electron_resource_${digestCanonicalValue(item, "CDP capture")}`;+ if (seen.has(resourceKey)) continue;+ seen.add(resourceKey);+ resources.push({+ resource_key: resourceKey,+ ...item,+ });}return resources.sort((left, right) =>compareUnicodeCodePoints(left.resource_key, right.resource_key),@@ -326,23 +326,30 @@ const captureDom = async (context.signal,),);+ const invalid = (count: number | null) =>+ completeness.exclude("dom", "invalid_protocol_value", count);+ if (!Array.isArray(result.strings)) invalid(null);const strings = Array.isArray(result.strings)? result.strings.map((value) => (typeof value === "string" ? value : "")): [];const nodes: ElectronPageInspection["dom"]["nodes"] = [];let total = 0;- for (const document of recordsValue(result.documents)) {+ for (const document of snapshotDocuments(result.documents, invalid)) {const documentUrl = stringAt(strings, document.documentURL);if ((await authorizedElectronFile(documentUrl)) === undefined) {completeness.exclude("dom", "out_of_target_scope");continue;}- const nodeData = recordValue(document.nodes);- const nodeTypes = arrayValue(nodeData?.nodeType);- const nodeNames = arrayValue(nodeData?.nodeName);- const nodeValues = arrayValue(nodeData?.nodeValue);- const parents = arrayValue(nodeData?.parentIndex);- const attributes = arrayValue(nodeData?.attributes);+ // The shared snapshot owner validates the parallel node arrays.+ const documentNodes = snapshotDocumentNodes(document.nodes);+ if (documentNodes === undefined) {+ invalid(1);+ continue;+ }+ if (documentNodes.excessAttributes > 0)+ invalid(documentNodes.excessAttributes);+ const { nodeTypes, nodeNames, nodeValues, parents, attributes } =+ documentNodes;const baseIndex = nodes.length;total += nodeTypes.length;for (let index = 0; index < nodeTypes.length; index += 1) {diff --git a/src/browser/CdpElectronWorkers.ts b/src/browser/CdpElectronWorkers.tsindex aa254e6d5..06a26eaf3 100644--- a/src/browser/CdpElectronWorkers.ts+++ b/src/browser/CdpElectronWorkers.ts@@ -4,11 +4,7 @@ import type {} from "../domain/javascript/electronObservation.js";import type { CdpConnection } from "./CdpConnection.js";import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";-import {- recordValue,- recordsValue,- cdpStringValue,-} from "./CdpCaptureValues.js";+import { recordValue, cdpStringValue } from "./CdpCaptureValues.js";import type { CdpEndpointTarget } from "./CdpEndpoint.js";import { optionalCdpCommand } from "./CdpOptionalCommand.js";import { authorizedElectronFile } from "./ElectronFileScope.js";@@ -39,7 +35,18 @@ export const captureElectronWorkers = async (input: {return [];}const workers: ElectronPageInspection["workers"] = [];- for (const target of recordsValue(recordValue(result)?.targetInfos)) {+ // A missing target list or a non-record entry is unreadable, not empty.+ const targetInfos = recordValue(result)?.targetInfos;+ if (!Array.isArray(targetInfos)) {+ input.completeness.exclude("workers", "invalid_protocol_value", null);+ return [];+ }+ for (const entry of targetInfos) {+ const target = recordValue(entry);+ if (target === undefined) {+ input.completeness.exclude("workers", "invalid_protocol_value");+ continue;+ }const type = cdpStringValue(target.type) ?? "";if (!type.includes("worker")) continue;const openerTargetId = boundedTargetField(target.openerId);diff --git a/tests/boundary/browser/cdpElectronProvider.test.ts b/tests/boundary/browser/cdpElectronProvider.test.tsindex 307f4cbbf..c8a3241f4 100644--- a/tests/boundary/browser/cdpElectronProvider.test.ts+++ b/tests/boundary/browser/cdpElectronProvider.test.ts@@ -348,6 +348,63 @@ describe("CdpElectronProvider malformed source replies", () => {);});+describe("CdpElectronProvider malformed inventory replies", () => {+ const inspectWith = async (+ method: string,+ reply: (fileUrl: string) => Readonly<Record<string, unknown>>,+ ) => {+ const root = await electronFixture();+ const fileUrl = pathToFileURL(join(root, "index.html")).href;+ const browser = await startFakeCdpBrowser({+ electronFileUrl: fileUrl,+ commandResult: (command) =>+ command.method === method ? reply(fileUrl) : undefined,+ });+ browsers.push(browser);+ const result = await new CdpElectronProvider().inspectPage(+ inspectElectronPageInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ target_id: "electron-page",+ observation_ms: 0,+ }),+ );+ if (!result.ok) throw result.error;+ return result.value;+ };++ it.each([+ ["dom", "DOMSnapshot.captureSnapshot", () => ({ strings: [] })],+ [+ "dom",+ "DOMSnapshot.captureSnapshot",+ (fileUrl: string) => ({+ strings: [fileUrl],+ documents: [{ documentURL: 0, nodes: { nodeType: null } }],+ }),+ ],+ [+ "resources",+ "Page.getResourceTree",+ (fileUrl: string) => ({+ frameTree: { frame: { id: "main", url: fileUrl }, resources: null },+ }),+ ],+ ["workers", "Target.getTargets", () => ({ targetInfos: null })],+ ] as const)(+ "keeps a malformed %s inventory incomplete (%s)",+ async (section, method, reply) => {+ const inspected = await inspectWith(method, reply);+ expect(inspected.completeness.status).not.toBe("complete_within_window");+ expect(inspected.completeness.excluded).toContainEqual(+ expect.objectContaining({+ section,+ reason: "invalid_protocol_value",+ }),+ );+ },+ );+});+describe("CdpElectronProvider script source capture", () => {it("retains an explicitly empty Electron producer script", async () => {const root = await electronFixture();