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): preserve frame identity across captures (#4040)
Can015414130402
diff --git a/docs/electron-observation.md b/docs/electron-observation.mdindex 50561742d..945661ac2 100644--- a/docs/electron-observation.md+++ b/docs/electron-observation.md@@ -70,7 +70,10 @@ DOM node indices retain their snapshot positions. Invalid rows are omitted withcompleteness diagnostics, so `total_nodes` can exceed the retained node countand a parent index can refer to an omitted source node.-Script metadata retains its execution-context frame ID when CDP supplies one. The capture also+Script metadata retains its execution-context frame ID when CDP supplies one and+the observed frame generation is authorized. Frames describe the current inventory;+script observations can retain earlier authorized frames that have since detached.+The capture alsoinventories worker, service-worker, and shared-worker targets withvalidated opener-target and parent-frame IDs. Worker discovery uses passivetarget metadata; REA does not attach to or execute code in those targets.diff --git a/src/browser/CdpAuthorizedMainFrame.ts b/src/browser/CdpAuthorizedMainFrame.tsindex 2c4abd82e..3569030c8 100644--- a/src/browser/CdpAuthorizedMainFrame.ts+++ b/src/browser/CdpAuthorizedMainFrame.ts@@ -1,12 +1,11 @@import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js";import { BrowserObservationError } from "../domain/browserObservationError.js";import type { CdpConnection } from "./CdpConnection.js";-import { mainFrameUrl } from "./CdpCaptureDocuments.js";import {- allowedSanitizedUrl,- delayWithCancellation,- isHttpUrl,-} from "./CdpCaptureValues.js";+ classifyCdpFrameUrl,+ observeMainFrameUrl,+} from "./CdpCaptureDocuments.js";+import { delayWithCancellation } from "./CdpCaptureValues.js";interface AuthorizedMainFrameOptions {readonly connection: CdpConnection;@@ -31,10 +30,15 @@ export const authorizedMainFrame = async ({sessionId,signal,);- const url = mainFrameUrl(result);- if (allowedSanitizedUrl(url, allowedOrigins) !== undefined) return result;- if (isHttpUrl(url))+ const observed = observeMainFrameUrl(result);+ const facts = classifyCdpFrameUrl(observed, allowedOrigins);+ if (facts.scope === "outside_policy")throw new BrowserObservationError(operation, "target_not_allowed");+ if (facts.scope === "approved" && observed.kind === "invalid_fragment")+ throw new BrowserObservationError(operation, "protocol_error");+ if (facts.url !== undefined) return result;+ // Unsupported or missing base evidence cannot establish a policy exit.+ // Keep the bounded startup retry even when the fragment is malformed.await delayWithCancellation(25, operation, signal);}throw new BrowserObservationError(operation, "target_not_allowed");diff --git a/src/browser/CdpCaptureDocuments.test.ts b/src/browser/CdpCaptureDocuments.test.tsindex 124ceb176..e945db089 100644--- a/src/browser/CdpCaptureDocuments.test.ts+++ b/src/browser/CdpCaptureDocuments.test.ts@@ -5,12 +5,96 @@ import {captureDom,captureFrames,captureResources,+ cdpFrameUrl,+ classifyCdpFrameUrl,+ observeCdpFrameUrl,} from "./CdpCaptureDocuments.js";import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";import { inspectWebPageInputSchema } from "../domain/browserObservation.js";const origin = "https://app.example.test";+it.each([+ [{ url: `${origin}/page?x=1#old` }, `${origin}/page?x=1#old`],+ [+ { url: `${origin}/page?x=1#old`, urlFragment: "#new" },+ `${origin}/page?x=1#new`,+ ],+ [{ url: `${origin}/page?x=1#old`, urlFragment: "" }, `${origin}/page?x=1`],+ [{ url: `${origin}/page`, urlFragment: null }, undefined],+ [{ url: `${origin}/page`, urlFragment: "missing-hash" }, undefined],+])("preserves frame URL fragment semantics: %j", (frame, expected) => {+ expect(cdpFrameUrl(frame)).toBe(expected);+});++it("keeps source identity and scope independent while redacting transport credentials", () => {+ const frame = {+ url: "https://user:[email protected]/page?token=local#old",+ urlFragment: "#new",+ };+ const allowed = new Set([origin]);+ expect(classifyCdpFrameUrl(observeCdpFrameUrl(frame), allowed)).toEqual({+ scope: "approved",+ origin,+ url: `${origin}/page?token=local#new`,+ });+ expect(+ classifyCdpFrameUrl(+ observeCdpFrameUrl({ ...frame, urlFragment: 7 }),+ allowed,+ ),+ ).toEqual({+ scope: "approved",+ origin,+ url: undefined,+ });+ expect(+ classifyCdpFrameUrl(+ observeCdpFrameUrl({ urlFragment: "#https://app.example.test" }),+ allowed,+ ),+ ).toEqual({+ scope: "unknown",+ origin: null,+ url: undefined,+ });+});++it("does not authorize a foreign origin through its fragment", () => {+ const completeness = new CdpCaptureCompleteness();+ const captured = captureFrames(+ {+ frameTree: {+ frame: {+ id: "foreign",+ url: "https://foreign.test/page",+ urlFragment: `#${origin}`,+ },+ },+ },+ new Set([origin]),+ undefined,+ completeness,+ );+ expect(captured.items).toEqual([]);+ expect(completeness.snapshot().policy_filtered_sections).toContain("frames");+});++it("classifies a malformed frame fragment as unknown protocol coverage", () => {+ const completeness = new CdpCaptureCompleteness();+ const captured = captureFrames(+ { frameTree: { frame: { id: "frame-main", url: origin, urlFragment: 7 } } },+ new Set([origin]),+ undefined,+ completeness,+ );+ expect(captured.items).toEqual([]);+ expect(completeness.snapshot()).toMatchObject({+ unavailable_sections: ["frames"],+ policy_filtered_sections: [],+ });+});+describe("CDP DOM capture", () => {it("preserves node names and parents when aligned arrays are valid", () => {const generator = captureDom(@@ -507,3 +591,49 @@ describe("CDP DOM snapshot empty strings", () => {expect(completeness.snapshot().excluded).toEqual([]);});});++it.each([7, null, "without-hash"])(+ "retains base URL evidence with malformed fragment %s",+ (urlFragment) => {+ expect(+ observeCdpFrameUrl({ url: `${origin}/page?x=1#old`, urlFragment }),+ ).toEqual({ kind: "invalid_fragment", scopeUrl: `${origin}/page?x=1#old` });+ },+);++it.each([7, "missing-hash"])(+ "retains foreign frame scope independently of malformed fragment %s",+ (urlFragment) => {+ const completeness = new CdpCaptureCompleteness();+ const captured = captureFrames(+ {+ frameTree: {+ frame: { id: "root", url: origin },+ childFrames: [+ {+ frame: {+ id: "foreign",+ parentId: "root",+ url: "https://foreign.test/page",+ urlFragment,+ },+ },+ ],+ },+ },+ new Set([origin]),+ undefined,+ completeness,+ );+ expect(captured.items.map((frame) => frame.frame_id)).toEqual(["root"]);+ expect(completeness.snapshot().excluded).toEqual(+ expect.arrayContaining([+ { section: "frames", reason: "invalid_protocol_value", count: 1 },+ { section: "frames", reason: "disallowed_origin", count: 1 },+ ]),+ );+ expect(completeness.snapshot().policy_filtered_sections).toContain(+ "frames",+ );+ },+);diff --git a/src/browser/CdpCaptureDocuments.ts b/src/browser/CdpCaptureDocuments.tsindex 40fbb3227..65908b024 100644--- a/src/browser/CdpCaptureDocuments.ts+++ b/src/browser/CdpCaptureDocuments.ts@@ -1,4 +1,5 @@import type { InspectWebPageInput } from "../domain/browserObservation.js";+import { sanitizeBrowserUrl } from "../domain/browserObservation.js";import type { WebPageInspection } from "../domain/browserObservationSchemas.js";import {allowedSanitizedUrl,@@ -55,16 +56,22 @@ export const captureFrames = ()) {const frame = recordValue(tree.frame);const frameId = cdpStringValue(frame?.id);- const sanitized = allowedSanitizedUrl(frame?.url, allowedOrigins);+ const observation = observeCdpFrameUrl(frame);+ const scopeUrl =+ observation.kind === "missing" ? undefined : observation.scopeUrl;+ const facts = classifyCdpFrameUrl(observation, allowedOrigins);if (frame === undefined || frameId === undefined) {completeness?.exclude("frames", "invalid_protocol_value");continue;}- if (sanitized === undefined || sanitized.origin === null) {- completeness?.exclude(- "frames",- exclusionReasonForUrl(cdpStringValue(frame.url)),- );+ if (observation.kind === "invalid_fragment") {+ completeness?.exclude("frames", "invalid_protocol_value");+ if (facts.scope !== "approved")+ completeness?.exclude("frames", exclusionReasonForUrl(scopeUrl));+ continue;+ }+ if (facts.url === undefined || facts.origin === null) {+ completeness?.exclude("frames", exclusionReasonForUrl(scopeUrl));continue;}if (maximum !== undefined && items.length >= maximum) continue;@@ -78,19 +85,86 @@ export const captureFrames = (items.push({frame_id: frameId,parent_frame_id: parentFrameId ?? null,- url: sanitized.url,- origin: sanitized.origin,+ url: facts.url,+ origin: facts.origin,});}return { items };};-/** Read the current main-frame URL from an untrusted Page.getFrameTree result. */-export const mainFrameUrl = (result: unknown): string | undefined =>- cdpStringValue(- recordValue(recordValue(requiredRecord(result).frameTree)?.frame)?.url,+export type CdpFrameUrlObservation =+ | {+ readonly kind: "observed";+ readonly url: string;+ readonly scopeUrl: string;+ }+ | { readonly kind: "invalid_fragment"; readonly scopeUrl: string }+ | { readonly kind: "missing" };++/** Parse identity and scope facts once; an invalid fragment cannot erase its base origin. */+export const observeCdpFrameUrl = (+ frame: UnknownRecord | undefined,+): CdpFrameUrlObservation => {+ const url = cdpStringValue(frame?.url);+ if (url === undefined) return { kind: "missing" };+ if (frame?.urlFragment === undefined)+ return { kind: "observed", url, scopeUrl: url };+ const fragment = cdpStringValue(frame.urlFragment);+ if (fragment === undefined || (fragment !== "" && !fragment.startsWith("#")))+ return { kind: "invalid_fragment", scopeUrl: url };+ return {+ kind: "observed",+ url: `${url.split("#", 1)[0] ?? ""}${fragment}`,+ scopeUrl: url,+ };+};++export const observeMainFrameUrl = (result: unknown): CdpFrameUrlObservation =>+ observeCdpFrameUrl(+ recordValue(recordValue(requiredRecord(result).frameTree)?.frame),);+/** Policy and readable identity are independent facts, including on malformed frames. */+export const classifyCdpFrameUrl = (+ observation: CdpFrameUrlObservation,+ allowedOrigins: ReadonlySet<string>,+): {+ readonly scope: "approved" | "outside_policy" | "unsupported" | "unknown";+ readonly origin: string | null;+ readonly url: string | undefined;+} => {+ if (observation.kind === "missing")+ return { scope: "unknown", origin: null, url: undefined };+ const base = sanitizeBrowserUrl(observation.scopeUrl);+ const scope =+ base.origin === null+ ? "unsupported"+ : allowedOrigins.has(base.origin)+ ? "approved"+ : "outside_policy";+ return {+ scope,+ origin: base.origin,+ url:+ observation.kind === "observed" && scope === "approved"+ ? sanitizeBrowserUrl(observation.url).url+ : undefined,+ };+};++/** Read the complete identity only when the protocol established it. */+export const cdpFrameUrl = (+ frame: UnknownRecord | undefined,+): string | undefined => {+ const observed = observeCdpFrameUrl(frame);+ return observed.kind === "observed" ? observed.url : undefined;+};++export const mainFrameUrl = (result: unknown): string | undefined => {+ const observed = observeMainFrameUrl(result);+ return observed.kind === "observed" ? observed.url : undefined;+};+/** Normalize every allowed resource. */export const captureResources = (result: unknown,diff --git a/src/browser/CdpElectronInspection.test.ts b/src/browser/CdpElectronInspection.test.tsindex 3d43b659b..06b07b478 100644--- a/src/browser/CdpElectronInspection.test.ts+++ b/src/browser/CdpElectronInspection.test.ts@@ -7,7 +7,11 @@ import { pathToFileURL } from "node:url";import { afterEach, describe, expect, it } from "vitest";import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";-import { captureFrames } from "./CdpElectronInspection.js";+import {+ captureFrames,+ inspectCdpElectronPage,+} from "./CdpElectronInspection.js";+import type { CdpEvent } from "./CdpConnection.js";import type { CdpConnection } from "./CdpConnection.js";import {ingestElectronScriptEvent,@@ -16,9 +20,202 @@ import {import { CDP_SCRIPT_SOURCE_BYTES_OMISSION_REASON } from "./CdpScriptSourceBudget.js";import { captureElectronScripts } from "./CdpElectronScripts.js";import { inspectElectronPageInputSchema } from "../domain/javascript/electronObservation.js";+import type { ProgressReporter } from "../application/ProgressReporter.js";const temporary: string[] = [];+const inspectRaceConnection = (+ connection: CdpConnection,+ mainUrl: string,+ progress?: ProgressReporter,+) =>+ inspectCdpElectronPage({+ connection,+ ...(progress === undefined ? {} : { progress }),+ sessionId: undefined,+ asarHeaderAdmission: DEFAULT_ASAR_HEADER_ADMISSION,+ discovery: {+ webSocket: { scope: "browser", url: "ws://127.0.0.1:9222" },+ version: {+ product: "fixture",+ protocol_version: "1",+ revision: "",+ user_agent: "fixture",+ js_version: "",+ },+ targets: [],+ },+ target: {+ id: "page",+ type: "page",+ title: "fixture",+ url: mainUrl,+ attached: false,+ },+ input: inspectElectronPageInputSchema.parse({+ cdp_endpoint: "http://127.0.0.1:9222",+ target_id: "page",+ observation_ms: 0,+ }),+ });++it.each([+ "initial",+ "refreshed",+ "final",+ "ancestor",+ "opaque-ancestor",+ "stable",+])(+ "binds frame authorization to the tree read across file checks: %s",+ async (stage) => {+ const isAncestor = stage.endsWith("ancestor");+ const root = await mkdtemp(join(tmpdir(), "rea-frame-generation-race-"));+ temporary.push(root);+ const main = join(root, "main.html"),+ child = join(root, "child.html"),+ script = join(root, "app.js");+ await Promise.all([+ writeFile(main, "main"),+ writeFile(child, "child"),+ writeFile(script, "void 0;"),+ ]);+ const mainUrl = pathToFileURL(main).href,+ childUrl = pathToFileURL(child).href;+ let listener: (event: CdpEvent) => void = () => {};+ let reads = 0,+ fired = false;+ const emitScript = () => {+ listener({+ method: "Runtime.executionContextCreated",+ params: { context: { id: 7, auxData: { frameId: "child" } } },+ });+ listener({+ method: "Debugger.scriptParsed",+ params: {+ scriptId: "new-document-script",+ url: pathToFileURL(script).href,+ executionContextId: 7,+ hash: "new-document",+ },+ });+ };+ const inject = () => {+ listener({+ method: "Page.frameNavigated",+ params: {+ frame: {+ id: isAncestor ? "parent" : "child",+ parentId: "main",+ url: "https://foreign.test/new-document",+ },+ },+ });+ if (stage !== "initial") emitScript();+ };+ const connection = {+ onEvent: (value: typeof listener) => {+ listener = value;+ return () => {};+ },+ send: async (method: string) => {+ if (method === "Page.getFrameTree") {+ reads++;+ const shouldInject =+ (stage === "initial" && reads === 1) ||+ (stage === "refreshed" && reads === 2) ||+ (isAncestor && reads === 2) ||+ (stage === "final" && reads === 3);+ return {+ frameTree: {+ frame: { id: "main", url: mainUrl },+ childFrames:+ (stage === "initial" && reads > 1) ||+ (stage === "refreshed" && reads !== 2) ||+ (isAncestor && reads !== 2) ||+ (stage === "final" && reads === 1)+ ? []+ : [+ {+ frame: {+ id: isAncestor ? "parent" : "child",+ parentId: "main",+ get url() {+ if (shouldInject && !isAncestor && !fired) {+ fired = true;+ queueMicrotask(inject);+ }+ return stage === "opaque-ancestor"+ ? "about:blank"+ : childUrl;+ },+ },+ ...(isAncestor+ ? {+ childFrames: [+ {+ frame: {+ id: "child",+ parentId: "parent",+ get url() {+ if (shouldInject && !fired) {+ fired = true;+ queueMicrotask(inject);+ }+ return childUrl;+ },+ },+ },+ ],+ }+ : {}),+ },+ ],+ },+ };+ }+ if (method === "Debugger.enable" && stage === "initial") emitScript();+ if (method === "Debugger.enable" && stage === "stable") {+ listener({+ method: "Runtime.executionContextCreated",+ params: { context: { id: 7, auxData: { frameId: "child" } } },+ });+ listener({+ method: "Debugger.scriptParsed",+ params: {+ scriptId: "stable-script",+ url: pathToFileURL(script).href,+ executionContextId: 7,+ hash: "stable",+ },+ });+ }+ if (method === "Page.getResourceTree")+ return {+ frameTree: { frame: { id: "main", url: mainUrl }, resources: [] },+ };+ if (method === "DOMSnapshot.captureSnapshot")+ return { strings: [], documents: [] };+ if (method === "Target.getTargets") return { targetInfos: [] };+ return {};+ },+ } as unknown as CdpConnection;+ const result = await inspectRaceConnection(connection, mainUrl);+ if (stage === "stable")+ expect(result.scripts.items).toContainEqual(+ expect.objectContaining({ frame_id: "child", cdp_hash: "stable" }),+ );+ else {+ expect(fired).toBe(true);+ if (stage !== "final")+ expect(result.scripts.items).toContainEqual(+ expect.objectContaining({ frame_id: null, cdp_hash: "new-document" }),+ );+ expect(result.completeness.attach_limited_sections).toContain("frames");+ }+ },+);+afterEach(async () => {await Promise.all(temporary@@ -27,6 +224,194 @@ afterEach(async () => {);});+it.each([+ "late-main",+ "late-main-progress",+ "duplicate-initial",+ "duplicate-main",+ "duplicate-child",+ "replacement-child",+ "unknown-child",+])(+ "preserves document identity through final file validation: %s",+ async (kind) => {+ const root = await mkdtemp(+ join(tmpdir(), "rea-electron-document-identity-"),+ );+ temporary.push(root);+ const main = join(root, "main.html"),+ child = join(root, "child.html"),+ script = join(root, "app.js");+ await Promise.all([+ writeFile(main, "main"),+ writeFile(child, "child"),+ writeFile(script, "void 0;"),+ ]);+ const mainUrl = pathToFileURL(main).href,+ childUrl = pathToFileURL(child).href;+ let listener: (event: CdpEvent) => void = () => {};+ let reads = 0,+ fired = false;+ const inject = () => {+ const isMain =+ kind.startsWith("late-main") ||+ kind === "duplicate-main" ||+ kind === "duplicate-initial";+ listener({+ method: "Page.frameNavigated",+ params: {+ frame: {+ id: isMain ? "main" : "child",+ ...(isMain ? {} : { parentId: "main" }),+ url: isMain ? mainUrl : childUrl,+ ...(kind === "unknown-child"+ ? {}+ : {+ loaderId:+ kind.startsWith("late-main") || kind === "replacement-child"+ ? "replacement-loader"+ : isMain+ ? "loader-main"+ : "loader-child",+ }),+ },+ },+ });+ if (!isMain) {+ listener({+ method: "Runtime.executionContextCreated",+ params: { context: { id: 7, auxData: { frameId: "child" } } },+ });+ listener({+ method: "Debugger.scriptParsed",+ params: {+ scriptId: "observed",+ url: pathToFileURL(script).href,+ executionContextId: 7,+ hash: "observed",+ },+ });+ }+ };+ const connection = {+ onEvent: (value: typeof listener) => {+ listener = value;+ return () => {};+ },+ send: async (method: string) => {+ if (method === "Page.getFrameTree") {+ reads++;+ const trigger =+ kind === "late-main-progress"+ ? false+ : kind === "duplicate-initial"+ ? reads === 1+ : kind === "late-main"+ ? reads === 3+ : reads === 2;+ let frameUrlReads = 0;+ return {+ frameTree: {+ frame: { id: "main", url: mainUrl, loaderId: "loader-main" },+ childFrames: [+ {+ frame: {+ id: "child",+ parentId: "main",+ loaderId: "loader-child",+ get url() {+ frameUrlReads++;+ // Seeded protocol facts are read first; inject during the later file check.+ if (+ trigger &&+ !fired &&+ (kind !== "late-main" || frameUrlReads === 2)+ ) {+ fired = true;+ queueMicrotask(inject);+ }+ return childUrl;+ },+ },+ },+ ],+ },+ };+ }+ if (method === "Page.getResourceTree")+ return {+ frameTree: { frame: { id: "main", url: mainUrl }, resources: [] },+ };+ if (method === "DOMSnapshot.captureSnapshot")+ return { strings: [], documents: [] };+ if (method === "Target.getTargets") return { targetInfos: [] };+ return {};+ },+ } as unknown as CdpConnection;+ const result = inspectRaceConnection(connection, mainUrl, {+ report: async (update) => {+ if (kind === "late-main-progress" && update.completed === 3) {+ fired = true;+ inject();+ }+ },+ });+ if (kind.startsWith("late-main"))+ await expect(result).rejects.toMatchObject({ reason: "target_changed" });+ else {+ const captured = await result;+ expect(fired).toBe(true);+ if (kind.startsWith("duplicate"))+ expect(captured.completeness.attach_limited_sections).not.toContain(+ "frames",+ );+ if (kind !== "duplicate-main" && kind !== "duplicate-initial")+ expect(captured.scripts.items).toContainEqual(+ expect.objectContaining({+ cdp_hash: "observed",+ frame_id: kind === "duplicate-child" ? "child" : null,+ }),+ );+ }+ },+);++it.each([7, null, "", "claimed-parent"])(+ "does not promote children when the enclosing root has a parent: %s",+ async (parentId) => {+ const root = await mkdtemp(join(tmpdir(), "rea-electron-root-role-"));+ temporary.push(root);+ const main = join(root, "index.html");+ await writeFile(main, "main");+ const completeness = new CdpCaptureCompleteness();+ const { frames } = await captureFrames(+ {+ frameTree: {+ frame: { id: "main", url: pathToFileURL(main).href, parentId },+ childFrames: [+ {+ frame: {+ id: "child",+ parentId: "main",+ url: pathToFileURL(main).href,+ },+ },+ ],+ },+ },+ completeness,+ DEFAULT_ASAR_HEADER_ADMISSION,+ );+ expect(frames).toEqual([]);+ expect(completeness.snapshot().excluded).toContainEqual({+ section: "frames",+ reason: "invalid_protocol_value",+ count: 2,+ });+ expect(completeness.snapshot().policy_filtered_sections).toEqual([]);+ },+);+describe("Electron frame capture", () => {it.each([7, undefined])("classifies a malformed child frame ID as unavailable: %s",@@ -40,7 +425,7 @@ describe("Electron frame capture", () => {const childUrl = pathToFileURL(child).href;const completeness = new CdpCaptureCompleteness();- const frames = await captureFrames(+ const { frames } = await captureFrames({frameTree: {frame: { id: "frame-main", url: mainUrl },@@ -133,7 +518,11 @@ describe("Electron frame capture", () => {include_script_sources: false,}),scripts,- frameIds: new Set(["frame-old", "frame-new"]),+ frameForScript: (script) =>+ script.frameId !== null &&+ new Set(["frame-old", "frame-new"]).has(script.frameId)+ ? script.frameId+ : null,completeness,asarHeaderAdmission: DEFAULT_ASAR_HEADER_ADMISSION,});@@ -213,7 +602,7 @@ it("admits a prefix and fitting suffix around an oversized Electron source", asyinclude_script_sources: true,}),scripts,- frameIds: new Set(),+ frameForScript: () => null,completeness,asarHeaderAdmission: DEFAULT_ASAR_HEADER_ADMISSION,});@@ -235,3 +624,177 @@ it("admits a prefix and fitting suffix around an oversized Electron source", asycount: 1,});});++it.each([+ ...[+ ...[2, 3].flatMap((stage) =>+ [false, true].map((lateEvent) => ({+ scope: "main",+ stage,+ lateEvent,+ changed: true,+ })),+ ),+ ...[false, true].map((lateEvent) => ({+ scope: "child",+ stage: 2,+ lateEvent,+ changed: true,+ })),+ ...["main", "child"].map((scope) => ({+ scope,+ stage: 2,+ lateEvent: true,+ changed: false,+ })),+ ].map((item) => ({ ...item, urlChange: "", fullReplay: false })),+ ...["#next", "?route=next"].flatMap((urlChange) =>+ [false, true].map((lateEvent) => ({+ scope: "child",+ stage: 2,+ lateEvent,+ changed: false,+ urlChange,+ fullReplay: false,+ })),+ ),+ {+ scope: "child",+ stage: 2,+ lateEvent: true,+ changed: false,+ urlChange: "#next",+ fullReplay: true,+ },+ ...[2, 3].map((stage) => ({+ scope: "main",+ stage,+ lateEvent: false,+ changed: false,+ urlChange: "#next",+ fullReplay: false,+ })),+])(+ "detects tree-first document replacement $scope/read$stage/late=$lateEvent/changed=$changed/url=$urlChange/full=$fullReplay",+ async ({ scope, stage, lateEvent, changed, urlChange, fullReplay }) => {+ const root = await mkdtemp(join(tmpdir(), "rea-tree-first-document-"));+ temporary.push(root);+ const main = join(root, "main.html"),+ child = join(root, "child.html"),+ script = join(root, "app.js");+ await Promise.all([+ writeFile(main, "main"),+ writeFile(child, "child"),+ writeFile(script, "void 0;"),+ ]);+ const mainUrl = pathToFileURL(main).href,+ childUrl = pathToFileURL(child).href;+ let listener: (event: CdpEvent) => void = () => {};+ let reads = 0;+ let replayed = false;+ const emitScript = (hash: string, frameId: string, contextId: number) => {+ listener({+ method: "Runtime.executionContextCreated",+ params: { context: { id: contextId, auxData: { frameId } } },+ });+ listener({+ method: "Debugger.scriptParsed",+ params: {+ scriptId: hash,+ url: pathToFileURL(script).href,+ executionContextId: contextId,+ hash,+ },+ });+ };+ const document = (id: string) => ({+ id,+ ...(id === "main" ? {} : { parentId: id === "child" ? "main" : "child" }),+ url:+ (id === "main" ? mainUrl : childUrl) ++ (reads >= stage && id === scope ? urlChange : ""),+ loaderId:+ changed && reads >= stage && id === scope+ ? "replacement"+ : `loader-${id}`,+ });+ const replay = () => {+ if (replayed || reads < stage) return;+ replayed = true;+ if (lateEvent)+ listener(+ urlChange && !fullReplay+ ? {+ method: "Page.navigatedWithinDocument",+ params: { frameId: scope, url: document(scope).url },+ }+ : {+ method: "Page.frameNavigated",+ params: { frame: document(scope) },+ },+ );+ emitScript("after-child", "child", 10);+ emitScript("after-grandchild", "grandchild", 11);+ };+ const connection = {+ onEvent: (value: typeof listener) => {+ listener = value;+ return () => {};+ },+ send: async (method: string) => {+ if (method === "Page.getFrameTree") {+ reads++;+ return {+ frameTree: {+ frame: document("main"),+ childFrames: [+ {+ frame: document("child"),+ childFrames: [{ frame: document("grandchild") }],+ },+ ],+ },+ };+ }+ if (method === "Debugger.enable") {+ emitScript("before-child", "child", 7);+ emitScript("before-grandchild", "grandchild", 8);+ }+ if (method === "Page.getResourceTree") {+ replay();+ return {+ frameTree: { frame: { id: "main", url: mainUrl }, resources: [] },+ };+ }+ if (method === "DOMSnapshot.captureSnapshot")+ return { strings: [], documents: [] };+ if (method === "Target.getTargets") return { targetInfos: [] };+ return {};+ },+ } as unknown as CdpConnection;+ const result = inspectRaceConnection(connection, mainUrl, {+ report: async (update) => {+ if (update.completed === 3) replay();+ },+ });+ if (scope === "main" && (changed || urlChange))+ await expect(result).rejects.toMatchObject({ reason: "target_changed" });+ else {+ const captured = await result;+ for (const id of ["child", "grandchild"]) {+ expect(captured.scripts.items).toContainEqual(+ expect.objectContaining({ cdp_hash: `before-${id}`, frame_id: id }),+ );+ expect(captured.scripts.items).toContainEqual(+ expect.objectContaining({+ cdp_hash: `after-${id}`,+ frame_id: changed ? null : id,+ }),+ );+ }+ expect(+ captured.completeness.attach_limited_sections.includes("frames"),+ ).toBe(changed);+ }+ },+);diff --git a/src/browser/CdpElectronInspection.ts b/src/browser/CdpElectronInspection.tsindex 1e1b75c84..ddf09e83f 100644--- a/src/browser/CdpElectronInspection.ts+++ b/src/browser/CdpElectronInspection.ts@@ -14,11 +14,14 @@ import {delayWithCancellation,resourceContentSize,recordValue,+ recordsValue,+ type UnknownRecord,requiredRecord,cdpStringValue,} from "./CdpCaptureValues.js";import {frameTreeResources,+ cdpFrameUrl,snapshotDocuments,walkFrameTrees,} from "./CdpCaptureDocuments.js";@@ -31,7 +34,10 @@ import {import { captureElectronScripts } from "./CdpElectronScripts.js";import { captureElectronWorkers } from "./CdpElectronWorkers.js";import { authorizedElectronFile } from "./ElectronFileScope.js";-import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";+import {+ compareUnicodeCodePoints,+ compositeKey,+} from "../domain/unicodeCodePointOrder.js";interface ElectronContext {readonly connection: CdpConnection;@@ -49,11 +55,31 @@ interface ElectronInspectionState {readonly completeness: CdpCaptureCompleteness;readonly scripts: ElectronScriptDraft[];readonly executionContextFrames: Map<string, string>;+ readonly frameGenerations: Map<string, number>;+ readonly frameParents: Map<string, string | null>;+ readonly frameDocuments: Map<string, ElectronFrameDocument>;+ readonly authorizedFrameGenerations: Set<string>;+ readonly scriptGenerations: WeakMap<ElectronScriptDraft, number>;readonly limitations: string[];mainFrameId: string | undefined;navigationDuringCapture: boolean;}+interface ElectronFrameInventory {+ readonly frames: ElectronPageInspection["frames"];+ readonly parents: ReadonlyMap<string, string | null>;+}++interface ElectronFrameRead extends ElectronFrameInventory {+ readonly generations: ReadonlyMap<string, number>;+}++interface ElectronFrameDocument {+ readonly url: string;+ readonly loaderId: string;+ readonly parentId: string | null;+}+/** Passively inspect one Electron file page from the selected CDP endpoint. */export const inspectCdpElectronPage = async (context: ElectronContext,@@ -62,6 +88,11 @@ export const inspectCdpElectronPage = async (completeness: new CdpCaptureCompleteness(),scripts: [],executionContextFrames: new Map(),+ frameGenerations: new Map(),+ frameParents: new Map(),+ frameDocuments: new Map(),+ authorizedFrameGenerations: new Set(),+ scriptGenerations: new WeakMap(),limitations: ["Local file paths exposed by the selected CDP target are retained in the observation.","REA does not evaluate renderer JavaScript, invoke Electron APIs, navigate, click, or close the page.",@@ -77,17 +108,20 @@ export const inspectCdpElectronPage = async (};const removeListener = context.connection.onEvent((event) => {if (event.sessionId !== context.sessionId) return;+ advanceFrameGeneration(event, state);+ const priorScripts = state.scripts.length;ingestElectronScriptEvent({event,scripts: state.scripts,executionContextFrames: state.executionContextFrames,completeness: state.completeness,});- if (- state.mainFrameId !== undefined &&- navigatedFrameId(event) === state.mainFrameId- )- state.navigationDuringCapture = true;+ const script = state.scripts[priorScripts];+ if (script?.frameId != null)+ state.scriptGenerations.set(+ script,+ state.frameGenerations.get(script.frameId) ?? 0,+ );});try {return await runElectronInspection(@@ -105,20 +139,53 @@ const runElectronInspection = async (state: ElectronInspectionState,startedAt: string,): Promise<ElectronPageInspection> => {- const frames = await authorizeInitialFrames(context, state);- const main = frames.at(0);+ const initialRead = await authorizeInitialFrames(context, state);+ const initialFrames = initialRead.frames;+ const main = initialFrames.at(0);if (main === undefined)throw new BrowserObservationError("inspect_web_page", "target_not_allowed");+ if (unprovenFrameIds(initialRead, state).has(main.frame_id))+ throw new BrowserObservationError("inspect_web_page", "target_changed");state.mainFrameId = main.frame_id;+ authorizeFrameGenerations(initialRead, state);await enableElectronCapture(context);await delayWithCancellation(context.input.observation_ms,"inspect_electron_page",context.signal,);+ // Current inventory owns structural content; script attribution retains+ // separately authorized generations observed during the whole window.+ const currentRead = await readCurrentFrames(+ context,+ state,+ state.completeness,+ );+ const frames = currentRead.frames;+ authorizeFrameGenerations(currentRead, state);+ if (+ frameInventoryIdentity(initialFrames) !== frameInventoryIdentity(frames)+ ) {+ state.limitations.push(+ "The frame inventory changed during observation. Returned frames describe the current inventory; retained script frame IDs can identify earlier authorized frames.",+ );+ }const captured = await captureElectronContent(context, state, frames);- await assertStableMainFrame(context, state, main.file_path);+ const finalFrames = await assertStableMainFrame(+ context,+ state,+ main.file_path,+ );+ if (frameInventoryIdentity(frames) !== frameInventoryIdentity(finalFrames)) {+ for (const section of ["frames", "scripts", "workers"] as const)+ state.completeness.attachLimited(section);+ state.limitations.push(+ "The frame inventory changed during content capture; frame membership and dependent attribution are incomplete.",+ );+ }await report(context.progress, 3, "Electron inspection complete");+ if (state.navigationDuringCapture)+ throw new BrowserObservationError("inspect_web_page", "target_changed");return {browser: context.discovery.version,target: {@@ -140,10 +207,223 @@ const runElectronInspection = async (};};+/** Sibling enumeration order is not a change to frame identity or ownership. */+const frameInventoryIdentity = (+ frames: ElectronPageInspection["frames"],+): string =>+ digestCanonicalValue(+ frames+ .map((frame) =>+ compositeKey([frame.frame_id, frame.parent_frame_id, frame.file_path]),+ )+ .sort(compareUnicodeCodePoints),+ );++const authorizeFrameGenerations = (+ read: ElectronFrameRead,+ state: ElectronInspectionState,+): void => {+ const unproven = markUnstableFrameRead(read, state);+ for (const [id, parent] of read.parents)+ if (!unproven.has(id)) state.frameParents.set(id, parent);+ for (const frame of read.frames) {+ const generation = read.generations.get(frame.frame_id) ?? 0;+ if (unproven.has(frame.frame_id)) continue;+ state.authorizedFrameGenerations.add(+ compositeKey([frame.frame_id, generation]),+ );+ }+};++/** A changed ancestor also invalidates descendants first discovered in this tree. */+const unprovenFrameIds = (+ read: ElectronFrameRead,+ state: ElectronInspectionState,+): Set<string> => {+ const children = new Map<string, string[]>();+ const unproven = new Set<string>();+ for (const [id, parent] of read.parents) {+ if (+ (read.generations.get(id) ?? 0) !== (state.frameGenerations.get(id) ?? 0)+ )+ unproven.add(id);+ if (parent === null) continue;+ if (!read.parents.has(parent)) unproven.add(id);+ const siblings = children.get(parent) ?? [];+ siblings.push(id);+ children.set(parent, siblings);+ }+ const pending = [...unproven];+ while (pending.length > 0) {+ const parent = pending.pop();+ if (parent === undefined) continue;+ for (const child of children.get(parent) ?? []) {+ if (unproven.has(child)) continue;+ unproven.add(child);+ pending.push(child);+ }+ }+ return unproven;+};++/** Lifecycle events invalidate future attribution, never earlier script facts. */+const advanceFrameGeneration = (+ event: CdpEvent,+ state: ElectronInspectionState,+): void => {+ // A same-document event changes the cached identity, never its generation+ // or authority. Later full-frame replay must compare with that current URL.+ if (event.method === "Page.navigatedWithinDocument") {+ const params = recordValue(event.params);+ const id = cdpStringValue(params?.frameId);+ if (id === undefined) return;+ if (id === state.mainFrameId) state.navigationDuringCapture = true;+ const previous = state.frameDocuments.get(id);+ if (previous === undefined) return;+ const url = cdpFrameUrl(params);+ if (url === undefined || url === "") state.frameDocuments.delete(id);+ else state.frameDocuments.set(id, { ...previous, url });+ return;+ }+ if (+ ![+ "Page.frameNavigated",+ "Page.frameDetached",+ "Page.frameAttached",+ ].includes(event.method)+ )+ return;+ const params = recordValue(event.params);+ const frame =+ event.method === "Page.frameNavigated"+ ? recordValue(params?.frame)+ : params;+ const id = cdpStringValue(frame?.id) ?? cdpStringValue(frame?.frameId);+ if (id === undefined) return;+ const document =+ event.method === "Page.frameNavigated" ? frameDocument(frame) : undefined;+ const previous = state.frameDocuments.get(id);+ if (+ document !== undefined &&+ previous !== undefined &&+ sameFrameDocument(document, previous) &&+ document.url === previous.url+ )+ return;+ invalidateFrameGenerations(id, state);+ // Event ancestry only invalidates future facts; it never authorizes a frame.+ const parent =+ cdpStringValue(frame?.parentId) ?? cdpStringValue(frame?.parentFrameId);+ if (parent !== undefined && parent !== "") state.frameParents.set(id, parent);+ else state.frameParents.delete(id);+ if (document !== undefined) retainFrameDocument(id, document, state);+};++/** A stable loader and parent identify the document independently of its URL. */+const sameFrameDocument = (+ left: ElectronFrameDocument,+ right: ElectronFrameDocument,+): boolean =>+ left.loaderId === right.loaderId && left.parentId === right.parentId;++/** URL observations can move without replacing the loader-owned document. */+const retainFrameDocument = (+ id: string,+ document: ElectronFrameDocument,+ state: ElectronInspectionState,+): void => {+ const previous = state.frameDocuments.get(id);+ if (+ previous !== undefined &&+ sameFrameDocument(previous, document) &&+ previous.url === document.url+ )+ return;+ if (+ id === state.mainFrameId &&+ previous !== undefined &&+ previous.url !== document.url+ )+ state.navigationDuringCapture = true;+ state.frameDocuments.set(id, document);+};++/** Tree and event observations invalidate the same document generation. */+const invalidateFrameGenerations = (+ id: string,+ state: ElectronInspectionState,+): void => {+ const pending = [id];+ const changed = new Set<string>();+ while (pending.length > 0) {+ const current = pending.pop();+ if (current === undefined || changed.has(current)) continue;+ changed.add(current);+ if (current === state.mainFrameId) state.navigationDuringCapture = true;+ state.frameGenerations.set(+ current,+ (state.frameGenerations.get(current) ?? 0) + 1,+ );+ state.frameDocuments.delete(current);+ for (const [child, parent] of state.frameParents)+ if (parent === current) pending.push(child);+ }+};++/** Only a known URL and loader together can prove a duplicate document event. */+const frameDocument = (+ frame: ReturnType<typeof recordValue>,+): ElectronFrameDocument | undefined => {+ const url = cdpFrameUrl(frame);+ const loaderId = cdpStringValue(frame?.loaderId);+ if (+ url === undefined ||+ url === "" ||+ loaderId === undefined ||+ loaderId === ""+ )+ return undefined;+ if (+ frame?.parentId !== undefined &&+ (cdpStringValue(frame.parentId) === undefined || frame.parentId === "")+ )+ return undefined;+ return { url, loaderId, parentId: cdpStringValue(frame?.parentId) ?? null };+};++/** Protocol identities are observations, separate from asynchronous file authorization. */+const seedFrameDocuments = (+ result: unknown,+ generations: ReadonlyMap<string, number>,+ documents: ReadonlyMap<string, ElectronFrameDocument>,+ state: ElectronInspectionState,+): void => {+ const tree = recordValue(recordValue(result)?.frameTree);+ if (tree === undefined) return;+ for (const entry of walkFrameTrees(tree)) {+ const frame = recordValue(entry.frame);+ const id = cdpStringValue(frame?.id);+ const document = frameDocument(frame);+ if (+ id !== undefined &&+ document !== undefined &&+ // A same-document event can update identity without changing generation.+ // Do not overwrite that newer observation with this in-flight tree.+ state.frameDocuments.get(id) === documents.get(id) &&+ (generations.get(id) ?? 0) === (state.frameGenerations.get(id) ?? 0)+ ) {+ const previous = documents.get(id);+ if (previous !== undefined && !sameFrameDocument(previous, document))+ invalidateFrameGenerations(id, state);+ retainFrameDocument(id, document, state);+ }+ }+};+const authorizeInitialFrames = async (context: ElectronContext,state: ElectronInspectionState,-): Promise<ElectronPageInspection["frames"]> => {+): Promise<ElectronFrameRead> => {await report(context.progress, 1, "Authorizing Electron file frames");await context.connection.send("Page.enable",@@ -151,21 +431,50 @@ const authorizeInitialFrames = async (context.sessionId,context.signal,);+ // Initial frames authorize attachment; the later inventory owns coverage.+ return await readCurrentFrames(context, state, new CdpCaptureCompleteness());+};++const readCurrentFrames = async (+ context: ElectronContext,+ state: ElectronInspectionState,+ completeness: CdpCaptureCompleteness,+): Promise<ElectronFrameRead> => {+ // Snapshot before the asynchronous protocol and filesystem boundaries.+ // A tree can only authorize the generations for which it was requested.+ const generations = new Map(state.frameGenerations);+ const documents = new Map(state.frameDocuments);const result = await context.connection.send("Page.getFrameTree",{},context.sessionId,context.signal,);- const frames = await captureFrames(+ seedFrameDocuments(result, generations, documents, state);+ const inventory = await captureFrames(result,- state.completeness,+ completeness,context.asarHeaderAdmission,context.signal,);- if (frames[0] === undefined)+ const main = inventory.frames[0];+ if (main === undefined || inventory.parents.get(main.frame_id) !== null)throw new BrowserObservationError("inspect_web_page", "target_not_allowed");- return frames;+ return { ...inventory, generations };+};++const markUnstableFrameRead = (+ read: ElectronFrameRead,+ state: ElectronInspectionState,+): Set<string> => {+ const unproven = unprovenFrameIds(read, state);+ if (unproven.size === 0) return unproven;+ for (const section of ["frames", "scripts", "workers"] as const)+ state.completeness.attachLimited(section);+ state.limitations.push(+ "A frame or its ancestry could not be verified across the tree read and local file checks; this read cannot authorize an unchecked document.",+ );+ return unproven;};const enableElectronCapture = async (@@ -202,7 +511,18 @@ const captureElectronContent = async (...(context.signal === undefined ? {} : { signal: context.signal }),request: context.input,scripts: state.scripts,- frameIds,+ frameForScript: (script) => {+ const generation = state.scriptGenerations.get(script);+ const authorized =+ script.frameId !== null &&+ generation !== undefined &&+ state.authorizedFrameGenerations.has(+ compositeKey([script.frameId, generation]),+ );+ if (script.frameId !== null && !authorized)+ state.completeness.attachLimited("scripts");+ return authorized ? script.frameId : null;+ },completeness: state.completeness,asarHeaderAdmission: context.asarHeaderAdmission,});@@ -223,32 +543,54 @@ const assertStableMainFrame = async (context: ElectronContext,state: ElectronInspectionState,expectedPath: string,-): Promise<void> => {+): Promise<ElectronPageInspection["frames"]> => {+ const generations = new Map(state.frameGenerations);+ const documents = new Map(state.frameDocuments);const result = await context.connection.send("Page.getFrameTree",{},context.sessionId,context.signal,);+ seedFrameDocuments(result, generations, documents, state);const afterPath = await mainFilePath(result,context.asarHeaderAdmission,context.signal,);+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;- if (event.method === "Page.frameNavigated")- return cdpStringValue(recordValue(params.frame)?.id);- if (event.method === "Page.navigatedWithinDocument")- return cdpStringValue(params.frameId);- return undefined;+ const completeness = new CdpCaptureCompleteness();+ const inventory = await captureFrames(+ result,+ completeness,+ context.asarHeaderAdmission,+ context.signal,+ );+ const { frames } = inventory;+ if (+ state.navigationDuringCapture ||+ (state.mainFrameId !== undefined &&+ (generations.get(state.mainFrameId) ?? 0) !==+ (state.frameGenerations.get(state.mainFrameId) ?? 0))+ )+ throw new BrowserObservationError("inspect_web_page", "target_changed");+ markUnstableFrameRead({ ...inventory, generations }, state);+ if (+ completeness+ .snapshot()+ .conditions.some((condition) => condition !== "complete_within_window")+ ) {+ for (const section of ["frames", "scripts", "workers"] as const)+ state.completeness.attachLimited(section);+ state.limitations.push(+ "The final frame inventory was incomplete; frame stability could not be fully verified.",+ );+ }+ return frames;};export const captureFrames = async (@@ -256,21 +598,42 @@ export const captureFrames = async (completeness: CdpCaptureCompleteness,asarHeaderAdmission: AsarHeaderAdmission,signal?: AbortSignal,-): Promise<ElectronPageInspection["frames"]> => {+): Promise<ElectronFrameInventory> => {const frameTree = recordValue(requiredRecord(result).frameTree);if (frameTree === undefined)throw new BrowserObservationError("inspect_web_page", "protocol_error");const frames: ElectronPageInspection["frames"] = [];- for (const tree of walkFrameTrees(frameTree, () =>- completeness.exclude("frames", "invalid_protocol_value"),+ const enclosingParents = new Map<UnknownRecord, string>();+ const parents = new Map<string, string | null>();+ for (const tree of walkFrameTrees(frameTree, (count) =>+ completeness.exclude("frames", "invalid_protocol_value", count),)) {throwIfElectronInspectionCancelled(signal);const frame = recordValue(tree.frame);const frameId = cdpStringValue(frame?.id);- if (frame === undefined || frameId === undefined) {+ const parentId = cdpStringValue(frame?.parentId);+ // Only the enclosing tree root may omit its parent. Children must agree+ // with a structurally proved enclosing frame, independent of its file policy.+ // Malformed ancestry cannot grant proof to a frame or its descendants.+ const ancestryKnown =+ tree === frameTree+ ? frame !== undefined && !Object.hasOwn(frame, "parentId")+ : parentId !== undefined &&+ parentId !== "" &&+ parentId !== frameId &&+ parentId === enclosingParents.get(tree);+ if (+ frame === undefined ||+ frameId === undefined ||+ frameId === "" ||+ !ancestryKnown+ ) {completeness.exclude("frames", "invalid_protocol_value");continue;}+ parents.set(frameId, parentId ?? null);+ for (const child of recordsValue(tree.childFrames))+ enclosingParents.set(child, frameId);const path = await authorizedElectronFile(cdpStringValue(frame.url) ?? "",signal,@@ -283,11 +646,11 @@ export const captureFrames = async (}frames.push({frame_id: frameId,- parent_frame_id: cdpStringValue(frame?.parentId) ?? null,+ parent_frame_id: parentId ?? null,file_path: path,});}- return frames;+ return { frames, parents };};const captureResources = async (diff --git a/src/browser/CdpElectronScripts.ts b/src/browser/CdpElectronScripts.tsindex fdeeba088..6f2b879ec 100644--- a/src/browser/CdpElectronScripts.ts+++ b/src/browser/CdpElectronScripts.ts@@ -25,7 +25,7 @@ interface ElectronScriptCaptureInput {readonly signal?: AbortSignal;readonly request: InspectElectronPageInput;readonly scripts: readonly ElectronScriptDraft[];- readonly frameIds: ReadonlySet<string>;+ readonly frameForScript: (script: ElectronScriptDraft) => string | null;readonly completeness: CdpCaptureCompleteness;readonly asarHeaderAdmission: AsarHeaderAdmission;}@@ -60,10 +60,7 @@ export const captureElectronScripts = async (continue;}const identity = {- frame_id:- script.frameId !== null && input.frameIds.has(script.frameId)- ? script.frameId- : null,+ frame_id: input.frameForScript(script),file_path: path,cdp_hash: script.hash,length: script.length,diff --git a/src/browser/CdpObservationSession.ts b/src/browser/CdpObservationSession.tsindex ed74a5c7f..a95602af1 100644--- a/src/browser/CdpObservationSession.ts+++ b/src/browser/CdpObservationSession.ts@@ -24,7 +24,12 @@ import {cdpStringValue,type UnknownRecord,} from "./CdpCaptureValues.js";-import { mainFrameUrl } from "./CdpCaptureDocuments.js";+import {+ mainFrameUrl,+ observeCdpFrameUrl,+ observeMainFrameUrl,+ classifyCdpFrameUrl,+} from "./CdpCaptureDocuments.js";import { cdpFrameIdentity } from "./CdpCaptureEventHelpers.js";import { cdpTargetEventMatches } from "./CdpTargetEvents.js";@@ -46,6 +51,7 @@ interface TimelineEntryOptions {readonly params: UnknownRecord;readonly timestamp?: number | null;readonly rawUrl?: string | null;+ readonly destinationScope?: TimelineEvent["destination_scope"];readonly requestId?: string | null;readonly detail?: string | null;}@@ -393,16 +399,20 @@ class TimelineCapture {if (identity.identityIssue !== null || identity.parentIssue !== null)this.completeness.exclude("timeline", "invalid_protocol_value");if (identity.selection !== "main" && !identity.isRootReplacement) return;- const rawUrl = cdpStringValue(frame?.url);- const destination = scopedUrl(rawUrl, this.allowedOrigins);+ const observation = observeCdpFrameUrl(frame);+ const rawUrl =+ observation.kind === "observed" ? observation.url : undefined;+ const destination = classifyCdpFrameUrl(observation, this.allowedOrigins);if (identity.isRootReplacement) {this.mainFrameId = identity.frameId ?? this.mainFrameId;this.#pendingReload = false;if (contextOnly) {+ if (observation.kind !== "observed") this.invalidateFinalUrl();this.#stopIfOutOfScope(destination);return;}}+this.#add({type:!identity.isRootReplacement && !contextOnly && this.#pendingReload@@ -411,13 +421,16 @@ class TimelineCapture {params: { ...params, frameId: frame?.id, loaderId: frame?.loaderId },timestamp: null,rawUrl: rawUrl ?? null,+ destinationScope:+ destination.scope === "unknown" ? null : destination.scope,requestId: null,detail: safeDetail(frame?.transitionType),});+ if (observation.kind !== "observed") this.invalidateFinalUrl();if (this.#stopIfOutOfScope(destination)) return;if (contextOnly) return;this.#pendingReload = false;- this.finalUrl = destination.url;+ this.finalUrl = destination.url ?? null;}#sameDocument(@@ -439,6 +452,7 @@ class TimelineCapture {requestId: null,detail: null,});+ if (!this.#hasObservedUrl(rawUrl)) return;if (this.#stopIfOutOfScope(destination)) return;if (contextOnly) return;this.finalUrl = destination.url;@@ -467,14 +481,27 @@ class TimelineCapture {requestId: cdpStringValue(params.requestId) ?? null,detail: null,});- if (this.#stopIfOutOfScope(destination)) return;+ if (!this.#hasObservedUrl(rawUrl)) return;+ this.#stopIfOutOfScope(destination);+ }++ invalidateFinalUrl(): void {+ this.completeness.exclude("timeline", "invalid_protocol_value");+ this.finalUrl = null;+ }++ /** Missing protocol identity cannot establish that the target left policy. */+ #hasObservedUrl(rawUrl: string | undefined): boolean {+ if (rawUrl !== undefined) return true;+ this.invalidateFinalUrl();+ return false;}#stopIfOutOfScope(destination: {- readonly url: string | null;- readonly scope: "approved" | "outside_policy" | "unsupported";+ readonly scope: "approved" | "outside_policy" | "unsupported" | "unknown";}): boolean {- if (destination.scope === "approved") return false;+ if (destination.scope === "approved" || destination.scope === "unknown")+ return false;this.excludeTargetScope("out_of_target_scope");this.end("target_left_scope");return true;@@ -572,7 +599,7 @@ class TimelineCapture {loader_id: boundedId(params.loaderId),request_id: requestId ?? null,url: destination?.scope === "approved" ? destination.url : null,- destination_scope: destination?.scope ?? null,+ destination_scope: options.destinationScope ?? destination?.scope ?? null,detail,});}@@ -651,18 +678,15 @@ const captureFinalUrl = async (context.signal,);if (capture.scopeExcluded) return "target_left_scope";- const url = mainFrameUrl(result);- if (- url !== undefined &&- allowedSanitizedUrl(url, allowedOrigins) !== undefined- ) {- capture.setFinalUrl(url);- return "window_elapsed";+ const observation = observeMainFrameUrl(result);+ const facts = classifyCdpFrameUrl(observation, allowedOrigins);+ if (observation.kind !== "observed") capture.invalidateFinalUrl();+ if (facts.scope === "outside_policy" || facts.scope === "unsupported") {+ capture.excludeTargetScope("out_of_target_scope");+ return "target_left_scope";}- capture.excludeTargetScope(- url === undefined ? "invalid_protocol_value" : "out_of_target_scope",- );- return "target_left_scope";+ if (facts.url !== undefined) capture.setFinalUrl(facts.url);+ return "window_elapsed";};const frameId = (result: unknown): string | undefined =>diff --git a/src/browser/CdpScreenshot.ts b/src/browser/CdpScreenshot.tsindex 172d06b05..0b9c6ff5f 100644--- a/src/browser/CdpScreenshot.ts+++ b/src/browser/CdpScreenshot.ts@@ -9,13 +9,17 @@ import { cdpFrameIdentity } from "./CdpCaptureEventHelpers.js";import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";import type { CdpConnection, CdpEvent } from "./CdpConnection.js";import {- allowedSanitizedUrl,recordValue,cdpStringValue,numberValue,} from "./CdpCaptureValues.js";-import { mainFrameUrl } from "./CdpCaptureDocuments.js";-import { captureFrames } from "./CdpCaptureDocuments.js";+import {+ observeCdpFrameUrl,+ observeMainFrameUrl,+ classifyCdpFrameUrl,+ captureFrames,+} from "./CdpCaptureDocuments.js";+import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";import { decodeCanonicalBase64 } from "../domain/webScreenshot.js";import { readPngHeaderDimensions } from "../domain/pngHeader.js";@@ -53,10 +57,22 @@ export const captureCdpScreenshot = async (context.sessionId,context.signal,);- const beforeUrl = mainFrameUrl(before);- const authorized = allowedSanitizedUrl(beforeUrl, origins);+ const beforeObservation = observeMainFrameUrl(before);+ const beforeFacts = classifyCdpFrameUrl(beforeObservation, origins);+ if (+ beforeFacts.scope === "outside_policy" ||+ beforeFacts.scope === "unsupported"+ )+ throw new BrowserObservationError("inspect_web_page", "target_not_allowed");+ if (beforeObservation.kind !== "observed")+ throw new BrowserObservationError("inspect_web_page", "protocol_error");+ const beforeUrl = beforeFacts.url;const mainFrame = captureFrames(before, origins, 1).items[0];- if (authorized === undefined || mainFrame === undefined)+ if (+ beforeUrl === undefined ||+ beforeFacts.origin === null ||+ mainFrame === undefined+ )throw new BrowserObservationError("inspect_web_page", "target_not_allowed");const initialFrame = recordValue(recordValue(recordValue(before)?.frameTree)?.frame,@@ -75,13 +91,13 @@ export const captureCdpScreenshot = async (observeScreenshotNavigation(event, origins, navigation);});const assertCurrentDocument = () => {- if (navigation.invalidIdentity)- throw new BrowserObservationError("inspect_web_page", "protocol_error");if (navigation.leftScope)throw new BrowserObservationError("inspect_web_page","target_not_allowed",);+ if (navigation.invalidIdentity)+ throw new BrowserObservationError("inspect_web_page", "protocol_error");if (navigation.changed)throw new BrowserObservationError("inspect_web_page", "target_changed");};@@ -123,11 +139,19 @@ export const captureCdpScreenshot = async (removeListener();}assertCurrentDocument();- const afterUrl = mainFrameUrl(after);+ if (navigation.leftScope)+ throw new BrowserObservationError("inspect_web_page", "target_not_allowed");+ const afterObservation = observeMainFrameUrl(after);+ const afterFacts = classifyCdpFrameUrl(afterObservation, origins);if (- afterUrl !== beforeUrl ||- allowedSanitizedUrl(afterUrl, origins) === undefined+ afterFacts.scope === "outside_policy" ||+ afterFacts.scope === "unsupported")+ throw new BrowserObservationError("inspect_web_page", "target_not_allowed");+ if (navigation.invalidIdentity || afterObservation.kind !== "observed")+ throw new BrowserObservationError("inspect_web_page", "protocol_error");+ const afterUrl = afterFacts.url;+ if (navigation.changed || afterUrl !== beforeUrl || afterUrl === undefined)throw new BrowserObservationError("inspect_web_page", "target_changed");await context.progress?.report({phase: "browser_observation",@@ -140,8 +164,8 @@ export const captureCdpScreenshot = async (browser: context.discovery.version,target: {target_id: context.target.id,- url: authorized.url,- origin: authorized.origin ?? "",+ url: beforeUrl,+ origin: beforeFacts.origin,},captured_at: new Date().toISOString(),viewport: screenshot.dimensions,@@ -319,27 +343,41 @@ const observeScreenshotNavigation = (if (identity.selection === "other" && !identity.isRootReplacement) return;const params = recordValue(event.params);if (params === undefined) return;+ // A requested navigation does not establish a committed document change.+ // The frame-tree read after capture still verifies the selected URL.+ if (event.method === "Page.frameRequestedNavigation") return;const frame =event.method === "Page.frameNavigated" ? recordValue(params.frame) : params;+ const observed = observeCdpFrameUrl(frame);+ const facts = classifyCdpFrameUrl(observed, origins);+ const frameUrl = facts.url;+ if (+ event.method === "Page.navigatedWithinDocument" &&+ state.loaderId !== undefined &&+ state.loaderId !== "" &&+ frameUrl === state.url+ )+ return;if (event.method === "Page.frameNavigated" &&!identity.isRootReplacement &&state.loaderId !== undefined &&state.loaderId !== "" &&cdpStringValue(frame?.loaderId) === state.loaderId &&- cdpStringValue(frame?.url) === state.url+ frameUrl === state.url)return;state.changed = true;- if (allowedSanitizedUrl(frame?.url, origins) === undefined)+ if (facts.scope === "outside_policy" || facts.scope === "unsupported")state.leftScope = true;+ if (observed.kind !== "observed") state.invalidIdentity = true;if (event.method === "Page.frameNavigated") {if (identity.isRootReplacement)state.frameId = identity.frameId ?? state.frameId;- state.url = cdpStringValue(frame?.url) ?? state.url;+ state.url = frameUrl ?? state.url;state.loaderId = cdpStringValue(frame?.loaderId);} else if (event.method === "Page.navigatedWithinDocument") {- state.url = cdpStringValue(frame?.url) ?? state.url;+ state.url = frameUrl ?? state.url;}};diff --git a/src/browser/CdpWebMcpDiscovery.ts b/src/browser/CdpWebMcpDiscovery.tsindex 713b207e1..61003bbbc 100644--- a/src/browser/CdpWebMcpDiscovery.ts+++ b/src/browser/CdpWebMcpDiscovery.ts@@ -24,8 +24,10 @@ import {type UnknownRecord,} from "./CdpCaptureValues.js";import {- captureFrames,+ classifyCdpFrameUrl,+ observeCdpFrameUrl,mainFrameUrl,+ observeMainFrameUrl,walkFrameTrees,} from "./CdpCaptureDocuments.js";import { optionalCdpCommand } from "./CdpOptionalCommand.js";@@ -63,16 +65,8 @@ export const discoverWebMcp = async (context.sessionId,context.signal,);- const initialUrl = mainFrameUrl(frameTree);- if (allowedSanitizedUrl(initialUrl, origins) === undefined)- throw new BrowserObservationError("inspect_web_page", "target_not_allowed");- const frames = captureFrames(- frameTree,- origins,- undefined,- completeness,- ).items;- const frameUrls = initialFrameScope(frameTree, frames, completeness);+ const initialUrl = requiredDiscoveryFrameUrl(frameTree, origins);+ const frameUrls = new Map<string, FrameScopeFrame>();const tools = new Map<string, WebMcpDiscovery["tools"]["items"][number]>();const frameScope = {origins,@@ -82,6 +76,7 @@ export const discoverWebMcp = async (transientFrames: new Set<string>(),resolvedTransientFrames: new Set<string>(),};+ ingestInitialFrameTree(frameTree, frameScope);const removeListener = context.connection.onEvent((event) => {if (event.sessionId !== context.sessionId) return;if (ingestFrameScopeEvent(event, frameScope)) return;@@ -157,36 +152,32 @@ interface FrameScopeFrame {readonly loaderId?: string | undefined;}-const initialFrameScope = (+const ingestInitialFrameTree = (frameTree: unknown,- frames: ReturnType<typeof captureFrames>["items"],- completeness: CdpCaptureCompleteness,-): Map<string, FrameScopeFrame> => {- const scoped = new Map<string, FrameScopeFrame>(- frames.map((frame) => [- frame.frame_id,- {- url: frame.url,- origin: frame.origin,- parentFrameId: frame.parent_frame_id,- },- ]),- );+ state: FrameScopeState,+): void => {const root = recordValue(recordValue(frameTree)?.frameTree);- if (root === undefined) return scoped;- for (const tree of walkFrameTrees(root, () =>- completeness.exclude("webmcp_tools", "invalid_protocol_value"),+ if (root === undefined) {+ state.completeness.exclude("webmcp_tools", "invalid_protocol_value");+ return;+ }+ for (const tree of walkFrameTrees(root, (omittedCount) =>+ state.completeness.exclude(+ "webmcp_tools",+ "invalid_protocol_value",+ omittedCount,+ ),)) {const frame = recordValue(tree.frame);- const frameId = cdpStringValue(frame?.id);- const prior = frameId === undefined ? undefined : scoped.get(frameId);- if (frameId !== undefined && prior !== undefined)- scoped.set(frameId, {- ...prior,- loaderId: cdpStringValue(frame?.loaderId),- });+ const parent = cdpStringValue(frame?.parentId);+ if (+ frame !== undefined &&+ (tree !== root || Object.hasOwn(frame, "parentId")) &&+ (parent === undefined || parent === "")+ )+ state.completeness.exclude("webmcp_tools", "invalid_protocol_value");+ handleFrameUpdate(frame, state, true);}- return scoped;};const ingestFrameScopeEvent = (@@ -236,12 +227,24 @@ const handleFrameUpdate = (state.completeness.exclude("webmcp_tools", "invalid_protocol_value");return true;}- const rawUrl = cdpStringValue(frame?.url);+ const observation = observeCdpFrameUrl(frame);+ const facts = classifyCdpFrameUrl(observation, state.origins);+ if (observation.kind !== "observed") {+ removeFrameTools(frameId, state.tools);+ state.frames.delete(frameId);+ state.resolvedTransientFrames.delete(frameId);+ state.completeness.exclude("webmcp_tools", "invalid_protocol_value");+ if (facts.scope === "outside_policy") {+ state.transientFrames.delete(frameId);+ state.completeness.exclude("webmcp_tools", "out_of_target_scope");+ } else state.transientFrames.add(frameId);+ return true;+ }// Chromium can briefly commit an inherited, empty document while replacing// a subframe. That intermediate URL says nothing about the frame's eventual- // scope or its registered tools; wait for the next committed URL (or the- // authoritative frame-tree re-probe at the end of discovery).- if (isTransientFrameUrl(rawUrl)) {+ // scope or its registered tools; wait for a committed URL and fresh replay.+ // Without those observations, discovery remains attach-limited.+ if (isTransientFrameUrl(observation.scopeUrl)) {if (documentCommitted) {removeFrameTools(frameId, state.tools);state.transientFrames.add(frameId);@@ -249,32 +252,34 @@ const handleFrameUpdate = (}return true;}- updateFrameScope(frame, frameId, state, documentCommitted);+ updateFrameScope(frame, frameId, facts, state, documentCommitted);return true;};const updateFrameScope = (frame: UnknownRecord,frameId: string,+ facts: ReturnType<typeof classifyCdpFrameUrl>,state: FrameScopeState,documentCommitted: boolean,): void => {- const url = allowedSanitizedUrl(frame?.url, state.origins);- if (url === undefined || url.origin === null) {+ if (facts.url === undefined || facts.origin === null) {removeFrameTools(frameId, state.tools);state.frames.delete(frameId);+ state.transientFrames.delete(frameId);+ state.resolvedTransientFrames.delete(frameId);state.completeness.exclude("webmcp_tools", "out_of_target_scope");return;}const previous = state.frames.get(frameId);const loaderId = cdpStringValue(frame?.loaderId);- if (hasNewDocument(documentCommitted, previous, url.url, loaderId))+ if (hasNewDocument(documentCommitted, previous, facts.url, loaderId))removeFrameTools(frameId, state.tools);if (documentCommitted && state.transientFrames.has(frameId))state.resolvedTransientFrames.add(frameId);state.frames.set(frameId, {- url: url.url,- origin: url.origin,+ url: facts.url,+ origin: facts.origin,...(loaderId === undefined ? {} : { loaderId }),parentFrameId:(cdpStringValue(frame?.parentId) ??@@ -305,8 +310,20 @@ const removeFrameTools = (if (tool.frame_id === frameId) tools.delete(key);};-const isTransientFrameUrl = (url: string | undefined): boolean =>- url === "" || url === "about:blank" || url === "about:srcdoc";+const isTransientFrameUrl = (url: string): boolean => {+ if (url === "") return true;+ try {+ const base = new URL(url);+ return (+ base.protocol === "about:" &&+ base.search === "" &&+ (base.pathname === "blank" || base.pathname === "srcdoc")+ );+ } catch (cause: unknown) {+ void cause;+ return false;+ }+};const removeFrame = (frameId: string,@@ -338,13 +355,26 @@ const assertStableAuthorizedFrame = async (context.sessionId,context.signal,);- const finalUrl = mainFrameUrl(finalTree);- if (allowedSanitizedUrl(finalUrl, origins) === undefined)- throw new BrowserObservationError("inspect_web_page", "target_not_allowed");+ const finalUrl = requiredDiscoveryFrameUrl(finalTree, origins);if (finalUrl !== initialUrl)throw new BrowserObservationError("inspect_web_page", "target_changed");};+const requiredDiscoveryFrameUrl = (+ result: unknown,+ origins: ReadonlySet<string>,+): string => {+ const observed = observeMainFrameUrl(result);+ const facts = classifyCdpFrameUrl(observed, origins);+ if (facts.scope === "outside_policy" || facts.scope === "unsupported")+ throw new BrowserObservationError("inspect_web_page", "target_not_allowed");+ if (observed.kind !== "observed")+ throw new BrowserObservationError("inspect_web_page", "protocol_error");+ if (facts.url === undefined)+ throw new BrowserObservationError("inspect_web_page", "target_not_allowed");+ return observed.url;+};+interface WebMcpIngestOptions {readonly event: CdpEvent;readonly input: DiscoverWebMcpToolsInput;diff --git a/src/browser/execution/CdpRuntimeProtocol.ts b/src/browser/execution/CdpRuntimeProtocol.tsindex 051d0200a..96317bc2a 100644--- a/src/browser/execution/CdpRuntimeProtocol.ts+++ b/src/browser/execution/CdpRuntimeProtocol.ts@@ -103,12 +103,11 @@ export const runtimeListenersSchema = z.object({}),),});-/** Current main frame identity protects same-URL reloads as well as URL changes. */+/** Runtime document IDs; frame URLs are interpreted by CdpCaptureDocuments. */export const runtimeFrameTreeSchema = z.object({frameTree: z.object({frame: z.object({id: z.string().min(1),- url: z.string(),loaderId: z.string().optional(),}),}),diff --git a/src/browser/execution/CdpRuntimeSession.ts b/src/browser/execution/CdpRuntimeSession.tsindex d64cdc884..09aa131e3 100644--- a/src/browser/execution/CdpRuntimeSession.ts+++ b/src/browser/execution/CdpRuntimeSession.ts@@ -11,7 +11,10 @@ import {selectedCdpCommandTimeoutMs,} from "../../domain/browserDeadline.js";import { CdpTargetSessionOwner } from "../CdpTargetSessionOwner.js";-import { sanitizeBrowserUrl } from "../../domain/browserObservation.js";+import {+ classifyCdpFrameUrl,+ observeMainFrameUrl,+} from "../CdpCaptureDocuments.js";import {WEB_RUNTIME_LIMITS,type webRuntimeTargetSchema,@@ -88,7 +91,7 @@ export class CdpRuntimeSession {owner,);try {- const tree = runtimeFrameTreeSchema.parse(+ const frame = runtimeMainFrame(await runtimeDeadline(operation,options.signal,@@ -103,11 +106,9 @@ export class CdpRuntimeSession {"command","Page.getFrameTree",),+ allowedOrigins,);- const frame = tree.frameTree.frame;- const url = sanitizeBrowserUrl(frame.url);- if (url.origin === null)- throw new BrowserObservationError(operation, "target_not_allowed");+ const url = runtimeFrameUrl(frame, operation);return new CdpRuntimeSession(transport,discovery,@@ -200,22 +201,26 @@ export class CdpRuntimeSession {/** Check document identity before joining any live node or final coverage evidence. */async assertDocument(): Promise<void> {- const frame = runtimeFrameTreeSchema.parse(+ const frame = runtimeMainFrame(await this.command("Page.getFrameTree"),- ).frameTree.frame;- const url = sanitizeBrowserUrl(frame.url);+ this.allowedOrigins,+ );if (frame.id !== this.target.frame_id ||(frame.loaderId ?? null) !== this.target.loader_id ||- (this.target.loader_id === null && url.url !== this.target.initial_url)+ (this.target.loader_id === null &&+ ((frame.url !== undefined && frame.url !== this.target.initial_url) ||+ frame.scope === "outside_policy" ||+ frame.scope === "unsupported")))throw new BrowserObservationError(this.operation, "target_changed", {detail: `Selected target ${this.target.target_id} changed document during ${this.operation}.`,});- if (url.origin === null || !this.allowedOrigins.has(url.origin))- throw new BrowserObservationError(this.operation, "target_not_allowed", {- detail: `Selected target ${this.target.target_id} moved to an unselected origin during ${this.operation}.`,- });+ runtimeFrameUrl(+ frame,+ this.operation,+ `Selected target ${this.target.target_id} moved to an unselected origin during ${this.operation}.`,+ );}/** Cleanup uses its own deadline after caller cancellation, then closes REA's transport. */@@ -319,6 +324,31 @@ export class CdpRuntimeSession {}}+/** Runtime validates document IDs; CDP owns URL and scope interpretation. */+const runtimeMainFrame = (+ result: unknown,+ allowedOrigins: ReadonlySet<string>,+) => ({+ ...runtimeFrameTreeSchema.parse(result).frameTree.frame,+ ...classifyCdpFrameUrl(observeMainFrameUrl(result), allowedOrigins),+});++const runtimeFrameUrl = (+ frame: ReturnType<typeof runtimeMainFrame>,+ operation: BrowserObservationOperation,+ detail?: string,+) => {+ if (frame.scope === "outside_policy" || frame.scope === "unsupported")+ throw new BrowserObservationError(+ operation,+ "target_not_allowed",+ detail === undefined ? {} : { detail },+ );+ if (frame.url === undefined || frame.origin === null)+ throw new BrowserObservationError(operation, "protocol_error");+ return { url: frame.url, origin: frame.origin };+};+/** Apply a disposable command deadline without turning timeout into caller cancellation. */export const runtimeDeadline = async <T>(operation: BrowserObservationOperation,diff --git a/tests/boundary/browser/cdpAuthorizedMainFrameRetry.test.ts b/tests/boundary/browser/cdpAuthorizedMainFrameRetry.test.tsnew file mode 100644index 000000000..afa7057c0--- /dev/null+++ b/tests/boundary/browser/cdpAuthorizedMainFrameRetry.test.ts@@ -0,0 +1,204 @@+import { expect, it } from "vitest";+import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";+import { CdpWebRuntimeProvider } from "../../../src/browser/execution/CdpWebRuntimeProvider.js";+import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";+import { observeWebSessionInputSchema } from "../../../src/domain/browserSession.js";+import { observeWebExecutionInputSchema } from "../../../src/domain/webExecution.js";+import { startRuntimeBrowser } from "../../fixtures/webRuntime.js";+import type { FakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";+import { trackBrowser } from "./cdpBrowserProvider.support.js";++const operations = ["inspect", "session", "runtime"] as const;+type Operation = (typeof operations)[number];+const run = async (+ browser: FakeCdpBrowser,+ operation: Operation,+ signal?: AbortSignal,+) => {+ const input = {+ cdp_endpoint: browser.endpoint,+ target_id: "allowed-page",+ allowed_origins: [browser.allowedOrigin],+ observation_ms: 1,+ };+ const options = signal === undefined ? {} : { signal };+ switch (operation) {+ case "inspect":+ return new CdpBrowserProvider().inspectPage(+ inspectWebPageInputSchema.parse(input),+ options,+ );+ case "session":+ return new CdpBrowserProvider().observeSession(+ observeWebSessionInputSchema.parse(input),+ options,+ );+ case "runtime":+ return new CdpWebRuntimeProvider().observeExecution(+ observeWebExecutionInputSchema.parse(input),+ options,+ );+ }+};++it.each(+ operations.flatMap((operation) =>+ ["about:blank", "about:srcdoc", "file:///local.html", "not a URL"].flatMap(+ (url) =>+ [7, "bad-fragment"].map((urlFragment) => ({+ operation,+ url,+ urlFragment,+ })),+ ),+ ),+)(+ "retries uncertain initial $url/$urlFragment before $operation authorizes",+ async ({ operation, url, urlFragment }) => {+ let reads = 0;+ const browser = await startRuntimeBrowser({+ commandResult: ({ method }) => {+ if (method !== "Page.getFrameTree" || ++reads > 2) return undefined;+ return {+ frameTree: { frame: { id: "runtime-main", url, urlFragment } },+ };+ },+ });+ trackBrowser(browser);+ const result = await run(browser, operation);+ expect(result.ok).toBe(true);+ expect(reads).toBeGreaterThan(2);+ },+);++it.each(+ operations.flatMap((operation) =>+ [false, true].flatMap((foreign) =>+ [7, "bad-fragment"].map((urlFragment) => ({+ operation,+ foreign,+ urlFragment,+ })),+ ),+ ),+)(+ "rejects known $foreign scope with malformed $urlFragment immediately for $operation",+ async ({ operation, foreign, urlFragment }) => {+ let reads = 0;+ const browser = await startRuntimeBrowser({+ commandResult: ({ method }, origin) => {+ if (method !== "Page.getFrameTree") return undefined;+ reads += 1;+ return {+ frameTree: {+ frame: {+ id: "runtime-main",+ url: foreign ? "https://foreign.example/page" : `${origin}/app`,+ urlFragment,+ },+ },+ };+ },+ });+ trackBrowser(browser);+ expect(await run(browser, operation)).toMatchObject({+ ok: false,+ error: { reason: foreign ? "target_not_allowed" : "protocol_error" },+ });+ expect(reads).toBe(1);+ },+);++it("bounds unsupported malformed frame retries without authorizing execution", async () => {+ let reads = 0;+ const browser = await startRuntimeBrowser({+ commandResult: ({ method }) => {+ if (method !== "Page.getFrameTree") return undefined;+ reads += 1;+ return {+ frameTree: {+ frame: { id: "runtime-main", url: "about:blank", urlFragment: 7 },+ },+ };+ },+ });+ trackBrowser(browser);+ expect(await run(browser, "runtime")).toMatchObject({+ ok: false,+ error: { reason: "target_not_allowed" },+ });+ expect(reads).toBe(80);+ expect(browser.commands.map(({ method }) => method)).not.toContain(+ "Debugger.enable",+ );+});++it("preserves cancellation while an unsupported malformed frame awaits authorization", async () => {+ const controller = new AbortController();+ const browser = await startRuntimeBrowser({+ commandResult: ({ method }) => {+ if (method !== "Page.getFrameTree") return undefined;+ setTimeout(() => controller.abort("caller stopped authorization"), 5);+ return {+ frameTree: {+ frame: { id: "runtime-main", url: "about:blank", urlFragment: 7 },+ },+ };+ },+ });+ trackBrowser(browser);+ expect(await run(browser, "inspect", controller.signal)).toMatchObject({+ ok: false,+ error: {+ _tag: "AnalysisCancelledError",+ cause: "caller stopped authorization",+ },+ });+ expect(+ browser.commands.filter(({ method }) => method === "Page.getFrameTree"),+ ).toHaveLength(1);+});++// Ordinary startup uncertainty and known policy exits keep their existing semantics.+it.each(+ operations.flatMap((operation) =>+ ["unsupported", "missing", "foreign"].map((kind) => ({ operation, kind })),+ ),+)(+ "preserves $kind authorization behavior for $operation",+ async ({ operation, kind }) => {+ let reads = 0;+ const browser = await startRuntimeBrowser({+ commandResult: ({ method }) => {+ if (method !== "Page.getFrameTree" || ++reads > 2) return undefined;+ return {+ frameTree: {+ frame: {+ id: "runtime-main",+ ...(kind === "missing"+ ? {}+ : {+ url:+ kind === "foreign"+ ? "https://foreign.example/page"+ : "about:blank",+ }),+ },+ },+ };+ },+ });+ trackBrowser(browser);+ const result = await run(browser, operation);+ if (kind === "foreign") {+ expect(result).toMatchObject({+ ok: false,+ error: { reason: "target_not_allowed" },+ });+ expect(reads).toBe(1);+ } else {+ expect(result.ok).toBe(true);+ expect(reads).toBeGreaterThan(2);+ }+ },+);diff --git a/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts b/tests/boundary/browser/cdpBrowserProvider.document_script.test.tsindex 812787987..07c867c9d 100644--- a/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts+++ b/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts@@ -10,9 +10,59 @@ import { inspectWebPageInputSchema } from "../../../src/domain/browserObservatioimport { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js";import { discoverWebMcpToolsInputSchema } from "../../../src/domain/webMcpDiscovery.js";import { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js";+import { observeWebSessionInputSchema } from "../../../src/domain/browserSession.js";import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";import { trackBrowser } from "./cdpBrowserProvider.support.js";+it("preserves CDP's separate frame fragment in all passive URL projections", async () => {+ const browser = await startFakeCdpBrowser({+ commandResult: ({ method }, origin) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: {+ id: "frame-main",+ loaderId: "loader-main",+ url: `${origin}/app?token=frame-secret`,+ urlFragment: "#details",+ },+ },+ }+ : undefined,+ });+ trackBrowser(browser);+ const provider = new CdpBrowserProvider();+ const input = {+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 0,+ };+ const inspected = await provider.inspectPage(+ inspectWebPageInputSchema.parse(input),+ );+ const screenshot = await provider.captureScreenshot(+ captureWebScreenshotInputSchema.parse({+ cdp_endpoint: input.cdp_endpoint,+ allowed_origins: input.allowed_origins,+ target_id: input.target_id,+ }),+ );+ const observed = await provider.observeSession(+ observeWebSessionInputSchema.parse({ ...input, observation_ms: 1 }),+ );+ if (!inspected.ok) throw inspected.error;+ if (!screenshot.ok) throw screenshot.error;+ if (!observed.ok) throw observed.error;+ const url = `${browser.allowedOrigin}/app?token=frame-secret#details`;+ expect(inspected.value.target.url).toBe(url);+ expect(inspected.value.frames[0]?.url).toBe(url);+ expect(screenshot.value.target.url).toBe(url);+ expect(observed.value.target).toMatchObject({+ initial_url: url,+ final_url: url,+ });+});describe("CdpBrowserProvider: approved accessibility and source capture", () => {it("captures approved accessibility text inline", async () => {const browser = await startFakeCdpBrowser();@@ -170,6 +220,285 @@ describe("CdpBrowserProvider: approved accessibility and source capture", () =>});});+it.each(["after-replay", "before-replay", "replacement", "malformed"])(+ "keeps split-fragment WebMCP frame identity: %s",+ async (kind) => {+ const browser = await startFakeCdpBrowser({+ eventsBeforeReply: ["WebMCP.enable"],+ commandResult: ({ method }, origin) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: {+ id: "frame-main",+ loaderId: "loader-main",+ url: `${origin}/app`,+ urlFragment: "#details",+ },+ },+ }+ : undefined,+ commandEvents: ({ method, sessionId }, origin) => {+ if (method !== "WebMCP.enable") return undefined;+ const frame = {+ method: "Page.frameNavigated",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ frame: {+ id: "frame-main",+ loaderId: kind === "replacement" ? "new-loader" : "loader-main",+ url: `${origin}/app`,+ urlFragment: kind === "malformed" ? 7 : "#details",+ },+ },+ };+ const tools = {+ method: "WebMCP.toolsAdded",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ tools: [+ {+ name: "catalog",+ description: "fixture",+ frameId: "frame-main",+ },+ ],+ },+ };+ return kind === "before-replay"+ ? [frame, tools]+ : kind === "malformed"+ ? [tools, frame, tools]+ : [tools, frame];+ },+ });+ trackBrowser(browser);+ const result = await new CdpBrowserProvider().discoverWebMcpTools(+ discoverWebMcpToolsInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 0,+ }),+ );+ if (!result.ok) throw result.error;+ if (kind === "replacement" || kind === "malformed")+ expect(result.value.tools.items).toEqual([]);+ else+ expect(result.value.tools.items).toEqual([+ expect.objectContaining({+ name: "catalog",+ frame_url: `${browser.allowedOrigin}/app#details`,+ }),+ ]);+ if (kind === "malformed")+ expect(result.value.completeness).toMatchObject({+ unavailable_sections: expect.arrayContaining(["webmcp_tools"]),+ policy_filtered_sections: [],+ });+ },+);++it.each(+ ["foreign", "allowed", "missing", "opaque", "unparseable"].flatMap((scope) =>+ [false, true].flatMap((blankFirst) =>+ [7, "not-a-fragment"].map((fragment) => ({+ scope,+ blankFirst,+ fragment,+ })),+ ),+ ),+)(+ "retains malformed WebMCP event scope: $scope/$blankFirst/$fragment",+ async ({ scope, blankFirst, fragment }) => {+ const browser = await startFakeCdpBrowser({+ eventsBeforeReply: ["WebMCP.enable"],+ commandResult: ({ method }, origin) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: { id: "frame-main", url: `${origin}/app` },+ childFrames: [+ {+ frame: {+ id: "child",+ parentId: "frame-main",+ url: `${origin}/child`,+ },+ },+ ],+ },+ }+ : undefined,+ commandEvents: ({ method, sessionId }, origin) => {+ if (method !== "WebMCP.enable") return undefined;+ const navigation = (frame: Record<string, unknown>) => ({+ method: "Page.frameNavigated",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: { frame: { id: "child", parentId: "frame-main", ...frame } },+ });+ return [+ {+ method: "WebMCP.toolsAdded",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ tools: [{ name: "stale", inputSchema: {}, frameId: "child" }],+ },+ },+ ...(blankFirst ? [navigation({ url: "about:blank" })] : []),+ navigation({+ ...(scope === "missing"+ ? {}+ : {+ url:+ scope === "foreign"+ ? "https://foreign.invalid/child"+ : scope === "opaque"+ ? "about:blank"+ : scope === "unparseable"+ ? "not-a-url"+ : `${origin}/child`,+ }),+ urlFragment: fragment,+ }),+ ];+ },+ });+ trackBrowser(browser);+ const result = await new CdpBrowserProvider().discoverWebMcpTools(+ discoverWebMcpToolsInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 0,+ }),+ );+ if (!result.ok) throw result.error;+ expect(result.value.tools.items).toEqual([]);+ expect(result.value.completeness.excluded).toContainEqual({+ section: "webmcp_tools",+ reason: "invalid_protocol_value",+ count: 1,+ });+ expect(+ result.value.completeness.attach_limited_sections.includes(+ "webmcp_tools",+ ),+ ).toBe(scope !== "foreign");+ expect(+ result.value.completeness.policy_filtered_sections.includes(+ "webmcp_tools",+ ),+ ).toBe(scope === "foreign");+ if (scope === "foreign")+ expect(result.value.completeness.excluded).toContainEqual({+ section: "webmcp_tools",+ reason: "out_of_target_scope",+ count: 1,+ });+ },+);++it.each(+ ["allowed", "foreign", "missing", "opaque", "unparseable"].flatMap((scope) =>+ (scope === "opaque" || scope === "unparseable"+ ? [7, "bad-fragment"]+ : [7, "bad-fragment", "#valid"]+ ).map((fragment) => ({ scope, fragment })),+ ),+)(+ "preserves initial child scope through WebMCP replay: $scope/$fragment",+ async ({ scope, fragment }) => {+ const browser = await startFakeCdpBrowser({+ eventsBeforeReply: ["WebMCP.enable"],+ commandResult: ({ method }, origin) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: { id: "frame-main", url: `${origin}/app` },+ childFrames: [+ {+ frame: {+ id: "child",+ parentId: "frame-main",+ ...(scope === "missing"+ ? {}+ : {+ url:+ scope === "foreign"+ ? "https://foreign.test/child"+ : scope === "opaque"+ ? "about:blank"+ : scope === "unparseable"+ ? "not-a-url"+ : `${origin}/child`,+ }),+ urlFragment: fragment,+ },+ },+ ],+ },+ }+ : undefined,+ commandEvents: ({ method, sessionId }) =>+ method === "WebMCP.enable"+ ? [+ {+ method: "WebMCP.toolsAdded",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ tools: [+ { name: "child_tool", inputSchema: {}, frameId: "child" },+ ],+ },+ },+ ]+ : undefined,+ });+ trackBrowser(browser);+ const result = await new CdpBrowserProvider().discoverWebMcpTools(+ discoverWebMcpToolsInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 0,+ }),+ );+ if (!result.ok) throw result.error;+ const valid = scope === "allowed" && fragment === "#valid";+ expect(result.value.tools.items.map(({ name }) => name)).toEqual(+ valid ? ["child_tool"] : [],+ );+ if (valid)+ expect(result.value.tools.items[0]?.frame_url).toBe(+ `${browser.allowedOrigin}/child#valid`,+ );+ const uncertain =+ scope === "missing" ||+ scope === "opaque" ||+ scope === "unparseable" ||+ (scope === "allowed" && !valid);+ expect(+ result.value.completeness.attach_limited_sections.includes(+ "webmcp_tools",+ ),+ ).toBe(uncertain);+ expect(+ result.value.completeness.policy_filtered_sections.includes(+ "webmcp_tools",+ ),+ ).toBe(scope === "foreign");+ if (uncertain || fragment !== "#valid")+ expect(result.value.completeness.excluded).toContainEqual(+ expect.objectContaining({+ section: "webmcp_tools",+ reason: "invalid_protocol_value",+ }),+ );+ },+);+describe("CdpBrowserProvider: transient WebMCP frames", () => {it("drops stale child tools and reports partial coverage when a blank commit remains", async () => {const browser = await startFakeCdpBrowser({@@ -247,11 +576,11 @@ describe("CdpBrowserProvider: transient WebMCP frames", () => {expect(result.value.tools.items.map(({ name }) => name)).not.toContain("child_tool",);- expect(- result.value.completeness.excluded.find(- ({ section }) => section === "webmcp_tools",- )?.count,- ).toBe(1);+ // The initial foreign frame and the excluded foreign replay declaration+ // are separate observed exclusions; replacing an allowed child adds none.+ expect(result.value.completeness.excluded).toEqual([+ { section: "webmcp_tools", reason: "out_of_target_scope", count: 2 },+ ]);});});@@ -806,3 +1135,78 @@ describe("CdpBrowserProvider: WebMCP registration owners", () => {},);});++it.each(["initial", "final"])(+ "reports malformed WebMCP %s frame identity as protocol uncertainty",+ async (phase) => {+ const browser = await startFakeCdpBrowser({+ commandResult: ({ method }, origin, reads) =>+ method === "Page.getFrameTree" && (phase === "initial" || reads > 1)+ ? {+ frameTree: {+ frame: {+ id: "frame-main",+ loaderId: "loader-main",+ url: `${origin}/app`,+ urlFragment: 7,+ },+ },+ }+ : undefined,+ });+ trackBrowser(browser);+ const result = await new CdpBrowserProvider().discoverWebMcpTools(+ discoverWebMcpToolsInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 0,+ }),+ );+ expect(result).toMatchObject({+ ok: false,+ error: { reason: "protocol_error" },+ });+ },+);++it.each([undefined, 7, ""])(+ "retains initial child ancestry uncertainty: %s",+ async (parentId) => {+ const browser = await startFakeCdpBrowser({+ commandResult: ({ method }, origin) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: { id: "frame-main", url: `${origin}/app` },+ childFrames: [+ {+ frame: {+ id: "child",+ url: `${origin}/child`,+ ...(parentId === undefined ? {} : { parentId }),+ },+ },+ ],+ },+ }+ : undefined,+ });+ trackBrowser(browser);+ const result = await new CdpBrowserProvider().discoverWebMcpTools(+ discoverWebMcpToolsInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 0,+ }),+ );+ if (!result.ok) throw result.error;+ expect(result.value.completeness.excluded).toContainEqual({+ section: "webmcp_tools",+ reason: "invalid_protocol_value",+ count: 1,+ });+ expect(result.value.completeness.policy_filtered_sections).toEqual([]);+ },+);diff --git a/tests/boundary/browser/cdpBrowserProvider.timelineEvents.test.ts b/tests/boundary/browser/cdpBrowserProvider.timelineEvents.test.tsindex 89f4c7732..f160a50de 100644--- a/tests/boundary/browser/cdpBrowserProvider.timelineEvents.test.ts+++ b/tests/boundary/browser/cdpBrowserProvider.timelineEvents.test.ts@@ -123,7 +123,305 @@ it("preserves cancellation at the armed handshake without starting a window timeawait provider.close();});+it.each([+ "malformed-event",+ "missing-same-document",+ "missing-redirect",+ "foreign-event",+ "malformed-final",+ "normal",+])("distinguishes protocol uncertainty in committed URLs: %s", async (kind) => {+ const browser = await startFakeCdpBrowser({+ eventsBeforeReply: ["Page.setLifecycleEventsEnabled"],+ commandResult: ({ method }, origin, reads) =>+ method === "Page.getFrameTree" && kind === "malformed-final" && reads > 1+ ? {+ frameTree: {+ frame: {+ id: "frame-main",+ url: `${origin}/app`,+ urlFragment: 7,+ },+ },+ }+ : undefined,+ commandEvents: ({ method, sessionId }, origin) => {+ if (method !== "Page.setLifecycleEventsEnabled") return undefined;+ const scope = sessionId === undefined ? {} : { sessionId };+ if (kind === "missing-same-document")+ return [+ {+ method: "Page.navigatedWithinDocument",+ ...scope,+ params: { frameId: "frame-main" },+ },+ ];+ if (kind === "missing-redirect")+ return [+ {+ method: "Network.requestWillBeSent",+ ...scope,+ params: {+ frameId: "frame-main",+ requestId: "redirect",+ type: "Document",+ redirectResponse: { status: 302 },+ request: {},+ },+ },+ ];+ return method === "Page.setLifecycleEventsEnabled"+ ? [+ {+ method: "Page.frameNavigated",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ frame: {+ id: "frame-main",+ loaderId: "loader-main",+ url:+ kind === "foreign-event"+ ? "https://foreign.test/"+ : `${origin}/app`,+ ...(kind === "malformed-event" ? { urlFragment: 7 } : {}),+ },+ },+ },+ ]+ : undefined;+ },+ });+ trackBrowser(browser);+ const result = await new CdpBrowserProvider().observeSession(+ observeWebSessionInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 1,+ }),+ );+ if (!result.ok) throw result.error;+ if (+ kind === "malformed-event" ||+ kind.startsWith("missing-") ||+ kind === "malformed-final"+ ) {+ expect(result.value.completeness.excluded).toContainEqual({+ section: "timeline",+ reason: "invalid_protocol_value",+ count: 1,+ });+ expect(result.value.completeness.policy_filtered_sections).toEqual([]);+ }+ if (kind === "malformed-final")+ expect(result.value.target.final_url).toBeNull();+ if (+ kind === "malformed-event" ||+ kind === "malformed-final" ||+ kind.startsWith("missing-")+ )+ expect(result.value.window.end_reason).toBe("window_elapsed");+ if (kind === "foreign-event")+ expect(result.value.completeness.excluded).toContainEqual({+ section: "timeline",+ reason: "out_of_target_scope",+ count: 1,+ });+ if (kind === "normal")+ expect(result.value.window.end_reason).toBe("window_elapsed");+});+it.each(+ [false, true].flatMap((foreign) =>+ [7, "bad-fragment"].map((urlFragment) => ({ foreign, urlFragment })),+ ),+)(+ "retains malformed committed identity and known scope: $foreign/$urlFragment",+ async ({ foreign, urlFragment }) => {+ const browser = await startFakeCdpBrowser({+ eventsBeforeReply: ["Page.setLifecycleEventsEnabled"],+ commandEvents: ({ method, sessionId }, origin) =>+ method === "Page.setLifecycleEventsEnabled"+ ? [+ {+ method: "Page.frameNavigated",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ frame: {+ id: "frame-main",+ url: foreign ? "https://foreign.test/" : `${origin}/app`,+ urlFragment,+ },+ },+ },+ ]+ : undefined,+ });+ trackBrowser(browser);+ const result = await new CdpBrowserProvider().observeSession(+ observeWebSessionInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 1,+ }),+ );+ if (!result.ok) throw result.error;+ expect(result.value.completeness.excluded).toContainEqual({+ section: "timeline",+ reason: "invalid_protocol_value",+ count: 1,+ });+ expect(+ result.value.timeline.find(({ type }) => type === "navigation_committed"),+ ).toMatchObject({+ url: null,+ destination_scope: foreign ? "outside_policy" : "approved",+ });+ expect(result.value.window.end_reason).toBe(+ foreign ? "target_left_scope" : "window_elapsed",+ );+ if (foreign) {+ expect(result.value.target.final_url).toBeNull();+ expect(result.value.completeness.excluded).toContainEqual({+ section: "timeline",+ reason: "out_of_target_scope",+ count: 1,+ });+ } else+ expect(result.value.completeness.policy_filtered_sections).toEqual([]);+ },+);++it.each(+ [7, "bad-fragment"].flatMap((fragment) =>+ ["allowed", "foreign", "missing"].map((scope) => ({ fragment, scope })),+ ),+)(+ "retains final-probe identity and scope without an event: $scope/$fragment",+ async ({ fragment, scope }) => {+ const browser = await startFakeCdpBrowser({+ commandResult: ({ method }, origin, reads) =>+ method === "Page.getFrameTree" && reads > 1+ ? {+ frameTree: {+ frame: {+ id: "frame-main",+ ...(scope === "missing"+ ? {}+ : {+ url:+ scope === "foreign"+ ? "https://foreign.test/"+ : `${origin}/app`,+ }),+ urlFragment: fragment,+ },+ },+ }+ : undefined,+ });+ trackBrowser(browser);+ const result = await new CdpBrowserProvider().observeSession(+ observeWebSessionInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 1,+ }),+ );+ if (!result.ok) throw result.error;+ expect(result.value.target.final_url).toBeNull();+ expect(result.value.window.end_reason).toBe(+ scope === "foreign" ? "target_left_scope" : "window_elapsed",+ );+ expect(result.value.completeness.excluded).toContainEqual({+ section: "timeline",+ reason: "invalid_protocol_value",+ count: 1,+ });+ expect(+ result.value.completeness.policy_filtered_sections.includes("timeline"),+ ).toBe(scope === "foreign");+ if (scope === "foreign")+ expect(result.value.completeness.excluded).toContainEqual({+ section: "timeline",+ reason: "out_of_target_scope",+ count: 1,+ });+ },+);+describe("CdpBrowserProvider navigation timeline", () => {+ it.each(["outside_policy", "target_detached"] as const)(+ "settles and releases a long wait after %s",+ async (sessionTimeline) => {+ const browser = await startFakeCdpBrowser({ sessionTimeline });+ trackBrowser(browser);+ const result = await new CdpBrowserProvider().observeSession(+ observeWebSessionInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 3_000_000_000,+ }),+ );+ if (!result.ok) throw result.error;+ expect(result.value.window.end_reason).toBe(+ sessionTimeline === "outside_policy"+ ? "target_left_scope"+ : "session_detached",+ );+ if (sessionTimeline === "target_detached") {+ expect(result.value.timeline).toContainEqual(+ expect.objectContaining({ type: "session_detached" }),+ );+ expect(result.value.timeline).not.toContainEqual(+ expect.objectContaining({ type: "target_terminated" }),+ );+ }+ },+ );+ it.each([2_147_483_648, 3_000_000_000])(+ "keeps a long observation pending until cancellation: %s",+ async (observation_ms) => {+ const browser = await startFakeCdpBrowser();+ trackBrowser(browser);+ const controller = new AbortController();+ let timer: ReturnType<typeof setTimeout> | undefined;+ let armed = false;+ try {+ const result = await new CdpBrowserProvider().observeSession(+ observeWebSessionInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms,+ }),+ {+ signal: controller.signal,+ progress: {+ report: async (update) => {+ if (+ update.phase === "browser_observation" &&+ update.completed === 1+ ) {+ armed = true;+ timer = setTimeout(() => controller.abort(), 150);+ }+ },+ },+ },+ );+ expect(result).toMatchObject({+ ok: false,+ error: { _tag: "AnalysisCancelledError" },+ });+ expect(armed).toBe(true);+ } finally {+ clearTimeout(timer);+ }+ },+ );it("returns every event beyond the former default collection cap", async () => {const additionalEvents = 2_001;const browser = await startFakeCdpBrowser({diff --git a/tests/boundary/browser/cdpElectronProvider.test.ts b/tests/boundary/browser/cdpElectronProvider.test.tsindex e071f4e91..609fcb64e 100644--- a/tests/boundary/browser/cdpElectronProvider.test.ts+++ b/tests/boundary/browser/cdpElectronProvider.test.ts@@ -30,6 +30,320 @@ afterEach(async () => {);});+it.each(["late", "initial", "destroyed", "final-malformed", "out-of-scope"])(+ "captures the current authorized frame inventory: %s",+ async (kind) => {+ const root = await electronFixture();+ const mainUrl = pathToFileURL(join(root, "index.html")).href;+ const childUrl = pathToFileURL(join(root, "child.html")).href;+ const scriptUrl = pathToFileURL(join(root, "app.js")).href;+ const browser = await startFakeCdpBrowser({+ electronFileUrl: mainUrl,+ eventsBeforeReply: ["Runtime.enable", "Debugger.enable"],+ commandResult: ({ method }, _origin, reads) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: { id: "frame-main", url: mainUrl },+ childFrames:+ reads > 1 || kind === "initial"+ ? [+ {+ frame: {+ id: "child",+ parentId: "frame-main",+ url:+ kind === "out-of-scope"+ ? "https://foreign.test/child"+ : childUrl,+ },+ },+ ]+ : [],+ ...(kind === "final-malformed" && reads > 2+ ? {+ childFrames: [+ {+ frame: {+ id: "child",+ parentId: "frame-main",+ url: childUrl,+ },+ },+ null,+ ],+ }+ : {}),+ },+ }+ : method === "Debugger.getScriptSource"+ ? { scriptSource: "void 0;" }+ : undefined,+ commandEvents: ({ method, sessionId }) =>+ method === "Runtime.enable"+ ? [+ {+ method: "Runtime.executionContextCreated",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: { context: { id: 7, auxData: { frameId: "child" } } },+ },+ ]+ : method === "Debugger.enable"+ ? [+ {+ method: "Debugger.scriptParsed",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ scriptId: "child-script",+ url: scriptUrl,+ executionContextId: 7,+ length: 7,+ scriptLanguage: "JavaScript",+ },+ },+ ...(kind === "destroyed"+ ? [+ {+ method: "Runtime.executionContextDestroyed",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: { executionContextId: 7 },+ },+ ]+ : []),+ ]+ : undefined,+ });+ browsers.push(browser);+ const inspected = await new CdpElectronProvider().inspectPage(+ inspectElectronPageInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ target_id: "electron-page",+ observation_ms: 0,+ include_script_sources: true,+ }),+ );+ if (!inspected.ok) throw inspected.error;+ expect(+ inspected.value.frames.some(({ frame_id }) => frame_id === "child"),+ ).toBe(kind !== "out-of-scope");+ expect(inspected.value.scripts.items).toContainEqual(+ expect.objectContaining({+ file_path: join(root, "app.js"),+ // Main snapshots historical frame identity at script ingestion, so+ // later context teardown does not erase this observed association.+ frame_id: kind === "out-of-scope" ? null : "child",+ }),+ );+ if (kind === "final-malformed") {+ expect(inspected.value.completeness.attach_limited_sections).toEqual(+ expect.arrayContaining(["frames", "scripts", "workers"]),+ );+ expect(+ inspected.value.completeness.excluded.filter(+ ({ section }) => section === "frames",+ ),+ ).toEqual([]);+ }+ },+);+it.each(["reordered", "parent-changed", "path-changed"])(+ "compares semantic frame inventory independent of sibling order: %s",+ async (kind) => {+ const root = await electronFixture();+ const main = pathToFileURL(join(root, "index.html")).href;+ const child = pathToFileURL(join(root, "child.html")).href;+ const app = pathToFileURL(join(root, "app.js")).href;+ const browser = await startFakeCdpBrowser({+ electronFileUrl: main,+ commandResult: ({ method }, _origin, reads) => {+ if (method !== "Page.getFrameTree") return undefined;+ const first = {+ frame: {+ id: "first",+ parentId:+ reads > 2 && kind === "parent-changed" ? "second" : "frame-main",+ url: reads > 2 && kind === "path-changed" ? app : child,+ },+ };+ const second = {+ frame: { id: "second", parentId: "frame-main", url: app },+ };+ return {+ frameTree: {+ frame: { id: "frame-main", url: main },+ childFrames: reads > 2 ? [second, first] : [first, second],+ },+ };+ },+ });+ 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;+ expect(result.value.frames.map(({ frame_id }) => frame_id)).toEqual([+ "frame-main",+ "first",+ "second",+ ]);+ for (const section of ["frames", "scripts", "workers"] as const)+ expect(+ result.value.completeness.attach_limited_sections.includes(section),+ ).toBe(kind !== "reordered");+ },+);++it.each([+ "detached",+ "foreign-reuse",+ "reparented",+ "unvalidated-context",+ "same-document",+])("retains authorized historical script owners after %s", async (kind) => {+ const root = await electronFixture();+ const main = pathToFileURL(join(root, "index.html")).href;+ const child = pathToFileURL(join(root, "child.html")).href;+ const script = pathToFileURL(join(root, "app.js")).href;+ const browser = await startFakeCdpBrowser({+ electronFileUrl: main,+ eventsBeforeReply: ["Debugger.enable"],+ commandResult: ({ method }, _origin, reads) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: { id: "frame-main", url: main },+ childFrames:+ reads === 1 || kind === "same-document"+ ? ["first", "second"].map((id) => ({+ frame: { id, parentId: "frame-main", url: child },+ }))+ : [],+ },+ }+ : undefined,+ commandEvents: ({ method, sessionId }) => {+ if (method !== "Debugger.enable")+ return method === "Runtime.enable" ? [] : undefined;+ const scope = sessionId === undefined ? {} : { sessionId };+ const sameDocument = (id: string, fragment: string) =>+ kind === "same-document"+ ? [+ {+ method: "Page.navigatedWithinDocument",+ ...scope,+ params: { frameId: id, url: `${child}#${fragment}` },+ },+ ]+ : [];+ const events = ["first", "second"].flatMap((id, index) => [+ {+ method: "Runtime.executionContextCreated",+ ...scope,+ params: { context: { id: index + 7, auxData: { frameId: id } } },+ },+ ...sameDocument(id, "before"),+ {+ method: "Debugger.scriptParsed",+ ...scope,+ params: {+ scriptId: id,+ url: script,+ executionContextId: index + 7,+ hash: "same",+ length: 7,+ scriptLanguage: "JavaScript",+ },+ },+ ...sameDocument(id, "after"),+ ...(kind === "detached"+ ? [+ {+ method: "Page.frameDetached",+ ...scope,+ params: { frameId: id, reason: "remove" },+ },+ ]+ : []),+ ]);+ return kind !== "detached" && kind !== "same-document"+ ? [+ ...events,+ {+ method:+ kind === "reparented"+ ? "Page.frameAttached"+ : "Page.frameNavigated",+ ...scope,+ params:+ kind === "reparented"+ ? { frameId: "first", parentFrameId: "unknown-parent" }+ : {+ frame: {+ id: "first",+ parentId: "frame-main",+ url: "https://foreign.test/",+ },+ },+ },+ ...(kind === "unvalidated-context"+ ? [+ {+ method: "Runtime.executionContextCreated",+ ...scope,+ params: {+ context: {+ id: 7,+ auxData: { frameId: "not-authorized" },+ },+ },+ },+ ]+ : []),+ {+ method: "Debugger.scriptParsed",+ ...scope,+ params: {+ scriptId: "foreign-reused",+ url: script,+ executionContextId: 7,+ hash: "foreign",+ },+ },+ ]+ : events;+ },+ });+ 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;+ expect(result.value.frames.map(({ frame_id }) => frame_id)).toEqual(+ kind === "same-document"+ ? ["frame-main", "first", "second"]+ : ["frame-main"],+ );+ expect(+ result.value.scripts.items+ .filter(({ cdp_hash }) => cdp_hash === "same")+ .map(({ frame_id }) => frame_id)+ .sort(),+ ).toEqual(["first", "second"]);+ if (kind !== "detached" && kind !== "same-document")+ expect(+ result.value.scripts.items.find(({ cdp_hash }) => cdp_hash === "foreign")+ ?.frame_id,+ ).toBeNull();+});+describe("CdpElectronProvider target access", () => {it("retains a completed page observation when cancellation arrives during final detach", async () => {const root = await electronFixture();@@ -576,3 +890,630 @@ const electronFixture = async (): Promise<string> => {await writeFile(join(root, "child.html"), "<div>child</div>");return root;};++it.each(+ ["initial", "refreshed"].flatMap((phase) =>+ ["missing", "number", "null", "empty", "foreign", "cycle", "valid"].map(+ (parent) => ({ phase, parent }),+ ),+ ),+)(+ "does not authorize unproved nested Electron ancestry: $phase/$parent",+ async ({ phase, parent }) => {+ const root = await electronFixture();+ const main = pathToFileURL(join(root, "index.html")).href;+ const child = pathToFileURL(join(root, "child.html")).href;+ const script = pathToFileURL(join(root, "app.js")).href;+ const parentValue =+ parent === "number"+ ? 7+ : parent === "null"+ ? null+ : parent === "empty"+ ? ""+ : parent === "foreign"+ ? "other"+ : parent === "cycle"+ ? "child"+ : "frame-main";+ let eventFrameReads = 0;+ const browser = await startFakeCdpBrowser({+ electronFileUrl: main,+ eventsBeforeReply: ["Debugger.enable", "Page.getFrameTree"],+ commandResult: ({ method }, _origin, reads) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: { id: "frame-main", url: main },+ childFrames:+ phase === "refreshed" && reads === 1+ ? []+ : [+ {+ frame: {+ id: "child",+ url: child,+ ...(parent === "missing"+ ? {}+ : { parentId: parentValue }),+ },+ childFrames: [+ {+ frame: {+ id: "grandchild",+ parentId: "child",+ url: child,+ },+ },+ ],+ },+ ],+ },+ }+ : undefined,+ commandEvents: ({ method, sessionId }) => {+ if (method === "Page.getFrameTree") eventFrameReads++;+ if (+ !(phase === "initial"+ ? method === "Debugger.enable"+ : method === "Page.getFrameTree" && eventFrameReads === 2)+ )+ return method === "Runtime.enable" || method === "Debugger.enable"+ ? []+ : undefined;+ const scope = sessionId === undefined ? {} : { sessionId };+ return ["child", "grandchild"].flatMap((id, index) => [+ {+ method: "Runtime.executionContextCreated",+ ...scope,+ params: { context: { id: 70 + index, auxData: { frameId: id } } },+ },+ {+ method: "Debugger.scriptParsed",+ ...scope,+ params: {+ scriptId: id,+ url: script,+ executionContextId: 70 + index,+ hash: id,+ length: 7,+ scriptLanguage: "JavaScript",+ },+ },+ ]);+ },+ });+ 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;+ expect(result.value.frames.map((f) => f.frame_id)).toEqual(+ parent === "valid"+ ? ["frame-main", "child", "grandchild"]+ : ["frame-main"],+ );+ for (const id of ["child", "grandchild"])+ expect(result.value.scripts.items).toContainEqual(+ expect.objectContaining({+ cdp_hash: id,+ frame_id: parent === "valid" ? id : null,+ }),+ );+ if (parent !== "valid") {+ expect(result.value.completeness.unavailable_sections).toContain(+ "frames",+ );+ expect(result.value.completeness.attach_limited_sections).toContain(+ "scripts",+ );+ expect(result.value.completeness.policy_filtered_sections).not.toContain(+ "frames",+ );+ }+ },+);++it.each(+ ["blank", "remote", "missing-file"].flatMap((parent) =>+ ["initial", "refreshed", "invalidated"].map((phase) => ({ parent, phase })),+ ),+)(+ "separates structural ancestry from parent file policy: $parent/$phase",+ async ({ parent, phase }) => {+ const root = await electronFixture();+ const main = pathToFileURL(join(root, "index.html")).href;+ const child = pathToFileURL(join(root, "child.html")).href;+ const script = pathToFileURL(join(root, "app.js")).href;+ const parentUrl =+ parent === "blank"+ ? "about:blank"+ : parent === "remote"+ ? "https://foreign.invalid/frame"+ : pathToFileURL(join(root, "absent.html")).href;+ let eventReads = 0;+ const browser = await startFakeCdpBrowser({+ electronFileUrl: main,+ eventsBeforeReply: ["Page.getFrameTree", "Debugger.enable"],+ commandResult: ({ method }, _origin, reads) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: { id: "frame-main", url: main },+ childFrames:+ phase === "refreshed" && reads === 1+ ? []+ : [+ {+ frame: {+ id: "parent",+ parentId: "frame-main",+ url: parentUrl,+ },+ childFrames: [+ {+ frame: {+ id: "local",+ parentId: "parent",+ url: child,+ },+ },+ ],+ },+ ],+ },+ }+ : undefined,+ commandEvents: ({ method, sessionId }) => {+ if (method === "Page.getFrameTree") eventReads++;+ if (+ !(phase === "refreshed" || phase === "invalidated"+ ? method === "Page.getFrameTree" && eventReads === 2+ : method === "Debugger.enable")+ )+ return method === "Runtime.enable" || method === "Debugger.enable"+ ? []+ : undefined;+ const scope = sessionId === undefined ? {} : { sessionId };+ return [+ ...(phase === "invalidated"+ ? [+ {+ method: "Page.frameNavigated",+ ...scope,+ params: {+ frame: {+ id: "parent",+ parentId: "frame-main",+ url: parentUrl,+ loaderId: "new-parent",+ },+ },+ },+ ]+ : []),+ {+ method: "Runtime.executionContextCreated",+ ...scope,+ params: { context: { id: 81, auxData: { frameId: "local" } } },+ },+ {+ method: "Debugger.scriptParsed",+ ...scope,+ params: {+ scriptId: "local",+ url: script,+ executionContextId: 81,+ hash: "local",+ length: 7,+ scriptLanguage: "JavaScript",+ },+ },+ ];+ },+ });+ 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;+ expect(result.value.frames.map((frame) => frame.frame_id)).toEqual([+ "frame-main",+ "local",+ ]);+ expect(result.value.scripts.items).toContainEqual(+ expect.objectContaining({+ cdp_hash: "local",+ frame_id: phase === "invalidated" ? null : "local",+ }),+ );+ expect(result.value.completeness.policy_filtered_sections).toContain(+ "frames",+ );+ expect(result.value.completeness.excluded).not.toContainEqual(+ expect.objectContaining({+ section: "frames",+ reason: "invalid_protocol_value",+ }),+ );+ },+);++it.each(["about:blank", "https://foreign.invalid/root"])(+ "does not replace an unauthorized tree root with a local descendant: %s",+ async (rootUrl) => {+ const root = await electronFixture();+ const local = pathToFileURL(join(root, "index.html")).href;+ const browser = await startFakeCdpBrowser({+ electronFileUrl: local,+ commandResult: ({ method }) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: { id: "frame-main", url: rootUrl },+ childFrames: [+ {+ frame: { id: "local", parentId: "frame-main", url: local },+ },+ ],+ },+ }+ : undefined,+ });+ browsers.push(browser);+ const result = await new CdpElectronProvider().inspectPage(+ inspectElectronPageInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ target_id: "electron-page",+ observation_ms: 0,+ }),+ );+ expect(result).toMatchObject({+ ok: false,+ error: { reason: "target_not_allowed" },+ });+ expect(browser.commands.map(({ method }) => method)).not.toContain(+ "Debugger.enable",+ );+ },+);++const replayScripts =+ (source: string, sessionId: string | undefined) =>+ (id: string, frameId: string, contextId: number) => [+ {+ method: "Runtime.executionContextCreated",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: { context: { id: contextId, auxData: { frameId } } },+ },+ {+ method: "Debugger.scriptParsed",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ scriptId: id,+ url: source,+ executionContextId: contextId,+ hash: id,+ length: 7,+ scriptLanguage: "JavaScript",+ },+ },+ ];++const replayFrameTree = (+ main: string,+ child: string,+ before: string,+ kind: string,+ reads: number,+) => ({+ frameTree: {+ frame: { id: "frame-main", url: main },+ childFrames:+ reads === 1 || (kind === "during-tree" && reads === 2)+ ? [+ {+ frame: {+ id: "child",+ parentId: "frame-main",+ url: before,+ ...(kind === "missing-loader"+ ? {}+ : { loaderId: "child-loader" }),+ },+ childFrames: [+ {+ frame: {+ id: "grandchild",+ parentId: "child",+ url: child,+ loaderId: "grandchild-loader",+ },+ },+ ],+ },+ ]+ : [],+ },+});++it.each([+ "inline",+ "split",+ "clear",+ "query",+ "during-tree",+ "post-detach",+ "changed-loader",+ "changed-parent",+ "unknown-frame",+ "missing-loader",+ "missing-url",+ "invalid-fragment",+])(+ "preserves authorized same-document history across replay and detach: %s",+ async (kind) => {+ const root = await electronFixture();+ const main = pathToFileURL(join(root, "index.html")).href;+ const child = pathToFileURL(join(root, "child.html")).href;+ const source = pathToFileURL(join(root, "app.js")).href;+ const before = `${child}#old`;+ const after =+ kind === "clear"+ ? child+ : kind === "query"+ ? `${child}?caller=retained#next`+ : `${child}#next`;+ const expectedOwner = [+ "inline",+ "split",+ "clear",+ "query",+ "during-tree",+ "post-detach",+ ].includes(kind);+ let eventReads = 0;+ const browser = await startFakeCdpBrowser({+ electronFileUrl: main,+ eventsBeforeReply: [+ "Debugger.enable",+ "Page.getFrameTree",+ "DOMSnapshot.captureSnapshot",+ ],+ commandResult: ({ method }, _origin, reads) =>+ method === "Page.getFrameTree"+ ? replayFrameTree(main, child, before, kind, reads)+ : undefined,+ commandEvents: ({ method, sessionId }) => {+ if (method === "Page.getFrameTree") eventReads += 1;+ if (+ method !== "Debugger.enable" &&+ !(+ kind === "during-tree" &&+ (method === "Page.getFrameTree" ||+ method === "DOMSnapshot.captureSnapshot")+ )+ )+ return method === "Runtime.enable" ? [] : undefined;+ const scope = sessionId === undefined ? {} : { sessionId };+ const script = replayScripts(source, sessionId);+ const events = [+ ...script("before", "child", 70),+ {+ method: "Page.navigatedWithinDocument",+ ...scope,+ params: {+ frameId: kind === "unknown-frame" ? "unknown" : "child",+ ...(kind === "missing-url"+ ? {}+ : kind === "split"+ ? { url: child, urlFragment: "#next" }+ : kind === "clear"+ ? { url: before, urlFragment: "" }+ : kind === "invalid-fragment"+ ? { url: child, urlFragment: 7 }+ : { url: after }),+ },+ },+ {+ method: "Page.frameNavigated",+ ...scope,+ params: {+ frame: {+ id: "child",+ parentId:+ kind === "changed-parent" ? "other-parent" : "frame-main",+ url: after,+ loaderId:+ kind === "changed-loader" ? "replacement" : "child-loader",+ },+ },+ },+ ...script("after-replay", "child", 71),+ ...script("descendant", "grandchild", 72),+ {+ method: "Page.frameDetached",+ ...scope,+ params: { frameId: "child", reason: "remove" },+ },+ ...(kind === "post-detach"+ ? script("after-detach", "child", 73)+ : []),+ ];+ if (kind !== "during-tree") return events;+ if (method === "Debugger.enable") return events.slice(0, 2);+ if (method === "Page.getFrameTree")+ return eventReads === 2 ? events.slice(2, 3) : [];+ return events.slice(3);+ },+ });+ 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;+ expect(result.value.scripts.items).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ cdp_hash: "before", frame_id: "child" }),+ expect.objectContaining({+ cdp_hash: "after-replay",+ frame_id: expectedOwner ? "child" : null,+ }),+ expect.objectContaining({+ cdp_hash: "descendant",+ frame_id: expectedOwner ? "grandchild" : null,+ }),+ ]),+ );+ if (kind === "post-detach")+ expect(result.value.scripts.items).toContainEqual(+ expect.objectContaining({ cdp_hash: "after-detach", frame_id: null }),+ );+ expect(+ result.value.completeness.attach_limited_sections.includes("scripts"),+ ).toBe(!expectedOwner || kind === "post-detach" || kind === "during-tree");+ expect(result.value.frames.map(({ frame_id }) => frame_id)).toEqual(+ kind === "during-tree"+ ? ["frame-main", "child", "grandchild"]+ : ["frame-main"],+ );+ },+);++it.each([+ { stage: 2, lateEvent: false },+ { stage: 2, lateEvent: true },+ { stage: 3, lateEvent: false },+])(+ "rejects a tree-first same-file main reload (read $stage, late event $lateEvent)",+ async ({ stage, lateEvent }) => {+ const root = await electronFixture();+ const main = pathToFileURL(join(root, "index.html")).href;+ let reads = 0;+ const frame = () => ({+ id: "frame-main",+ url: main,+ loaderId: reads >= stage ? "replacement" : "initial",+ });+ const browser = await startFakeCdpBrowser({+ electronFileUrl: main,+ commandResult: ({ method }) => {+ if (method !== "Page.getFrameTree") return undefined;+ reads++;+ return { frameTree: { frame: frame() } };+ },+ commandEvents: ({ method, sessionId }) =>+ lateEvent && method === "DOMSnapshot.captureSnapshot"+ ? [+ {+ method: "Page.frameNavigated",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: { frame: frame() },+ },+ ]+ : undefined,+ });+ browsers.push(browser);+ const result = await new CdpElectronProvider().inspectPage(+ inspectElectronPageInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ target_id: "electron-page",+ observation_ms: 0,+ }),+ );+ expect(result).toMatchObject({+ ok: false,+ error: { reason: "target_changed" },+ });+ expect(reads).toBeGreaterThanOrEqual(stage);+ },+);++it.each(["#next", "?route=next#details"])(+ "keeps script authority for a tree-first same-document child URL %s",+ async (suffix) => {+ const root = await electronFixture();+ const main = pathToFileURL(join(root, "index.html")).href;+ const child = pathToFileURL(join(root, "child.html")).href;+ const source = pathToFileURL(join(root, "app.js")).href;+ const tree = (reads: number) => ({+ frameTree: {+ frame: { id: "frame-main", url: main, loaderId: "main-loader" },+ childFrames: [+ {+ frame: {+ id: "child",+ parentId: "frame-main",+ url: child + (reads > 1 ? suffix : ""),+ loaderId: "child-loader",+ },+ childFrames: [+ {+ frame: {+ id: "grandchild",+ parentId: "child",+ url: child,+ loaderId: "grandchild-loader",+ },+ },+ ],+ },+ ],+ },+ });+ const browser = await startFakeCdpBrowser({+ electronFileUrl: main,+ commandResult: ({ method }, _origin, reads) =>+ method === "Page.getFrameTree" ? tree(reads) : undefined,+ commandEvents: ({ method, sessionId }) => {+ const scripts = replayScripts(source, sessionId);+ if (method === "Runtime.enable") return [];+ if (method === "Debugger.enable")+ return [+ ...scripts("before-child", "child", 70),+ ...scripts("before-grandchild", "grandchild", 71),+ ];+ if (method === "DOMSnapshot.captureSnapshot")+ return [+ {+ method: "Page.navigatedWithinDocument",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: { frameId: "child", url: child + suffix },+ },+ ...scripts("after-child", "child", 72),+ ...scripts("after-grandchild", "grandchild", 73),+ ];+ return 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;+ for (const id of ["child", "grandchild"])+ for (const phase of ["before", "after"])+ expect(result.value.scripts.items).toContainEqual(+ expect.objectContaining({ cdp_hash: `${phase}-${id}`, frame_id: id }),+ );+ expect(result.value.completeness.attach_limited_sections).not.toContain(+ "scripts",+ );+ },+);diff --git a/tests/boundary/browser/cdpRuntimeFrameIdentity.test.ts b/tests/boundary/browser/cdpRuntimeFrameIdentity.test.tsnew file mode 100644index 000000000..4bb255455--- /dev/null+++ b/tests/boundary/browser/cdpRuntimeFrameIdentity.test.ts@@ -0,0 +1,168 @@+import { BrowserObservationError } from "../../../src/domain/browserObservationError.js";+import { expect, it } from "vitest";+import { CdpWebRuntimeProvider } from "../../../src/browser/execution/CdpWebRuntimeProvider.js";+import { observeWebExecutionInputSchema } from "../../../src/domain/webExecution.js";+import { inspectWebEventListenersInputSchema } from "../../../src/domain/webEventListeners.js";+import { startRuntimeBrowser } from "../../fixtures/webRuntime.js";+import type { FakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";+import { trackBrowser } from "./cdpBrowserProvider.support.js";++const actions = ["execution", "listeners"] as const;+const run = async (+ browser: FakeCdpBrowser,+ action: (typeof actions)[number],+) => {+ const provider = new CdpWebRuntimeProvider();+ const input = {+ cdp_endpoint: browser.endpoint,+ target_id: "allowed-page",+ allowed_origins: [browser.allowedOrigin],+ };+ return action === "execution"+ ? provider.observeExecution(+ observeWebExecutionInputSchema.parse({ ...input, observation_ms: 1 }),+ )+ : provider.inspectEventListeners(+ inspectWebEventListenersInputSchema.parse({+ ...input,+ selector: "#selected",+ }),+ );+};++it.each(+ actions.flatMap((action) =>+ [false, true].flatMap((loader) =>+ ["split", "clear", "inline", "credentials"].map((kind) => ({+ action,+ loader,+ kind,+ })),+ ),+ ),+)(+ "preserves full $kind frame identity in $action evidence with loader=$loader",+ async ({ action, loader, kind }) => {+ const browser = await startRuntimeBrowser({+ commandResult: ({ method }, origin) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: {+ id: "runtime-main",+ ...(loader ? { loaderId: "document-1" } : {}),+ url: `${kind === "credentials" ? origin.replace("://", "://user:password@") : origin}/app?caller=retained#old`,+ ...(kind === "inline"+ ? {}+ : { urlFragment: kind === "clear" ? "" : "#details" }),+ },+ },+ }+ : undefined,+ });+ trackBrowser(browser);+ const result = await run(browser, action);+ if (!result.ok) throw result.error;+ expect(result.value.target).toMatchObject({+ initial_url: `${browser.allowedOrigin}/app?caller=retained${kind === "inline" ? "#old" : kind === "clear" ? "" : "#details"}`,+ origin: browser.allowedOrigin,+ loader_id: loader ? "document-1" : null,+ });+ },+);++const transitions = [+ { kind: "equivalent", loader: false, reason: null },+ { kind: "fragment-change", loader: false, reason: "target_changed" },+ { kind: "fragment-change", loader: true, reason: null },+ { kind: "malformed", loader: false, reason: "protocol_error" },+ { kind: "malformed", loader: true, reason: "protocol_error" },+ { kind: "foreign-malformed", loader: true, reason: "target_not_allowed" },+ { kind: "foreign-loader-change", loader: true, reason: "target_changed" },+ { kind: "foreign", loader: false, reason: "target_changed" },+ { kind: "foreign", loader: true, reason: "target_not_allowed" },+ { kind: "missing", loader: true, reason: "protocol_error" },+ { kind: "frame-change", loader: true, reason: "target_changed" },+ { kind: "loader-change", loader: true, reason: "target_changed" },+ { kind: "unsupported", loader: true, reason: "target_not_allowed" },+] as const;+it.each(+ actions.flatMap((action) => transitions.map((item) => ({ action, ...item }))),+)(+ "checks parsed $kind final identity in $action with loader=$loader",+ async ({ action, kind, loader, reason }) => {+ const browser = await startRuntimeBrowser({+ commandResult: ({ method }, origin, reads) => {+ if (method !== "Page.getFrameTree") return undefined;+ const changed = reads > 1;+ const url = `${origin}/app?caller=retained`;+ return {+ frameTree: {+ frame: {+ id:+ changed && kind === "frame-change"+ ? "replacement"+ : "runtime-main",+ ...(loader+ ? {+ loaderId:+ changed &&+ (kind === "loader-change" ||+ kind === "foreign-loader-change")+ ? "replacement"+ : "document-1",+ }+ : {}),+ ...(changed && kind === "missing"+ ? {}+ : {+ url:+ changed &&+ (kind === "foreign-malformed" ||+ kind === "foreign" ||+ kind === "foreign-loader-change")+ ? "https://foreign.example/app"+ : changed && kind === "unsupported"+ ? "about:blank"+ : changed && kind === "equivalent"+ ? `${url}#details`+ : url,+ }),+ ...(changed && kind === "equivalent"+ ? {}+ : {+ urlFragment:+ changed &&+ (kind === "malformed" || kind === "foreign-malformed")+ ? 7+ : changed && kind === "fragment-change"+ ? "#changed"+ : "#details",+ }),+ },+ },+ };+ },+ });+ trackBrowser(browser);+ const result = await run(browser, action);+ if (reason === null) {+ if (!result.ok) throw result.error;+ expect(result.value.target.initial_url).toBe(+ `${browser.allowedOrigin}/app?caller=retained#details`,+ );+ } else {+ expect(result).toMatchObject({ ok: false, error: { reason } });+ if (kind === "foreign" && loader && !result.ok) {+ if (!(result.error instanceof BrowserObservationError))+ throw result.error;+ expect(result.error.detail).toBe(+ `Selected target allowed-page moved to an unselected origin during ${result.error.operation}.`,+ );+ }+ }+ const methods = browser.commands.map(({ method }) => method);+ expect(methods).toContain("Debugger.disable");+ expect(methods).toContain("Target.detachFromTarget");+ },+);diff --git a/tests/boundary/browser/cdpScreenshotDocumentIdentity.test.ts b/tests/boundary/browser/cdpScreenshotDocumentIdentity.test.tsindex 2060e305e..da41eeb5e 100644--- a/tests/boundary/browser/cdpScreenshotDocumentIdentity.test.ts+++ b/tests/boundary/browser/cdpScreenshotDocumentIdentity.test.ts@@ -553,6 +553,42 @@ describe("screenshot viewport protocol validation", () => {});describe("screenshot committed document identity", () => {+ it.each(["requested-only", "same-url-history"])(+ "accepts unchanged identity after %s",+ async (kind) => {+ const browser = await startFakeCdpBrowser({+ commandEvents: ({ method, sessionId }, origin) =>+ method !== "Page.captureScreenshot"+ ? undefined+ : [+ {+ method:+ kind === "requested-only"+ ? "Page.frameRequestedNavigation"+ : "Page.navigatedWithinDocument",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ frameId: "frame-main",+ url: `${origin}${kind === "requested-only" ? "/pending" : "/app?token=frame-secret"}`,+ reason: "scriptInitiated",+ disposition: "currentTab",+ navigationType: "historyApi",+ },+ },+ ],+ });+ onTestFinished(async () => browser.close());+ const result = await new CdpBrowserProvider().captureScreenshot(+ captureWebScreenshotInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ }),+ );+ expect(result.ok).toBe(true);+ },+ );+it.each([["missing screenshot data", {}],["invalid base64 screenshot data", { data: "not base64%%%" }],@@ -577,6 +613,7 @@ describe("screenshot committed document identity", () => {"base64",);bytes.writeUInt32BE(value, offset);+ bytes.writeUInt32BE(crc32(bytes.subarray(12, 29)), 29);const { result } = await captureWithFake({commandResult: ({ method }) =>method === "Page.captureScreenshot"@@ -794,6 +831,117 @@ describe("screenshot navigation event applicability", () => {});});+it.each(+ [7, "missing-hash"].flatMap((fragment) =>+ ["initial", "event", "final"].flatMap((phase) =>+ ["allowed", "foreign", "missing"].map((scope) => ({+ fragment,+ phase,+ scope,+ })),+ ),+ ),+)(+ "keeps malformed screenshot fragments distinct from scope exits: $phase/$scope/$fragment",+ async ({ fragment, phase, scope }) => {+ const browser = await startFakeCdpBrowser({+ commandResult: ({ method }, origin, reads) =>+ method === "Page.getFrameTree" &&+ (phase === "initial" || (phase === "final" && reads > 1))+ ? {+ frameTree: {+ frame: {+ id: "frame-main",+ loaderId: "loader-main",+ ...(scope === "missing"+ ? {}+ : {+ url:+ scope === "foreign"+ ? "https://foreign.test/"+ : `${origin}/app?token=frame-secret`,+ }),+ urlFragment: fragment,+ },+ },+ }+ : undefined,+ commandEvents: ({ method, sessionId }, origin) =>+ phase === "event" && method === "Page.captureScreenshot"+ ? [+ {+ method: "Page.frameNavigated",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ frame: {+ id: "frame-main",+ loaderId: "loader-main",+ ...(scope === "missing"+ ? {}+ : {+ url:+ scope === "foreign"+ ? "https://foreign.test/"+ : `${origin}/app?token=frame-secret`,+ }),+ urlFragment: fragment,+ },+ },+ },+ ]+ : undefined,+ });+ onTestFinished(async () => browser.close());+ const result = await new CdpBrowserProvider().captureScreenshot(+ captureWebScreenshotInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ }),+ );+ expect(result).toMatchObject({+ ok: false,+ error: {+ reason: scope === "foreign" ? "target_not_allowed" : "protocol_error",+ },+ });+ },+);++it("retains a foreign base scope even when its fragment is malformed", async () => {+ const browser = await startFakeCdpBrowser({+ commandEvents: ({ method, sessionId }) =>+ method === "Page.captureScreenshot"+ ? [+ {+ method: "Page.frameNavigated",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ frame: {+ id: "frame-main",+ loaderId: "foreign",+ url: "https://foreign.test/",+ urlFragment: 7,+ },+ },+ },+ ]+ : undefined,+ });+ onTestFinished(async () => browser.close());+ const result = await new CdpBrowserProvider().captureScreenshot(+ captureWebScreenshotInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ }),+ );+ expect(result).toMatchObject({+ ok: false,+ error: { reason: "target_not_allowed" },+ });+});+it.each([24, 32, "crc"])("rejects incomplete or corrupt PNG IHDR: %s",async (kind) => {diff --git a/tests/boundary/browser/cdpWebMcpTransientIdentity.test.ts b/tests/boundary/browser/cdpWebMcpTransientIdentity.test.tsnew file mode 100644index 000000000..4f766ffd8--- /dev/null+++ b/tests/boundary/browser/cdpWebMcpTransientIdentity.test.ts@@ -0,0 +1,204 @@+import { expect, it } from "vitest";+import type { CdpEvent } from "../../../src/browser/CdpConnection.js";+import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";+import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";+import { discoverWebMcpToolsInputSchema } from "../../../src/domain/webMcpDiscovery.js";+import { compareWebCaptures } from "../../../src/domain/webCaptureDiff.js";+import { compareWebCapturesInputSchema } from "../../../src/domain/webCaptureDiffSchemas.js";+import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";+import { trackBrowser } from "./cdpBrowserProvider.support.js";++it.each(+ ["about:blank", "about:srcdoc"].flatMap((base) =>+ ["inline", "split"].flatMap((encoding) =>+ ["initial", "event"].flatMap((phase) =>+ [false, true].map((recover) => ({ base, encoding, phase, recover })),+ ),+ ),+ ),+)(+ "keeps temporary document policy separate from fragment identity: $base/$encoding/$phase/$recover",+ async ({ base, encoding, phase, recover }) => {+ let document = phase === "initial" ? "transient" : "old";+ const blank =+ encoding === "split"+ ? { url: base, urlFragment: "#details" }+ : { url: base + "#details" };+ const frame = (origin: string) => ({+ id: "child",+ parentId: "frame-main",+ loaderId: document,+ ...(document === "transient"+ ? blank+ : {+ url: origin + "/child",+ urlFragment: document === "fresh" ? "#current" : "#old",+ }),+ });+ const tool = (name: string) => ({+ name,+ frameId: "child",+ inputSchema: {},+ annotations: {+ readOnly: true,+ untrustedContent: true,+ consequential: false,+ autosubmit: false,+ },+ });+ const browser = await startFakeCdpBrowser({+ webMcpTools: true,+ eventsBeforeReply: ["WebMCP.enable"],+ commandResult: ({ method }, origin) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: { id: "frame-main", url: origin + "/app" },+ childFrames: [{ frame: frame(origin) }],+ },+ }+ : undefined,+ commandEvents: ({ method, sessionId }, origin) => {+ if (method !== "WebMCP.enable") return undefined;+ const scope = sessionId === undefined ? {} : { sessionId };+ const events: CdpEvent[] = [+ {+ method: "WebMCP.toolsAdded",+ ...scope,+ params: { tools: [tool("stale")] },+ },+ ];+ document = "transient";+ if (phase === "event")+ events.push({+ method: "Page.frameNavigated",+ ...scope,+ params: { frame: frame(origin) },+ });+ if (recover) {+ document = "fresh";+ events.push({+ method: "Page.frameNavigated",+ ...scope,+ params: { frame: frame(origin) },+ });+ events.push({+ method: "WebMCP.toolsAdded",+ ...scope,+ params: { tools: [tool("current")] },+ });+ }+ return events;+ },+ });+ trackBrowser(browser);+ const provider = new CdpBrowserProvider();+ const input = {+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 0,+ };+ const result = await provider.discoverWebMcpTools(+ discoverWebMcpToolsInputSchema.parse(input),+ );+ if (!result.ok) throw result.error;+ expect(result.value.tools.items.map(({ name }) => name)).toEqual(+ recover ? ["current"] : [],+ );+ expect(result.value.completeness.policy_filtered_sections).not.toContain(+ "webmcp_tools",+ );+ expect(+ result.value.completeness.attach_limited_sections.includes(+ "webmcp_tools",+ ),+ ).toBe(!recover);+ if (recover)+ expect(result.value.tools.items[0]?.frame_url).toBe(+ browser.allowedOrigin + "/child#current",+ );+ const inspection = await provider.inspectPage(+ inspectWebPageInputSchema.parse(input),+ );+ if (!inspection.ok) throw inspection.error;+ const snapshot = { inspection: inspection.value, webmcp: result.value };+ const compared = compareWebCaptures(+ compareWebCapturesInputSchema.parse({+ before: snapshot,+ after: snapshot,+ }),+ );+ expect(compared.dimensions.webmcp.status).toBe(+ recover ? "unchanged" : "unknown",+ );+ },+);++it.each([+ "about:blanker#details",+ "about:srcdoc-other#details",+ "about:blank?policy=1#details",+ "https://foreign.invalid/child#about:blank",+ "allowed",+])("does not broaden temporary document policy: %s", async (rawUrl) => {+ const browser = await startFakeCdpBrowser({+ webMcpTools: true,+ eventsBeforeReply: ["WebMCP.enable"],+ commandResult: ({ method }, origin) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: { id: "frame-main", url: origin + "/app" },+ childFrames: [+ {+ frame: {+ id: "child",+ parentId: "frame-main",+ url:+ rawUrl === "allowed"+ ? origin + "/child#about:blank"+ : rawUrl,+ },+ },+ ],+ },+ }+ : undefined,+ commandEvents: ({ method, sessionId }) =>+ method === "WebMCP.enable"+ ? [+ {+ method: "WebMCP.toolsAdded",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ tools: [{ name: "current", frameId: "child", inputSchema: {} }],+ },+ },+ ]+ : undefined,+ });+ trackBrowser(browser);+ const result = await new CdpBrowserProvider().discoverWebMcpTools(+ discoverWebMcpToolsInputSchema.parse({+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 0,+ }),+ );+ if (!result.ok) throw result.error;+ expect(result.value.tools.items.map(({ name }) => name)).toEqual(+ rawUrl === "allowed" ? ["current"] : [],+ );+ expect(+ result.value.completeness.policy_filtered_sections.includes("webmcp_tools"),+ ).toBe(rawUrl !== "allowed");+ expect(result.value.completeness.attach_limited_sections).not.toContain(+ "webmcp_tools",+ );+ if (rawUrl === "allowed")+ expect(result.value.tools.items[0]?.frame_url).toBe(+ browser.allowedOrigin + "/child#about:blank",+ );+});diff --git a/tests/boundary/mcp/browserMcp.test.ts b/tests/boundary/mcp/browserMcp.test.tsindex 3f03fb0d7..7bdd13a0a 100644--- a/tests/boundary/mcp/browserMcp.test.ts+++ b/tests/boundary/mcp/browserMcp.test.ts@@ -27,6 +27,93 @@ const resources: Array<{ close(): Promise<unknown> }> = [];const browsers: FakeCdpBrowser[] = [];const INTEGRATION_TEST_TIMEOUT_MS = 20_000;+it(+ "preserves full document URL identity through CLI and MCP",+ async () => {+ const source =+ 'document.modelContext.registerTool({name:"catalog",[``]:0,inputSchema:{properties:{"":{},ordinary:{}}}});';+ const browser = await startFakeCdpBrowser({+ commandResult: ({ method }, origin) =>+ method === "Debugger.getScriptSource"+ ? { scriptSource: source }+ : method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: {+ id: "frame-main",+ loaderId: "loader-main",+ url: `${origin}/app?token=frame-secret`,+ urlFragment: "#details",+ },+ },+ }+ : undefined,+ commandEvents: ({ method, sessionId }, origin) =>+ method === "Page.captureScreenshot"+ ? [+ {+ method: "Page.frameRequestedNavigation",+ ...(sessionId === undefined ? {} : { sessionId }),+ params: {+ frameId: "frame-main",+ url: `${origin}/not-committed`,+ reason: "scriptInitiated",+ disposition: "currentTab",+ },+ },+ ]+ : undefined,+ });+ browsers.push(browser);+ const { client, session } = await connectBrowser();+ const args = {+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ };+ const cli = await runCliJson([+ "analyze-web-bundle",+ browser.endpoint,+ "allowed-page",+ "--allowed-origins",+ browser.allowedOrigin,+ "--observation-ms",+ "0",+ "--json",+ ]);+ const mcp = await client.callTool({+ name: "analyze_web_bundle",+ arguments: { ...args, observation_ms: 0 },+ });+ for (const result of [cli, mcp.structuredContent])+ expect(result).toMatchObject({+ normalized_result: {+ capture: {+ target_url: `${browser.allowedOrigin}/app?token=frame-secret#details`,+ },+ },+ });+ expect(+ session.evidenceById(parseEvidence(mcp.structuredContent).evidence_id),+ ).toEqual(parseEvidence(mcp.structuredContent));+ const screenshot = await client.callTool({+ name: "capture_web_screenshot",+ arguments: args,+ });+ expect(screenshot).toMatchObject({+ structuredContent: {+ normalized_result: {+ target: {+ url: `${browser.allowedOrigin}/app?token=frame-secret#details`,+ },+ artifact: { media_type: "image/png" },+ },+ },+ });+ },+ INTEGRATION_TEST_TIMEOUT_MS,+);+afterEach(async () => {await Promise.all(resources.splice(0).map(async (resource) => resource.close()),diff --git a/tests/boundary/mcp/webRuntimeMcp.test.ts b/tests/boundary/mcp/webRuntimeMcp.test.tsindex f27297ffe..f66c0abae 100644--- a/tests/boundary/mcp/webRuntimeMcp.test.ts+++ b/tests/boundary/mcp/webRuntimeMcp.test.ts@@ -86,6 +86,87 @@ it("advertises actual SDK schemas, instrumentation effects and session-owned inlexpect(invalid.isError).toBe(true);});+it("preserves the same reconstructed runtime identity through compiled CLI and MCP evidence", async () => {+ const { runCliJson } = await import("../../fixtures/cliJsonProcess.js");+ const browser = await startRuntimeBrowser({+ commandResult: ({ method }, origin) =>+ method === "Page.getFrameTree"+ ? {+ frameTree: {+ frame: {+ id: "runtime-main",+ loaderId: "document-1",+ url: `${origin}/app?caller=retained#old`,+ urlFragment: "#details",+ },+ },+ }+ : undefined,+ });+ const provider = new CdpWebRuntimeProvider();+ const session = createTestBinarySession(() => {+ throw new Error("Binary provider must not start");+ });+ const server = createServer(+ { kind: "session", session },+ { webRuntime: new WebRuntimeService(provider) },+ );+ const client = new Client({ name: "runtime-frame-identity", version: "1" });+ onTestFinished(async () => {+ await client.close();+ await server.close();+ await provider.close();+ await session.close();+ await browser.close();+ });+ const [clientTransport, serverTransport] =+ InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ for (const name of [+ "observe_web_execution",+ "inspect_web_event_listeners",+ ] as const) {+ const response = await client.callTool({+ name,+ arguments: {+ cdp_endpoint: browser.endpoint,+ target_id: "allowed-page",+ allowed_origins: [browser.allowedOrigin],+ ...(name === "observe_web_execution"+ ? { observation_ms: 1 }+ : { selector: "#selected" }),+ },+ });+ expect(response.isError).not.toBe(true);+ const evidence = parseEvidence(+ toolContract(name).outputSchema.parse(response.structuredContent),+ );+ expect(evidence.normalized_result).toMatchObject({+ target: {+ initial_url: `${browser.allowedOrigin}/app?caller=retained#details`,+ },+ });+ expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);+ const cli = await runCliJson([+ name.replaceAll("_", "-"),+ browser.endpoint,+ "allowed-page",+ ...(name === "observe_web_execution"+ ? ["--observation-ms", "1"]+ : ["#selected"]),+ "--allowed-origins",+ browser.allowedOrigin,+ "--json",+ ]);+ expect(parseEvidence(cli).normalized_result).toMatchObject({+ target: {+ initial_url: `${browser.allowedOrigin}/app?caller=retained#details`,+ },+ });+ }+}, 20_000);+it.each([{name: "observe_web_execution" as const,