mirror of
https://github.com/morluto/rea.git
synced 2026-11-15 19:23:24 +00:00
* refactor(browser): parse frame lifecycle events once by a registered event schema CdpConnection admits each event through protocol/CdpEvents.ts, which parses the five Page frame lifecycle events once into identity facts plus a frame URL observation, like a frame-tree node. Screenshot, page capture, the observation timeline, WebMCP, Electron inspection and the execution window read those facts instead of re-parsing the raw payload; CdpFrameFacts no longer carries the raw source record. Playwright CDP session subscriptions name an event from Playwright's protocol table, and an architecture guard counts the remaining raw event payload reads so they can only shrink. * refactor(browser): parse Runtime and Debugger events once by registered schemas Register Debugger.scriptParsed, Debugger.scriptFailedToParse, Runtime.executionContextCreated, Runtime.executionContextDestroyed and Runtime.consoleAPICalled. Script and context payloads carry both the tolerant facts passive capture uses and the active runtime's strict declaration, derived from one parse, plus the declaration's byte size for the runtime retention budget. Page capture, Electron script capture, the V8 Inspector provider and the runtime source inventory now read the registered payload. The cdp-raw-event-params baseline drops from 20 to 7. * refactor(browser): admit transport events through the registered-event owner Remove the unused cdpFrameUrl wrapper; its fragment cases now exercise observeCdpFrameUrl. Add a connection-level test that two subscribers share one parsed payload and the raw params. * fix(browser): report an unserializable event declaration's size instead of throwing JSON.stringify can throw on a declaration JSON.parse accepted (nesting deeper than the serializer's stack). The registry sized script and context declarations inside the connection's WebSocket callback, so such an event escaped as an uncaught exception. The size is now a Result; the runtime source inventory raises the failure inside its own catch, as before. * refactor(browser): parse Network events once by registered schemas (#10743) * refactor(browser): parse Network events once by registered schemas Register Network.requestWillBeSent, responseReceived, loadingFinished, loadingFailed, webSocketCreated and webSocketFrameSent/Received. The request payload carries the tolerant facts page capture and the timeline read plus the active runtime's strict declaration. Page capture's network and WebSocket handlers, the timeline's request tracking and the runtime request inventory now read the registered payload. The cdp-raw-event-params baseline drops from 7 to 5. * refactor(browser): drop payload helpers the capture handlers no longer use * refactor(browser): read every CDP event payload through the registry (#10745) * refactor(browser): read every CDP event payload through the registry Register Target.attachedToTarget, Target.detachedFromTarget, Page.lifecycleEvent and WebMCP.toolsAdded/toolsRemoved, and carry a requested navigation's reason and a commit's transition type in the frame-event payload. The timeline no longer threads raw params into its entries: each entry receives its timestamp, frame and loader identity explicitly. WebMCP discovery, the service-worker policy blocker and the target-event matcher read the registered payload. With no raw reads left, the cdp-raw-event-params guard is enforced at zero instead of counted. * refactor(browser): drop raw payload helpers the timeline and worker blocker no longer use * refactor(browser): type Playwright CDP session events by the registry (#10751) PlaywrightCdpSession.on subscribes only to registered events and hands the listener the payload parsed by its registered schema, returning the unsubscribe function. Private storage seeding reads registered payloads, including the events of non-flat child sessions, and applies its strict seeding policy to the parsed facts. Its local attach, detach, nested message and pause schemas and the storage-only script/context schemas are removed; Debugger.paused, Runtime.executionContextsCleared and Target.receivedMessageFromTarget join the registry. * test(browser): admit fake policy events through the event registry The service-worker policy now reads event.registered, but the PlaywrightScenarioSession fake connection delivered raw events, so three detached-target tests never reached the policy. The fake now admits each event with receiveCdpEvent as CdpConnection does. * fix(browser): fail the CDP session closed when an event listener throws (#10758) * fix(browser): fail the CDP session closed when an event listener throws An exception from a CDP event subscriber escaped CdpTransportCore's socket message callback uncaught (for example the service-worker blocker's protocol_error on a Target event without a sessionId). The transport now stops delivery, fails the connection as a protocol error whose cause is the listener's exception, rejects pending and later commands with it, and notifies protocol-failure subscribers. The Playwright CDP session relay applies the same rule to its event listeners. * fix(browser): report a failed service-worker policy connection at the next policy check The policy's event listener rejects a malformed Target event, which now fails its connection. With no policy command pending, nothing reported it and later iframe targets went unprotected. The policy records its connection's protocol failure and assertBlocked, run before each scenario step, rethrows it. * fix(browser): keep cleanup commands available after a listener failure A listener failure no longer marks the wire as broken. The transport still rejects pending commands, notifies protocol-failure subscribers, stops delivering events and refuses reuse, but it keeps reading replies and admits commands sent in cleanup grace. The service-worker policy can then remove its init scripts, restore the main realm, detach and release its socket. Wire-level protocol errors still refuse every later command. The PlaywrightScenarioSession policy fake gains onProtocolFailure, which the policy now subscribes to. * refactor(browser): keep raw CDP event payloads out of the received event (#10764) * refactor(browser): keep raw CDP event payloads out of the received event CdpReceivedEvent and CdpTransportEvent no longer carry params: receiveCdpEvent hands the raw payload only to the registered schema, so a subscriber cannot read it by property access, destructuring or computed keys. This supersedes the event.params text guard in architecture-guards, which is removed. * refactor(browser): read registered event payloads in the JavaScript verifiers The runtime, storage and URL-userinfo verifiers subscribe to CdpConnection, which no longer hands subscribers raw params. They now read event.registered. A test scans every scripts/ onEvent callback for raw payload reads, since the TypeScript check does not cover them. The storage verifier's pause trace records a malformed pause instead of the unregistered reason member. * refactor(browser): track the timeline's main frame with the document tracker (#10779) TimelineCapture kept its own mutable main frame id and replaced it on a root replacement. It now holds the CdpDocumentTracker that CdpTargetSession owns and observes the replacement document through it; every main-frame check (lifecycle, navigation, document request, redirect) reads the tracker's current frame. A characterization test pins that the replaced root's lifecycle events are no longer recorded. * refactor(browser): select CDP events only by their registered name (#10829) CdpReceivedEvent carried the wire method as a plain string, so a subscriber could compare it with a misspelt or unregistered name and the check compiled but never matched. Three owners selected Inspector.targetCrashed, an unregistered event, that way. Register Inspector.targetCrashed and drop the wire method from the received event. Subscribers select events by registered.method, whose type is the registered event names. The capture coverage start keeps reading the wire domain, now the event's domain field. * fix(browser): retire a policy child session that CDP reports gone After a listener failure the connection stops delivering events, so an iframe's Target.detachedFromTarget never retires its policy target. Cleanup then sent Page.removeScriptToEvaluateOnNewDocument to the dead session, kept the stale child, and every retry failed before detaching the root. The service-worker policy owner now treats CDP's session-not-found rejection as proof that the child is gone and retires it. The classifier moves from CdpTargetSession to CdpCommandRejection, its owner, and the target-session detach path uses the same one. * refactor(browser): route target events through one session owner (#10835) * refactor(browser): route target events through one session owner Page capture, WebMCP discovery, screenshot capture and the runtime sources each compared the envelope session ID themselves, while the observation window and execution collection used cdpTargetEventMatches, which also routes the root Target.detachedFromTarget that names the target's session. onCdpTargetEvent in CdpTargetEvents.ts now subscribes every target consumer with that one rule; the matcher is private and the per-subscriber comparisons are removed. Electron inspection keeps its own filter while its capture isolation awaits a maintainer decision. * fix(browser): report WebMCP subframe tools whose document is unverified (#10839) * fix(browser): report WebMCP subframe tools whose document is unverified A committed subframe navigation kept the frame's tools silently when CDP reported no loader at the same URL, and removed them on any URL change even when the loader proved the same document. Each frame now carries a CdpDocumentTracker, the session's document identity owner. Only a proven change removes the frame's tools. An unknown comparison keeps them visible, marks webmcp_tools attach-limited and names the frames whose document identity could not be established. * test(browser): prove an unverified live subframe limits WebMCP coverage * fix(browser): key a WebMCP registration by its frame and tool name A subframe tool kept across a committed navigation that changed the URL but not the loader was stored under a key built from the old URL, so a later toolsAdded for the same frame and name added a second entry. Registrations are now keyed by frame and name; tool_key still records the registering frame URL. * test(browser): deliver fake CDP events through the transport's admission (#10840) Event fakes each rebuilt the received event: CdpAgentHints typed its listeners as raw wire events behind an unknown cast, and the Electron, scenario-session and routing tests each wrapped receiveCdpEvent by hand. fakeCdpEvents (tests/fixtures) is a CdpConnection.onEvent fake whose emit admits each raw event with receiveCdpEvent and the wire byte count, so a change to the received event shape fails at the fake instead of silently not exercising subscribers. * refactor(browser): own the selected page generation in one target document tracker (#10860) * refactor(browser): own the selected page generation in one target document tracker Page capture, screenshot, the observation window, the runtime session and the execution window each built a document tracker or rule of their own from root-frame navigation events. CdpTargetDocument now follows the target session's root-frame events and the frame-tree replies its consumers read, classifies root identity once, and reports each navigation to consumers that decide only what it means for their evidence. * fix(browser): report a lost scenario policy connection before the next step (#10864) * fix(browser): report a lost scenario policy connection before the next step The service-worker policy recorded only protocol failures. When its CDP socket closed or its page session detached, later documents lost the blocking script, but the scenario learned of it only when a frame check found an unprotected realm. The owner now records the disconnect or detach when CDP reports it; the next policy check and the next step's action report it first. * fix(browser): refuse an unregistered CDP command before it reaches the browser (#10868) JavaScript verifiers can name any command, and the send owners refused an unregistered one only when its reply arrived, after the browser had acted on it. CdpConnection and the Playwright session now refuse the name before sending, and the Playwright session refuses an unregistered event name instead of subscribing to events no listener receives. The verifier text scan stays as an early warning and documents what it cannot see. * fix(browser): keep a proven root change and the loaderless selection's uncertainty Two review findings on the target document owner. A root event naming another frame with a malformed loader set `changed` but was announced as unidentified, so the execution window failed with protocol_error and dropped what it had collected; the owner now announces it as the proven change it is. The runtime session compared each frame-tree reply with the tracker's current document, which can learn a loader from an event, so a loaderless selection followed by an event and a reply with that loader compared as same; it now compares the reply with the selected document through the owner, and reports target_changed as before. * test(browser): refuse the next scenario step after the policy session detaches * refactor(browser): read WebMCP document identity from the target document owner (#10884) * refactor(browser): read WebMCP document identity from the target document owner WebMCP discovery compared the first and last frame-tree roots itself and kept a document tracker per subframe. CdpTargetDocument now follows the selected root and each committed subframe for it: the final frame tree feeds the owner, a root change proven by a navigation event during discovery is target_changed as in page capture, and a subframe whose committed document changed loses its tools. A subframe navigation without a loader still keeps the tools and reports them as unverified. * fix(browser): start a subframe first seen within its document with an unknown loader A subframe absent from the initial frame tree and first seen through Page.navigatedWithinDocument had no document tracker, so a later commit started a fresh one and the tools it registered meanwhile lost the unverified-document limitation. The owner now starts such a subframe with an unknown loader. * fix(browser): refuse a verifier's unregistered CDP event name at subscription (#10885) JavaScript verifiers subscribed to every event with CdpConnection.onEvent and compared registered.method with a string literal. A misspelt or unregistered name never matched and the verifier waited until its timeout. CdpConnection.onRegisteredEvent now takes one event name, refuses an unregistered one before subscribing (the same registry check the Playwright session applies), and hands the listener only that event's registered parse. The verifiers subscribe only through it, and the evaluation test rejects a raw onEvent subscription in scripts. * fix(browser): keep subframe documents by frame and loader without their URLs
605 lines
21 KiB
TypeScript
605 lines
21 KiB
TypeScript
import type { InspectWebPageInput } from "../domain/browserObservation.js";
|
|
import type { WebPageInspection } from "../domain/browserObservationSchemas.js";
|
|
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
|
import { BrowserObservationError } from "../domain/browserObservationError.js";
|
|
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
|
import {
|
|
AnalysisCancelledError,
|
|
OwnerCancellation,
|
|
} from "../domain/analysisErrorCore.js";
|
|
import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js";
|
|
import { stableWebResources } from "../domain/webInventory.js";
|
|
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
|
import { CdpConnection } from "./CdpConnection.js";
|
|
import { onCdpTargetEvent } from "./CdpTargetEvents.js";
|
|
import { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
|
import { authorizedMainFrame } from "./CdpAuthorizedMainFrame.js";
|
|
import { cdpOriginScopeRefusal } from "./CdpOriginScopeError.js";
|
|
import { captureStorage } from "./CdpCaptureStorage.js";
|
|
import { CdpTargetDocument } from "./CdpTargetDocument.js";
|
|
import {
|
|
cdpRootDocument,
|
|
unverifiedDocumentLimitation,
|
|
} from "./CdpTargetSession.js";
|
|
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
|
import { CdpCommandRejection } from "./CdpCommandRejection.js";
|
|
import {
|
|
captureAccessibility,
|
|
captureDom,
|
|
captureFrames,
|
|
captureResources,
|
|
emptyDomCapture,
|
|
excludeDocumentEvidence,
|
|
type CapturedResource,
|
|
type DomCapture,
|
|
} from "./CdpCaptureDocuments.js";
|
|
import { observedFrameUrl } from "./protocol/CdpFrameTree.js";
|
|
import {
|
|
CdpMalformedReply,
|
|
type CdpCommandResult,
|
|
} from "./protocol/CdpCommands.js";
|
|
import { capturedSvgNodeKind } from "./CdpCaptureDomNamespaces.js";
|
|
import {
|
|
allowedSanitizedUrl,
|
|
delayWithCancellation,
|
|
} from "./CdpCaptureValues.js";
|
|
import {
|
|
captureScripts,
|
|
finalizeScriptInventory,
|
|
} from "./CdpPageCaptureScripts.js";
|
|
import { captureWorkers } from "./CdpPageCaptureWorkers.js";
|
|
import type { WebSourceMapRequest } from "./WebSourceMapFetcher.js";
|
|
|
|
export interface CaptureContext {
|
|
readonly connection: CdpConnection;
|
|
readonly sessionId: string | undefined;
|
|
readonly operation: Extract<
|
|
BrowserObservationOperation,
|
|
"inspect_web_page" | "analyze_web_bundle"
|
|
>;
|
|
readonly discovery: CdpEndpointDiscovery;
|
|
readonly target: CdpEndpointTarget;
|
|
readonly input: InspectWebPageInput;
|
|
readonly signal?: AbortSignal;
|
|
readonly progress?: ProgressReporter;
|
|
}
|
|
|
|
interface CaptureState {
|
|
readonly context: CaptureContext;
|
|
readonly events: CdpCaptureEvents;
|
|
readonly allowedOrigins: ReadonlySet<string>;
|
|
readonly limitations: string[];
|
|
readonly startedAt: string;
|
|
}
|
|
|
|
interface CapturedSections {
|
|
readonly attachedUrl: string;
|
|
readonly frames: WebPageInspection["frames"];
|
|
readonly dom: DomCapture;
|
|
readonly accessibility: ReturnType<typeof captureAccessibility>;
|
|
readonly scripts: WebPageInspection["scripts"];
|
|
readonly resources: WebPageInspection["resources"];
|
|
readonly workers: WebPageInspection["workers"];
|
|
readonly storage: WebPageInspection["storage"];
|
|
}
|
|
|
|
export interface CapturedPage {
|
|
readonly inspection: WebPageInspection;
|
|
readonly sourceMapRequests: readonly WebSourceMapRequest[];
|
|
}
|
|
|
|
/** Capture and normalize one attached page without evaluating page JavaScript. */
|
|
export const capturePage = async (
|
|
context: CaptureContext,
|
|
): Promise<CapturedPage> => {
|
|
const allowedOrigins = new Set(context.input.allowed_origins);
|
|
const events = new CdpCaptureEvents(context.input, allowedOrigins);
|
|
const removeListener = onCdpTargetEvent(
|
|
context.connection,
|
|
context.sessionId,
|
|
(event) => events.ingest(event),
|
|
);
|
|
const state: CaptureState = {
|
|
context,
|
|
events,
|
|
allowedOrigins,
|
|
limitations: [
|
|
...(context.discovery.limitations ?? []),
|
|
"Observation starts when REA attaches; prior network and console activity is unavailable.",
|
|
"Worker targets are a final inventory snapshot, not worker-session observation. Their attached flag describes any debugging client; this page-session collector does not observe worker network, console, or script events, and short-lived workers may be absent from the snapshot.",
|
|
"Raw network headers, bodies, cookies, storage values, console objects, and WebSocket payloads are never retained; explicitly requested primitive console text is retained verbatim, while payload captures retain value-free shapes.",
|
|
"Source maps are reported only as declarative URLs and are not fetched.",
|
|
"URL-less scripts and console events without an allowed source URL are excluded because their origin cannot be proven.",
|
|
...(context.target.attached === null
|
|
? [
|
|
"CDP discovery could not establish the target's debugger attachment state.",
|
|
]
|
|
: []),
|
|
],
|
|
startedAt: new Date().toISOString(),
|
|
};
|
|
try {
|
|
return await captureAuthorizedPage(state);
|
|
} catch (cause: unknown) {
|
|
// A navigation can invalidate an in-flight script ID or another document
|
|
// read. Report the observed capture invalidation before its stale-read
|
|
// symptom, while preserving caller cancellation.
|
|
if (
|
|
context.signal?.aborted !== true &&
|
|
!(cause instanceof AnalysisCancelledError) &&
|
|
!(cause instanceof AnalysisError && cause.userCategory === "cancelled")
|
|
)
|
|
assertObservedCaptureValid(state, cause);
|
|
throw cause;
|
|
} finally {
|
|
removeListener();
|
|
events.document?.close();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* A document change is reported first, carrying any failure it caused. Scope
|
|
* applies to the current document only when the selected one is unchanged.
|
|
*/
|
|
const assertObservedCaptureValid = (
|
|
state: CaptureState,
|
|
cause?: unknown,
|
|
): void => {
|
|
const reason =
|
|
state.events.document?.changed === true
|
|
? "target_changed"
|
|
: state.events.unknownRootIdentity
|
|
? "protocol_error"
|
|
: state.events.originViolation
|
|
? "target_not_allowed"
|
|
: undefined;
|
|
if (reason === "target_not_allowed")
|
|
throw cdpOriginScopeRefusal(state.context.operation, { cause });
|
|
if (reason !== undefined) {
|
|
if (cause instanceof BrowserObservationError && cause.reason === reason)
|
|
throw cause;
|
|
throw new BrowserObservationError(state.context.operation, reason, {
|
|
cause,
|
|
});
|
|
}
|
|
};
|
|
|
|
const captureAuthorizedPage = async (
|
|
state: CaptureState,
|
|
): Promise<CapturedPage> => {
|
|
const { context, allowedOrigins, limitations } = state;
|
|
const { input } = context;
|
|
await authorizeObservationWindow(state);
|
|
await captureJsonResponseBodies(state);
|
|
const frameResult = await authorizedMainFrame({
|
|
connection: context.connection,
|
|
sessionId: context.sessionId,
|
|
signal: context.signal,
|
|
allowedOrigins,
|
|
operation: context.operation,
|
|
document: state.events.document,
|
|
});
|
|
const attachedUrl = observedFrameUrl(frameResult.root.url) ?? "";
|
|
const frameCapture = captureFrames(
|
|
frameResult,
|
|
allowedOrigins,
|
|
undefined,
|
|
state.events.completeness,
|
|
);
|
|
const frames = frameCapture.items;
|
|
const captureDocument = cdpRootDocument(frameResult);
|
|
if (frameCapture.root === undefined || captureDocument === undefined)
|
|
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
|
assertObservedCaptureValid(state);
|
|
const resourceCapture = await capturePageResources(state);
|
|
const resources = stableWebResources(
|
|
resourceCapture.items.map(publicResource),
|
|
);
|
|
const dom = await capturePageDom(state);
|
|
const accessibility = await accessibilityForFrames(state, frames);
|
|
const scripts = await captureScripts({
|
|
context,
|
|
events: state.events,
|
|
rawResources: resourceCapture.items,
|
|
resources,
|
|
frameIds: new Set(frames.map((frame) => frame.frame_id)),
|
|
});
|
|
const workers = await captureWorkers(
|
|
{ context, allowedOrigins, limitations, events: state.events },
|
|
new Set(frames.map((frame) => frame.frame_id)),
|
|
);
|
|
const storageCapture = await captureStorage(
|
|
context,
|
|
attachedUrl,
|
|
limitations,
|
|
);
|
|
if (!input.include_storage_keys)
|
|
state.events.completeness.exclude("storage_keys", "not_approved", null);
|
|
else if (storageCapture.keysExclusion !== undefined)
|
|
state.events.completeness.exclude(
|
|
"storage_keys",
|
|
storageCapture.keysExclusion,
|
|
null,
|
|
);
|
|
await report(context.progress, 3, "Normalizing browser evidence");
|
|
await assertCompletedDocument(state);
|
|
// Body IDs were enumerated before asynchronous CDP reads. Events remain
|
|
// enabled through the final capture, so account for eligible responses that
|
|
// arrived while those reads were pending.
|
|
state.events.settleUnexaminedResponseBodies();
|
|
const scriptInventory = finalizeScriptInventory(scripts, state.events);
|
|
state.events.recordScriptMetadataBudgetExclusions();
|
|
return {
|
|
inspection: normalizedInspection(state, {
|
|
attachedUrl,
|
|
frames,
|
|
dom,
|
|
accessibility,
|
|
scripts: scriptInventory,
|
|
resources,
|
|
workers,
|
|
storage: storageCapture.value,
|
|
}),
|
|
sourceMapRequests: scripts.sourceMapRequests,
|
|
};
|
|
};
|
|
|
|
/** Compare the final document first; scope then applies to that document. */
|
|
const assertCompletedDocument = async (state: CaptureState): Promise<void> => {
|
|
const { context, allowedOrigins, events } = state;
|
|
const completed = await context.connection.send(
|
|
"Page.getFrameTree",
|
|
{},
|
|
context.sessionId,
|
|
context.signal,
|
|
);
|
|
const comparison = events.document?.observeTree(completed);
|
|
assertObservedCaptureValid(state);
|
|
if (comparison === undefined)
|
|
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
|
await authorizedMainFrame({
|
|
connection: context.connection,
|
|
sessionId: context.sessionId,
|
|
signal: context.signal,
|
|
allowedOrigins,
|
|
operation: context.operation,
|
|
initial: completed,
|
|
document: events.document,
|
|
});
|
|
// Navigation events can arrive while an unavailable URL is retried.
|
|
assertObservedCaptureValid(state);
|
|
if (events.document?.unknown === true) {
|
|
events.completeness.attachLimited("frames");
|
|
state.limitations.push(
|
|
unverifiedDocumentLimitation(events.document.selected),
|
|
);
|
|
}
|
|
};
|
|
|
|
/** A malformed resource tree omits only the resource inventory, never empties it. */
|
|
const capturePageResources = async (
|
|
state: CaptureState,
|
|
): Promise<ReturnType<typeof captureResources>> => {
|
|
const { connection, sessionId, signal } = state.context;
|
|
try {
|
|
return captureResources(
|
|
await connection.send("Page.getResourceTree", {}, sessionId, signal),
|
|
state.allowedOrigins,
|
|
state.events.completeness,
|
|
);
|
|
} catch (cause: unknown) {
|
|
if (!(cause instanceof CdpMalformedReply)) throw cause;
|
|
state.events.completeness.exclude(
|
|
"resources",
|
|
"invalid_protocol_value",
|
|
null,
|
|
);
|
|
return { items: [] };
|
|
}
|
|
};
|
|
|
|
const captureJsonResponseBodies = async (
|
|
state: CaptureState,
|
|
): Promise<void> => {
|
|
const requests = state.events.responseBodyRequests();
|
|
for (let index = 0; index < requests.length; index += 1) {
|
|
const candidate = requests[index];
|
|
if (candidate === undefined) continue;
|
|
const current = state.events.currentResponseBodyRequest(candidate);
|
|
if (current === undefined) continue;
|
|
if (current.encoded_data_length === null) {
|
|
state.events.responseBodyUnavailable(candidate);
|
|
continue;
|
|
}
|
|
let reply: Awaited<
|
|
ReturnType<typeof optionalCdpCommand<"Network.getResponseBody">>
|
|
>;
|
|
try {
|
|
reply = await optionalCdpCommand(
|
|
state.context,
|
|
"Network.getResponseBody",
|
|
{ requestId: candidate.requestId },
|
|
state.limitations,
|
|
);
|
|
} catch (cause: unknown) {
|
|
if (
|
|
!(cause instanceof CdpCommandRejection) ||
|
|
cause.command !== "Network.getResponseBody" ||
|
|
cause.code !== -32_000 ||
|
|
cause.reportedMessage === null
|
|
)
|
|
throw cause;
|
|
state.events.responseBodyUnavailable(candidate);
|
|
state.limitations.push(
|
|
`Response body unavailable for request ${candidate.requestId}: ${cause.userMessage}`,
|
|
);
|
|
continue;
|
|
}
|
|
if (reply.ok || reply.error._tag === "CdpMalformedReply") {
|
|
state.events.ingestResponseBody(
|
|
candidate,
|
|
reply.ok ? reply.value : "malformed",
|
|
);
|
|
continue;
|
|
}
|
|
for (const remaining of requests.slice(index))
|
|
state.events.responseBodyUnavailable(remaining);
|
|
return;
|
|
}
|
|
};
|
|
|
|
const authorizeObservationWindow = async (
|
|
state: CaptureState,
|
|
): Promise<void> => {
|
|
const { context, allowedOrigins, events } = state;
|
|
const { connection, sessionId, signal } = context;
|
|
await report(context.progress, 1, "Enabling passive CDP domains");
|
|
await connection.send("Page.enable", {}, sessionId, signal);
|
|
const initialFrameResult = await authorizedMainFrame({
|
|
connection: context.connection,
|
|
sessionId: context.sessionId,
|
|
signal: context.signal,
|
|
allowedOrigins,
|
|
operation: context.operation,
|
|
});
|
|
const mainFrame = captureFrames(initialFrameResult, allowedOrigins).root;
|
|
const document = cdpRootDocument(initialFrameResult);
|
|
if (mainFrame === undefined || document === undefined)
|
|
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
|
events.beginAuthorizedFrame(CdpTargetDocument.watch(context, document));
|
|
await enableObservationDomains(state);
|
|
await report(context.progress, 2, "Observing page events");
|
|
await delayWithCancellation(
|
|
context.input.observation_ms,
|
|
context.operation,
|
|
signal,
|
|
);
|
|
assertObservedCaptureValid(state);
|
|
};
|
|
|
|
const capturePageDom = async (state: CaptureState): Promise<DomCapture> => {
|
|
const { context, allowedOrigins } = state;
|
|
let result: CdpCommandResult<"DOMSnapshot.captureSnapshot">;
|
|
try {
|
|
result = await context.connection.send(
|
|
"DOMSnapshot.captureSnapshot",
|
|
{
|
|
computedStyles: [],
|
|
includePaintOrder: false,
|
|
includeDOMRects: false,
|
|
},
|
|
context.sessionId,
|
|
context.signal,
|
|
);
|
|
} catch (cause: unknown) {
|
|
// A malformed snapshot leaves the DOM and its derived metadata unknown.
|
|
if (!(cause instanceof CdpMalformedReply)) throw cause;
|
|
excludeDocumentEvidence(
|
|
state.events.completeness,
|
|
"invalid_protocol_value",
|
|
null,
|
|
);
|
|
return emptyDomCapture;
|
|
}
|
|
const capture = captureDom(
|
|
result,
|
|
allowedOrigins,
|
|
context.input,
|
|
state.events.completeness,
|
|
);
|
|
let step = capture.next();
|
|
let descriptionUnavailable = false;
|
|
const pendingController = new AbortController();
|
|
const signal =
|
|
context.signal === undefined
|
|
? pendingController.signal
|
|
: AbortSignal.any([context.signal, pendingController.signal]);
|
|
while (!step.done) {
|
|
const pending = step.value.map(async (query) => {
|
|
if (descriptionUnavailable) return undefined;
|
|
try {
|
|
return capturedSvgNodeKind(
|
|
query,
|
|
await context.connection.send(
|
|
"DOM.describeNode",
|
|
{ backendNodeId: query.backendNodeId, depth: 0 },
|
|
context.sessionId,
|
|
signal,
|
|
),
|
|
);
|
|
} catch (cause: unknown) {
|
|
// A detached node can disappear between snapshot and description, and
|
|
// one malformed description leaves only that node's kind unknown.
|
|
// Preserve partial metadata, but propagate transport/cancellation errors.
|
|
if (cause instanceof CdpMalformedReply) return undefined;
|
|
if (!(cause instanceof CdpCommandRejection)) throw cause;
|
|
if (cause.code === -32_601) descriptionUnavailable = true;
|
|
else if (cause.code !== -32_000) throw cause;
|
|
return undefined;
|
|
}
|
|
});
|
|
try {
|
|
// Promise.all preserves snapshot order even when CDP replies out of order.
|
|
step = capture.next(await Promise.all(pending));
|
|
} catch (cause: unknown) {
|
|
// Stop and settle this bounded batch before the session can be detached.
|
|
pendingController.abort(OwnerCancellation.noLongerNeeded);
|
|
await Promise.allSettled(pending);
|
|
throw cause;
|
|
}
|
|
}
|
|
if (step.value.unresolvedSvgNodes > 0)
|
|
state.limitations.push(
|
|
`SVG identity was unavailable for ${String(step.value.unresolvedSvgNodes)} snapshotted XLink candidate nodes; their URL destinations remain unknown.`,
|
|
);
|
|
return step.value;
|
|
};
|
|
|
|
const normalizedInspection = (
|
|
state: CaptureState,
|
|
captured: CapturedSections,
|
|
): WebPageInspection => ({
|
|
browser: state.context.discovery.version,
|
|
target: normalizedTarget(
|
|
state.context.target,
|
|
captured.attachedUrl,
|
|
state.allowedOrigins,
|
|
),
|
|
capture_window: {
|
|
started_at: state.startedAt,
|
|
ended_at: new Date().toISOString(),
|
|
observation_ms: state.context.input.observation_ms,
|
|
},
|
|
completeness: state.events.completeness.snapshot(),
|
|
frames: [...captured.frames],
|
|
dom: {
|
|
total_nodes: captured.dom.total,
|
|
node_value_length_unit: captured.dom.nodeValueLengthUnit,
|
|
nodes: [...captured.dom.nodes],
|
|
},
|
|
accessibility: {
|
|
total_nodes: captured.accessibility.total,
|
|
text_capture: captured.accessibility.textCapture,
|
|
nodes: [...captured.accessibility.nodes],
|
|
},
|
|
scripts: captured.scripts,
|
|
resources: [...captured.resources],
|
|
network: {
|
|
requests: [...state.events.network.values()],
|
|
websocket_connections: [...state.events.webSocketConnectionsById.values()],
|
|
coverage_started_at: state.events.coverageStartedAt("Network"),
|
|
prior_activity_available: false,
|
|
},
|
|
console: {
|
|
events: [...state.events.console],
|
|
coverage_started_at: state.events.coverageStartedAt("Runtime"),
|
|
prior_activity_available: false,
|
|
},
|
|
workers: [...captured.workers],
|
|
metadata: {
|
|
responses: [...state.events.responseMetadata],
|
|
dom_urls: [...captured.dom.urls],
|
|
agent_hints: deduplicatedAgentHints([
|
|
...state.events.agentHints,
|
|
...captured.dom.agentHints,
|
|
]),
|
|
excluded_dom_urls: captured.dom.excludedUrls,
|
|
headers_allowlisted: true,
|
|
},
|
|
storage: captured.storage,
|
|
limitations: state.limitations,
|
|
});
|
|
|
|
const enableObservationDomains = async (state: CaptureState): Promise<void> => {
|
|
const { connection, sessionId, signal } = state.context;
|
|
await connection.send("Runtime.enable", {}, sessionId, signal);
|
|
state.events.markDomainEnabled("Runtime");
|
|
await connection.send("Debugger.enable", {}, sessionId, signal);
|
|
await connection.send("Network.enable", {}, sessionId, signal);
|
|
state.events.markDomainEnabled("Network");
|
|
};
|
|
|
|
const accessibilityForFrames = async (
|
|
state: CaptureState,
|
|
frames: readonly { readonly frame_id: string }[],
|
|
): Promise<ReturnType<typeof captureAccessibility>> => {
|
|
const { context, limitations, events } = state;
|
|
const results: CdpCommandResult<"Accessibility.getFullAXTree">[] = [];
|
|
let unavailable = false;
|
|
for (const frame of frames) {
|
|
const reply = await optionalCdpCommand(
|
|
context,
|
|
"Accessibility.getFullAXTree",
|
|
{ frameId: frame.frame_id },
|
|
limitations,
|
|
);
|
|
if (reply.ok) results.push(reply.value);
|
|
else if (reply.error._tag === "CdpCommandUnavailable") unavailable = true;
|
|
else
|
|
events.completeness.exclude(
|
|
"accessibility",
|
|
"invalid_protocol_value",
|
|
null,
|
|
);
|
|
}
|
|
if (unavailable) events.completeness.unavailable("accessibility");
|
|
const capture = captureAccessibility(results, {
|
|
includeText: context.input.include_accessibility_text,
|
|
...(results.length === 0 && unavailable ? { unavailable: true } : {}),
|
|
completeness: events.completeness,
|
|
});
|
|
if (!context.input.include_accessibility_text)
|
|
events.completeness.exclude(
|
|
"accessibility",
|
|
"not_approved",
|
|
capture.textCapture.excluded_fields,
|
|
);
|
|
if (capture.hasUnobservedChildren)
|
|
events.completeness.truncate("accessibility");
|
|
return capture;
|
|
};
|
|
|
|
const publicResource = ({ rawUrl: _rawUrl, ...resource }: CapturedResource) =>
|
|
resource;
|
|
|
|
const deduplicatedAgentHints = (
|
|
hints: WebPageInspection["metadata"]["agent_hints"],
|
|
): WebPageInspection["metadata"]["agent_hints"] => {
|
|
const seen = new Set<string>();
|
|
return hints.filter((hint) => {
|
|
const key = `${hint.mechanism}\0${hint.declaration}\0${hint.url ?? ""}`;
|
|
if (seen.has(key)) return false;
|
|
seen.add(key);
|
|
return true;
|
|
});
|
|
};
|
|
|
|
const normalizedTarget = (
|
|
target: CdpEndpointTarget,
|
|
currentUrl: string,
|
|
allowedOrigins: ReadonlySet<string>,
|
|
): WebPageInspection["target"] => {
|
|
const url = allowedSanitizedUrl(currentUrl, allowedOrigins);
|
|
return {
|
|
target_id: target.id,
|
|
type: target.type,
|
|
title: target.title,
|
|
url: url?.url ?? "[unsupported-url]",
|
|
origin: url?.origin ?? "",
|
|
attached: target.attached,
|
|
};
|
|
};
|
|
|
|
const report = async (
|
|
progress: ProgressReporter | undefined,
|
|
completed: number,
|
|
message: string,
|
|
): Promise<void> =>
|
|
await progress?.report({
|
|
phase: "browser_observation",
|
|
completed,
|
|
total: 3,
|
|
message,
|
|
...(completed === 3 ? { terminal: true } : {}),
|
|
});
|