Files
reverse-engineering-anything/scripts/lib/browser-url-userinfo-e2e.mjs
T
67a1e2c937 feat(browser)!: size inspect_web_page delivery and page captures by section (#14368)
* feat(browser)!: size inspect_web_page delivery and page captures by section

inspect_web_page returned the complete capture inline with no detail
choice. A local page with 2,000 list rows, 200 buttons and three bundled
libraries produced a 4.6 MB MCP result, mostly 6,423 DOM nodes and 10,614
accessibility nodes.

inspect_web_page now declares the size-aware detail. Omitted, a capture
up to 32 KiB is inline and a larger one is retained behind a summary of
its small sections and counts. A new web-page view pages dom (node_names),
accessibility (roles), console (types), network (methods), scripts and
resources. The shared Evidence handler applies the same size decision as
the other size-aware tools and keeps detail out of the capture parameters.

BREAKING CHANGE: an MCP inspect_web_page call that omits detail on a
capture above 32 KiB now returns the retained summary. Pass
detail: "complete" for the previous shape, for example before
compare_web_captures.

Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* feat(cli): deliver inspect-web-page summaries through the Evidence bundle

The contract's size-aware detail also generated a --detail option for
rea inspect-web-page, but the command ignored it and always printed the
complete capture. The command now uses the shared CLI Evidence delivery,
as analyze-web-bundle does: omitted or complete detail prints the
capture, and --detail summary requires --evidence_output and prints the
summary with the bundle receipt.

Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(browser): bound web-page summaries and keep capture context on pages

Review found three gaps in the new web-page view:
- pages dropped the capture's completeness and the section's context, so
  an empty accessibility page looked like an exhausted one;
- script rows carried their complete captured source, so one large
  bundle could not be paged;
- the summary copied every frame and worker.

Every page now carries the capture's completeness and its section's own
context beside the page coverage. Script rows keep source metadata
without text, and a script-source collection pages one script's text by
UTF-16 offset. The summary counts frames and workers, which page through
their own collections.

Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* test(browser): request complete captures in the real-browser verifiers

The metadata-budget, URL userinfo, DOM destination and script export
verifiers read the complete inspect_web_page capture through MCP. With
size-aware delivery, an omitted detail above 32 KiB returns the summary,
and the metadata-budget verifier failed reading scripts.items from it.
These calls now request detail complete; their CLI calls already return
the complete capture.

Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

---------

Co-authored-by: gensokyo-dev <gensokyo-dev@users.noreply.github.com>
Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-11-24 10:08:21 -05:00

180 lines
6.1 KiB
JavaScript

import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { CdpConnection } from "../../dist/browser/CdpConnection.js";
import { parseEvidence } from "../../dist/domain/evidence.js";
import { artifactCliEvidence } from "./artifact-e2e.mjs";
import { withVerifierCleanup } from "./verifier-cleanup.mjs";
/** Verify real V8 source labels, which retain spelling that navigation normalizes. */
export async function verifyBrowserUrlUserInfo(endpoint, origin) {
const rawUrl = `${origin.replace("://", "://user:pass@")}\\path@tail/../keep.js?x=1#frag`;
const expectedUrl = `${origin}\\path@tail/../keep.js?x=1#frag`;
const sources = [rawUrl, expectedUrl].map(
(url, index) =>
`globalThis.reaUserinfoUrlProbe${index} = () => 4731;\n//# sourceURL=${url}`,
);
const response = await fetch(`${endpoint}/json/new?about:blank`, {
method: "PUT",
});
assert.equal(
response.ok,
true,
"Browser refused the owned URL fixture target",
);
const target = await response.json();
assert.equal(typeof target.id, "string");
let connection;
let transport;
let client;
return withVerifierCleanup(async () => {
connection = await CdpConnection.connect(
target.webSocketDebuggerUrl,
"inspect_web_page",
);
await loadFixturePage(connection, `${origin}/app?userinfo-probe`);
const producerUrls = [];
connection.onRegisteredEvent("Debugger.scriptParsed", (registered) => {
producerUrls.push(registered.payload.facts.url);
});
await connection.send("Debugger.enable");
const browserUrl = await connection.send("Runtime.evaluate", {
expression: `new URL(${JSON.stringify(rawUrl)}).href`,
returnByValue: true,
});
assert.equal(browserUrl.exceptionDetails, undefined);
assert.equal(browserUrl.result.value, new URL(rawUrl).href);
assert.notEqual(browserUrl.result.value, rawUrl);
assert.equal(new URL(browserUrl.result.value).pathname, "/keep.js");
for (const source of sources) {
const evaluated = await connection.send("Runtime.evaluate", {
expression: source,
returnByValue: true,
});
assert.equal(evaluated.exceptionDetails, undefined);
}
assert.ok(
[rawUrl, expectedUrl].every((url) => producerUrls.includes(url)),
"Real V8 did not retain the exact sourceURL spelling on the CDP wire",
);
const assertScripts = (evidence) => {
const result = parseEvidence(evidence).normalized_result;
return sources.map((source) => {
const script = result.scripts.items.find(
(item) =>
item.source.included && item.source.artifact.text === source,
);
assert.ok(
script,
"Public capture omitted the retained V8 fixture script",
);
assert.equal(script.url, expectedUrl);
assert.equal(new URL(script.url).origin, origin);
assert.equal(
script.source.artifact.sha256,
createHash("sha256").update(source).digest("hex"),
);
return script.url;
});
};
const cliUrl = assertScripts(
await artifactCliEvidence("inspect-web-page", endpoint, [
target.id,
"--allowed-origins",
origin,
"--include-script-sources",
"--observation-ms",
"0",
]),
);
transport = new StdioClientTransport({
command: process.execPath,
args: [fileURLToPath(new URL("../rea.mjs", import.meta.url)), "mcp"],
env: { ...process.env, REA_LOG_LEVEL: "silent" },
stderr: "pipe",
});
client = new Client({ name: "browser-url-userinfo-e2e", version: "1" });
await client.connect(transport);
const mcp = await client.callTool({
name: "inspect_web_page",
arguments: {
cdp_endpoint: endpoint,
allowed_origins: [origin],
target_id: target.id,
include_script_sources: true,
observation_ms: 0,
detail: "complete",
},
});
assert.notEqual(mcp.isError, true, JSON.stringify(mcp));
assert.deepEqual(assertScripts(mcp.structuredContent), cliUrl);
return {
cli: true,
stdio_mcp: true,
raw_v8_source_url: true,
credential_free_control: true,
original_source_digest: true,
browser_url_parser_normalizes_backslash_and_dot_segments: true,
};
}, [
async () => client?.close(),
async () => transport?.close(),
async () => connection?.close(),
async () => {
const closed = await fetch(`${endpoint}/json/close/${target.id}`);
assert.equal(
closed.ok,
true,
"Browser retained the owned URL fixture target",
);
},
]);
}
async function loadFixturePage(connection, url) {
const loaded = new Set();
let loaderId;
let resolveLoaded;
let timer;
const load = new Promise((resolve) => {
resolveLoaded = resolve;
});
const unsubscribe = connection.onRegisteredEvent(
"Page.lifecycleEvent",
(registered) => {
if (registered.payload.name !== "load") return;
loaded.add(registered.payload.loaderId);
if (registered.payload.loaderId === loaderId) resolveLoaded();
},
);
try {
await connection.send("Page.enable");
await connection.send("Page.setLifecycleEventsEnabled", { enabled: true });
const navigation = await connection.send("Page.navigate", { url });
assert.equal(navigation.errorText, undefined);
assert.equal(typeof navigation.loaderId, "string");
loaderId = navigation.loaderId;
if (!loaded.has(loaderId))
await Promise.race([
load,
new Promise((_, reject) => {
timer = setTimeout(
() => reject(new Error("Owned URL fixture did not finish loading")),
10_000,
);
}),
]);
assert.equal(
(await connection.send("Page.getFrameTree")).root.url.url,
url,
);
} finally {
clearTimeout(timer);
unsubscribe();
await connection.send("Page.setLifecycleEventsEnabled", { enabled: false });
}
}