feat: add passive website reverse engineering
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
import type { BrowserObservationPort } from "../application/BrowserObservationPort.js";
|
||||
import type { ProviderIdentity } from "../application/AnalysisProvider.js";
|
||||
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
|
||||
import {
|
||||
browserTargetListSchema,
|
||||
sanitizeBrowserUrl,
|
||||
webPageInspectionSchema,
|
||||
type BrowserTargetList,
|
||||
type InspectWebPageInput,
|
||||
type ListBrowserTargetsInput,
|
||||
type WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
BrowserObservationError,
|
||||
ProviderAdapterError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import {
|
||||
discoverCdpEndpoint,
|
||||
type CdpEndpointDiscovery,
|
||||
type CdpEndpointTarget,
|
||||
} from "./CdpEndpoint.js";
|
||||
import { capturePage } from "./CdpPageCapture.js";
|
||||
|
||||
const IDENTITY: ProviderIdentity = {
|
||||
id: "rea-cdp-browser",
|
||||
name: "REA Chrome DevTools Protocol observation provider",
|
||||
version: "1",
|
||||
};
|
||||
|
||||
/** Passive, origin-scoped browser observation through a user-owned CDP endpoint. */
|
||||
export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
identity(): ProviderIdentity {
|
||||
return IDENTITY;
|
||||
}
|
||||
|
||||
async listTargets(
|
||||
input: ListBrowserTargetsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<BrowserTargetList, AnalysisError>> {
|
||||
try {
|
||||
const discovery = await discoverCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
"list_browser_targets",
|
||||
options.signal,
|
||||
);
|
||||
const allowedOrigins = new Set(input.allowed_origins);
|
||||
const selected = selectTargets(discovery, allowedOrigins);
|
||||
const items = selected.allowed.slice(
|
||||
input.offset,
|
||||
input.offset + input.limit,
|
||||
);
|
||||
const nextOffset = input.offset + items.length;
|
||||
return ok(
|
||||
browserTargetListSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: discovery.version,
|
||||
targets: {
|
||||
items,
|
||||
offset: input.offset,
|
||||
limit: input.limit,
|
||||
total: selected.allowed.length,
|
||||
next_offset:
|
||||
nextOffset < selected.allowed.length ? nextOffset : null,
|
||||
has_more: nextOffset < selected.allowed.length,
|
||||
},
|
||||
excluded: selected.excluded,
|
||||
limitations: [
|
||||
"Only page targets whose current URL matches an approved exact origin are listed.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "list_browser_targets"));
|
||||
}
|
||||
}
|
||||
|
||||
async inspectPage(
|
||||
input: InspectWebPageInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<WebPageInspection, AnalysisError>> {
|
||||
let connection: CdpConnection | undefined;
|
||||
let sessionId: string | undefined;
|
||||
try {
|
||||
const discovery = await discoverCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
"inspect_web_page",
|
||||
options.signal,
|
||||
);
|
||||
const target = authorizeTarget(discovery, input);
|
||||
connection = await CdpConnection.connect(
|
||||
discovery.browserWebSocketUrl,
|
||||
options.signal,
|
||||
);
|
||||
const attached = await connection.send(
|
||||
"Target.attachToTarget",
|
||||
{ targetId: target.id, flatten: true },
|
||||
undefined,
|
||||
options.signal,
|
||||
);
|
||||
sessionId = attachedSessionId(attached);
|
||||
const result = await capturePage({
|
||||
connection,
|
||||
sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
: { progress: options.progress }),
|
||||
});
|
||||
return ok(webPageInspectionSchema.parse(result));
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "inspect_web_page"));
|
||||
} finally {
|
||||
if (connection !== undefined) {
|
||||
if (sessionId !== undefined)
|
||||
await bestEffortCleanup(connection, sessionId);
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const selectTargets = (
|
||||
discovery: CdpEndpointDiscovery,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): {
|
||||
readonly allowed: readonly BrowserTargetList["targets"]["items"][number][];
|
||||
readonly excluded: BrowserTargetList["excluded"];
|
||||
} => {
|
||||
const allowed = [];
|
||||
let disallowedOrigin = 0;
|
||||
let unsupportedUrl = 0;
|
||||
let nonPage = 0;
|
||||
for (const target of discovery.targets) {
|
||||
if (target.type !== "page") {
|
||||
nonPage += 1;
|
||||
continue;
|
||||
}
|
||||
const url = sanitizeBrowserUrl(target.url);
|
||||
if (url.origin === null) {
|
||||
unsupportedUrl += 1;
|
||||
continue;
|
||||
}
|
||||
if (!allowedOrigins.has(url.origin)) {
|
||||
disallowedOrigin += 1;
|
||||
continue;
|
||||
}
|
||||
allowed.push({
|
||||
target_id: target.id,
|
||||
type: target.type,
|
||||
title: target.title.slice(0, 16_384),
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
attached: target.attached,
|
||||
});
|
||||
}
|
||||
allowed.sort((left, right) => left.target_id.localeCompare(right.target_id));
|
||||
return {
|
||||
allowed,
|
||||
excluded: {
|
||||
disallowed_origin: disallowedOrigin,
|
||||
unsupported_url: unsupportedUrl,
|
||||
non_page: nonPage,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const authorizeTarget = (
|
||||
discovery: CdpEndpointDiscovery,
|
||||
input: InspectWebPageInput,
|
||||
): CdpEndpointTarget => {
|
||||
const target = discovery.targets.find(
|
||||
(candidate) => candidate.id === input.target_id,
|
||||
);
|
||||
if (target === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_found");
|
||||
const origin = sanitizeBrowserUrl(target.url).origin;
|
||||
if (
|
||||
target.type !== "page" ||
|
||||
origin === null ||
|
||||
!input.allowed_origins.includes(origin)
|
||||
)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
return target;
|
||||
};
|
||||
|
||||
const attachedSessionId = (value: unknown): string => {
|
||||
if (typeof value !== "object" || value === null || !("sessionId" in value))
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
if (typeof value.sessionId !== "string" || value.sessionId.length > 256)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
return value.sessionId;
|
||||
};
|
||||
|
||||
const bestEffortCleanup = async (
|
||||
connection: CdpConnection,
|
||||
sessionId: string,
|
||||
): Promise<void> => {
|
||||
for (const method of [
|
||||
"Network.disable",
|
||||
"Debugger.disable",
|
||||
"Runtime.disable",
|
||||
"Page.disable",
|
||||
]) {
|
||||
try {
|
||||
await connection.send(method, {}, sessionId);
|
||||
} catch {
|
||||
// Cleanup continues so detach is still attempted.
|
||||
}
|
||||
}
|
||||
try {
|
||||
await connection.send("Target.detachFromTarget", { sessionId });
|
||||
} catch {
|
||||
// Closing REA's socket is the final non-destructive cleanup boundary.
|
||||
}
|
||||
};
|
||||
|
||||
const providerError = (
|
||||
cause: unknown,
|
||||
operation: "list_browser_targets" | "inspect_web_page",
|
||||
): AnalysisError =>
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderAdapterError(IDENTITY.id, operation, { cause });
|
||||
@@ -0,0 +1,198 @@
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
requiredRecord,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
/** Normalize allowed frames while retaining a bounded prefix and total count. */
|
||||
export const captureFrames = (
|
||||
result: unknown,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
maximum: number,
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["frames"];
|
||||
} => {
|
||||
const root = recordValue(requiredRecord(result).frameTree);
|
||||
if (root === undefined) return { total: 0, items: [] };
|
||||
const items: WebPageInspection["frames"] = [];
|
||||
let total = 0;
|
||||
for (const tree of walkFrameTrees(root)) {
|
||||
const frame = recordValue(tree.frame);
|
||||
const frameId = stringValue(frame?.id);
|
||||
const sanitized = allowedSanitizedUrl(frame?.url, allowedOrigins);
|
||||
if (
|
||||
frame === undefined ||
|
||||
frameId === undefined ||
|
||||
frameId.length > 256 ||
|
||||
sanitized === undefined ||
|
||||
sanitized.origin === null
|
||||
)
|
||||
continue;
|
||||
total += 1;
|
||||
if (items.length >= maximum) continue;
|
||||
items.push({
|
||||
frame_id: frameId,
|
||||
parent_frame_id:
|
||||
(stringValue(frame.parentId) ?? "").slice(0, 256) || null,
|
||||
url: sanitized.url,
|
||||
origin: sanitized.origin,
|
||||
});
|
||||
}
|
||||
return { total, items };
|
||||
};
|
||||
|
||||
/** Read the current main-frame URL from an untrusted Page.getFrameTree result. */
|
||||
export const mainFrameUrl = (result: unknown): string | undefined =>
|
||||
stringValue(
|
||||
recordValue(recordValue(requiredRecord(result).frameTree)?.frame)?.url,
|
||||
);
|
||||
|
||||
/** Normalize allowed resources while retaining a bounded prefix and total count. */
|
||||
export const captureResources = (
|
||||
result: unknown,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
maximum: number,
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["resources"];
|
||||
} => {
|
||||
const root = recordValue(requiredRecord(result).frameTree);
|
||||
if (root === undefined) return { total: 0, items: [] };
|
||||
const items: WebPageInspection["resources"] = [];
|
||||
let total = 0;
|
||||
for (const tree of walkFrameTrees(root)) {
|
||||
for (const resource of recordsValue(tree.resources)) {
|
||||
const url = allowedSanitizedUrl(resource.url, allowedOrigins);
|
||||
if (url === undefined || url.origin === null) continue;
|
||||
total += 1;
|
||||
if (items.length >= maximum) continue;
|
||||
const contentSize = numberValue(resource.contentSize);
|
||||
items.push({
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
type: (stringValue(resource.type) ?? "Other").slice(0, 100),
|
||||
mime_type: (stringValue(resource.mimeType) ?? "").slice(0, 256),
|
||||
content_size:
|
||||
contentSize === undefined ? null : Math.max(0, contentSize),
|
||||
});
|
||||
}
|
||||
}
|
||||
return { total, items };
|
||||
};
|
||||
|
||||
const walkFrameTrees = function* (
|
||||
root: UnknownRecord,
|
||||
): Generator<UnknownRecord> {
|
||||
const pending = [root];
|
||||
while (pending.length > 0) {
|
||||
const tree = pending.pop();
|
||||
if (tree === undefined) return;
|
||||
const children = recordsValue(tree.childFrames);
|
||||
for (let index = children.length - 1; index >= 0; index -= 1) {
|
||||
const child = children[index];
|
||||
if (child !== undefined) pending.push(child);
|
||||
}
|
||||
yield tree;
|
||||
}
|
||||
};
|
||||
|
||||
export const captureDom = (
|
||||
result: unknown,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
input: InspectWebPageInput,
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly nodes: WebPageInspection["dom"]["nodes"];
|
||||
} => {
|
||||
const root = requiredRecord(result);
|
||||
const strings = Array.isArray(root.strings)
|
||||
? root.strings.map((value) => stringValue(value) ?? "")
|
||||
: [];
|
||||
const nodes: WebPageInspection["dom"]["nodes"] = [];
|
||||
let total = 0;
|
||||
for (const document of recordsValue(root.documents)) {
|
||||
const documentUrl = indexedString(strings, document.documentURL);
|
||||
if (allowedSanitizedUrl(documentUrl, allowedOrigins) === undefined)
|
||||
continue;
|
||||
const documentNodes = recordValue(document.nodes);
|
||||
if (documentNodes === undefined) continue;
|
||||
const nodeTypes = numberArray(documentNodes.nodeType);
|
||||
const nodeNames = numberArray(documentNodes.nodeName);
|
||||
const nodeValues = numberArray(documentNodes.nodeValue);
|
||||
const parents = numberArray(documentNodes.parentIndex);
|
||||
const attributes = Array.isArray(documentNodes.attributes)
|
||||
? documentNodes.attributes
|
||||
: [];
|
||||
const baseIndex = nodes.length;
|
||||
total += nodeTypes.length;
|
||||
for (
|
||||
let index = 0;
|
||||
index < nodeTypes.length && nodes.length < input.limits.max_dom_nodes;
|
||||
index += 1
|
||||
) {
|
||||
const attributeIndexes = numberArray(attributes[index]);
|
||||
const parent = Math.trunc(parents[index] ?? -1);
|
||||
nodes.push({
|
||||
index: nodes.length,
|
||||
parent_index: parent < 0 ? -1 : baseIndex + parent,
|
||||
node_type: Math.max(0, Math.trunc(nodeTypes[index] ?? 0)),
|
||||
node_name: indexedString(strings, nodeNames[index]).slice(0, 256),
|
||||
node_value_length: indexedString(strings, nodeValues[index]).length,
|
||||
attribute_names: attributeIndexes
|
||||
.filter((_value, attributeIndex) => attributeIndex % 2 === 0)
|
||||
.map((value) => indexedString(strings, value).slice(0, 256))
|
||||
.slice(0, 200),
|
||||
});
|
||||
}
|
||||
}
|
||||
return { total, nodes };
|
||||
};
|
||||
|
||||
export const captureAccessibility = (
|
||||
results: readonly unknown[],
|
||||
maximum: number,
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly nodes: WebPageInspection["accessibility"]["nodes"];
|
||||
} => {
|
||||
const all = results.flatMap((result) =>
|
||||
recordsValue(requiredRecord(result).nodes),
|
||||
);
|
||||
return {
|
||||
total: all.length,
|
||||
nodes: all.slice(0, maximum).map((node) => ({
|
||||
node_id: (stringValue(node.nodeId) ?? "").slice(0, 256),
|
||||
parent_id: (stringValue(node.parentId) ?? "").slice(0, 256) || null,
|
||||
role: axText(node.role),
|
||||
name: axText(node.name),
|
||||
description: axText(node.description),
|
||||
ignored: node.ignored === true,
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
const axText = (value: unknown): string | null =>
|
||||
boundedText(recordValue(value)?.value, 1_024);
|
||||
|
||||
const indexedString = (strings: readonly string[], index: unknown): string => {
|
||||
const integer = numberValue(index);
|
||||
return integer === undefined ? "" : (strings[Math.trunc(integer)] ?? "");
|
||||
};
|
||||
|
||||
const numberArray = (value: unknown): readonly number[] =>
|
||||
Array.isArray(value)
|
||||
? value.flatMap((item) => {
|
||||
const number = numberValue(item);
|
||||
return number === undefined ? [] : [number];
|
||||
})
|
||||
: [];
|
||||
@@ -0,0 +1,300 @@
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { CdpEvent } from "./CdpConnection.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
export interface CapturedScript {
|
||||
readonly scriptId: string;
|
||||
readonly url: string;
|
||||
readonly origin: string | null;
|
||||
readonly hash: string;
|
||||
readonly length: number;
|
||||
readonly isModule: boolean;
|
||||
readonly language: string | null;
|
||||
readonly sourceMapUrl: string | null;
|
||||
}
|
||||
|
||||
type NetworkState = WebPageInspection["network"]["requests"][number];
|
||||
|
||||
/** Bounded event accumulator that drops payload values at ingestion time. */
|
||||
export class CdpCaptureEvents {
|
||||
readonly scripts = new Map<string, CapturedScript>();
|
||||
readonly network = new Map<string, NetworkState>();
|
||||
readonly allowedWebSockets = new Set<string>();
|
||||
readonly console: WebPageInspection["console"]["events"] = [];
|
||||
readonly websockets: WebPageInspection["network"]["websocket_events"] = [];
|
||||
dropped = 0;
|
||||
originViolation = false;
|
||||
navigationDuringCapture = false;
|
||||
#mainFrameId: string | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly input: InspectWebPageInput,
|
||||
private readonly allowedOrigins: ReadonlySet<string>,
|
||||
) {}
|
||||
|
||||
beginAuthorizedFrame(frameId: string): void {
|
||||
this.#mainFrameId = frameId;
|
||||
this.originViolation = false;
|
||||
this.navigationDuringCapture = false;
|
||||
this.dropped = 0;
|
||||
this.scripts.clear();
|
||||
this.network.clear();
|
||||
this.allowedWebSockets.clear();
|
||||
this.console.length = 0;
|
||||
this.websockets.length = 0;
|
||||
}
|
||||
|
||||
beginFinalCapture(frameId: string): void {
|
||||
this.#mainFrameId = frameId;
|
||||
this.navigationDuringCapture = false;
|
||||
}
|
||||
|
||||
ingest(event: CdpEvent): void {
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return;
|
||||
switch (event.method) {
|
||||
case "Debugger.scriptParsed":
|
||||
this.#script(params);
|
||||
break;
|
||||
case "Network.requestWillBeSent":
|
||||
this.#request(params);
|
||||
break;
|
||||
case "Network.responseReceived":
|
||||
this.#response(params);
|
||||
break;
|
||||
case "Network.loadingFinished":
|
||||
this.#finished(params);
|
||||
break;
|
||||
case "Runtime.consoleAPICalled":
|
||||
this.#console(params);
|
||||
break;
|
||||
case "Page.frameNavigated":
|
||||
this.#frameNavigated(params);
|
||||
break;
|
||||
case "Network.webSocketCreated":
|
||||
this.#websocketCreated(params);
|
||||
break;
|
||||
case "Network.webSocketFrameSent":
|
||||
this.#websocket(params, "sent");
|
||||
break;
|
||||
case "Network.webSocketFrameReceived":
|
||||
this.#websocket(params, "received");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#script(params: UnknownRecord): void {
|
||||
const scriptId = stringValue(params.scriptId);
|
||||
const rawUrl = stringValue(params.url) ?? "";
|
||||
const sanitized = allowedSanitizedUrl(rawUrl, this.allowedOrigins);
|
||||
if (
|
||||
scriptId === undefined ||
|
||||
scriptId.length > 256 ||
|
||||
sanitized === undefined
|
||||
)
|
||||
return;
|
||||
if (
|
||||
this.scripts.size >= this.input.limits.max_scripts &&
|
||||
!this.scripts.has(scriptId)
|
||||
) {
|
||||
this.dropped += 1;
|
||||
return;
|
||||
}
|
||||
this.scripts.set(scriptId, {
|
||||
scriptId,
|
||||
url: sanitized.url,
|
||||
origin: sanitized.origin,
|
||||
hash: (stringValue(params.hash) ?? "").slice(0, 512),
|
||||
length: Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
Math.trunc(numberValue(params.length) ?? 0),
|
||||
),
|
||||
),
|
||||
isModule: params.isModule === true,
|
||||
language: boundedText(params.scriptLanguage, 100),
|
||||
sourceMapUrl: this.#sourceMap(params.sourceMapURL),
|
||||
});
|
||||
}
|
||||
|
||||
#sourceMap(value: unknown): string | null {
|
||||
const sanitized = allowedSanitizedUrl(value, this.allowedOrigins);
|
||||
return sanitized?.url ?? null;
|
||||
}
|
||||
|
||||
#request(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const request = recordValue(params.request);
|
||||
const sanitized = allowedSanitizedUrl(request?.url, this.allowedOrigins);
|
||||
if (
|
||||
requestId === undefined ||
|
||||
requestId.length > 256 ||
|
||||
request === undefined ||
|
||||
sanitized === undefined
|
||||
)
|
||||
return;
|
||||
if (
|
||||
this.network.size >= this.input.limits.max_network_events &&
|
||||
!this.network.has(requestId)
|
||||
) {
|
||||
this.dropped += 1;
|
||||
return;
|
||||
}
|
||||
const initiator = recordValue(params.initiator);
|
||||
const initiatorUrl = allowedSanitizedUrl(
|
||||
firstCallFrame(initiator)?.url,
|
||||
this.allowedOrigins,
|
||||
);
|
||||
this.network.set(requestId, {
|
||||
request_id: requestId,
|
||||
url: sanitized.url,
|
||||
origin: sanitized.origin ?? "",
|
||||
method: (stringValue(request.method) ?? "GET").slice(0, 32),
|
||||
resource_type: boundedText(params.type, 100),
|
||||
status: null,
|
||||
mime_type: null,
|
||||
encoded_data_length: null,
|
||||
initiator: {
|
||||
type: (stringValue(initiator?.type) ?? "other").slice(0, 100),
|
||||
url: initiatorUrl?.url ?? null,
|
||||
line: integerOrNull(firstCallFrame(initiator)?.lineNumber),
|
||||
column: integerOrNull(firstCallFrame(initiator)?.columnNumber),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
#response(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) return;
|
||||
const current = this.network.get(requestId);
|
||||
const response = recordValue(params.response);
|
||||
if (current === undefined || response === undefined) return;
|
||||
this.network.set(requestId, {
|
||||
...current,
|
||||
status: numberValue(response.status) ?? null,
|
||||
mime_type: boundedText(response.mimeType, 256),
|
||||
});
|
||||
}
|
||||
|
||||
#finished(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) return;
|
||||
const current = this.network.get(requestId);
|
||||
if (current === undefined) return;
|
||||
this.network.set(requestId, {
|
||||
...current,
|
||||
encoded_data_length: Math.max(
|
||||
0,
|
||||
numberValue(params.encodedDataLength) ?? 0,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
#console(params: UnknownRecord): void {
|
||||
const frame = firstCallFrame(recordValue(params.stackTrace));
|
||||
const source = allowedSanitizedUrl(frame?.url, this.allowedOrigins);
|
||||
if (frame === undefined || source === undefined) return;
|
||||
if (this.console.length >= this.input.limits.max_console_events) {
|
||||
this.dropped += 1;
|
||||
return;
|
||||
}
|
||||
this.console.push({
|
||||
type: (stringValue(params.type) ?? "unknown").slice(0, 100),
|
||||
timestamp: numberValue(params.timestamp) ?? 0,
|
||||
argument_types: recordsValue(params.args)
|
||||
.map((argument) =>
|
||||
(stringValue(argument.type) ?? "unknown").slice(0, 100),
|
||||
)
|
||||
.slice(0, 100),
|
||||
url: source?.url ?? null,
|
||||
line: integerOrNull(frame?.lineNumber),
|
||||
column: integerOrNull(frame?.columnNumber),
|
||||
});
|
||||
}
|
||||
|
||||
#websocket(params: UnknownRecord, direction: "sent" | "received"): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (
|
||||
requestId === undefined ||
|
||||
requestId.length > 256 ||
|
||||
(!this.network.has(requestId) && !this.allowedWebSockets.has(requestId))
|
||||
)
|
||||
return;
|
||||
if (this.websockets.length >= this.input.limits.max_websocket_events) {
|
||||
this.dropped += 1;
|
||||
return;
|
||||
}
|
||||
const response = recordValue(params.response);
|
||||
const payload = stringValue(response?.payloadData) ?? "";
|
||||
this.websockets.push({
|
||||
request_id: requestId,
|
||||
direction,
|
||||
opcode: Math.max(0, Math.trunc(numberValue(response?.opcode) ?? 0)),
|
||||
payload_bytes: Buffer.byteLength(payload),
|
||||
});
|
||||
}
|
||||
|
||||
#websocketCreated(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const rawUrl = stringValue(params.url);
|
||||
if (
|
||||
requestId === undefined ||
|
||||
requestId.length > 256 ||
|
||||
rawUrl === undefined
|
||||
)
|
||||
return;
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (parsed.protocol === "ws:") parsed.protocol = "http:";
|
||||
else if (parsed.protocol === "wss:") parsed.protocol = "https:";
|
||||
else return;
|
||||
if (
|
||||
this.allowedOrigins.has(parsed.origin) &&
|
||||
(this.allowedWebSockets.has(requestId) ||
|
||||
this.allowedWebSockets.size < this.input.limits.max_websocket_events)
|
||||
)
|
||||
this.allowedWebSockets.add(requestId);
|
||||
else if (this.allowedOrigins.has(parsed.origin)) this.dropped += 1;
|
||||
}
|
||||
|
||||
#frameNavigated(params: UnknownRecord): void {
|
||||
const frame = recordValue(params.frame);
|
||||
if (stringValue(frame?.id) !== this.#mainFrameId) return;
|
||||
this.navigationDuringCapture = true;
|
||||
const rawUrl = stringValue(frame?.url);
|
||||
if (
|
||||
isHttpUrl(rawUrl) &&
|
||||
allowedSanitizedUrl(rawUrl, this.allowedOrigins) === undefined
|
||||
)
|
||||
this.originViolation = true;
|
||||
}
|
||||
}
|
||||
|
||||
const firstCallFrame = (
|
||||
value: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => {
|
||||
const callFrames = recordsValue(value?.callFrames);
|
||||
return callFrames[0];
|
||||
};
|
||||
|
||||
const integerOrNull = (value: unknown): number | null => {
|
||||
const number = numberValue(value);
|
||||
return number === undefined ? null : Math.max(0, Math.trunc(number));
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
import {
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
/** Capture redacted, bounded storage metadata for one authorized origin. */
|
||||
export const captureStorage = async (
|
||||
context: {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string;
|
||||
readonly input: InspectWebPageInput;
|
||||
readonly signal?: AbortSignal;
|
||||
},
|
||||
origin: string,
|
||||
limitations: string[],
|
||||
): Promise<{
|
||||
readonly value: WebPageInspection["storage"];
|
||||
readonly truncated: boolean;
|
||||
}> => {
|
||||
const quota = recordValue(
|
||||
await optionalCdpCommand(
|
||||
context,
|
||||
"Storage.getUsageAndQuota",
|
||||
{ origin },
|
||||
limitations,
|
||||
),
|
||||
);
|
||||
const local = context.input.include_storage_keys
|
||||
? await storageKeys(context, origin, true, limitations)
|
||||
: [];
|
||||
const session = context.input.include_storage_keys
|
||||
? await storageKeys(context, origin, false, limitations)
|
||||
: [];
|
||||
const indexed = context.input.include_storage_keys
|
||||
? stringArray(
|
||||
recordValue(
|
||||
await optionalCdpCommand(
|
||||
context,
|
||||
"IndexedDB.requestDatabaseNames",
|
||||
{ securityOrigin: origin },
|
||||
limitations,
|
||||
),
|
||||
)?.databaseNames,
|
||||
)
|
||||
: [];
|
||||
const caches = context.input.include_storage_keys
|
||||
? recordsValue(
|
||||
recordValue(
|
||||
await optionalCdpCommand(
|
||||
context,
|
||||
"CacheStorage.requestCacheNames",
|
||||
{ securityOrigin: origin },
|
||||
limitations,
|
||||
),
|
||||
)?.caches,
|
||||
).flatMap((cache) => {
|
||||
const name = stringValue(cache.cacheName);
|
||||
return name === undefined ? [] : [name.slice(0, 1_024)];
|
||||
})
|
||||
: [];
|
||||
const maximum = context.input.limits.max_storage_keys;
|
||||
return {
|
||||
value: {
|
||||
origin,
|
||||
usage_bytes: numberValue(quota?.usage) ?? null,
|
||||
quota_bytes: numberValue(quota?.quota) ?? null,
|
||||
local_storage_keys: local.slice(0, maximum),
|
||||
session_storage_keys: session.slice(0, maximum),
|
||||
indexed_db_names: indexed.slice(0, maximum),
|
||||
cache_names: caches.slice(0, maximum),
|
||||
values_redacted: true,
|
||||
},
|
||||
truncated: [local, session, indexed, caches].some(
|
||||
(items) => items.length > maximum,
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const storageKeys = async (
|
||||
context: Parameters<typeof captureStorage>[0],
|
||||
origin: string,
|
||||
isLocalStorage: boolean,
|
||||
limitations: string[],
|
||||
): Promise<readonly string[]> => {
|
||||
const result = recordValue(
|
||||
await optionalCdpCommand(
|
||||
context,
|
||||
"DOMStorage.getDOMStorageItems",
|
||||
{ storageId: { securityOrigin: origin, isLocalStorage } },
|
||||
limitations,
|
||||
),
|
||||
);
|
||||
return Array.isArray(result?.entries)
|
||||
? result.entries.flatMap((entry) => {
|
||||
if (!Array.isArray(entry)) return [];
|
||||
const key = stringValue(entry[0]);
|
||||
return key === undefined ? [] : [key.slice(0, 1_024)];
|
||||
})
|
||||
: [];
|
||||
};
|
||||
|
||||
const stringArray = (value: unknown): readonly string[] =>
|
||||
Array.isArray(value)
|
||||
? value.flatMap((item) => {
|
||||
const text = stringValue(item);
|
||||
return text === undefined ? [] : [text.slice(0, 1_024)];
|
||||
})
|
||||
: [];
|
||||
@@ -0,0 +1,98 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
BrowserObservationError,
|
||||
} from "../domain/errors.js";
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
|
||||
export type UnknownRecord = Readonly<Record<string, unknown>>;
|
||||
|
||||
const isRecord = (value: unknown): value is UnknownRecord =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
export const recordValue = (value: unknown): UnknownRecord | undefined =>
|
||||
isRecord(value) ? value : undefined;
|
||||
|
||||
export const recordsValue = (value: unknown): readonly UnknownRecord[] =>
|
||||
Array.isArray(value)
|
||||
? value.flatMap((item) => {
|
||||
const record = recordValue(item);
|
||||
return record === undefined ? [] : [record];
|
||||
})
|
||||
: [];
|
||||
|
||||
export const stringValue = (value: unknown): string | undefined =>
|
||||
typeof value === "string" ? value : undefined;
|
||||
|
||||
export const numberValue = (value: unknown): number | undefined =>
|
||||
typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
|
||||
export const requiredRecord = (value: unknown): UnknownRecord => {
|
||||
const record = recordValue(value);
|
||||
if (record === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
return record;
|
||||
};
|
||||
|
||||
export const boundedText = (value: unknown, maximum = 1_024): string | null => {
|
||||
const text = stringValue(value);
|
||||
return text === undefined ? null : text.slice(0, maximum);
|
||||
};
|
||||
|
||||
export const isHttpUrl = (value: string | undefined): boolean => {
|
||||
if (value === undefined) return false;
|
||||
try {
|
||||
const protocol = new URL(value).protocol;
|
||||
return protocol === "http:" || protocol === "https:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const allowedSanitizedUrl = (
|
||||
value: unknown,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): ReturnType<typeof sanitizeBrowserUrl> | undefined => {
|
||||
const text = stringValue(value);
|
||||
if (text === undefined) return undefined;
|
||||
const sanitized = sanitizeBrowserUrl(text);
|
||||
return sanitized.origin !== null && allowedOrigins.has(sanitized.origin)
|
||||
? sanitized
|
||||
: undefined;
|
||||
};
|
||||
|
||||
export const sourceResult = (
|
||||
source: string,
|
||||
): { included: true; sha256: string; bytes: number; content: string } => ({
|
||||
included: true,
|
||||
sha256: createHash("sha256").update(source).digest("hex"),
|
||||
bytes: Buffer.byteLength(source),
|
||||
content: source,
|
||||
});
|
||||
|
||||
export const sourceExcluded = (
|
||||
reason: string,
|
||||
): { included: false; reason: string } => ({ included: false, reason });
|
||||
|
||||
export const delayWithCancellation = async (
|
||||
durationMs: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
if (durationMs === 0) return;
|
||||
if (signal?.aborted === true)
|
||||
throw new AnalysisCancelledError("inspect_web_page");
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
resolve();
|
||||
}, durationMs);
|
||||
const onAbort = (): void => {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
reject(new AnalysisCancelledError("inspect_web_page"));
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal?.aborted === true) onAbort();
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,252 @@
|
||||
import WebSocket, { type RawData } from "ws";
|
||||
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisError,
|
||||
AnalysisTimeoutError,
|
||||
BrowserObservationError,
|
||||
} from "../domain/errors.js";
|
||||
|
||||
export interface CdpEvent {
|
||||
readonly method: string;
|
||||
readonly params: unknown;
|
||||
readonly sessionId?: string;
|
||||
}
|
||||
|
||||
interface PendingCommand {
|
||||
readonly resolve: (value: unknown) => void;
|
||||
readonly reject: (error: AnalysisError) => void;
|
||||
readonly timer: ReturnType<typeof setTimeout>;
|
||||
readonly removeAbort: () => void;
|
||||
}
|
||||
|
||||
const CONNECT_TIMEOUT_MS = 5_000;
|
||||
const COMMAND_TIMEOUT_MS = 5_000;
|
||||
const MAX_PAYLOAD_BYTES = 16 * 1_024 * 1_024;
|
||||
const MAX_PENDING_COMMANDS = 128;
|
||||
|
||||
/** Correlated, bounded JSON-RPC transport for a browser-level CDP socket. */
|
||||
export class CdpConnection {
|
||||
readonly #pending = new Map<number, PendingCommand>();
|
||||
readonly #listeners = new Set<(event: CdpEvent) => void>();
|
||||
#nextId = 1;
|
||||
#closed = false;
|
||||
#protocolFailed = false;
|
||||
|
||||
private constructor(private readonly socket: WebSocket) {
|
||||
socket.on("message", (data) => this.#receive(data));
|
||||
socket.on("close", () => this.#failPending("disconnected"));
|
||||
socket.on("error", () => this.#failPending("disconnected"));
|
||||
}
|
||||
|
||||
/** Connect to one already-validated loopback browser WebSocket. */
|
||||
static async connect(
|
||||
url: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CdpConnection> {
|
||||
if (signal?.aborted === true)
|
||||
throw new AnalysisCancelledError("inspect_web_page");
|
||||
const socket = new WebSocket(url, {
|
||||
handshakeTimeout: CONNECT_TIMEOUT_MS,
|
||||
maxPayload: MAX_PAYLOAD_BYTES,
|
||||
perMessageDeflate: false,
|
||||
});
|
||||
await waitForOpen(socket, signal);
|
||||
return new CdpConnection(socket);
|
||||
}
|
||||
|
||||
/** Subscribe to validated CDP event envelopes. */
|
||||
onEvent(listener: (event: CdpEvent) => void): () => void {
|
||||
this.#listeners.add(listener);
|
||||
return () => this.#listeners.delete(listener);
|
||||
}
|
||||
|
||||
/** Execute one bounded command, optionally within a flat target session. */
|
||||
async send(
|
||||
method: string,
|
||||
params: Readonly<Record<string, unknown>> = {},
|
||||
sessionId?: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<unknown> {
|
||||
if (this.#protocolFailed)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
if (this.#closed || this.socket.readyState !== WebSocket.OPEN)
|
||||
throw new BrowserObservationError("inspect_web_page", "disconnected");
|
||||
if (this.#pending.size >= MAX_PENDING_COMMANDS)
|
||||
throw new BrowserObservationError("inspect_web_page", "payload_limit");
|
||||
if (signal?.aborted === true)
|
||||
throw new AnalysisCancelledError("inspect_web_page");
|
||||
const id = this.#nextId;
|
||||
this.#nextId += 1;
|
||||
return await new Promise((resolve, reject) => {
|
||||
const onAbort = (): void => {
|
||||
const pending = this.#pending.get(id);
|
||||
if (pending === undefined) return;
|
||||
clearTimeout(pending.timer);
|
||||
pending.removeAbort();
|
||||
this.#pending.delete(id);
|
||||
reject(new AnalysisCancelledError("inspect_web_page"));
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
this.#pending.delete(id);
|
||||
reject(
|
||||
new AnalysisTimeoutError("inspect_web_page", COMMAND_TIMEOUT_MS),
|
||||
);
|
||||
}, COMMAND_TIMEOUT_MS);
|
||||
this.#pending.set(id, {
|
||||
resolve,
|
||||
reject,
|
||||
timer,
|
||||
removeAbort: () => signal?.removeEventListener("abort", onAbort),
|
||||
});
|
||||
this.socket.send(
|
||||
JSON.stringify({
|
||||
id,
|
||||
method,
|
||||
params,
|
||||
...(sessionId ? { sessionId } : {}),
|
||||
}),
|
||||
(error) => {
|
||||
if (error === undefined || error === null) return;
|
||||
const pending = this.#pending.get(id);
|
||||
if (pending === undefined) return;
|
||||
this.#complete(id, pending);
|
||||
reject(
|
||||
new BrowserObservationError("inspect_web_page", "disconnected", {
|
||||
cause: error,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Close only REA's socket; never close the browser or selected page. */
|
||||
async close(): Promise<void> {
|
||||
if (this.#closed) return;
|
||||
this.#closed = true;
|
||||
this.#failPending("disconnected");
|
||||
if (this.socket.readyState === WebSocket.CLOSED) return;
|
||||
await new Promise<void>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.socket.terminate();
|
||||
resolve();
|
||||
}, 1_000);
|
||||
this.socket.once("close", () => {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
});
|
||||
this.socket.close();
|
||||
});
|
||||
}
|
||||
|
||||
#receive(data: RawData): void {
|
||||
let message: unknown;
|
||||
try {
|
||||
message = JSON.parse(rawText(data));
|
||||
} catch {
|
||||
this.#failPending("protocol_error");
|
||||
return;
|
||||
}
|
||||
if (!isRecord(message)) {
|
||||
this.#failPending("protocol_error");
|
||||
return;
|
||||
}
|
||||
if ("id" in message && typeof message.id === "number") {
|
||||
this.#receiveResponse(message, message.id);
|
||||
return;
|
||||
}
|
||||
if ("method" in message && typeof message.method === "string") {
|
||||
const event: CdpEvent = {
|
||||
method: message.method,
|
||||
params: "params" in message ? message.params : {},
|
||||
...(typeof message.sessionId === "string"
|
||||
? { sessionId: message.sessionId }
|
||||
: {}),
|
||||
};
|
||||
for (const listener of this.#listeners) listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
#receiveResponse(message: Record<string, unknown>, id: number): void {
|
||||
const pending = this.#pending.get(id);
|
||||
if (pending === undefined) return;
|
||||
this.#complete(id, pending);
|
||||
if ("error" in message) {
|
||||
pending.reject(
|
||||
new BrowserObservationError("inspect_web_page", "protocol_error"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.resolve("result" in message ? message.result : {});
|
||||
}
|
||||
|
||||
#complete(id: number, pending: PendingCommand): void {
|
||||
clearTimeout(pending.timer);
|
||||
pending.removeAbort();
|
||||
this.#pending.delete(id);
|
||||
}
|
||||
|
||||
#failPending(reason: "disconnected" | "protocol_error"): void {
|
||||
if (reason === "disconnected") this.#closed = true;
|
||||
else this.#protocolFailed = true;
|
||||
for (const [id, pending] of this.#pending) {
|
||||
this.#complete(id, pending);
|
||||
pending.reject(new BrowserObservationError("inspect_web_page", reason));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const rawText = (data: RawData): string =>
|
||||
Array.isArray(data)
|
||||
? Buffer.concat(data).toString("utf8")
|
||||
: Buffer.isBuffer(data)
|
||||
? data.toString("utf8")
|
||||
: Buffer.from(data).toString("utf8");
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const waitForOpen = async (
|
||||
socket: WebSocket,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> =>
|
||||
await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
socket.terminate();
|
||||
reject(new AnalysisTimeoutError("inspect_web_page", CONNECT_TIMEOUT_MS));
|
||||
}, CONNECT_TIMEOUT_MS);
|
||||
const onOpen = (): void => {
|
||||
cleanup();
|
||||
resolve();
|
||||
};
|
||||
const onFailure = (cause: unknown): void => {
|
||||
cleanup();
|
||||
reject(
|
||||
signal?.aborted === true
|
||||
? new AnalysisCancelledError("inspect_web_page")
|
||||
: new BrowserObservationError(
|
||||
"inspect_web_page",
|
||||
"endpoint_unreachable",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
socket.terminate();
|
||||
onFailure(new AnalysisCancelledError("inspect_web_page"));
|
||||
};
|
||||
const cleanup = (): void => {
|
||||
clearTimeout(timer);
|
||||
socket.off("open", onOpen);
|
||||
socket.off("error", onFailure);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
};
|
||||
socket.once("open", onOpen);
|
||||
socket.once("error", onFailure);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal?.aborted === true) onAbort();
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
import { request } from "node:http";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisError,
|
||||
AnalysisTimeoutError,
|
||||
BrowserObservationError,
|
||||
} from "../domain/errors.js";
|
||||
|
||||
const HTTP_TIMEOUT_MS = 5_000;
|
||||
const MAX_VERSION_BYTES = 64 * 1_024;
|
||||
const MAX_TARGET_LIST_BYTES = 2 * 1_024 * 1_024;
|
||||
|
||||
const endpointVersionSchema = z.object({
|
||||
Browser: z.string().min(1).max(1_024),
|
||||
"Protocol-Version": z.string().min(1).max(100),
|
||||
"User-Agent": z.string().max(16_384),
|
||||
"V8-Version": z.string().max(1_024),
|
||||
"WebKit-Version": z.string().max(1_024),
|
||||
webSocketDebuggerUrl: z.string().min(1).max(2_048),
|
||||
});
|
||||
|
||||
const endpointTargetSchema = z.object({
|
||||
id: z.string().min(1).max(256),
|
||||
type: z.string().min(1).max(100),
|
||||
title: z.string().max(16_384).default(""),
|
||||
url: z.string().max(65_536),
|
||||
attached: z.boolean().default(false),
|
||||
});
|
||||
const endpointTargetsSchema = z.array(endpointTargetSchema).max(1_000);
|
||||
|
||||
export type CdpEndpointTarget = z.infer<typeof endpointTargetSchema>;
|
||||
|
||||
export interface CdpEndpointDiscovery {
|
||||
readonly browserWebSocketUrl: string;
|
||||
readonly version: {
|
||||
readonly product: string;
|
||||
readonly protocol_version: string;
|
||||
readonly revision: string;
|
||||
readonly user_agent: string;
|
||||
readonly js_version: string;
|
||||
};
|
||||
readonly targets: readonly CdpEndpointTarget[];
|
||||
}
|
||||
|
||||
type BrowserOperation = "list_browser_targets" | "inspect_web_page";
|
||||
|
||||
/** Read bounded CDP discovery endpoints without following redirects. */
|
||||
export const discoverCdpEndpoint = async (
|
||||
endpoint: string,
|
||||
operation: BrowserOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CdpEndpointDiscovery> => {
|
||||
const versionInput = await readJson(
|
||||
new URL("/json/version", endpoint),
|
||||
MAX_VERSION_BYTES,
|
||||
operation,
|
||||
signal,
|
||||
);
|
||||
const targetsInput = await readJson(
|
||||
new URL("/json/list", endpoint),
|
||||
MAX_TARGET_LIST_BYTES,
|
||||
operation,
|
||||
signal,
|
||||
);
|
||||
const version = parseEndpointValue(
|
||||
endpointVersionSchema,
|
||||
versionInput,
|
||||
operation,
|
||||
);
|
||||
const targets = parseEndpointValue(
|
||||
endpointTargetsSchema,
|
||||
targetsInput,
|
||||
operation,
|
||||
);
|
||||
return {
|
||||
browserWebSocketUrl: safeBrowserWebSocketUrl(
|
||||
endpoint,
|
||||
version.webSocketDebuggerUrl,
|
||||
operation,
|
||||
),
|
||||
version: {
|
||||
product: version.Browser,
|
||||
protocol_version: version["Protocol-Version"],
|
||||
revision: version["WebKit-Version"],
|
||||
user_agent: version["User-Agent"],
|
||||
js_version: version["V8-Version"],
|
||||
},
|
||||
targets,
|
||||
};
|
||||
};
|
||||
|
||||
const parseEndpointValue = <Output>(
|
||||
schema: z.ZodType<Output>,
|
||||
input: unknown,
|
||||
operation: BrowserOperation,
|
||||
): Output => {
|
||||
const parsed = schema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
throw new BrowserObservationError(operation, "invalid_endpoint_response", {
|
||||
cause: parsed.error,
|
||||
});
|
||||
return parsed.data;
|
||||
};
|
||||
|
||||
const safeBrowserWebSocketUrl = (
|
||||
endpoint: string,
|
||||
reported: string,
|
||||
operation: BrowserOperation,
|
||||
): string => {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(reported);
|
||||
} catch (cause: unknown) {
|
||||
throw new BrowserObservationError(operation, "invalid_endpoint_response", {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
const trustedEndpoint = new URL(endpoint);
|
||||
if (
|
||||
parsed.protocol !== "ws:" ||
|
||||
parsed.port !== trustedEndpoint.port ||
|
||||
parsed.username !== "" ||
|
||||
parsed.password !== "" ||
|
||||
parsed.search !== "" ||
|
||||
parsed.hash !== "" ||
|
||||
!parsed.pathname.startsWith("/devtools/browser/")
|
||||
)
|
||||
throw new BrowserObservationError(operation, "invalid_endpoint_response");
|
||||
parsed.hostname = trustedEndpoint.hostname;
|
||||
return parsed.href;
|
||||
};
|
||||
|
||||
const readJson = async (
|
||||
url: URL,
|
||||
maximumBytes: number,
|
||||
operation: BrowserOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<unknown> =>
|
||||
await new Promise((resolve, reject) => {
|
||||
if (signal?.aborted === true) {
|
||||
reject(new AnalysisCancelledError(operation));
|
||||
return;
|
||||
}
|
||||
const request_ = request(
|
||||
url,
|
||||
{ method: "GET", signal, headers: { Accept: "application/json" } },
|
||||
(response) => {
|
||||
if (response.statusCode !== 200) {
|
||||
response.resume();
|
||||
reject(
|
||||
new BrowserObservationError(operation, "invalid_endpoint_response"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
response.on("data", (chunk: Buffer) => {
|
||||
bytes += chunk.length;
|
||||
if (bytes > maximumBytes) {
|
||||
response.destroy(
|
||||
new BrowserObservationError(operation, "payload_limit"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
response.on("end", () => {
|
||||
try {
|
||||
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||
} catch (cause: unknown) {
|
||||
reject(
|
||||
new BrowserObservationError(
|
||||
operation,
|
||||
"invalid_endpoint_response",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
response.on("error", (cause: unknown) =>
|
||||
reject(endpointFailure(cause, operation, signal)),
|
||||
);
|
||||
},
|
||||
);
|
||||
request_.setTimeout(HTTP_TIMEOUT_MS, () =>
|
||||
request_.destroy(new AnalysisTimeoutError(operation, HTTP_TIMEOUT_MS)),
|
||||
);
|
||||
request_.on("error", (cause: unknown) =>
|
||||
reject(endpointFailure(cause, operation, signal)),
|
||||
);
|
||||
request_.end();
|
||||
});
|
||||
|
||||
const endpointFailure = (
|
||||
cause: unknown,
|
||||
operation: BrowserOperation,
|
||||
signal?: AbortSignal,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (signal?.aborted === true) return new AnalysisCancelledError(operation);
|
||||
return new BrowserObservationError(operation, "endpoint_unreachable", {
|
||||
cause,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import { BrowserObservationError } from "../domain/errors.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
|
||||
/** Execute an optional CDP method while preserving transport and cancellation failures. */
|
||||
export const optionalCdpCommand = async (
|
||||
context: {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string | undefined;
|
||||
readonly signal?: AbortSignal;
|
||||
},
|
||||
method: string,
|
||||
parameters: Readonly<Record<string, unknown>>,
|
||||
limitations: string[],
|
||||
): Promise<unknown | undefined> => {
|
||||
try {
|
||||
return await context.connection.send(
|
||||
method,
|
||||
parameters,
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
!(cause instanceof BrowserObservationError) ||
|
||||
cause.reason !== "protocol_error"
|
||||
)
|
||||
throw cause;
|
||||
limitations.push(`${method} was unavailable from this browser target.`);
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,446 @@
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import { BrowserObservationError } from "../domain/errors.js";
|
||||
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
import { captureStorage } from "./CdpCaptureStorage.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
import {
|
||||
captureAccessibility,
|
||||
captureDom,
|
||||
captureFrames,
|
||||
captureResources,
|
||||
mainFrameUrl,
|
||||
} from "./CdpCaptureDocuments.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
delayWithCancellation,
|
||||
isHttpUrl,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
requiredRecord,
|
||||
sourceExcluded,
|
||||
sourceResult,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
interface CaptureContext {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string;
|
||||
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 truncatedSections: Set<string>;
|
||||
readonly startedAt: string;
|
||||
}
|
||||
|
||||
interface CapturedSections {
|
||||
readonly attachedUrl: string;
|
||||
readonly frames: WebPageInspection["frames"];
|
||||
readonly dom: ReturnType<typeof captureDom>;
|
||||
readonly accessibility: ReturnType<typeof captureAccessibility>;
|
||||
readonly scripts: WebPageInspection["scripts"];
|
||||
readonly resources: WebPageInspection["resources"];
|
||||
readonly workers: WebPageInspection["workers"];
|
||||
readonly storage: WebPageInspection["storage"];
|
||||
}
|
||||
|
||||
/** Capture and normalize one attached page without evaluating page JavaScript. */
|
||||
export const capturePage = async (
|
||||
context: CaptureContext,
|
||||
): Promise<WebPageInspection> => {
|
||||
const allowedOrigins = new Set(context.input.allowed_origins);
|
||||
const events = new CdpCaptureEvents(context.input, allowedOrigins);
|
||||
const removeListener = context.connection.onEvent((event) =>
|
||||
events.ingest(event),
|
||||
);
|
||||
const state: CaptureState = {
|
||||
context,
|
||||
events,
|
||||
allowedOrigins,
|
||||
limitations: [
|
||||
"Observation starts when REA attaches; prior network and console activity is unavailable.",
|
||||
"Network headers, request bodies, response bodies, cookies, storage values, console values, and WebSocket payloads are not retained.",
|
||||
"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.",
|
||||
],
|
||||
truncatedSections: new Set<string>(),
|
||||
startedAt: new Date().toISOString(),
|
||||
};
|
||||
try {
|
||||
return await captureAuthorizedPage(state);
|
||||
} finally {
|
||||
removeListener();
|
||||
}
|
||||
};
|
||||
|
||||
const captureAuthorizedPage = async (
|
||||
state: CaptureState,
|
||||
): Promise<WebPageInspection> => {
|
||||
const { context, allowedOrigins, limitations, truncatedSections } = state;
|
||||
const { connection, sessionId, input, signal } = context;
|
||||
await authorizeObservationWindow(state);
|
||||
const frameResult = await authorizedFrameTree(context, allowedOrigins);
|
||||
const attachedUrl = mainFrameUrl(frameResult) ?? "";
|
||||
const frameCapture = captureFrames(
|
||||
frameResult,
|
||||
allowedOrigins,
|
||||
input.limits.max_frames,
|
||||
);
|
||||
const frames = frameCapture.items;
|
||||
if (frameCapture.total > frames.length) truncatedSections.add("frames");
|
||||
const captureFrame = frames[0];
|
||||
if (captureFrame === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
state.events.beginFinalCapture(captureFrame.frame_id);
|
||||
const resourceCapture = captureResources(
|
||||
await connection.send("Page.getResourceTree", {}, sessionId, signal),
|
||||
allowedOrigins,
|
||||
input.limits.max_resources,
|
||||
);
|
||||
if (resourceCapture.total > resourceCapture.items.length)
|
||||
truncatedSections.add("resources");
|
||||
const dom = await capturePageDom(state);
|
||||
if (dom.total > dom.nodes.length) truncatedSections.add("dom");
|
||||
const accessibility = await accessibilityForFrames(
|
||||
context,
|
||||
frames,
|
||||
limitations,
|
||||
);
|
||||
if (accessibility.total > accessibility.nodes.length)
|
||||
truncatedSections.add("accessibility");
|
||||
const scripts = await captureScripts(
|
||||
context,
|
||||
state.events,
|
||||
truncatedSections,
|
||||
);
|
||||
const workerCapture = await captureWorkers(
|
||||
context,
|
||||
allowedOrigins,
|
||||
limitations,
|
||||
);
|
||||
if (workerCapture.total > workerCapture.items.length)
|
||||
truncatedSections.add("workers");
|
||||
const storageCapture = await captureStorage(
|
||||
context,
|
||||
frames[0]?.origin ?? new URL(attachedUrl).origin,
|
||||
limitations,
|
||||
);
|
||||
if (storageCapture.truncated) truncatedSections.add("storage_keys");
|
||||
if (state.events.dropped > 0) truncatedSections.add("events");
|
||||
const completedFrameResult = await authorizedFrameTree(
|
||||
context,
|
||||
allowedOrigins,
|
||||
);
|
||||
const completedUrl = mainFrameUrl(completedFrameResult) ?? "";
|
||||
if (state.events.originViolation)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
if (state.events.navigationDuringCapture || completedUrl !== attachedUrl)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_changed");
|
||||
await report(context.progress, 3, "Normalizing browser evidence");
|
||||
return normalizedInspection(state, {
|
||||
attachedUrl,
|
||||
frames,
|
||||
dom,
|
||||
accessibility,
|
||||
scripts,
|
||||
resources: resourceCapture.items,
|
||||
workers: workerCapture.items,
|
||||
storage: storageCapture.value,
|
||||
});
|
||||
};
|
||||
|
||||
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 authorizedFrameTree(context, allowedOrigins);
|
||||
const mainFrame = captureFrames(initialFrameResult, allowedOrigins, 1)
|
||||
.items[0];
|
||||
if (mainFrame === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
events.beginAuthorizedFrame(mainFrame.frame_id);
|
||||
await enableObservationDomains(connection, sessionId, signal);
|
||||
await report(context.progress, 2, "Observing page events");
|
||||
await delayWithCancellation(context.input.observation_ms, signal);
|
||||
if (events.originViolation)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
};
|
||||
|
||||
const capturePageDom = async (
|
||||
state: CaptureState,
|
||||
): Promise<ReturnType<typeof captureDom>> => {
|
||||
const { context, allowedOrigins } = state;
|
||||
const result = await context.connection.send(
|
||||
"DOMSnapshot.captureSnapshot",
|
||||
{
|
||||
computedStyles: [],
|
||||
includePaintOrder: false,
|
||||
includeDOMRects: false,
|
||||
},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
return captureDom(result, allowedOrigins, context.input);
|
||||
};
|
||||
|
||||
const normalizedInspection = (
|
||||
state: CaptureState,
|
||||
captured: CapturedSections,
|
||||
): WebPageInspection => ({
|
||||
schema_version: 1,
|
||||
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: {
|
||||
status: state.truncatedSections.size === 0 ? "complete" : "truncated",
|
||||
truncated_sections: [...state.truncatedSections].sort(),
|
||||
dropped_events: state.events.dropped,
|
||||
},
|
||||
frames: [...captured.frames],
|
||||
dom: { total_nodes: captured.dom.total, nodes: [...captured.dom.nodes] },
|
||||
accessibility: {
|
||||
total_nodes: captured.accessibility.total,
|
||||
nodes: [...captured.accessibility.nodes],
|
||||
},
|
||||
scripts: captured.scripts,
|
||||
resources: [...captured.resources],
|
||||
network: {
|
||||
requests: [...state.events.network.values()],
|
||||
websocket_events: [...state.events.websockets],
|
||||
coverage_started_at: state.startedAt,
|
||||
prior_activity_available: false,
|
||||
},
|
||||
console: {
|
||||
events: [...state.events.console],
|
||||
coverage_started_at: state.startedAt,
|
||||
prior_activity_available: false,
|
||||
},
|
||||
workers: [...captured.workers],
|
||||
storage: captured.storage,
|
||||
limitations: state.limitations,
|
||||
});
|
||||
|
||||
const authorizedFrameTree = async (
|
||||
context: CaptureContext,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): Promise<unknown> => {
|
||||
for (let attempt = 0; attempt < 80; attempt += 1) {
|
||||
const result = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const currentUrl = mainFrameUrl(result);
|
||||
if (allowedSanitizedUrl(currentUrl, allowedOrigins) !== undefined)
|
||||
return result;
|
||||
if (isHttpUrl(currentUrl))
|
||||
throw new BrowserObservationError(
|
||||
"inspect_web_page",
|
||||
"target_not_allowed",
|
||||
);
|
||||
await delayWithCancellation(25, context.signal);
|
||||
}
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
};
|
||||
|
||||
const enableObservationDomains = async (
|
||||
connection: CdpConnection,
|
||||
sessionId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
await connection.send("Runtime.enable", {}, sessionId, signal);
|
||||
await connection.send(
|
||||
"Debugger.enable",
|
||||
{ maxScriptsCacheSize: 4 * 1_024 * 1_024 },
|
||||
sessionId,
|
||||
signal,
|
||||
);
|
||||
await connection.send(
|
||||
"Network.enable",
|
||||
{
|
||||
maxTotalBufferSize: 4 * 1_024 * 1_024,
|
||||
maxResourceBufferSize: 1_024 * 1_024,
|
||||
},
|
||||
sessionId,
|
||||
signal,
|
||||
);
|
||||
};
|
||||
|
||||
const accessibilityForFrames = async (
|
||||
context: CaptureContext,
|
||||
frames: readonly { readonly frame_id: string }[],
|
||||
limitations: string[],
|
||||
): Promise<ReturnType<typeof captureAccessibility>> => {
|
||||
const nodes: WebPageInspection["accessibility"]["nodes"] = [];
|
||||
let total = 0;
|
||||
for (const frame of frames) {
|
||||
const result = await optionalCdpCommand(
|
||||
context,
|
||||
"Accessibility.getFullAXTree",
|
||||
{ depth: 32, frameId: frame.frame_id },
|
||||
limitations,
|
||||
);
|
||||
if (result === undefined) continue;
|
||||
const capture = captureAccessibility(
|
||||
[result],
|
||||
Math.max(0, context.input.limits.max_ax_nodes - nodes.length),
|
||||
);
|
||||
total += capture.total;
|
||||
nodes.push(...capture.nodes);
|
||||
}
|
||||
return { total, nodes };
|
||||
};
|
||||
|
||||
const captureScripts = async (
|
||||
context: CaptureContext,
|
||||
events: CdpCaptureEvents,
|
||||
truncatedSections: Set<string>,
|
||||
): Promise<WebPageInspection["scripts"]> => {
|
||||
let totalSourceBytes = 0;
|
||||
const items: WebPageInspection["scripts"]["items"] = [];
|
||||
for (const script of events.scripts.values()) {
|
||||
let source: WebPageInspection["scripts"]["items"][number]["source"] =
|
||||
sourceExcluded("source capture was not approved");
|
||||
if (context.input.include_script_sources) {
|
||||
if (script.length > context.input.limits.max_script_source_bytes) {
|
||||
source = sourceExcluded(
|
||||
"declared script length exceeds per-script limit",
|
||||
);
|
||||
truncatedSections.add("script_sources");
|
||||
} else if (
|
||||
totalSourceBytes + script.length >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
source = sourceExcluded("total script source limit reached");
|
||||
truncatedSections.add("script_sources");
|
||||
} else {
|
||||
const result = requiredRecord(
|
||||
await context.connection.send(
|
||||
"Debugger.getScriptSource",
|
||||
{ scriptId: script.scriptId },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
),
|
||||
);
|
||||
const content = stringValue(result.scriptSource) ?? "";
|
||||
const bytes = Buffer.byteLength(content);
|
||||
if (
|
||||
bytes > context.input.limits.max_script_source_bytes ||
|
||||
totalSourceBytes + bytes >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
source = sourceExcluded(
|
||||
"actual source exceeds configured byte limits",
|
||||
);
|
||||
truncatedSections.add("script_sources");
|
||||
} else {
|
||||
source = sourceResult(content);
|
||||
totalSourceBytes += bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
items.push({
|
||||
script_id: script.scriptId,
|
||||
url: script.url,
|
||||
origin: script.origin,
|
||||
cdp_hash: script.hash,
|
||||
length: script.length,
|
||||
is_module: script.isModule,
|
||||
language: script.language,
|
||||
source_map_url: script.sourceMapUrl,
|
||||
source,
|
||||
});
|
||||
}
|
||||
return { total: events.scripts.size, items };
|
||||
};
|
||||
|
||||
const captureWorkers = async (
|
||||
context: CaptureContext,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
limitations: string[],
|
||||
): Promise<{
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["workers"];
|
||||
}> => {
|
||||
const result = await optionalCdpCommand(
|
||||
{ ...context, sessionId: undefined },
|
||||
"Target.getTargets",
|
||||
{},
|
||||
limitations,
|
||||
);
|
||||
const items: WebPageInspection["workers"] = [];
|
||||
let total = 0;
|
||||
for (const target of recordsValue(recordValue(result)?.targetInfos)) {
|
||||
const type = stringValue(target.type) ?? "";
|
||||
const url = allowedSanitizedUrl(target.url, allowedOrigins);
|
||||
if (!type.includes("worker") || url === undefined) continue;
|
||||
total += 1;
|
||||
if (items.length >= context.input.limits.max_workers) continue;
|
||||
items.push({
|
||||
target_id: (stringValue(target.targetId) ?? "").slice(0, 256),
|
||||
type: type.slice(0, 100),
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
attached: target.attached === true,
|
||||
});
|
||||
}
|
||||
return {
|
||||
total,
|
||||
items,
|
||||
};
|
||||
};
|
||||
|
||||
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.slice(0, 16_384),
|
||||
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 } : {}),
|
||||
});
|
||||
Reference in New Issue
Block a user