feat: add web and Electron reverse-engineering workflows
This commit is contained in:
@@ -10,10 +10,41 @@ import {
|
||||
type ListBrowserTargetsInput,
|
||||
type WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import { analyzeCapturedWebBundle } from "../domain/webBundleAnalyzer.js";
|
||||
import {
|
||||
webBundleAnalysisSchema,
|
||||
type AnalyzeWebBundleInput,
|
||||
type WebBundleAnalysis,
|
||||
} from "../domain/webBundleAnalysis.js";
|
||||
import {
|
||||
webObservationSessionSchema,
|
||||
type ObserveWebSessionInput,
|
||||
type WebObservationSession,
|
||||
} from "../domain/browserSession.js";
|
||||
import {
|
||||
webMcpDiscoverySchema,
|
||||
type DiscoverWebMcpToolsInput,
|
||||
type WebMcpDiscovery,
|
||||
} from "../domain/webMcpDiscovery.js";
|
||||
import {
|
||||
compareWebCaptures,
|
||||
webCaptureDiffSchema,
|
||||
type CompareWebCapturesInput,
|
||||
type WebCaptureDiff,
|
||||
} from "../domain/webCaptureDiff.js";
|
||||
import {
|
||||
webScreenshotDiffSchema,
|
||||
webScreenshotSchema,
|
||||
type CaptureWebScreenshotInput,
|
||||
type CompareWebScreenshotsInput,
|
||||
type WebScreenshot,
|
||||
type WebScreenshotDiff,
|
||||
} from "../domain/webScreenshot.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
BrowserObservationError,
|
||||
ProviderAdapterError,
|
||||
type BrowserObservationOperation,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
@@ -22,12 +53,17 @@ import {
|
||||
type CdpEndpointDiscovery,
|
||||
type CdpEndpointTarget,
|
||||
} from "./CdpEndpoint.js";
|
||||
import { capturePage } from "./CdpPageCapture.js";
|
||||
import { capturePage, type CapturedPage } from "./CdpPageCapture.js";
|
||||
import { fetchWebSourceMaps } from "./WebSourceMapFetcher.js";
|
||||
import { observeCdpSession } from "./CdpObservationSession.js";
|
||||
import { discoverWebMcp } from "./CdpWebMcpDiscovery.js";
|
||||
import { captureCdpScreenshot } from "./CdpScreenshot.js";
|
||||
import { comparePngScreenshots } from "./PngVisualDiff.js";
|
||||
|
||||
const IDENTITY: ProviderIdentity = {
|
||||
id: "rea-cdp-browser",
|
||||
name: "REA Chrome DevTools Protocol observation provider",
|
||||
version: "1",
|
||||
version: "2",
|
||||
};
|
||||
|
||||
/** Passive, origin-scoped browser observation through a user-owned CDP endpoint. */
|
||||
@@ -81,6 +117,41 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
input: InspectWebPageInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<WebPageInspection, AnalysisError>> {
|
||||
try {
|
||||
const captured = await this.#capture(input, options);
|
||||
return ok(webPageInspectionSchema.parse(captured.inspection));
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "inspect_web_page"));
|
||||
}
|
||||
}
|
||||
|
||||
async analyzeBundle(
|
||||
input: AnalyzeWebBundleInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<WebBundleAnalysis, AnalysisError>> {
|
||||
try {
|
||||
const captured = await this.#capture(input, options);
|
||||
const sourceMaps = input.fetch_source_maps
|
||||
? await fetchWebSourceMaps(
|
||||
captured.sourceMapRequests,
|
||||
input,
|
||||
options.signal,
|
||||
)
|
||||
: undefined;
|
||||
return ok(
|
||||
webBundleAnalysisSchema.parse(
|
||||
analyzeCapturedWebBundle(captured.inspection, input, sourceMaps),
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "analyze_web_bundle"));
|
||||
}
|
||||
}
|
||||
|
||||
async observeSession(
|
||||
input: ObserveWebSessionInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<WebObservationSession, AnalysisError>> {
|
||||
let connection: CdpConnection | undefined;
|
||||
let sessionId: string | undefined;
|
||||
try {
|
||||
@@ -101,7 +172,177 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
options.signal,
|
||||
);
|
||||
sessionId = attachedSessionId(attached);
|
||||
const result = await capturePage({
|
||||
return ok(
|
||||
webObservationSessionSchema.parse(
|
||||
await observeCdpSession({
|
||||
connection,
|
||||
sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
: { progress: options.progress }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "observe_web_session"));
|
||||
} finally {
|
||||
if (connection !== undefined) {
|
||||
if (sessionId !== undefined)
|
||||
await bestEffortCleanup(connection, sessionId);
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async discoverWebMcpTools(
|
||||
input: DiscoverWebMcpToolsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<WebMcpDiscovery, 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);
|
||||
return ok(
|
||||
webMcpDiscoverySchema.parse(
|
||||
await discoverWebMcp({
|
||||
connection,
|
||||
sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
: { progress: options.progress }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "discover_webmcp_tools"));
|
||||
} finally {
|
||||
if (connection !== undefined) {
|
||||
if (sessionId !== undefined)
|
||||
await bestEffortCleanup(connection, sessionId);
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async compareCaptures(
|
||||
input: CompareWebCapturesInput,
|
||||
): Promise<Result<WebCaptureDiff, AnalysisError>> {
|
||||
try {
|
||||
return ok(webCaptureDiffSchema.parse(compareWebCaptures(input)));
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "compare_web_captures"));
|
||||
}
|
||||
}
|
||||
|
||||
async captureScreenshot(
|
||||
input: CaptureWebScreenshotInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<WebScreenshot, 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);
|
||||
return ok(
|
||||
webScreenshotSchema.parse(
|
||||
await captureCdpScreenshot({
|
||||
connection,
|
||||
sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
: { progress: options.progress }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "capture_web_screenshot"));
|
||||
} finally {
|
||||
if (connection !== undefined) {
|
||||
if (sessionId !== undefined)
|
||||
await bestEffortCleanup(connection, sessionId);
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async compareScreenshots(
|
||||
input: CompareWebScreenshotsInput,
|
||||
): Promise<Result<WebScreenshotDiff, AnalysisError>> {
|
||||
try {
|
||||
return ok(webScreenshotDiffSchema.parse(comparePngScreenshots(input)));
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "compare_web_screenshots"));
|
||||
}
|
||||
}
|
||||
|
||||
async #capture(
|
||||
input: InspectWebPageInput,
|
||||
options: ExecutionOptions,
|
||||
): Promise<CapturedPage> {
|
||||
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);
|
||||
return await capturePage({
|
||||
connection,
|
||||
sessionId,
|
||||
discovery,
|
||||
@@ -112,9 +353,6 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
? {}
|
||||
: { 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)
|
||||
@@ -172,7 +410,7 @@ const selectTargets = (
|
||||
|
||||
const authorizeTarget = (
|
||||
discovery: CdpEndpointDiscovery,
|
||||
input: InspectWebPageInput,
|
||||
input: Pick<InspectWebPageInput, "target_id" | "allowed_origins">,
|
||||
): CdpEndpointTarget => {
|
||||
const target = discovery.targets.find(
|
||||
(candidate) => candidate.id === input.target_id,
|
||||
@@ -222,8 +460,10 @@ const bestEffortCleanup = async (
|
||||
|
||||
const providerError = (
|
||||
cause: unknown,
|
||||
operation: "list_browser_targets" | "inspect_web_page",
|
||||
operation: BrowserObservationOperation,
|
||||
): AnalysisError =>
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderAdapterError(IDENTITY.id, operation, { cause });
|
||||
cause instanceof BrowserObservationError && cause.operation !== operation
|
||||
? new BrowserObservationError(operation, cause.reason, { cause })
|
||||
: cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderAdapterError(IDENTITY.id, operation, { cause });
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import {
|
||||
classifyBrowserCompleteness,
|
||||
type BrowserCompleteness,
|
||||
type BrowserDroppedEventKind,
|
||||
type BrowserDroppedEvents,
|
||||
type BrowserExclusion,
|
||||
type BrowserExclusionReason,
|
||||
type BrowserSection,
|
||||
} from "../domain/browserCompleteness.js";
|
||||
|
||||
const EVENT_SECTIONS: Readonly<
|
||||
Record<BrowserDroppedEventKind, BrowserSection>
|
||||
> = {
|
||||
scripts: "scripts",
|
||||
network_requests: "network_requests",
|
||||
console_events: "console_events",
|
||||
websocket_connections: "websocket_connections",
|
||||
websocket_frames: "websocket_frames",
|
||||
webmcp_tools: "webmcp_tools",
|
||||
timeline_events: "timeline",
|
||||
};
|
||||
|
||||
const POLICY_REASONS = new Set<BrowserExclusionReason>([
|
||||
"disallowed_origin",
|
||||
"unsupported_url",
|
||||
"unattributed_origin",
|
||||
"not_approved",
|
||||
"out_of_target_scope",
|
||||
]);
|
||||
|
||||
/** Mutable adapter ledger projected into immutable, canonical completeness v2. */
|
||||
export class CdpCaptureCompleteness {
|
||||
readonly #initialAttachLimited: readonly BrowserSection[];
|
||||
readonly #policyFiltered = new Set<BrowserSection>();
|
||||
readonly #attachLimited = new Set<BrowserSection>();
|
||||
readonly #truncated = new Set<BrowserSection>();
|
||||
readonly #unavailable = new Set<BrowserSection>();
|
||||
readonly #excluded = new Map<string, BrowserExclusion>();
|
||||
readonly #dropped: Omit<BrowserDroppedEvents, "total"> = emptyDropped();
|
||||
|
||||
constructor(initialAttachLimited: readonly BrowserSection[] = []) {
|
||||
this.#initialAttachLimited = [...initialAttachLimited];
|
||||
this.reset();
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.#policyFiltered.clear();
|
||||
this.#attachLimited.clear();
|
||||
this.#truncated.clear();
|
||||
this.#unavailable.clear();
|
||||
this.#excluded.clear();
|
||||
Object.assign(this.#dropped, emptyDropped());
|
||||
for (const section of this.#initialAttachLimited)
|
||||
this.#attachLimited.add(section);
|
||||
}
|
||||
|
||||
exclude(
|
||||
section: BrowserSection,
|
||||
reason: BrowserExclusionReason,
|
||||
count: number | null = 1,
|
||||
): void {
|
||||
if (POLICY_REASONS.has(reason)) this.#policyFiltered.add(section);
|
||||
if (
|
||||
reason === "provider_unavailable" ||
|
||||
reason === "invalid_protocol_value"
|
||||
)
|
||||
this.#unavailable.add(section);
|
||||
const key = `${section}\0${reason}`;
|
||||
const existing = this.#excluded.get(key);
|
||||
const combined =
|
||||
count === null || existing?.count === null
|
||||
? null
|
||||
: (existing?.count ?? 0) + count;
|
||||
this.#excluded.set(key, { section, reason, count: combined });
|
||||
}
|
||||
|
||||
attachLimited(section: BrowserSection): void {
|
||||
this.#attachLimited.add(section);
|
||||
}
|
||||
|
||||
unavailable(section: BrowserSection): void {
|
||||
this.#unavailable.add(section);
|
||||
this.exclude(section, "provider_unavailable", null);
|
||||
}
|
||||
|
||||
truncate(section: BrowserSection): void {
|
||||
this.#truncated.add(section);
|
||||
}
|
||||
|
||||
drop(kind: BrowserDroppedEventKind, count = 1): void {
|
||||
this.#dropped[kind] += count;
|
||||
this.#truncated.add(EVENT_SECTIONS[kind]);
|
||||
}
|
||||
|
||||
get droppedTotal(): number {
|
||||
return Object.values(this.#dropped).reduce((sum, count) => sum + count, 0);
|
||||
}
|
||||
|
||||
snapshot(): BrowserCompleteness {
|
||||
return classifyBrowserCompleteness({
|
||||
policyFilteredSections: this.#policyFiltered,
|
||||
attachLimitedSections: this.#attachLimited,
|
||||
truncatedSections: this.#truncated,
|
||||
unavailableSections: this.#unavailable,
|
||||
excluded: [...this.#excluded.values()],
|
||||
droppedEvents: this.#dropped,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const emptyDropped = (): Omit<BrowserDroppedEvents, "total"> => ({
|
||||
scripts: 0,
|
||||
network_requests: 0,
|
||||
console_events: 0,
|
||||
websocket_connections: 0,
|
||||
websocket_frames: 0,
|
||||
webmcp_tools: 0,
|
||||
timeline_events: 0,
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
@@ -12,12 +13,19 @@ import {
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import type { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
|
||||
export type CapturedResource = Omit<
|
||||
WebPageInspection["resources"][number],
|
||||
"resource_key"
|
||||
> & { readonly rawUrl: string };
|
||||
|
||||
/** Normalize allowed frames while retaining a bounded prefix and total count. */
|
||||
export const captureFrames = (
|
||||
result: unknown,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
maximum: number,
|
||||
completeness?: CdpCaptureCompleteness,
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["frames"];
|
||||
@@ -30,14 +38,17 @@ export const captureFrames = (
|
||||
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
|
||||
)
|
||||
if (frame === undefined || frameId === undefined || frameId.length > 256) {
|
||||
completeness?.exclude("frames", "invalid_protocol_value");
|
||||
continue;
|
||||
}
|
||||
if (sanitized === undefined || sanitized.origin === null) {
|
||||
completeness?.exclude(
|
||||
"frames",
|
||||
exclusionReasonForUrl(stringValue(frame.url)),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
total += 1;
|
||||
if (items.length >= maximum) continue;
|
||||
items.push({
|
||||
@@ -62,22 +73,30 @@ export const captureResources = (
|
||||
result: unknown,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
maximum: number,
|
||||
completeness?: CdpCaptureCompleteness,
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["resources"];
|
||||
readonly items: readonly CapturedResource[];
|
||||
} => {
|
||||
const root = recordValue(requiredRecord(result).frameTree);
|
||||
if (root === undefined) return { total: 0, items: [] };
|
||||
const items: WebPageInspection["resources"] = [];
|
||||
const items: CapturedResource[] = [];
|
||||
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;
|
||||
if (url === undefined || url.origin === null) {
|
||||
completeness?.exclude(
|
||||
"resources",
|
||||
exclusionReasonForUrl(stringValue(resource.url)),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
total += 1;
|
||||
if (items.length >= maximum) continue;
|
||||
const contentSize = numberValue(resource.contentSize);
|
||||
items.push({
|
||||
rawUrl: stringValue(resource.url) ?? "",
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
type: (stringValue(resource.type) ?? "Other").slice(0, 100),
|
||||
@@ -110,20 +129,29 @@ export const captureDom = (
|
||||
result: unknown,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
input: InspectWebPageInput,
|
||||
completeness?: CdpCaptureCompleteness,
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly nodes: WebPageInspection["dom"]["nodes"];
|
||||
readonly urls: WebPageInspection["metadata"]["dom_urls"];
|
||||
readonly agentHints: WebPageInspection["metadata"]["agent_hints"];
|
||||
readonly excludedUrls: number;
|
||||
} => {
|
||||
const root = requiredRecord(result);
|
||||
const strings = Array.isArray(root.strings)
|
||||
? root.strings.map((value) => stringValue(value) ?? "")
|
||||
: [];
|
||||
const nodes: WebPageInspection["dom"]["nodes"] = [];
|
||||
const urls: WebPageInspection["metadata"]["dom_urls"] = [];
|
||||
const agentHints: WebPageInspection["metadata"]["agent_hints"] = [];
|
||||
let excludedUrls = 0;
|
||||
let total = 0;
|
||||
for (const document of recordsValue(root.documents)) {
|
||||
const documentUrl = indexedString(strings, document.documentURL);
|
||||
if (allowedSanitizedUrl(documentUrl, allowedOrigins) === undefined)
|
||||
if (allowedSanitizedUrl(documentUrl, allowedOrigins) === undefined) {
|
||||
completeness?.exclude("dom", exclusionReasonForUrl(documentUrl));
|
||||
continue;
|
||||
}
|
||||
const documentNodes = recordValue(document.nodes);
|
||||
if (documentNodes === undefined) continue;
|
||||
const nodeTypes = numberArray(documentNodes.nodeType);
|
||||
@@ -142,42 +170,129 @@ export const captureDom = (
|
||||
) {
|
||||
const attributeIndexes = numberArray(attributes[index]);
|
||||
const parent = Math.trunc(parents[index] ?? -1);
|
||||
const nodeIndex = nodes.length;
|
||||
const nodeName = indexedString(strings, nodeNames[index]).slice(0, 256);
|
||||
nodes.push({
|
||||
index: nodes.length,
|
||||
index: nodeIndex,
|
||||
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_name: nodeName,
|
||||
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),
|
||||
});
|
||||
const metadata = domMetadata(
|
||||
strings,
|
||||
attributeIndexes,
|
||||
documentUrl,
|
||||
nodeIndex,
|
||||
nodeName,
|
||||
allowedOrigins,
|
||||
);
|
||||
for (const url of metadata.urls) {
|
||||
if (urls.length >= input.limits.max_resources) {
|
||||
completeness?.truncate("metadata");
|
||||
continue;
|
||||
}
|
||||
urls.push(url);
|
||||
if (url.destination_scope !== "approved") {
|
||||
excludedUrls += 1;
|
||||
completeness?.exclude(
|
||||
"metadata",
|
||||
url.destination_scope === "outside_policy"
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url",
|
||||
);
|
||||
}
|
||||
}
|
||||
agentHints.push(...metadata.agentHints);
|
||||
}
|
||||
}
|
||||
return { total, nodes };
|
||||
return {
|
||||
total,
|
||||
nodes,
|
||||
urls,
|
||||
agentHints: agentHints.slice(0, input.limits.max_resources),
|
||||
excludedUrls,
|
||||
};
|
||||
};
|
||||
|
||||
export const captureAccessibility = (
|
||||
results: readonly unknown[],
|
||||
maximum: number,
|
||||
options: {
|
||||
readonly includeText: boolean;
|
||||
readonly maximumFieldBytes: number;
|
||||
readonly maximumTotalBytes: number;
|
||||
readonly unavailable?: boolean;
|
||||
},
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly nodes: WebPageInspection["accessibility"]["nodes"];
|
||||
readonly textCapture: WebPageInspection["accessibility"]["text_capture"];
|
||||
} => {
|
||||
const all = results.flatMap((result) =>
|
||||
recordsValue(requiredRecord(result).nodes),
|
||||
);
|
||||
return {
|
||||
total: all.length,
|
||||
nodes: all.slice(0, maximum).map((node) => ({
|
||||
let retainedBytes = 0;
|
||||
let excludedFields = 0;
|
||||
let truncatedFields = 0;
|
||||
const nodes = all.slice(0, maximum).map((node) => {
|
||||
const captureText = (value: unknown): string | null => {
|
||||
const raw = stringValue(recordValue(value)?.value);
|
||||
if (raw === undefined) return null;
|
||||
if (!options.includeText) {
|
||||
excludedFields += 1;
|
||||
return null;
|
||||
}
|
||||
const available = Math.max(0, options.maximumTotalBytes - retainedBytes);
|
||||
const captured = boundedUtf8(
|
||||
raw,
|
||||
Math.min(options.maximumFieldBytes, available),
|
||||
);
|
||||
retainedBytes += captured.bytes;
|
||||
if (captured.truncated) {
|
||||
truncatedFields += 1;
|
||||
if (captured.text === "" && raw !== "") {
|
||||
excludedFields += 1;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return captured.text;
|
||||
};
|
||||
return {
|
||||
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),
|
||||
name: captureText(node.name),
|
||||
description: captureText(node.description),
|
||||
ignored: node.ignored === true,
|
||||
})),
|
||||
};
|
||||
});
|
||||
for (const node of all.slice(maximum)) {
|
||||
for (const value of [node.name, node.description]) {
|
||||
if (stringValue(recordValue(value)?.value) === undefined) continue;
|
||||
excludedFields += 1;
|
||||
if (options.includeText) truncatedFields += 1;
|
||||
}
|
||||
}
|
||||
return {
|
||||
total: all.length,
|
||||
nodes,
|
||||
textCapture: {
|
||||
status: options.unavailable
|
||||
? "unavailable"
|
||||
: !options.includeText
|
||||
? "not_approved"
|
||||
: truncatedFields > 0
|
||||
? "truncated"
|
||||
: "included",
|
||||
retained_bytes: retainedBytes,
|
||||
excluded_fields: excludedFields,
|
||||
truncated_fields: truncatedFields,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -196,3 +311,112 @@ const numberArray = (value: unknown): readonly number[] =>
|
||||
return number === undefined ? [] : [number];
|
||||
})
|
||||
: [];
|
||||
|
||||
const domMetadata = (
|
||||
strings: readonly string[],
|
||||
attributes: readonly number[],
|
||||
documentUrl: string,
|
||||
nodeIndex: number,
|
||||
nodeName: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): {
|
||||
readonly urls: WebPageInspection["metadata"]["dom_urls"];
|
||||
readonly agentHints: WebPageInspection["metadata"]["agent_hints"];
|
||||
} => {
|
||||
const pairs = new Map<string, string>();
|
||||
for (let index = 0; index + 1 < attributes.length; index += 2) {
|
||||
const name = indexedString(strings, attributes[index]).toLowerCase();
|
||||
const value = indexedString(strings, attributes[index + 1]);
|
||||
pairs.set(name, value);
|
||||
}
|
||||
const urls: WebPageInspection["metadata"]["dom_urls"] = [];
|
||||
for (const attribute of domUrlAttributes) {
|
||||
const value = pairs.get(attribute);
|
||||
if (value === undefined) continue;
|
||||
const destination = domDestination(value, documentUrl, allowedOrigins);
|
||||
urls.push({
|
||||
node_index: nodeIndex,
|
||||
attribute,
|
||||
url: destination.url,
|
||||
destination_scope: destination.scope,
|
||||
});
|
||||
}
|
||||
const rel = (pairs.get("rel") ?? "")
|
||||
.toLowerCase()
|
||||
.split(/\s+/u)
|
||||
.filter((value) => agentRelValues.includes(value));
|
||||
const href = urls.find(({ attribute }) => attribute === "href")?.url ?? null;
|
||||
const agentHints =
|
||||
nodeName.toLowerCase() === "link" && rel.length > 0
|
||||
? rel.map((declaration) => ({
|
||||
mechanism: "dom_link_rel" as const,
|
||||
declaration,
|
||||
url: href,
|
||||
trust: "page-declared-untrusted" as const,
|
||||
}))
|
||||
: [];
|
||||
return { urls, agentHints };
|
||||
};
|
||||
|
||||
const domDestination = (
|
||||
value: string,
|
||||
documentUrl: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): {
|
||||
readonly url: string | null;
|
||||
readonly scope: "approved" | "outside_policy" | "unsupported";
|
||||
} => {
|
||||
try {
|
||||
const parsed = new URL(value, documentUrl);
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
||||
return { url: null, scope: "unsupported" };
|
||||
if (!allowedOrigins.has(parsed.origin))
|
||||
return { url: null, scope: "outside_policy" };
|
||||
return {
|
||||
url: allowedSanitizedUrl(parsed.href, allowedOrigins)?.url ?? null,
|
||||
scope: "approved",
|
||||
};
|
||||
} catch {
|
||||
return { url: null, scope: "unsupported" };
|
||||
}
|
||||
};
|
||||
|
||||
const boundedUtf8 = (
|
||||
value: string,
|
||||
maximumBytes: number,
|
||||
): {
|
||||
readonly text: string;
|
||||
readonly bytes: number;
|
||||
readonly truncated: boolean;
|
||||
} => {
|
||||
const total = Buffer.byteLength(value);
|
||||
if (total <= maximumBytes)
|
||||
return { text: value, bytes: total, truncated: false };
|
||||
let text = "";
|
||||
let bytes = 0;
|
||||
for (const character of value) {
|
||||
const characterBytes = Buffer.byteLength(character);
|
||||
if (bytes + characterBytes > maximumBytes) break;
|
||||
text += character;
|
||||
bytes += characterBytes;
|
||||
}
|
||||
return { text, bytes, truncated: true };
|
||||
};
|
||||
|
||||
const exclusionReasonForUrl = (
|
||||
value: string | undefined,
|
||||
): "disallowed_origin" | "unsupported_url" | "unattributed_origin" =>
|
||||
value === undefined || value === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(value)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url";
|
||||
|
||||
const domUrlAttributes = [
|
||||
"href",
|
||||
"src",
|
||||
"action",
|
||||
"formaction",
|
||||
"poster",
|
||||
] as const;
|
||||
const agentRelValues = ["mcp", "model-context", "ai-plugin", "service-desc"];
|
||||
|
||||
+410
-47
@@ -2,7 +2,11 @@ import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import { inferJsonShape, type JsonShape } from "../domain/jsonShape.js";
|
||||
import type { CdpEvent } from "./CdpConnection.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import { safeResponseMetadata } from "./CdpSafeMetadata.js";
|
||||
import { boundedSensitiveText } from "./SensitiveTextCapture.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
@@ -16,6 +20,7 @@ import {
|
||||
|
||||
export interface CapturedScript {
|
||||
readonly scriptId: string;
|
||||
readonly rawUrl: string;
|
||||
readonly url: string;
|
||||
readonly origin: string | null;
|
||||
readonly hash: string;
|
||||
@@ -23,6 +28,7 @@ export interface CapturedScript {
|
||||
readonly isModule: boolean;
|
||||
readonly language: string | null;
|
||||
readonly sourceMapUrl: string | null;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
}
|
||||
|
||||
type NetworkState = WebPageInspection["network"]["requests"][number];
|
||||
@@ -34,10 +40,21 @@ export class CdpCaptureEvents {
|
||||
readonly allowedWebSockets = new Set<string>();
|
||||
readonly console: WebPageInspection["console"]["events"] = [];
|
||||
readonly websockets: WebPageInspection["network"]["websocket_events"] = [];
|
||||
dropped = 0;
|
||||
readonly responseMetadata: WebPageInspection["metadata"]["responses"] = [];
|
||||
readonly agentHints: WebPageInspection["metadata"]["agent_hints"] = [];
|
||||
readonly completeness = new CdpCaptureCompleteness([
|
||||
"network_requests",
|
||||
"console_events",
|
||||
"websocket_connections",
|
||||
"websocket_frames",
|
||||
"metadata",
|
||||
]);
|
||||
originViolation = false;
|
||||
navigationDuringCapture = false;
|
||||
#mainFrameId: string | undefined;
|
||||
#consoleTextBytes = 0;
|
||||
#jsonBodyBytes = 0;
|
||||
#websocketShapeBytes = 0;
|
||||
|
||||
constructor(
|
||||
private readonly input: InspectWebPageInput,
|
||||
@@ -48,12 +65,23 @@ export class CdpCaptureEvents {
|
||||
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;
|
||||
this.responseMetadata.length = 0;
|
||||
this.agentHints.length = 0;
|
||||
this.#consoleTextBytes = 0;
|
||||
this.#jsonBodyBytes = 0;
|
||||
this.#websocketShapeBytes = 0;
|
||||
this.completeness.reset();
|
||||
if (!this.input.include_console_text)
|
||||
this.completeness.exclude("console_text", "not_approved", null);
|
||||
if (!this.input.include_json_body_shapes)
|
||||
this.completeness.exclude("json_body_shapes", "not_approved", null);
|
||||
if (!this.input.include_websocket_shapes)
|
||||
this.completeness.exclude("websocket_shapes", "not_approved", null);
|
||||
}
|
||||
|
||||
beginFinalCapture(frameId: string): void {
|
||||
@@ -99,21 +127,25 @@ export class CdpCaptureEvents {
|
||||
const scriptId = stringValue(params.scriptId);
|
||||
const rawUrl = stringValue(params.url) ?? "";
|
||||
const sanitized = allowedSanitizedUrl(rawUrl, this.allowedOrigins);
|
||||
if (
|
||||
scriptId === undefined ||
|
||||
scriptId.length > 256 ||
|
||||
sanitized === undefined
|
||||
)
|
||||
if (scriptId === undefined || scriptId.length > 256) {
|
||||
this.completeness.exclude("scripts", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (sanitized === undefined) {
|
||||
this.completeness.exclude("scripts", exclusionReasonForUrl(rawUrl));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.scripts.size >= this.input.limits.max_scripts &&
|
||||
!this.scripts.has(scriptId)
|
||||
) {
|
||||
this.dropped += 1;
|
||||
this.completeness.drop("scripts");
|
||||
return;
|
||||
}
|
||||
const sourceMap = this.#sourceMap(params.sourceMapURL);
|
||||
this.scripts.set(scriptId, {
|
||||
scriptId,
|
||||
rawUrl,
|
||||
url: sanitized.url,
|
||||
origin: sanitized.origin,
|
||||
hash: (stringValue(params.hash) ?? "").slice(0, 512),
|
||||
@@ -126,21 +158,43 @@ export class CdpCaptureEvents {
|
||||
),
|
||||
isModule: params.isModule === true,
|
||||
language: boundedText(params.scriptLanguage, 100),
|
||||
sourceMapUrl: this.#sourceMap(params.sourceMapURL),
|
||||
sourceMapUrl: sourceMap.sanitized,
|
||||
sourceMapRawUrl: sourceMap.raw,
|
||||
});
|
||||
}
|
||||
|
||||
#sourceMap(value: unknown): string | null {
|
||||
const sanitized = allowedSanitizedUrl(value, this.allowedOrigins);
|
||||
return sanitized?.url ?? null;
|
||||
#sourceMap(value: unknown): {
|
||||
readonly sanitized: string | null;
|
||||
readonly raw: string | null;
|
||||
} {
|
||||
const rawUrl = stringValue(value);
|
||||
if (rawUrl === undefined || rawUrl === "")
|
||||
return { sanitized: null, raw: null };
|
||||
const sanitized = allowedSanitizedUrl(rawUrl, this.allowedOrigins);
|
||||
if (sanitized !== undefined)
|
||||
return { sanitized: sanitized.url, raw: rawUrl };
|
||||
this.completeness.exclude("source_maps", exclusionReasonForUrl(rawUrl));
|
||||
return { sanitized: null, raw: 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) return;
|
||||
if (request === undefined || sanitized === undefined) {
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
this.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (request === undefined) {
|
||||
this.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
this.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
const sanitized = allowedSanitizedUrl(request.url, this.allowedOrigins);
|
||||
if (sanitized === undefined) {
|
||||
this.completeness.exclude(
|
||||
"network_requests",
|
||||
exclusionReasonForUrl(stringValue(request.url)),
|
||||
);
|
||||
this.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
@@ -148,14 +202,21 @@ export class CdpCaptureEvents {
|
||||
this.network.size >= this.input.limits.max_network_events &&
|
||||
!this.network.has(requestId)
|
||||
) {
|
||||
this.dropped += 1;
|
||||
this.completeness.drop("network_requests");
|
||||
return;
|
||||
}
|
||||
const initiator = recordValue(params.initiator);
|
||||
const initiatorFrame = initiatorLocation(initiator);
|
||||
const rawInitiatorUrl = stringValue(initiatorFrame?.url);
|
||||
const initiatorUrl = allowedSanitizedUrl(
|
||||
firstCallFrame(initiator)?.url,
|
||||
rawInitiatorUrl,
|
||||
this.allowedOrigins,
|
||||
);
|
||||
if (rawInitiatorUrl !== undefined && initiatorUrl === undefined)
|
||||
this.completeness.exclude(
|
||||
"network_initiators",
|
||||
exclusionReasonForUrl(rawInitiatorUrl),
|
||||
);
|
||||
this.network.set(requestId, {
|
||||
request_id: requestId,
|
||||
url: sanitized.url,
|
||||
@@ -168,20 +229,30 @@ export class CdpCaptureEvents {
|
||||
initiator: {
|
||||
type: (stringValue(initiator?.type) ?? "other").slice(0, 100),
|
||||
url: initiatorUrl?.url ?? null,
|
||||
line: integerOrNull(firstCallFrame(initiator)?.lineNumber),
|
||||
column: integerOrNull(firstCallFrame(initiator)?.columnNumber),
|
||||
line: integerOrNull(initiatorFrame?.lineNumber),
|
||||
column: integerOrNull(initiatorFrame?.columnNumber),
|
||||
},
|
||||
body_shapes: this.#requestBodyShape(request),
|
||||
});
|
||||
}
|
||||
|
||||
#response(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) return;
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
this.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
const current = this.network.get(requestId);
|
||||
const response = recordValue(params.response);
|
||||
const sanitized = allowedSanitizedUrl(response?.url, this.allowedOrigins);
|
||||
if (current === undefined) return;
|
||||
const sanitized = allowedSanitizedUrl(response?.url, this.allowedOrigins);
|
||||
if (response === undefined || sanitized === undefined) {
|
||||
this.completeness.exclude(
|
||||
"network_requests",
|
||||
response === undefined
|
||||
? "invalid_protocol_value"
|
||||
: exclusionReasonForUrl(stringValue(response.url)),
|
||||
);
|
||||
this.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
@@ -190,6 +261,18 @@ export class CdpCaptureEvents {
|
||||
status: numberValue(response.status) ?? null,
|
||||
mime_type: boundedText(response.mimeType, 256),
|
||||
});
|
||||
if (this.responseMetadata.length >= this.input.limits.max_network_events) {
|
||||
this.completeness.truncate("metadata");
|
||||
return;
|
||||
}
|
||||
const metadata = safeResponseMetadata(
|
||||
requestId,
|
||||
sanitized.url,
|
||||
response,
|
||||
this.allowedOrigins,
|
||||
);
|
||||
this.responseMetadata.push(metadata.response);
|
||||
this.agentHints.push(...metadata.agentHints);
|
||||
}
|
||||
|
||||
#finished(params: UnknownRecord): void {
|
||||
@@ -208,23 +291,35 @@ export class CdpCaptureEvents {
|
||||
|
||||
#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;
|
||||
if (frame === undefined) {
|
||||
this.completeness.exclude("console_events", "unattributed_origin");
|
||||
return;
|
||||
}
|
||||
const source = allowedSanitizedUrl(frame.url, this.allowedOrigins);
|
||||
if (source === undefined) {
|
||||
this.completeness.exclude(
|
||||
"console_events",
|
||||
exclusionReasonForUrl(stringValue(frame.url)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (this.console.length >= this.input.limits.max_console_events) {
|
||||
this.completeness.drop("console_events");
|
||||
return;
|
||||
}
|
||||
const arguments_ = recordsValue(params.args);
|
||||
this.console.push({
|
||||
type: (stringValue(params.type) ?? "unknown").slice(0, 100),
|
||||
timestamp: numberValue(params.timestamp) ?? 0,
|
||||
argument_types: recordsValue(params.args)
|
||||
argument_types: arguments_
|
||||
.map((argument) =>
|
||||
(stringValue(argument.type) ?? "unknown").slice(0, 100),
|
||||
)
|
||||
.slice(0, 100),
|
||||
url: source?.url ?? null,
|
||||
line: integerOrNull(frame?.lineNumber),
|
||||
column: integerOrNull(frame?.columnNumber),
|
||||
url: source.url,
|
||||
line: integerOrNull(frame.lineNumber),
|
||||
column: integerOrNull(frame.columnNumber),
|
||||
text_capture: this.#consoleText(arguments_),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -237,48 +332,243 @@ export class CdpCaptureEvents {
|
||||
)
|
||||
return;
|
||||
if (this.websockets.length >= this.input.limits.max_websocket_events) {
|
||||
this.dropped += 1;
|
||||
this.completeness.drop("websocket_frames");
|
||||
return;
|
||||
}
|
||||
const response = recordValue(params.response);
|
||||
const payload = stringValue(response?.payloadData) ?? "";
|
||||
const opcode = Math.max(0, Math.trunc(numberValue(response?.opcode) ?? 0));
|
||||
const decoded = opcode === 1 ? undefined : decodeBase64(payload);
|
||||
if (opcode !== 1 && decoded === undefined)
|
||||
this.completeness.exclude("websocket_frames", "invalid_protocol_value");
|
||||
this.websockets.push({
|
||||
request_id: requestId,
|
||||
direction,
|
||||
opcode,
|
||||
payload_bytes:
|
||||
opcode === 1
|
||||
? Buffer.byteLength(payload)
|
||||
: Buffer.from(payload, "base64").byteLength,
|
||||
opcode === 1 ? Buffer.byteLength(payload) : (decoded?.byteLength ?? 0),
|
||||
payload_shape: this.#websocketShape(payload, opcode),
|
||||
});
|
||||
}
|
||||
|
||||
responseBodyRequestIds(): readonly string[] {
|
||||
if (!this.input.include_json_body_shapes) return [];
|
||||
return [...this.network.values()]
|
||||
.filter((request) => isJsonMediaType(request.mime_type))
|
||||
.map((request) => request.request_id);
|
||||
}
|
||||
|
||||
responseBodyUnavailable(requestId: string): void {
|
||||
this.#updateResponseShape(requestId, null, false);
|
||||
this.completeness.unavailable("json_body_shapes");
|
||||
}
|
||||
|
||||
ingestResponseBody(requestId: string, value: unknown): void {
|
||||
const result = recordValue(value);
|
||||
const body = stringValue(result?.body);
|
||||
if (body === undefined) {
|
||||
this.#invalidResponseBody(requestId);
|
||||
return;
|
||||
}
|
||||
const decoded =
|
||||
result?.base64Encoded === true
|
||||
? decodeBase64(body)?.toString("utf8")
|
||||
: body;
|
||||
if (decoded === undefined) {
|
||||
this.#invalidResponseBody(requestId);
|
||||
return;
|
||||
}
|
||||
const inferred = this.#inferBodyShape(decoded);
|
||||
this.#updateResponseShape(requestId, inferred.shape, inferred.truncated);
|
||||
}
|
||||
|
||||
#invalidResponseBody(requestId: string): void {
|
||||
this.#updateResponseShape(requestId, null, false);
|
||||
this.completeness.exclude("json_body_shapes", "invalid_protocol_value");
|
||||
}
|
||||
|
||||
#requestBodyShape(request: UnknownRecord): NetworkState["body_shapes"] {
|
||||
if (!this.input.include_json_body_shapes)
|
||||
return { status: "not_approved", request: null, response: null };
|
||||
const body = stringValue(request.postData);
|
||||
if (!isJsonContentType(recordValue(request.headers)) || body === undefined)
|
||||
return { status: "unavailable", request: null, response: null };
|
||||
const inferred = this.#inferBodyShape(body);
|
||||
return {
|
||||
status: inferred.truncated
|
||||
? "truncated"
|
||||
: inferred.shape === null
|
||||
? "unavailable"
|
||||
: "included",
|
||||
request: inferred.shape,
|
||||
response: null,
|
||||
};
|
||||
}
|
||||
|
||||
#inferBodyShape(text: string): {
|
||||
readonly shape: JsonShape | null;
|
||||
readonly truncated: boolean;
|
||||
} {
|
||||
const bytes = Buffer.byteLength(text);
|
||||
const remaining =
|
||||
this.input.limits.max_total_json_body_bytes - this.#jsonBodyBytes;
|
||||
if (bytes > this.input.limits.max_json_body_bytes || bytes > remaining) {
|
||||
this.completeness.truncate("json_body_shapes");
|
||||
return { shape: null, truncated: true };
|
||||
}
|
||||
this.#jsonBodyBytes += bytes;
|
||||
const shape = inferJsonShape(text, {
|
||||
maximumBytes: this.input.limits.max_json_body_bytes,
|
||||
maximumNodes: this.input.limits.max_json_shape_nodes,
|
||||
maximumDepth: this.input.limits.max_json_shape_depth,
|
||||
});
|
||||
if (shape?.truncated === true)
|
||||
this.completeness.truncate("json_body_shapes");
|
||||
return { shape, truncated: shape?.truncated === true };
|
||||
}
|
||||
|
||||
#updateResponseShape(
|
||||
requestId: string,
|
||||
response: JsonShape | null,
|
||||
truncated: boolean,
|
||||
): void {
|
||||
const current = this.network.get(requestId);
|
||||
if (current === undefined) return;
|
||||
const request = current.body_shapes.request;
|
||||
const status =
|
||||
truncated || current.body_shapes.status === "truncated"
|
||||
? "truncated"
|
||||
: response !== null
|
||||
? "included"
|
||||
: request !== null
|
||||
? "partial"
|
||||
: "unavailable";
|
||||
this.network.set(requestId, {
|
||||
...current,
|
||||
body_shapes: { status, request, response },
|
||||
});
|
||||
}
|
||||
|
||||
#consoleText(
|
||||
arguments_: readonly UnknownRecord[],
|
||||
): WebPageInspection["console"]["events"][number]["text_capture"] {
|
||||
if (!this.input.include_console_text)
|
||||
return {
|
||||
status: "not_approved",
|
||||
values: [],
|
||||
retained_bytes: 0,
|
||||
truncated_values: 0,
|
||||
};
|
||||
const values: WebPageInspection["console"]["events"][number]["text_capture"]["values"] =
|
||||
[];
|
||||
let retainedBytes = 0;
|
||||
let truncatedValues = 0;
|
||||
for (const [argumentIndex, argument] of arguments_.entries()) {
|
||||
const primitive = consolePrimitive(argument);
|
||||
if (primitive === undefined) continue;
|
||||
const remaining =
|
||||
this.input.limits.max_total_console_text_bytes - this.#consoleTextBytes;
|
||||
if (remaining <= 0) {
|
||||
truncatedValues += 1;
|
||||
continue;
|
||||
}
|
||||
const bounded = boundedSensitiveText(
|
||||
primitive.text,
|
||||
Math.min(this.input.limits.max_console_text_field_bytes, remaining),
|
||||
);
|
||||
values.push({
|
||||
argument_index: argumentIndex,
|
||||
type: primitive.type,
|
||||
text: bounded.text,
|
||||
});
|
||||
retainedBytes += bounded.bytes;
|
||||
this.#consoleTextBytes += bounded.bytes;
|
||||
if (bounded.truncated) truncatedValues += 1;
|
||||
}
|
||||
if (truncatedValues > 0) this.completeness.truncate("console_text");
|
||||
return {
|
||||
status: truncatedValues > 0 ? "truncated" : "included",
|
||||
values,
|
||||
retained_bytes: retainedBytes,
|
||||
truncated_values: truncatedValues,
|
||||
};
|
||||
}
|
||||
|
||||
#websocketShape(
|
||||
payload: string,
|
||||
opcode: number,
|
||||
): WebPageInspection["network"]["websocket_events"][number]["payload_shape"] {
|
||||
if (!this.input.include_websocket_shapes) return null;
|
||||
if (opcode !== 1)
|
||||
return { format: "binary", json_shape: null, truncated: false };
|
||||
const bytes = Buffer.byteLength(payload);
|
||||
const remaining =
|
||||
this.input.limits.max_total_websocket_shape_bytes -
|
||||
this.#websocketShapeBytes;
|
||||
if (
|
||||
bytes > this.input.limits.max_websocket_shape_bytes ||
|
||||
bytes > remaining
|
||||
) {
|
||||
this.completeness.truncate("websocket_shapes");
|
||||
return { format: "text", json_shape: null, truncated: true };
|
||||
}
|
||||
this.#websocketShapeBytes += bytes;
|
||||
const shape = inferJsonShape(payload, {
|
||||
maximumBytes: this.input.limits.max_websocket_shape_bytes,
|
||||
maximumNodes: this.input.limits.max_json_shape_nodes,
|
||||
maximumDepth: this.input.limits.max_json_shape_depth,
|
||||
});
|
||||
if (shape?.truncated === true)
|
||||
this.completeness.truncate("websocket_shapes");
|
||||
return {
|
||||
format: shape === null ? "text" : "json",
|
||||
json_shape: shape,
|
||||
truncated: shape?.truncated === true,
|
||||
};
|
||||
}
|
||||
|
||||
#websocketCreated(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const rawUrl = stringValue(params.url);
|
||||
if (
|
||||
requestId === undefined ||
|
||||
requestId.length > 256 ||
|
||||
rawUrl === undefined
|
||||
)
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
this.completeness.exclude(
|
||||
"websocket_connections",
|
||||
"invalid_protocol_value",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (rawUrl === undefined) {
|
||||
this.completeness.exclude(
|
||||
"websocket_connections",
|
||||
"invalid_protocol_value",
|
||||
);
|
||||
return;
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
this.completeness.exclude("websocket_connections", "unsupported_url");
|
||||
return;
|
||||
}
|
||||
if (parsed.protocol === "ws:") parsed.protocol = "http:";
|
||||
else if (parsed.protocol === "wss:") parsed.protocol = "https:";
|
||||
else return;
|
||||
else {
|
||||
this.completeness.exclude("websocket_connections", "unsupported_url");
|
||||
return;
|
||||
}
|
||||
if (!this.allowedOrigins.has(parsed.origin)) {
|
||||
this.completeness.exclude("websocket_connections", "disallowed_origin");
|
||||
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;
|
||||
!this.allowedWebSockets.has(requestId) &&
|
||||
this.allowedWebSockets.size >= this.input.limits.max_websocket_events
|
||||
) {
|
||||
this.completeness.drop("websocket_connections");
|
||||
return;
|
||||
}
|
||||
this.allowedWebSockets.add(requestId);
|
||||
}
|
||||
|
||||
#frameNavigated(params: UnknownRecord): void {
|
||||
@@ -296,12 +586,85 @@ export class CdpCaptureEvents {
|
||||
|
||||
const firstCallFrame = (
|
||||
value: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => recordsValue(value?.callFrames)[0];
|
||||
|
||||
const initiatorLocation = (
|
||||
initiator: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => {
|
||||
const callFrames = recordsValue(value?.callFrames);
|
||||
return callFrames[0];
|
||||
let stack = recordValue(initiator?.stack);
|
||||
for (let depth = 0; depth < 32 && stack !== undefined; depth += 1) {
|
||||
const frame = firstCallFrame(stack);
|
||||
if (frame !== undefined) return frame;
|
||||
stack = recordValue(stack.parent);
|
||||
}
|
||||
return stringValue(initiator?.url) === undefined ? undefined : initiator;
|
||||
};
|
||||
|
||||
const exclusionReasonForUrl = (
|
||||
value: string | undefined,
|
||||
): "disallowed_origin" | "unsupported_url" | "unattributed_origin" =>
|
||||
value === undefined || value === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(value)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url";
|
||||
|
||||
const integerOrNull = (value: unknown): number | null => {
|
||||
const number = numberValue(value);
|
||||
return number === undefined ? null : Math.max(0, Math.trunc(number));
|
||||
};
|
||||
|
||||
const isJsonContentType = (headers: UnknownRecord | undefined): boolean => {
|
||||
if (headers === undefined) return false;
|
||||
for (const [name, value] of Object.entries(headers))
|
||||
if (
|
||||
name.toLowerCase() === "content-type" &&
|
||||
isJsonMediaType(stringValue(value))
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
const isJsonMediaType = (value: string | null | undefined): boolean => {
|
||||
const mediaType = value?.split(";", 1)[0]?.trim().toLowerCase();
|
||||
return (
|
||||
mediaType === "application/json" || mediaType?.endsWith("+json") === true
|
||||
);
|
||||
};
|
||||
|
||||
const consolePrimitive = (
|
||||
value: UnknownRecord,
|
||||
): { readonly type: string; readonly text: string } | undefined => {
|
||||
const type = stringValue(value.type);
|
||||
switch (type) {
|
||||
case "string":
|
||||
return typeof value.value === "string"
|
||||
? { type, text: value.value }
|
||||
: undefined;
|
||||
case "boolean":
|
||||
return typeof value.value === "boolean"
|
||||
? { type, text: String(value.value) }
|
||||
: undefined;
|
||||
case "number":
|
||||
return typeof value.value === "number"
|
||||
? { type, text: String(value.value) }
|
||||
: typeof value.unserializableValue === "string"
|
||||
? { type, text: value.unserializableValue }
|
||||
: undefined;
|
||||
case "bigint":
|
||||
return typeof value.unserializableValue === "string"
|
||||
? { type, text: value.unserializableValue }
|
||||
: undefined;
|
||||
case "undefined":
|
||||
return { type, text: "undefined" };
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const BASE64 = /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/u;
|
||||
|
||||
const decodeBase64 = (value: string): Buffer | undefined =>
|
||||
value.length % 4 === 0 && BASE64.test(value)
|
||||
? Buffer.from(value, "base64")
|
||||
: undefined;
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
BrowserObservationError,
|
||||
} from "../domain/errors.js";
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
|
||||
|
||||
export type UnknownRecord = Readonly<Record<string, unknown>>;
|
||||
|
||||
@@ -64,11 +63,9 @@ export const allowedSanitizedUrl = (
|
||||
|
||||
export const sourceResult = (
|
||||
source: string,
|
||||
): { included: true; sha256: string; bytes: number; content: string } => ({
|
||||
): { included: true; artifact: ReturnType<typeof createWebTextArtifact> } => ({
|
||||
included: true,
|
||||
sha256: createHash("sha256").update(source).digest("hex"),
|
||||
bytes: Buffer.byteLength(source),
|
||||
content: source,
|
||||
artifact: createWebTextArtifact(source, "text/javascript"),
|
||||
});
|
||||
|
||||
export const sourceExcluded = (
|
||||
|
||||
@@ -0,0 +1,481 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import type {
|
||||
ElectronPageInspection,
|
||||
InspectElectronPageInput,
|
||||
} from "../domain/electronObservation.js";
|
||||
import { BrowserObservationError } from "../domain/errors.js";
|
||||
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
|
||||
import type { CdpConnection, CdpEvent } from "./CdpConnection.js";
|
||||
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import {
|
||||
boundedText,
|
||||
delayWithCancellation,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
requiredRecord,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import {
|
||||
authorizedElectronFile,
|
||||
canonicalElectronRoots,
|
||||
} from "./ElectronFileScope.js";
|
||||
|
||||
interface ElectronContext {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string;
|
||||
readonly discovery: CdpEndpointDiscovery;
|
||||
readonly target: CdpEndpointTarget;
|
||||
readonly input: InspectElectronPageInput;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly progress?: ProgressReporter;
|
||||
}
|
||||
|
||||
interface ScriptDraft {
|
||||
readonly scriptId: string;
|
||||
readonly rawUrl: string;
|
||||
readonly hash: string;
|
||||
readonly length: number;
|
||||
readonly isModule: boolean;
|
||||
readonly language: string | null;
|
||||
}
|
||||
|
||||
/** Passively inspect one root-confined Electron file page. */
|
||||
export const inspectCdpElectronPage = async (
|
||||
context: ElectronContext,
|
||||
): Promise<ElectronPageInspection> => {
|
||||
const roots = await canonicalElectronRoots(context.input.allowed_file_roots);
|
||||
const completeness = new CdpCaptureCompleteness();
|
||||
const scripts: ScriptDraft[] = [];
|
||||
let mainFrameId: string | undefined;
|
||||
let navigationDuringCapture = false;
|
||||
const removeListener = context.connection.onEvent((event) => {
|
||||
if (event.sessionId !== context.sessionId) return;
|
||||
ingestScript(event, scripts, completeness);
|
||||
if (mainFrameId !== undefined && navigatedFrameId(event) === mainFrameId)
|
||||
navigationDuringCapture = true;
|
||||
});
|
||||
const startedAt = new Date().toISOString();
|
||||
try {
|
||||
await report(context.progress, 1, "Authorizing Electron file frames");
|
||||
await context.connection.send(
|
||||
"Page.enable",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const before = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const frames = await captureFrames(
|
||||
before,
|
||||
roots,
|
||||
context.input.limits.max_frames,
|
||||
completeness,
|
||||
);
|
||||
const main = frames[0];
|
||||
if (main === undefined)
|
||||
throw new BrowserObservationError(
|
||||
"inspect_web_page",
|
||||
"target_not_allowed",
|
||||
);
|
||||
mainFrameId = main.frame_id;
|
||||
await context.connection.send(
|
||||
"Debugger.enable",
|
||||
{ maxScriptsCacheSize: 4 * 1_024 * 1_024 },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
await delayWithCancellation(context.input.observation_ms, context.signal);
|
||||
await report(context.progress, 2, "Capturing Electron structure");
|
||||
const resources = await captureResources(context, roots, completeness);
|
||||
const dom = await captureDom(context, roots, completeness);
|
||||
const normalizedScripts = await captureScripts(
|
||||
context,
|
||||
roots,
|
||||
scripts,
|
||||
completeness,
|
||||
);
|
||||
const after = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const afterMain = await mainFilePath(after, roots);
|
||||
if (afterMain === undefined)
|
||||
throw new BrowserObservationError(
|
||||
"inspect_web_page",
|
||||
"target_not_allowed",
|
||||
);
|
||||
if (navigationDuringCapture || afterMain !== main.file_path)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_changed");
|
||||
await report(context.progress, 3, "Electron inspection complete");
|
||||
return {
|
||||
schema_version: 1,
|
||||
browser: context.discovery.version,
|
||||
target: {
|
||||
target_id: context.target.id,
|
||||
type: context.target.type,
|
||||
title: context.target.title.slice(0, 16_384),
|
||||
file_path: main.file_path,
|
||||
attached: context.target.attached,
|
||||
},
|
||||
capture_window: {
|
||||
started_at: startedAt,
|
||||
ended_at: new Date().toISOString(),
|
||||
observation_ms: context.input.observation_ms,
|
||||
},
|
||||
completeness: completeness.snapshot(),
|
||||
frames,
|
||||
dom,
|
||||
scripts: normalizedScripts,
|
||||
resources,
|
||||
limitations: [
|
||||
"Only canonical file paths contained by an approved root are retained.",
|
||||
"REA does not evaluate renderer JavaScript, invoke Electron APIs, navigate, click, or close the page.",
|
||||
"Script contents require separate source-capture approval and remain byte bounded.",
|
||||
],
|
||||
};
|
||||
} finally {
|
||||
removeListener();
|
||||
}
|
||||
};
|
||||
|
||||
const navigatedFrameId = (event: CdpEvent): string | undefined => {
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return undefined;
|
||||
if (event.method === "Page.frameNavigated")
|
||||
return stringValue(recordValue(params.frame)?.id);
|
||||
if (event.method === "Page.navigatedWithinDocument")
|
||||
return stringValue(params.frameId);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const ingestScript = (
|
||||
event: CdpEvent,
|
||||
scripts: ScriptDraft[],
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): void => {
|
||||
if (event.method !== "Debugger.scriptParsed") return;
|
||||
const value = recordValue(event.params);
|
||||
const scriptId = stringValue(value?.scriptId);
|
||||
const rawUrl = stringValue(value?.url);
|
||||
if (scriptId === undefined || scriptId.length > 256) {
|
||||
completeness.exclude("scripts", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (rawUrl === undefined || rawUrl === "") {
|
||||
completeness.exclude("scripts", "unattributed_origin");
|
||||
return;
|
||||
}
|
||||
if (scripts.length >= 2_000) {
|
||||
completeness.drop("scripts");
|
||||
return;
|
||||
}
|
||||
scripts.push({
|
||||
scriptId,
|
||||
rawUrl,
|
||||
hash: (stringValue(value?.hash) ?? "").slice(0, 512),
|
||||
length: nonnegativeInteger(value?.length),
|
||||
isModule: value?.isModule === true,
|
||||
language: boundedText(value?.scriptLanguage, 100),
|
||||
});
|
||||
};
|
||||
|
||||
const captureFrames = async (
|
||||
result: unknown,
|
||||
roots: readonly string[],
|
||||
maximum: number,
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): Promise<ElectronPageInspection["frames"]> => {
|
||||
const frameTree = recordValue(requiredRecord(result).frameTree);
|
||||
if (frameTree === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
const pending: Array<{
|
||||
readonly tree: UnknownRecord;
|
||||
readonly parent: string | null;
|
||||
}> = [{ tree: frameTree, parent: null }];
|
||||
const frames: ElectronPageInspection["frames"] = [];
|
||||
while (pending.length > 0) {
|
||||
const current = pending.shift();
|
||||
if (current === undefined) break;
|
||||
const frame = recordValue(current.tree.frame);
|
||||
const frameId = stringValue(frame?.id);
|
||||
const path = await authorizedElectronFile(
|
||||
stringValue(frame?.url) ?? "",
|
||||
roots,
|
||||
);
|
||||
if (frameId === undefined || path === undefined) {
|
||||
completeness.exclude("frames", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
if (frames.length >= maximum) {
|
||||
completeness.truncate("frames");
|
||||
continue;
|
||||
}
|
||||
frames.push({
|
||||
frame_id: frameId.slice(0, 256),
|
||||
parent_frame_id: current.parent,
|
||||
file_path: path,
|
||||
});
|
||||
for (const child of recordsValue(current.tree.childFrames))
|
||||
pending.push({ tree: child, parent: frameId.slice(0, 256) });
|
||||
}
|
||||
return frames;
|
||||
};
|
||||
|
||||
const captureResources = async (
|
||||
context: ElectronContext,
|
||||
roots: readonly string[],
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): Promise<ElectronPageInspection["resources"]> => {
|
||||
const result = await context.connection.send(
|
||||
"Page.getResourceTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const root = recordValue(requiredRecord(result).frameTree);
|
||||
if (root === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
const pending = [root];
|
||||
const resources: ElectronPageInspection["resources"] = [];
|
||||
const seen = new Set<string>();
|
||||
while (pending.length > 0) {
|
||||
const tree = pending.shift();
|
||||
if (tree === undefined) break;
|
||||
for (const resource of recordsValue(tree.resources)) {
|
||||
const path = await authorizedElectronFile(
|
||||
stringValue(resource.url) ?? "",
|
||||
roots,
|
||||
);
|
||||
if (path === undefined) {
|
||||
completeness.exclude("resources", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
const item = {
|
||||
file_path: path,
|
||||
type: (stringValue(resource.type) ?? "Other").slice(0, 100),
|
||||
mime_type: (stringValue(resource.mimeType) ?? "").slice(0, 256),
|
||||
content_size:
|
||||
numberValue(resource.contentSize) === undefined
|
||||
? null
|
||||
: Math.max(0, numberValue(resource.contentSize) ?? 0),
|
||||
};
|
||||
const resourceKey = `electron_resource_${digest(item)}`;
|
||||
if (seen.has(resourceKey)) continue;
|
||||
seen.add(resourceKey);
|
||||
if (resources.length >= context.input.limits.max_resources) {
|
||||
completeness.truncate("resources");
|
||||
continue;
|
||||
}
|
||||
resources.push({
|
||||
resource_key: resourceKey,
|
||||
...item,
|
||||
});
|
||||
}
|
||||
pending.push(...recordsValue(tree.childFrames));
|
||||
}
|
||||
return resources.sort((left, right) =>
|
||||
left.resource_key.localeCompare(right.resource_key),
|
||||
);
|
||||
};
|
||||
|
||||
const captureDom = async (
|
||||
context: ElectronContext,
|
||||
roots: readonly string[],
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): Promise<ElectronPageInspection["dom"]> => {
|
||||
const result = requiredRecord(
|
||||
await context.connection.send(
|
||||
"DOMSnapshot.captureSnapshot",
|
||||
{ computedStyles: [], includePaintOrder: false, includeDOMRects: false },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
),
|
||||
);
|
||||
const strings = Array.isArray(result.strings)
|
||||
? result.strings.map((value) => (typeof value === "string" ? value : ""))
|
||||
: [];
|
||||
const nodes: ElectronPageInspection["dom"]["nodes"] = [];
|
||||
let total = 0;
|
||||
for (const document of recordsValue(result.documents)) {
|
||||
const documentUrl = stringAt(strings, document.documentURL);
|
||||
if ((await authorizedElectronFile(documentUrl, roots)) === undefined) {
|
||||
completeness.exclude("dom", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
const nodeData = recordValue(document.nodes);
|
||||
const nodeTypes = arrayValue(nodeData?.nodeType);
|
||||
const nodeNames = arrayValue(nodeData?.nodeName);
|
||||
const nodeValues = arrayValue(nodeData?.nodeValue);
|
||||
const parents = arrayValue(nodeData?.parentIndex);
|
||||
const attributes = arrayValue(nodeData?.attributes);
|
||||
const baseIndex = nodes.length;
|
||||
total += nodeTypes.length;
|
||||
for (let index = 0; index < nodeTypes.length; index += 1) {
|
||||
if (nodes.length >= context.input.limits.max_dom_nodes) continue;
|
||||
const attributeIndexes = arrayValue(attributes[index]);
|
||||
const parent = integer(parents[index], -1);
|
||||
nodes.push({
|
||||
index: nodes.length,
|
||||
parent_index: parent < 0 ? -1 : baseIndex + parent,
|
||||
node_type: integer(nodeTypes[index], 0),
|
||||
node_name: stringAt(strings, nodeNames[index]).slice(0, 1_024),
|
||||
node_value_length: Buffer.byteLength(
|
||||
stringAt(strings, nodeValues[index]),
|
||||
),
|
||||
attribute_names: attributeIndexes
|
||||
.filter((_value, attributeIndex) => attributeIndex % 2 === 0)
|
||||
.map((value) => stringAt(strings, value).slice(0, 1_024))
|
||||
.slice(0, 256),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (total > nodes.length) completeness.truncate("dom");
|
||||
return { total_nodes: total, nodes };
|
||||
};
|
||||
|
||||
const captureScripts = async (
|
||||
context: ElectronContext,
|
||||
roots: readonly string[],
|
||||
scripts: readonly ScriptDraft[],
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): Promise<ElectronPageInspection["scripts"]> => {
|
||||
let total = 0;
|
||||
let sourceBytes = 0;
|
||||
const items: ElectronPageInspection["scripts"]["items"] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const script of scripts) {
|
||||
const path = await authorizedElectronFile(script.rawUrl, roots);
|
||||
if (path === undefined) {
|
||||
completeness.exclude("scripts", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
const identity = {
|
||||
file_path: path,
|
||||
cdp_hash: script.hash,
|
||||
length: script.length,
|
||||
is_module: script.isModule,
|
||||
language: script.language,
|
||||
};
|
||||
const scriptKey = `electron_script_${digest(identity)}`;
|
||||
if (seen.has(scriptKey)) continue;
|
||||
seen.add(scriptKey);
|
||||
total += 1;
|
||||
if (items.length >= context.input.limits.max_scripts) {
|
||||
completeness.drop("scripts");
|
||||
continue;
|
||||
}
|
||||
let source: ElectronPageInspection["scripts"]["items"][number]["source"] = {
|
||||
included: false,
|
||||
reason: "source capture was not approved",
|
||||
};
|
||||
if (context.input.include_script_sources) {
|
||||
if (
|
||||
script.length > context.input.limits.max_script_source_bytes ||
|
||||
sourceBytes + script.length >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
source = {
|
||||
included: false,
|
||||
reason: "script source byte limit reached",
|
||||
};
|
||||
completeness.truncate("script_sources");
|
||||
} else {
|
||||
const result = requiredRecord(
|
||||
await context.connection.send(
|
||||
"Debugger.getScriptSource",
|
||||
{ scriptId: script.scriptId },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
),
|
||||
);
|
||||
const text = stringValue(result.scriptSource) ?? "";
|
||||
const bytes = Buffer.byteLength(text);
|
||||
if (
|
||||
bytes > context.input.limits.max_script_source_bytes ||
|
||||
sourceBytes + bytes >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
source = {
|
||||
included: false,
|
||||
reason: "script source byte limit reached",
|
||||
};
|
||||
completeness.truncate("script_sources");
|
||||
} else {
|
||||
source = {
|
||||
included: true,
|
||||
artifact: createWebTextArtifact(text, "text/javascript"),
|
||||
};
|
||||
sourceBytes += bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
items.push({
|
||||
script_key: scriptKey,
|
||||
...identity,
|
||||
source,
|
||||
});
|
||||
}
|
||||
if (!context.input.include_script_sources)
|
||||
completeness.exclude("script_sources", "not_approved", total);
|
||||
return {
|
||||
total,
|
||||
items: items.sort((left, right) =>
|
||||
left.script_key.localeCompare(right.script_key),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const mainFilePath = async (
|
||||
result: unknown,
|
||||
roots: readonly string[],
|
||||
): Promise<string | undefined> => {
|
||||
const frameTree = recordValue(requiredRecord(result).frameTree);
|
||||
const frame = recordValue(frameTree?.frame);
|
||||
return await authorizedElectronFile(stringValue(frame?.url) ?? "", roots);
|
||||
};
|
||||
|
||||
const arrayValue = (value: unknown): readonly unknown[] =>
|
||||
Array.isArray(value) ? value : [];
|
||||
|
||||
const stringAt = (strings: readonly string[], value: unknown): string =>
|
||||
strings[integer(value, -1)] ?? "";
|
||||
|
||||
const integer = (value: unknown, fallback: number): number => {
|
||||
const number = numberValue(value);
|
||||
return number === undefined ? fallback : Math.trunc(number);
|
||||
};
|
||||
|
||||
const nonnegativeInteger = (value: unknown): number =>
|
||||
Math.max(0, integer(value, 0));
|
||||
|
||||
const digest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined) throw new TypeError("Expected canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
|
||||
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 } : {}),
|
||||
});
|
||||
@@ -0,0 +1,223 @@
|
||||
import type {
|
||||
ExecutionOptions,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { ElectronObservationPort } from "../application/ElectronObservationPort.js";
|
||||
import {
|
||||
electronPageInspectionSchema,
|
||||
electronTargetListSchema,
|
||||
type ElectronPageInspection,
|
||||
type ElectronTargetList,
|
||||
type InspectElectronPageInput,
|
||||
type ListElectronTargetsInput,
|
||||
} from "../domain/electronObservation.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
BrowserObservationError,
|
||||
ProviderAdapterError,
|
||||
type BrowserObservationOperation,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import { discoverCdpEndpoint, type CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import { inspectCdpElectronPage } from "./CdpElectronInspection.js";
|
||||
import {
|
||||
authorizedElectronFile,
|
||||
canonicalElectronRoots,
|
||||
} from "./ElectronFileScope.js";
|
||||
|
||||
const IDENTITY: ProviderIdentity = {
|
||||
id: "rea-cdp-electron",
|
||||
name: "REA Electron file-page CDP observation provider",
|
||||
version: "1",
|
||||
};
|
||||
|
||||
/** Passive Electron provider with canonical file-root confinement. */
|
||||
export class CdpElectronProvider implements ElectronObservationPort {
|
||||
identity(): ProviderIdentity {
|
||||
return IDENTITY;
|
||||
}
|
||||
|
||||
async listTargets(
|
||||
input: ListElectronTargetsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<ElectronTargetList, AnalysisError>> {
|
||||
try {
|
||||
const roots = await canonicalElectronRoots(input.allowed_file_roots);
|
||||
const discovery = await discoverCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
"list_browser_targets",
|
||||
options.signal,
|
||||
);
|
||||
const allowed = [];
|
||||
let outsideRoot = 0;
|
||||
let unsupportedUrl = 0;
|
||||
let nonPage = 0;
|
||||
for (const target of discovery.targets) {
|
||||
if (target.type !== "page") {
|
||||
nonPage += 1;
|
||||
continue;
|
||||
}
|
||||
const path = await authorizedElectronFile(target.url, roots);
|
||||
if (path === undefined) {
|
||||
if (isFileUrl(target.url)) outsideRoot += 1;
|
||||
else unsupportedUrl += 1;
|
||||
continue;
|
||||
}
|
||||
allowed.push({
|
||||
target_id: target.id,
|
||||
type: target.type,
|
||||
title: target.title.slice(0, 16_384),
|
||||
file_path: path,
|
||||
attached: target.attached,
|
||||
});
|
||||
}
|
||||
allowed.sort((left, right) =>
|
||||
left.target_id.localeCompare(right.target_id),
|
||||
);
|
||||
const items = allowed.slice(input.offset, input.offset + input.limit);
|
||||
const next = input.offset + items.length;
|
||||
return ok(
|
||||
electronTargetListSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: discovery.version,
|
||||
targets: {
|
||||
items,
|
||||
offset: input.offset,
|
||||
limit: input.limit,
|
||||
total: allowed.length,
|
||||
next_offset: next < allowed.length ? next : null,
|
||||
has_more: next < allowed.length,
|
||||
},
|
||||
excluded: {
|
||||
outside_root: outsideRoot,
|
||||
unsupported_url: unsupportedUrl,
|
||||
non_page: nonPage,
|
||||
},
|
||||
limitations: [
|
||||
"Only page targets whose canonical file path is contained by an approved root are listed.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "list_electron_targets"));
|
||||
}
|
||||
}
|
||||
|
||||
async inspectPage(
|
||||
input: InspectElectronPageInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<ElectronPageInspection, AnalysisError>> {
|
||||
let connection: CdpConnection | undefined;
|
||||
let sessionId: string | undefined;
|
||||
try {
|
||||
const roots = await canonicalElectronRoots(input.allowed_file_roots);
|
||||
const discovery = await discoverCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
"inspect_web_page",
|
||||
options.signal,
|
||||
);
|
||||
const target = await authorizeTarget(
|
||||
discovery.targets,
|
||||
input.target_id,
|
||||
roots,
|
||||
);
|
||||
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);
|
||||
return ok(
|
||||
electronPageInspectionSchema.parse(
|
||||
await inspectCdpElectronPage({
|
||||
connection,
|
||||
sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
: { progress: options.progress }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "inspect_electron_page"));
|
||||
} finally {
|
||||
if (connection !== undefined) {
|
||||
if (sessionId !== undefined) await cleanup(connection, sessionId);
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const authorizeTarget = async (
|
||||
targets: readonly CdpEndpointTarget[],
|
||||
targetId: string,
|
||||
roots: readonly string[],
|
||||
): Promise<CdpEndpointTarget> => {
|
||||
const target = targets.find(({ id }) => id === targetId);
|
||||
if (target === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_found");
|
||||
if (
|
||||
target.type !== "page" ||
|
||||
(await authorizedElectronFile(target.url, roots)) === undefined
|
||||
)
|
||||
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) ||
|
||||
typeof value.sessionId !== "string" ||
|
||||
value.sessionId.length > 256
|
||||
)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
return value.sessionId;
|
||||
};
|
||||
|
||||
const cleanup = async (
|
||||
connection: CdpConnection,
|
||||
sessionId: string,
|
||||
): Promise<void> => {
|
||||
for (const method of ["Debugger.disable", "Page.disable"])
|
||||
try {
|
||||
await connection.send(method, {}, sessionId);
|
||||
} catch {
|
||||
// Detach remains the final non-destructive cleanup boundary.
|
||||
}
|
||||
try {
|
||||
await connection.send("Target.detachFromTarget", { sessionId });
|
||||
} catch {
|
||||
// Closing REA's socket never closes the Electron target.
|
||||
}
|
||||
};
|
||||
|
||||
const isFileUrl = (value: string): boolean => {
|
||||
try {
|
||||
return new URL(value).protocol === "file:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const providerError = (
|
||||
cause: unknown,
|
||||
operation: BrowserObservationOperation,
|
||||
): AnalysisError =>
|
||||
cause instanceof BrowserObservationError && cause.operation !== operation
|
||||
? new BrowserObservationError(operation, cause.reason, { cause })
|
||||
: cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderAdapterError(IDENTITY.id, operation, { cause });
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
AnalysisError,
|
||||
AnalysisTimeoutError,
|
||||
BrowserObservationError,
|
||||
type BrowserObservationOperation,
|
||||
} from "../domain/errors.js";
|
||||
|
||||
const HTTP_TIMEOUT_MS = 5_000;
|
||||
@@ -45,12 +46,10 @@ export interface CdpEndpointDiscovery {
|
||||
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,
|
||||
operation: BrowserObservationOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CdpEndpointDiscovery> => {
|
||||
const versionInput = await readJson(
|
||||
@@ -95,7 +94,7 @@ export const discoverCdpEndpoint = async (
|
||||
const parseEndpointValue = <Output>(
|
||||
schema: z.ZodType<Output>,
|
||||
input: unknown,
|
||||
operation: BrowserOperation,
|
||||
operation: BrowserObservationOperation,
|
||||
): Output => {
|
||||
const parsed = schema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
@@ -108,7 +107,7 @@ const parseEndpointValue = <Output>(
|
||||
const safeBrowserWebSocketUrl = (
|
||||
endpoint: string,
|
||||
reported: string,
|
||||
operation: BrowserOperation,
|
||||
operation: BrowserObservationOperation,
|
||||
): string => {
|
||||
let parsed: URL;
|
||||
try {
|
||||
@@ -136,7 +135,7 @@ const safeBrowserWebSocketUrl = (
|
||||
const readJson = async (
|
||||
url: URL,
|
||||
maximumBytes: number,
|
||||
operation: BrowserOperation,
|
||||
operation: BrowserObservationOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<unknown> =>
|
||||
await new Promise((resolve, reject) => {
|
||||
@@ -196,7 +195,7 @@ const readJson = async (
|
||||
|
||||
const endpointFailure = (
|
||||
cause: unknown,
|
||||
operation: BrowserOperation,
|
||||
operation: BrowserObservationOperation,
|
||||
signal?: AbortSignal,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import type {
|
||||
ObserveWebSessionInput,
|
||||
WebObservationSession,
|
||||
} from "../domain/browserSession.js";
|
||||
import { BrowserObservationError } from "../domain/errors.js";
|
||||
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import { CdpConnection, type CdpEvent } from "./CdpConnection.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
delayWithCancellation,
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { mainFrameUrl } from "./CdpCaptureDocuments.js";
|
||||
|
||||
interface ObservationContext {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string;
|
||||
readonly discovery: CdpEndpointDiscovery;
|
||||
readonly target: CdpEndpointTarget;
|
||||
readonly input: ObserveWebSessionInput;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly progress?: ProgressReporter;
|
||||
}
|
||||
|
||||
type EndReason = WebObservationSession["window"]["end_reason"];
|
||||
type TimelineEvent = WebObservationSession["timeline"][number];
|
||||
|
||||
/** Observe external user actions without rejecting approved same-origin navigation. */
|
||||
export const observeCdpSession = async (
|
||||
context: ObservationContext,
|
||||
): Promise<WebObservationSession> => {
|
||||
const allowedOrigins = new Set(context.input.allowed_origins);
|
||||
const initial = await authorizedFrame(context, allowedOrigins);
|
||||
const initialUrl = mainFrameUrl(initial) ?? "";
|
||||
const mainFrameId = frameId(initial);
|
||||
if (mainFrameId === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
const capture = new TimelineCapture(
|
||||
context.input.max_timeline_events,
|
||||
allowedOrigins,
|
||||
mainFrameId,
|
||||
initialUrl,
|
||||
);
|
||||
const removeListener = context.connection.onEvent((event) => {
|
||||
if (event.sessionId === context.sessionId) capture.ingest(event);
|
||||
});
|
||||
try {
|
||||
await context.connection.send(
|
||||
"Page.enable",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
await context.connection.send(
|
||||
"Network.enable",
|
||||
{ maxTotalBufferSize: 1_024 * 1_024 },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
await context.connection.send(
|
||||
"Page.setLifecycleEventsEnabled",
|
||||
{ enabled: true },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const armedAt = new Date().toISOString();
|
||||
await context.progress?.report({
|
||||
phase: "browser_observation",
|
||||
completed: 1,
|
||||
total: 2,
|
||||
message:
|
||||
"Browser observation armed; perform the approved user action now",
|
||||
});
|
||||
let endReason = await waitForWindow(
|
||||
context.input.observation_ms,
|
||||
capture,
|
||||
context.signal,
|
||||
);
|
||||
if (endReason === "window_elapsed")
|
||||
endReason = await captureFinalUrl(context, capture, allowedOrigins);
|
||||
await context.progress?.report({
|
||||
phase: "browser_observation",
|
||||
completed: 2,
|
||||
total: 2,
|
||||
message: "Browser observation window ended",
|
||||
terminal: true,
|
||||
});
|
||||
return {
|
||||
schema_version: 1,
|
||||
browser: context.discovery.version,
|
||||
target: {
|
||||
target_id: context.target.id,
|
||||
initial_url: allowedSanitizedUrl(initialUrl, allowedOrigins)?.url ?? "",
|
||||
final_url: capture.finalUrl,
|
||||
},
|
||||
window: {
|
||||
armed_at: armedAt,
|
||||
ended_at: new Date().toISOString(),
|
||||
requested_ms: context.input.observation_ms,
|
||||
end_reason: endReason,
|
||||
},
|
||||
timeline: capture.timeline,
|
||||
completeness: capture.completeness.snapshot(),
|
||||
limitations: [
|
||||
"The timeline begins after REA attaches; earlier navigation and network activity is unavailable.",
|
||||
"Only navigation metadata is retained; headers, bodies, cookies, console values, and payloads are not captured by this tool.",
|
||||
"An out-of-policy destination ends collection immediately and is recorded without its URL.",
|
||||
],
|
||||
};
|
||||
} finally {
|
||||
removeListener();
|
||||
}
|
||||
};
|
||||
|
||||
class TimelineCapture {
|
||||
readonly timeline: TimelineEvent[] = [];
|
||||
readonly completeness = new CdpCaptureCompleteness(["timeline"]);
|
||||
finalUrl: string | null;
|
||||
#sequence = 0;
|
||||
#pendingReload = false;
|
||||
#endReason: EndReason | undefined;
|
||||
readonly #listeners = new Set<(reason: EndReason) => void>();
|
||||
|
||||
constructor(
|
||||
private readonly maximum: number,
|
||||
private readonly allowedOrigins: ReadonlySet<string>,
|
||||
private readonly mainFrameId: string,
|
||||
initialUrl: string,
|
||||
) {
|
||||
this.finalUrl =
|
||||
allowedSanitizedUrl(initialUrl, allowedOrigins)?.url ?? null;
|
||||
}
|
||||
|
||||
ingest(event: CdpEvent): void {
|
||||
if (this.#endReason !== undefined) return;
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return;
|
||||
switch (event.method) {
|
||||
case "Page.frameRequestedNavigation":
|
||||
this.#navigationRequested(params);
|
||||
break;
|
||||
case "Page.frameNavigated":
|
||||
this.#navigationCommitted(params);
|
||||
break;
|
||||
case "Page.navigatedWithinDocument":
|
||||
this.#sameDocument(params);
|
||||
break;
|
||||
case "Network.requestWillBeSent":
|
||||
this.#redirect(params);
|
||||
break;
|
||||
case "Network.loadingFailed":
|
||||
this.#loadingFailed(params);
|
||||
break;
|
||||
case "Page.lifecycleEvent":
|
||||
this.#lifecycle(params);
|
||||
break;
|
||||
case "Inspector.targetCrashed":
|
||||
case "Target.detachedFromTarget":
|
||||
this.#add("target_terminated", params, null, null, "target_terminated");
|
||||
this.end("target_terminated");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
onEnd(listener: (reason: EndReason) => void): () => void {
|
||||
if (this.#endReason !== undefined) listener(this.#endReason);
|
||||
else this.#listeners.add(listener);
|
||||
return () => this.#listeners.delete(listener);
|
||||
}
|
||||
|
||||
end(reason: EndReason): void {
|
||||
if (this.#endReason !== undefined) return;
|
||||
this.#endReason = reason;
|
||||
for (const listener of this.#listeners) listener(reason);
|
||||
this.#listeners.clear();
|
||||
}
|
||||
|
||||
setFinalUrl(rawUrl: string): void {
|
||||
const destination = scopedUrl(rawUrl, this.allowedOrigins);
|
||||
this.finalUrl = destination.scope === "approved" ? destination.url : null;
|
||||
}
|
||||
|
||||
#navigationRequested(params: UnknownRecord): void {
|
||||
if (stringValue(params.frameId) !== this.mainFrameId) return;
|
||||
const reason = safeDetail(params.reason);
|
||||
this.#pendingReload = reason === "reload";
|
||||
this.#add(
|
||||
"navigation_requested",
|
||||
params,
|
||||
stringValue(params.url),
|
||||
null,
|
||||
reason,
|
||||
);
|
||||
}
|
||||
|
||||
#navigationCommitted(params: UnknownRecord): void {
|
||||
const frame = recordValue(params.frame);
|
||||
if (stringValue(frame?.id) !== this.mainFrameId) return;
|
||||
const rawUrl = stringValue(frame?.url);
|
||||
const destination = scopedUrl(rawUrl, this.allowedOrigins);
|
||||
this.#add(
|
||||
this.#pendingReload ? "same_origin_reload" : "navigation_committed",
|
||||
{ ...params, frameId: frame?.id, loaderId: frame?.loaderId },
|
||||
rawUrl,
|
||||
null,
|
||||
safeDetail(frame?.transitionType),
|
||||
);
|
||||
this.#pendingReload = false;
|
||||
if (destination.scope === "approved") this.finalUrl = destination.url;
|
||||
else {
|
||||
this.finalUrl = null;
|
||||
this.completeness.exclude("timeline", "out_of_target_scope");
|
||||
this.end("target_left_scope");
|
||||
}
|
||||
}
|
||||
|
||||
#sameDocument(params: UnknownRecord): void {
|
||||
if (stringValue(params.frameId) !== this.mainFrameId) return;
|
||||
const rawUrl = stringValue(params.url);
|
||||
const destination = scopedUrl(rawUrl, this.allowedOrigins);
|
||||
this.#add("same_document_navigation", params, rawUrl, null, null);
|
||||
if (destination.scope === "approved") this.finalUrl = destination.url;
|
||||
else {
|
||||
this.finalUrl = null;
|
||||
this.completeness.exclude("timeline", "out_of_target_scope");
|
||||
this.end("target_left_scope");
|
||||
}
|
||||
}
|
||||
|
||||
#redirect(params: UnknownRecord): void {
|
||||
if (
|
||||
stringValue(params.frameId) !== this.mainFrameId ||
|
||||
recordValue(params.redirectResponse) === undefined
|
||||
)
|
||||
return;
|
||||
const request = recordValue(params.request);
|
||||
const rawUrl = stringValue(request?.url);
|
||||
const destination = scopedUrl(rawUrl, this.allowedOrigins);
|
||||
this.#add(
|
||||
"redirect",
|
||||
params,
|
||||
rawUrl,
|
||||
stringValue(params.requestId) ?? null,
|
||||
null,
|
||||
);
|
||||
if (destination.scope !== "approved") {
|
||||
this.completeness.exclude("timeline", "out_of_target_scope");
|
||||
this.end("target_left_scope");
|
||||
}
|
||||
}
|
||||
|
||||
#loadingFailed(params: UnknownRecord): void {
|
||||
const frame = stringValue(params.frameId);
|
||||
if (frame !== undefined && frame !== this.mainFrameId) return;
|
||||
this.#add(
|
||||
"load_failed",
|
||||
params,
|
||||
null,
|
||||
stringValue(params.requestId) ?? null,
|
||||
safeNetworkError(params.errorText),
|
||||
);
|
||||
}
|
||||
|
||||
#lifecycle(params: UnknownRecord): void {
|
||||
if (stringValue(params.frameId) !== this.mainFrameId) return;
|
||||
this.#add("lifecycle", params, null, null, safeDetail(params.name));
|
||||
}
|
||||
|
||||
#add(
|
||||
type: TimelineEvent["type"],
|
||||
params: UnknownRecord,
|
||||
rawUrl: string | null | undefined,
|
||||
requestId: string | null,
|
||||
detail: string | null,
|
||||
): void {
|
||||
const destination =
|
||||
rawUrl == null ? null : scopedUrl(rawUrl, this.allowedOrigins);
|
||||
if (this.timeline.length >= this.maximum) {
|
||||
this.completeness.drop("timeline_events");
|
||||
return;
|
||||
}
|
||||
this.#sequence += 1;
|
||||
this.timeline.push({
|
||||
sequence: this.#sequence,
|
||||
type,
|
||||
timestamp: Math.max(0, numberValue(params.timestamp) ?? 0),
|
||||
frame_id: boundedId(params.frameId),
|
||||
loader_id: boundedId(params.loaderId),
|
||||
request_id: requestId?.slice(0, 256) ?? null,
|
||||
url: destination?.scope === "approved" ? destination.url : null,
|
||||
destination_scope: destination?.scope ?? null,
|
||||
detail,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const waitForWindow = async (
|
||||
durationMs: number,
|
||||
capture: TimelineCapture,
|
||||
signal?: AbortSignal,
|
||||
): Promise<EndReason> =>
|
||||
await new Promise<EndReason>((resolve, reject) => {
|
||||
let settled = false;
|
||||
let removeEnd = (): void => {};
|
||||
const finish = (reason: EndReason): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
removeEnd();
|
||||
resolve(reason);
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
removeEnd();
|
||||
reject(signal?.reason ?? new Error("browser observation cancelled"));
|
||||
};
|
||||
const timer = setTimeout(() => finish("window_elapsed"), durationMs);
|
||||
removeEnd = capture.onEnd(finish);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal?.aborted === true) onAbort();
|
||||
});
|
||||
|
||||
const authorizedFrame = async (
|
||||
context: ObservationContext,
|
||||
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 url = mainFrameUrl(result);
|
||||
if (allowedSanitizedUrl(url, allowedOrigins) !== undefined) return result;
|
||||
if (isHttpUrl(url))
|
||||
throw new BrowserObservationError(
|
||||
"inspect_web_page",
|
||||
"target_not_allowed",
|
||||
);
|
||||
await delayWithCancellation(25, context.signal);
|
||||
}
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
};
|
||||
|
||||
const captureFinalUrl = async (
|
||||
context: ObservationContext,
|
||||
capture: TimelineCapture,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): Promise<EndReason> => {
|
||||
const result = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const url = mainFrameUrl(result);
|
||||
if (
|
||||
url !== undefined &&
|
||||
allowedSanitizedUrl(url, allowedOrigins) !== undefined
|
||||
) {
|
||||
capture.setFinalUrl(url);
|
||||
return "window_elapsed";
|
||||
}
|
||||
capture.finalUrl = null;
|
||||
capture.completeness.exclude(
|
||||
"timeline",
|
||||
url === undefined ? "invalid_protocol_value" : "out_of_target_scope",
|
||||
);
|
||||
return "target_left_scope";
|
||||
};
|
||||
|
||||
const frameId = (result: unknown): string | undefined =>
|
||||
stringValue(
|
||||
recordValue(recordValue(recordValue(result)?.frameTree)?.frame)?.id,
|
||||
);
|
||||
|
||||
const scopedUrl = (
|
||||
value: string | undefined,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): {
|
||||
readonly url: string | null;
|
||||
readonly scope: "approved" | "outside_policy" | "unsupported";
|
||||
} => {
|
||||
const allowed = allowedSanitizedUrl(value, allowedOrigins);
|
||||
if (allowed !== undefined) return { url: allowed.url, scope: "approved" };
|
||||
return isHttpUrl(value)
|
||||
? { url: null, scope: "outside_policy" }
|
||||
: { url: null, scope: "unsupported" };
|
||||
};
|
||||
|
||||
const boundedId = (value: unknown): string | null =>
|
||||
stringValue(value)?.slice(0, 256) ?? null;
|
||||
|
||||
const safeDetail = (value: unknown): string | null => {
|
||||
const detail = stringValue(value)?.toLowerCase();
|
||||
return detail !== undefined && /^[a-z0-9_.:-]{1,100}$/u.test(detail)
|
||||
? detail
|
||||
: null;
|
||||
};
|
||||
|
||||
const safeNetworkError = (value: unknown): string | null => {
|
||||
const error = stringValue(value);
|
||||
return error !== undefined && /^net::ERR_[A-Z0-9_]{1,100}$/u.test(error)
|
||||
? error
|
||||
: null;
|
||||
};
|
||||
+226
-66
@@ -4,6 +4,11 @@ import type {
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import { BrowserObservationError } from "../domain/errors.js";
|
||||
import {
|
||||
reconcileCapturedWebScript,
|
||||
stableWebResources,
|
||||
stableWebScriptKey,
|
||||
} from "../domain/webInventory.js";
|
||||
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
@@ -14,6 +19,7 @@ import {
|
||||
captureDom,
|
||||
captureFrames,
|
||||
captureResources,
|
||||
type CapturedResource,
|
||||
mainFrameUrl,
|
||||
} from "./CdpCaptureDocuments.js";
|
||||
import {
|
||||
@@ -27,6 +33,7 @@ import {
|
||||
sourceResult,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import type { WebSourceMapRequest } from "./WebSourceMapFetcher.js";
|
||||
|
||||
interface CaptureContext {
|
||||
readonly connection: CdpConnection;
|
||||
@@ -43,7 +50,6 @@ interface CaptureState {
|
||||
readonly events: CdpCaptureEvents;
|
||||
readonly allowedOrigins: ReadonlySet<string>;
|
||||
readonly limitations: string[];
|
||||
readonly truncatedSections: Set<string>;
|
||||
readonly startedAt: string;
|
||||
}
|
||||
|
||||
@@ -58,10 +64,20 @@ interface CapturedSections {
|
||||
readonly storage: WebPageInspection["storage"];
|
||||
}
|
||||
|
||||
export interface CapturedPage {
|
||||
readonly inspection: WebPageInspection;
|
||||
readonly sourceMapRequests: readonly WebSourceMapRequest[];
|
||||
}
|
||||
|
||||
interface CapturedScripts {
|
||||
readonly inventory: WebPageInspection["scripts"];
|
||||
readonly sourceMapRequests: readonly WebSourceMapRequest[];
|
||||
}
|
||||
|
||||
/** Capture and normalize one attached page without evaluating page JavaScript. */
|
||||
export const capturePage = async (
|
||||
context: CaptureContext,
|
||||
): Promise<WebPageInspection> => {
|
||||
): Promise<CapturedPage> => {
|
||||
const allowedOrigins = new Set(context.input.allowed_origins);
|
||||
const events = new CdpCaptureEvents(context.input, allowedOrigins);
|
||||
const removeListener = context.connection.onEvent((event) => {
|
||||
@@ -74,11 +90,10 @@ export const capturePage = async (
|
||||
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.",
|
||||
"Raw network headers, bodies, cookies, storage values, console objects, and WebSocket payloads are never retained; separately approved captures retain only bounded redacted text or 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.",
|
||||
],
|
||||
truncatedSections: new Set<string>(),
|
||||
startedAt: new Date().toISOString(),
|
||||
};
|
||||
try {
|
||||
@@ -90,19 +105,22 @@ export const capturePage = async (
|
||||
|
||||
const captureAuthorizedPage = async (
|
||||
state: CaptureState,
|
||||
): Promise<WebPageInspection> => {
|
||||
const { context, allowedOrigins, limitations, truncatedSections } = state;
|
||||
): Promise<CapturedPage> => {
|
||||
const { context, allowedOrigins, limitations } = state;
|
||||
const { connection, sessionId, input, signal } = context;
|
||||
await authorizeObservationWindow(state);
|
||||
await captureJsonResponseBodies(state);
|
||||
const frameResult = await authorizedFrameTree(context, allowedOrigins);
|
||||
const attachedUrl = mainFrameUrl(frameResult) ?? "";
|
||||
const frameCapture = captureFrames(
|
||||
frameResult,
|
||||
allowedOrigins,
|
||||
input.limits.max_frames,
|
||||
state.events.completeness,
|
||||
);
|
||||
const frames = frameCapture.items;
|
||||
if (frameCapture.total > frames.length) truncatedSections.add("frames");
|
||||
if (frameCapture.total > frames.length)
|
||||
state.events.completeness.truncate("frames");
|
||||
const captureFrame = frames[0];
|
||||
if (captureFrame === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
@@ -111,38 +129,39 @@ const captureAuthorizedPage = async (
|
||||
await connection.send("Page.getResourceTree", {}, sessionId, signal),
|
||||
allowedOrigins,
|
||||
input.limits.max_resources,
|
||||
state.events.completeness,
|
||||
);
|
||||
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,
|
||||
state.events.completeness.truncate("resources");
|
||||
const resources = stableWebResources(
|
||||
resourceCapture.items.map(publicResource),
|
||||
);
|
||||
const dom = await capturePageDom(state);
|
||||
if (dom.total > dom.nodes.length) state.events.completeness.truncate("dom");
|
||||
const accessibility = await accessibilityForFrames(state, frames);
|
||||
if (accessibility.total > accessibility.nodes.length)
|
||||
truncatedSections.add("accessibility");
|
||||
state.events.completeness.truncate("accessibility");
|
||||
const scripts = await captureScripts(
|
||||
context,
|
||||
state.events,
|
||||
truncatedSections,
|
||||
resourceCapture.items,
|
||||
resources,
|
||||
);
|
||||
const workerCapture = await captureWorkers(
|
||||
context,
|
||||
allowedOrigins,
|
||||
state,
|
||||
new Set(frames.map((frame) => frame.frame_id)),
|
||||
limitations,
|
||||
);
|
||||
if (workerCapture.total > workerCapture.items.length)
|
||||
truncatedSections.add("workers");
|
||||
state.events.completeness.truncate("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");
|
||||
if (storageCapture.truncated)
|
||||
state.events.completeness.truncate("storage_keys");
|
||||
if (!input.include_storage_keys)
|
||||
state.events.completeness.exclude("storage_keys", "not_approved", null);
|
||||
const completedFrameResult = await authorizedFrameTree(
|
||||
context,
|
||||
allowedOrigins,
|
||||
@@ -153,16 +172,42 @@ const captureAuthorizedPage = async (
|
||||
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,
|
||||
});
|
||||
return {
|
||||
inspection: normalizedInspection(state, {
|
||||
attachedUrl,
|
||||
frames,
|
||||
dom,
|
||||
accessibility,
|
||||
scripts: scripts.inventory,
|
||||
resources,
|
||||
workers: workerCapture.items,
|
||||
storage: storageCapture.value,
|
||||
}),
|
||||
sourceMapRequests: scripts.sourceMapRequests,
|
||||
};
|
||||
};
|
||||
|
||||
const captureJsonResponseBodies = async (
|
||||
state: CaptureState,
|
||||
): Promise<void> => {
|
||||
const requestIds = state.events.responseBodyRequestIds();
|
||||
for (let index = 0; index < requestIds.length; index += 1) {
|
||||
const requestId = requestIds[index];
|
||||
if (requestId === undefined) continue;
|
||||
const result = await optionalCdpCommand(
|
||||
state.context,
|
||||
"Network.getResponseBody",
|
||||
{ requestId },
|
||||
state.limitations,
|
||||
);
|
||||
if (result !== undefined) {
|
||||
state.events.ingestResponseBody(requestId, result);
|
||||
continue;
|
||||
}
|
||||
for (const remaining of requestIds.slice(index))
|
||||
state.events.responseBodyUnavailable(remaining);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const authorizeObservationWindow = async (
|
||||
@@ -199,14 +244,19 @@ const capturePageDom = async (
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
return captureDom(result, allowedOrigins, context.input);
|
||||
return captureDom(
|
||||
result,
|
||||
allowedOrigins,
|
||||
context.input,
|
||||
state.events.completeness,
|
||||
);
|
||||
};
|
||||
|
||||
const normalizedInspection = (
|
||||
state: CaptureState,
|
||||
captured: CapturedSections,
|
||||
): WebPageInspection => ({
|
||||
schema_version: 1,
|
||||
schema_version: 2,
|
||||
browser: state.context.discovery.version,
|
||||
target: normalizedTarget(
|
||||
state.context.target,
|
||||
@@ -218,15 +268,12 @@ const normalizedInspection = (
|
||||
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,
|
||||
},
|
||||
completeness: state.events.completeness.snapshot(),
|
||||
frames: [...captured.frames],
|
||||
dom: { total_nodes: captured.dom.total, nodes: [...captured.dom.nodes] },
|
||||
accessibility: {
|
||||
total_nodes: captured.accessibility.total,
|
||||
text_capture: captured.accessibility.textCapture,
|
||||
nodes: [...captured.accessibility.nodes],
|
||||
},
|
||||
scripts: captured.scripts,
|
||||
@@ -243,6 +290,16 @@ const normalizedInspection = (
|
||||
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,
|
||||
});
|
||||
@@ -295,12 +352,12 @@ const enableObservationDomains = async (
|
||||
};
|
||||
|
||||
const accessibilityForFrames = async (
|
||||
context: CaptureContext,
|
||||
state: CaptureState,
|
||||
frames: readonly { readonly frame_id: string }[],
|
||||
limitations: string[],
|
||||
): Promise<ReturnType<typeof captureAccessibility>> => {
|
||||
const nodes: WebPageInspection["accessibility"]["nodes"] = [];
|
||||
let total = 0;
|
||||
const { context, limitations, events } = state;
|
||||
const results: unknown[] = [];
|
||||
let unavailable = false;
|
||||
for (const frame of frames) {
|
||||
const result = await optionalCdpCommand(
|
||||
context,
|
||||
@@ -308,24 +365,45 @@ const accessibilityForFrames = async (
|
||||
{ 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);
|
||||
if (result === undefined) unavailable = true;
|
||||
else results.push(result);
|
||||
}
|
||||
return { total, nodes };
|
||||
if (unavailable) events.completeness.unavailable("accessibility");
|
||||
const capture = captureAccessibility(
|
||||
results,
|
||||
context.input.limits.max_ax_nodes,
|
||||
{
|
||||
includeText: context.input.include_accessibility_text,
|
||||
maximumFieldBytes: context.input.limits.max_ax_text_field_bytes,
|
||||
maximumTotalBytes: context.input.limits.max_total_ax_text_bytes,
|
||||
...(results.length === 0 && unavailable ? { unavailable: true } : {}),
|
||||
},
|
||||
);
|
||||
if (!context.input.include_accessibility_text)
|
||||
events.completeness.exclude(
|
||||
"accessibility",
|
||||
"not_approved",
|
||||
capture.textCapture.excluded_fields,
|
||||
);
|
||||
if (capture.textCapture.status === "truncated")
|
||||
events.completeness.truncate("accessibility");
|
||||
return capture;
|
||||
};
|
||||
|
||||
const captureScripts = async (
|
||||
context: CaptureContext,
|
||||
events: CdpCaptureEvents,
|
||||
truncatedSections: Set<string>,
|
||||
): Promise<WebPageInspection["scripts"]> => {
|
||||
rawResources: readonly CapturedResource[],
|
||||
resources: WebPageInspection["resources"],
|
||||
): Promise<CapturedScripts> => {
|
||||
let totalSourceBytes = 0;
|
||||
const items: WebPageInspection["scripts"]["items"] = [];
|
||||
const drafts: {
|
||||
readonly item: Omit<
|
||||
WebPageInspection["scripts"]["items"][number],
|
||||
"script_key"
|
||||
>;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
}[] = [];
|
||||
for (const script of events.scripts.values()) {
|
||||
let source: WebPageInspection["scripts"]["items"][number]["source"] =
|
||||
sourceExcluded("source capture was not approved");
|
||||
@@ -334,13 +412,13 @@ const captureScripts = async (
|
||||
source = sourceExcluded(
|
||||
"declared script length exceeds per-script limit",
|
||||
);
|
||||
truncatedSections.add("script_sources");
|
||||
events.completeness.truncate("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");
|
||||
events.completeness.truncate("script_sources");
|
||||
} else {
|
||||
const result = requiredRecord(
|
||||
await context.connection.send(
|
||||
@@ -360,37 +438,103 @@ const captureScripts = async (
|
||||
source = sourceExcluded(
|
||||
"actual source exceeds configured byte limits",
|
||||
);
|
||||
truncatedSections.add("script_sources");
|
||||
events.completeness.truncate("script_sources");
|
||||
} else {
|
||||
source = sourceResult(content);
|
||||
totalSourceBytes += bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
items.push({
|
||||
script_id: script.scriptId,
|
||||
const inventoryScript = {
|
||||
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,
|
||||
};
|
||||
drafts.push({
|
||||
item: {
|
||||
...inventoryScript,
|
||||
origin: script.origin,
|
||||
resource_reconciliation: reconcileCapturedWebScript(
|
||||
{ ...inventoryScript, rawUrl: script.rawUrl },
|
||||
rawResources,
|
||||
resources,
|
||||
),
|
||||
source,
|
||||
},
|
||||
sourceMapRawUrl: script.sourceMapRawUrl,
|
||||
});
|
||||
}
|
||||
return { total: events.scripts.size, items };
|
||||
if (!context.input.include_script_sources)
|
||||
events.completeness.exclude(
|
||||
"script_sources",
|
||||
"not_approved",
|
||||
events.scripts.size,
|
||||
);
|
||||
const keyed = drafts.map((draft) => ({
|
||||
...draft,
|
||||
base: stableWebScriptKey(draft.item),
|
||||
}));
|
||||
keyed.sort(
|
||||
(left, right) =>
|
||||
left.base.localeCompare(right.base) ||
|
||||
sourceDigest(left.item.source).localeCompare(
|
||||
sourceDigest(right.item.source),
|
||||
),
|
||||
);
|
||||
const totals = new Map<string, number>();
|
||||
for (const { base } of keyed) totals.set(base, (totals.get(base) ?? 0) + 1);
|
||||
const seen = new Map<string, number>();
|
||||
const sourceMapRequests: WebSourceMapRequest[] = [];
|
||||
const items = keyed.map(({ base, item, sourceMapRawUrl }) => {
|
||||
const occurrence = (seen.get(base) ?? 0) + 1;
|
||||
seen.set(base, occurrence);
|
||||
const scriptKey =
|
||||
totals.get(base) === 1 ? base : `${base}_${String(occurrence)}`;
|
||||
if (item.source_map_url !== null && sourceMapRawUrl !== null)
|
||||
sourceMapRequests.push({
|
||||
scriptKey,
|
||||
declaredUrl: item.source_map_url,
|
||||
fetchUrl: sourceMapRawUrl,
|
||||
});
|
||||
return { script_key: scriptKey, ...item };
|
||||
});
|
||||
return {
|
||||
inventory: { total: events.scripts.size, items },
|
||||
sourceMapRequests,
|
||||
};
|
||||
};
|
||||
|
||||
const sourceDigest = (
|
||||
source: WebPageInspection["scripts"]["items"][number]["source"],
|
||||
): string => (source.included ? source.artifact.sha256 : source.reason);
|
||||
|
||||
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 captureWorkers = async (
|
||||
context: CaptureContext,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
state: CaptureState,
|
||||
frameIds: ReadonlySet<string>,
|
||||
limitations: string[],
|
||||
): Promise<{
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["workers"];
|
||||
}> => {
|
||||
const { context, allowedOrigins, limitations, events } = state;
|
||||
const completeness = events.completeness;
|
||||
const result = await optionalCdpCommand(
|
||||
{ ...context, sessionId: undefined },
|
||||
"Target.getTargets",
|
||||
@@ -399,6 +543,7 @@ const captureWorkers = async (
|
||||
);
|
||||
const items: WebPageInspection["workers"] = [];
|
||||
let total = 0;
|
||||
if (result === undefined) completeness.unavailable("workers");
|
||||
for (const target of recordsValue(recordValue(result)?.targetInfos)) {
|
||||
const type = stringValue(target.type) ?? "";
|
||||
const url = allowedSanitizedUrl(target.url, allowedOrigins);
|
||||
@@ -406,8 +551,23 @@ const captureWorkers = async (
|
||||
stringValue(target.openerId) === context.target.id ||
|
||||
(stringValue(target.parentFrameId) !== undefined &&
|
||||
frameIds.has(stringValue(target.parentFrameId) ?? ""));
|
||||
if (!type.includes("worker") || url === undefined || !relatedToPage)
|
||||
if (!type.includes("worker")) continue;
|
||||
if (!relatedToPage) {
|
||||
completeness.exclude("workers", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
if (url === undefined) {
|
||||
const rawUrl = stringValue(target.url);
|
||||
completeness.exclude(
|
||||
"workers",
|
||||
rawUrl === undefined || rawUrl === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(rawUrl)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
total += 1;
|
||||
if (items.length >= context.input.limits.max_workers) continue;
|
||||
items.push({
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
import type { WebPageInspection } from "../domain/browserObservation.js";
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import {
|
||||
numberValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
type ResponseMetadata = WebPageInspection["metadata"]["responses"][number];
|
||||
type LinkMetadata = ResponseMetadata["links"][number];
|
||||
type AgentHint = WebPageInspection["metadata"]["agent_hints"][number];
|
||||
|
||||
/** Normalize an allowlisted subset of response metadata and discard raw headers. */
|
||||
export const safeResponseMetadata = (
|
||||
requestId: string,
|
||||
url: string,
|
||||
response: UnknownRecord,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): {
|
||||
readonly response: ResponseMetadata;
|
||||
readonly agentHints: AgentHint[];
|
||||
} => {
|
||||
const headers = normalizedHeaders(response.headers);
|
||||
const links = parseLinks(headers.get("link"), url, allowedOrigins);
|
||||
const csp = parseCsp(
|
||||
headers.get("content-security-policy"),
|
||||
url,
|
||||
allowedOrigins,
|
||||
);
|
||||
const agentHints = [
|
||||
...links.flatMap((link) =>
|
||||
link.rel.some(isAgentRel)
|
||||
? [agentHint("link_rel", link.rel.join(" "), link.href)]
|
||||
: [],
|
||||
),
|
||||
...agentHeaderNames.flatMap((name) =>
|
||||
headers.has(name) ? [agentHint("response_header", name, null)] : [],
|
||||
),
|
||||
...wellKnownHint(url),
|
||||
];
|
||||
return {
|
||||
response: {
|
||||
request_id: requestId,
|
||||
url,
|
||||
mime_type: boundedHeader(stringValue(response.mimeType)),
|
||||
content_length: nonnegativeInteger(headers.get("content-length")),
|
||||
content_encoding: boundedHeader(headers.get("content-encoding")),
|
||||
csp,
|
||||
links,
|
||||
policies: {
|
||||
coop: policyToken(headers.get("cross-origin-opener-policy")),
|
||||
coep: policyToken(headers.get("cross-origin-embedder-policy")),
|
||||
corp: policyToken(headers.get("cross-origin-resource-policy")),
|
||||
referrer_policy: policyToken(headers.get("referrer-policy")),
|
||||
x_content_type_options: policyToken(
|
||||
headers.get("x-content-type-options"),
|
||||
),
|
||||
permissions_policy_features: permissionFeatures(
|
||||
headers.get("permissions-policy"),
|
||||
),
|
||||
},
|
||||
},
|
||||
agentHints,
|
||||
};
|
||||
};
|
||||
|
||||
const normalizedHeaders = (value: unknown): ReadonlyMap<string, string> => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return new Map();
|
||||
const headers = new Map<string, string>();
|
||||
for (const [name, raw] of Object.entries(value).slice(0, 500)) {
|
||||
const normalized = name.toLowerCase().slice(0, 256);
|
||||
const header =
|
||||
typeof raw === "string"
|
||||
? raw
|
||||
: typeof raw === "number" && Number.isFinite(raw)
|
||||
? String(raw)
|
||||
: undefined;
|
||||
if (header !== undefined) headers.set(normalized, header.slice(0, 65_536));
|
||||
}
|
||||
return headers;
|
||||
};
|
||||
|
||||
const parseCsp = (
|
||||
value: string | undefined,
|
||||
baseUrl: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): ResponseMetadata["csp"] => {
|
||||
const directives: ResponseMetadata["csp"]["directives"] = [];
|
||||
let nonceCount = 0;
|
||||
let hashCount = 0;
|
||||
for (const rawDirective of (value ?? "").split(";").slice(0, 100)) {
|
||||
const [rawName, ...tokens] = rawDirective.trim().split(/\s+/u);
|
||||
const name = (rawName ?? "").toLowerCase();
|
||||
if (!/^[a-z][a-z0-9-]{0,99}$/u.test(name)) continue;
|
||||
const sources: ResponseMetadata["csp"]["directives"][number]["sources"] =
|
||||
[];
|
||||
for (const token of tokens.slice(0, 100)) {
|
||||
const lower = token.toLowerCase();
|
||||
if (lower.startsWith("'nonce-")) {
|
||||
nonceCount += 1;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
lower.startsWith("'sha256-") ||
|
||||
lower.startsWith("'sha384-") ||
|
||||
lower.startsWith("'sha512-")
|
||||
) {
|
||||
hashCount += 1;
|
||||
continue;
|
||||
}
|
||||
sources.push(cspSource(token, baseUrl, allowedOrigins));
|
||||
}
|
||||
directives.push({ name, sources });
|
||||
}
|
||||
return { directives, nonce_count: nonceCount, hash_count: hashCount };
|
||||
};
|
||||
|
||||
const cspSource = (
|
||||
token: string,
|
||||
baseUrl: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): ResponseMetadata["csp"]["directives"][number]["sources"][number] => {
|
||||
const lower = token.toLowerCase();
|
||||
if (/^'[a-z0-9-]+'$/u.test(lower))
|
||||
return { kind: "keyword", value: lower.slice(0, 100) };
|
||||
if (/^[a-z][a-z0-9+.-]*:$/u.test(lower))
|
||||
return { kind: "scheme", value: lower.slice(0, 100) };
|
||||
try {
|
||||
const parsed = new URL(token, baseUrl);
|
||||
return allowedOrigins.has(parsed.origin)
|
||||
? { kind: "approved_origin", value: parsed.origin }
|
||||
: { kind: "external_origin", value: null };
|
||||
} catch {
|
||||
return { kind: "other", value: null };
|
||||
}
|
||||
};
|
||||
|
||||
const parseLinks = (
|
||||
value: string | undefined,
|
||||
baseUrl: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): LinkMetadata[] => {
|
||||
const links: LinkMetadata[] = [];
|
||||
for (const entry of splitLinkHeader(value ?? "").slice(0, 100)) {
|
||||
const match = /^\s*<([^>]{1,4096})>(.*)$/u.exec(entry);
|
||||
if (match === null) continue;
|
||||
const parameters = linkParameters(match[2] ?? "");
|
||||
const destination = safeDestination(
|
||||
match[1] ?? "",
|
||||
baseUrl,
|
||||
allowedOrigins,
|
||||
);
|
||||
links.push({
|
||||
href: destination.url,
|
||||
destination_scope: destination.scope,
|
||||
rel: (parameters.get("rel") ?? "")
|
||||
.toLowerCase()
|
||||
.split(/\s+/u)
|
||||
.filter(Boolean)
|
||||
.slice(0, 32),
|
||||
as: boundedHeader(parameters.get("as")),
|
||||
type: boundedHeader(parameters.get("type")),
|
||||
crossorigin: boundedHeader(parameters.get("crossorigin")),
|
||||
});
|
||||
}
|
||||
return links;
|
||||
};
|
||||
|
||||
const splitLinkHeader = (value: string): string[] => {
|
||||
const entries: string[] = [];
|
||||
let start = 0;
|
||||
let quoted = false;
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
const character = value[index];
|
||||
if (character === '"' && value[index - 1] !== "\\") quoted = !quoted;
|
||||
if (character !== "," || quoted) continue;
|
||||
entries.push(value.slice(start, index));
|
||||
start = index + 1;
|
||||
}
|
||||
entries.push(value.slice(start));
|
||||
return entries;
|
||||
};
|
||||
|
||||
const linkParameters = (value: string): ReadonlyMap<string, string> => {
|
||||
const parameters = new Map<string, string>();
|
||||
for (const raw of value.split(";").slice(1, 50)) {
|
||||
const separator = raw.indexOf("=");
|
||||
const name = (separator < 0 ? raw : raw.slice(0, separator))
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (!/^[a-z][a-z0-9-]{0,99}$/u.test(name)) continue;
|
||||
const parameter = separator < 0 ? "" : raw.slice(separator + 1).trim();
|
||||
parameters.set(name, unquote(parameter).slice(0, 1_024));
|
||||
}
|
||||
return parameters;
|
||||
};
|
||||
|
||||
const safeDestination = (
|
||||
value: string,
|
||||
baseUrl: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): {
|
||||
readonly url: string | null;
|
||||
readonly scope: LinkMetadata["destination_scope"];
|
||||
} => {
|
||||
try {
|
||||
const parsed = new URL(value, baseUrl);
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
||||
return { url: null, scope: "unsupported" };
|
||||
if (!allowedOrigins.has(parsed.origin))
|
||||
return { url: null, scope: "outside_policy" };
|
||||
return { url: sanitizeBrowserUrl(parsed.href).url, scope: "approved" };
|
||||
} catch {
|
||||
return { url: null, scope: "unsupported" };
|
||||
}
|
||||
};
|
||||
|
||||
const permissionFeatures = (value: string | undefined): string[] =>
|
||||
[
|
||||
...new Set(
|
||||
(value ?? "")
|
||||
.split(",")
|
||||
.map((entry) => entry.split("=", 1)[0]?.trim().toLowerCase() ?? "")
|
||||
.filter((feature) => /^[a-z][a-z0-9-]{0,99}$/u.test(feature)),
|
||||
),
|
||||
]
|
||||
.sort()
|
||||
.slice(0, 200);
|
||||
|
||||
const wellKnownHint = (url: string): AgentHint[] => {
|
||||
try {
|
||||
const path = new URL(url).pathname.toLowerCase();
|
||||
return wellKnownAgentPaths.has(path)
|
||||
? [agentHint("well_known_resource", path, sanitizeBrowserUrl(url).url)]
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const agentHint = (
|
||||
mechanism: AgentHint["mechanism"],
|
||||
declaration: string,
|
||||
url: string | null,
|
||||
): AgentHint => ({
|
||||
mechanism,
|
||||
declaration: declaration.slice(0, 256),
|
||||
url,
|
||||
trust: "page-declared-untrusted",
|
||||
});
|
||||
|
||||
const isAgentRel = (value: string): boolean =>
|
||||
["mcp", "model-context", "ai-plugin", "service-desc"].includes(value);
|
||||
|
||||
const policyToken = (value: string | undefined): string | null => {
|
||||
const token = (value ?? "").trim().toLowerCase();
|
||||
return /^[a-z][a-z0-9_.-]{0,99}$/u.test(token) ? token : null;
|
||||
};
|
||||
|
||||
const nonnegativeInteger = (value: string | undefined): number | null => {
|
||||
const number = numberValue(value === undefined ? undefined : Number(value));
|
||||
return number === undefined ? null : Math.max(0, Math.trunc(number));
|
||||
};
|
||||
|
||||
const boundedHeader = (value: string | undefined): string | null =>
|
||||
value === undefined ? null : value.trim().toLowerCase().slice(0, 256);
|
||||
|
||||
const unquote = (value: string): string =>
|
||||
value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1) : value;
|
||||
|
||||
const agentHeaderNames = ["x-model-context", "x-webmcp", "mcp-server"] as const;
|
||||
const wellKnownAgentPaths: ReadonlySet<string> = new Set([
|
||||
"/.well-known/ai-plugin.json",
|
||||
"/.well-known/mcp",
|
||||
"/.well-known/model-context",
|
||||
]);
|
||||
@@ -0,0 +1,164 @@
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import type {
|
||||
CaptureWebScreenshotInput,
|
||||
WebScreenshot,
|
||||
} from "../domain/webScreenshot.js";
|
||||
import { createWebScreenshotArtifact } from "../domain/webScreenshot.js";
|
||||
import { BrowserObservationError } from "../domain/errors.js";
|
||||
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import type { CdpConnection, CdpEvent } from "./CdpConnection.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
recordValue,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { mainFrameUrl } from "./CdpCaptureDocuments.js";
|
||||
import { captureFrames } from "./CdpCaptureDocuments.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import { decodeCanonicalBase64 } from "../domain/webScreenshot.js";
|
||||
|
||||
interface ScreenshotContext {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string;
|
||||
readonly discovery: CdpEndpointDiscovery;
|
||||
readonly target: CdpEndpointTarget;
|
||||
readonly input: CaptureWebScreenshotInput;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly progress?: ProgressReporter;
|
||||
}
|
||||
|
||||
/** Capture the current viewport without navigation, evaluation, or page mutation. */
|
||||
export const captureCdpScreenshot = async (
|
||||
context: ScreenshotContext,
|
||||
): Promise<WebScreenshot> => {
|
||||
const origins = new Set(context.input.allowed_origins);
|
||||
await context.progress?.report({
|
||||
phase: "browser_observation",
|
||||
completed: 1,
|
||||
total: 2,
|
||||
message: "Authorizing current screenshot frame",
|
||||
});
|
||||
await context.connection.send(
|
||||
"Page.enable",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const before = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const beforeUrl = mainFrameUrl(before);
|
||||
const authorized = allowedSanitizedUrl(beforeUrl, origins);
|
||||
const mainFrame = captureFrames(before, origins, 1).items[0];
|
||||
if (authorized === undefined || mainFrame === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
const navigation = { changed: false, leftScope: false };
|
||||
const removeListener = context.connection.onEvent((event) => {
|
||||
if (event.sessionId !== context.sessionId) return;
|
||||
observeScreenshotNavigation(event, mainFrame.frame_id, origins, navigation);
|
||||
});
|
||||
let result: ReturnType<typeof recordValue>;
|
||||
let after: unknown;
|
||||
try {
|
||||
result = recordValue(
|
||||
await context.connection.send(
|
||||
"Page.captureScreenshot",
|
||||
{ format: "png", fromSurface: true, captureBeyondViewport: false },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
),
|
||||
);
|
||||
after = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
} finally {
|
||||
removeListener();
|
||||
}
|
||||
const encoded = stringValue(result?.data);
|
||||
const bytes =
|
||||
encoded === undefined ? undefined : decodeCanonicalBase64(encoded);
|
||||
if (
|
||||
bytes === undefined ||
|
||||
bytes.byteLength > context.input.maximum_image_bytes
|
||||
)
|
||||
throw new BrowserObservationError("inspect_web_page", "payload_limit");
|
||||
const dimensions = pngDimensions(bytes);
|
||||
if (navigation.leftScope)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
const afterUrl = mainFrameUrl(after);
|
||||
if (
|
||||
navigation.changed ||
|
||||
afterUrl !== beforeUrl ||
|
||||
allowedSanitizedUrl(afterUrl, origins) === undefined
|
||||
)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_changed");
|
||||
await context.progress?.report({
|
||||
phase: "browser_observation",
|
||||
completed: 2,
|
||||
total: 2,
|
||||
message: "Screenshot capture complete",
|
||||
terminal: true,
|
||||
});
|
||||
return {
|
||||
schema_version: 1,
|
||||
browser: context.discovery.version,
|
||||
target: {
|
||||
target_id: context.target.id,
|
||||
url: authorized.url,
|
||||
origin: authorized.origin ?? "",
|
||||
},
|
||||
captured_at: new Date().toISOString(),
|
||||
viewport: dimensions,
|
||||
artifact: createWebScreenshotArtifact(bytes),
|
||||
completeness: new CdpCaptureCompleteness().snapshot(),
|
||||
limitations: [
|
||||
"The screenshot contains the visible viewport and may include sensitive on-screen content; capture requires separate approval.",
|
||||
"REA does not scroll, evaluate JavaScript, or capture beyond the current viewport.",
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const observeScreenshotNavigation = (
|
||||
event: CdpEvent,
|
||||
mainFrameId: string,
|
||||
origins: ReadonlySet<string>,
|
||||
state: { changed: boolean; leftScope: boolean },
|
||||
): void => {
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return;
|
||||
const frame =
|
||||
event.method === "Page.frameNavigated" ? recordValue(params.frame) : params;
|
||||
if (
|
||||
(event.method !== "Page.frameNavigated" &&
|
||||
event.method !== "Page.navigatedWithinDocument") ||
|
||||
(stringValue(frame?.id) ?? stringValue(frame?.frameId)) !== mainFrameId
|
||||
)
|
||||
return;
|
||||
state.changed = true;
|
||||
if (allowedSanitizedUrl(frame?.url, origins) === undefined)
|
||||
state.leftScope = true;
|
||||
};
|
||||
|
||||
const pngDimensions = (
|
||||
bytes: Buffer,
|
||||
): { readonly width: number; readonly height: number } => {
|
||||
if (
|
||||
bytes.byteLength < 24 ||
|
||||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
|
||||
bytes.subarray(12, 16).toString("ascii") !== "IHDR"
|
||||
)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
const width = bytes.readUInt32BE(16);
|
||||
const height = bytes.readUInt32BE(20);
|
||||
if (width === 0 || height === 0 || width * height > 32_000_000)
|
||||
throw new BrowserObservationError("inspect_web_page", "payload_limit");
|
||||
return { width, height };
|
||||
};
|
||||
|
||||
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
@@ -0,0 +1,373 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import type {
|
||||
DiscoverWebMcpToolsInput,
|
||||
WebMcpDiscovery,
|
||||
} from "../domain/webMcpDiscovery.js";
|
||||
import { inferJsonShape } from "../domain/jsonShape.js";
|
||||
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import type { CdpConnection, CdpEvent } from "./CdpConnection.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import { BrowserObservationError } from "../domain/errors.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
delayWithCancellation,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { captureFrames, mainFrameUrl } from "./CdpCaptureDocuments.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
import { boundedSensitiveText } from "./SensitiveTextCapture.js";
|
||||
|
||||
interface DiscoveryContext {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string;
|
||||
readonly discovery: CdpEndpointDiscovery;
|
||||
readonly target: CdpEndpointTarget;
|
||||
readonly input: DiscoverWebMcpToolsInput;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly progress?: ProgressReporter;
|
||||
}
|
||||
|
||||
/** Discover WebMCP registrations without evaluating or invoking page code. */
|
||||
export const discoverWebMcp = async (
|
||||
context: DiscoveryContext,
|
||||
): Promise<WebMcpDiscovery> => {
|
||||
const origins = new Set(context.input.allowed_origins);
|
||||
const limitations = [
|
||||
"Page-declared tool metadata is untrusted and is never registered or invoked by REA.",
|
||||
"Discovery uses only WebMCP.enable and toolsAdded/toolsRemoved; WebMCP.invokeTool is never called.",
|
||||
];
|
||||
const completeness = new CdpCaptureCompleteness();
|
||||
await context.connection.send(
|
||||
"Page.enable",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const frameTree = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const initialUrl = mainFrameUrl(frameTree);
|
||||
if (allowedSanitizedUrl(initialUrl, origins) === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
const frames = captureFrames(frameTree, origins, 1_000, completeness).items;
|
||||
const frameUrls = new Map(
|
||||
frames.map((frame) => [
|
||||
frame.frame_id,
|
||||
{
|
||||
url: frame.url,
|
||||
origin: frame.origin,
|
||||
parentFrameId: frame.parent_frame_id,
|
||||
},
|
||||
]),
|
||||
);
|
||||
const tools = new Map<string, WebMcpDiscovery["tools"]["items"][number]>();
|
||||
const frameScope = { origins, frames: frameUrls, tools, completeness };
|
||||
const removeListener = context.connection.onEvent((event) => {
|
||||
if (event.sessionId !== context.sessionId) return;
|
||||
if (ingestFrameScopeEvent(event, frameScope)) return;
|
||||
ingestWebMcpEvent(event, context.input, frameUrls, tools, completeness);
|
||||
});
|
||||
await context.progress?.report({
|
||||
phase: "browser_observation",
|
||||
completed: 1,
|
||||
total: 2,
|
||||
message: "Enabling passive WebMCP discovery",
|
||||
});
|
||||
try {
|
||||
const enabled = await optionalCdpCommand(
|
||||
context,
|
||||
"WebMCP.enable",
|
||||
{},
|
||||
limitations,
|
||||
);
|
||||
const available = enabled !== undefined;
|
||||
if (!available) {
|
||||
completeness.unavailable("webmcp_tools");
|
||||
} else
|
||||
// CDP sends the enable response before the required toolsAdded replay.
|
||||
await delayWithCancellation(
|
||||
Math.max(context.input.observation_ms, 25),
|
||||
context.signal,
|
||||
);
|
||||
await assertStableAuthorizedFrame(context, initialUrl, origins);
|
||||
return result(
|
||||
context,
|
||||
frameTree,
|
||||
tools,
|
||||
completeness,
|
||||
limitations,
|
||||
available,
|
||||
);
|
||||
} finally {
|
||||
removeListener();
|
||||
await context.progress?.report({
|
||||
phase: "browser_observation",
|
||||
completed: 2,
|
||||
total: 2,
|
||||
message: "WebMCP discovery complete",
|
||||
terminal: true,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
interface FrameScopeState {
|
||||
readonly origins: ReadonlySet<string>;
|
||||
readonly frames: Map<string, FrameScopeFrame>;
|
||||
readonly tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>;
|
||||
readonly completeness: CdpCaptureCompleteness;
|
||||
}
|
||||
|
||||
interface FrameScopeFrame {
|
||||
readonly url: string;
|
||||
readonly origin: string | null;
|
||||
readonly parentFrameId: string | null;
|
||||
}
|
||||
|
||||
const ingestFrameScopeEvent = (
|
||||
event: CdpEvent,
|
||||
state: FrameScopeState,
|
||||
): boolean => {
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return false;
|
||||
if (event.method === "Page.frameDetached") {
|
||||
const frameId = stringValue(params.frameId);
|
||||
if (frameId === undefined || frameId.length > 256)
|
||||
state.completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
else removeFrame(frameId, state.frames, state.tools);
|
||||
return true;
|
||||
}
|
||||
const frame =
|
||||
event.method === "Page.frameNavigated" ? recordValue(params.frame) : params;
|
||||
if (
|
||||
event.method !== "Page.frameNavigated" &&
|
||||
event.method !== "Page.navigatedWithinDocument"
|
||||
)
|
||||
return false;
|
||||
const frameId = stringValue(frame?.id) ?? stringValue(frame?.frameId);
|
||||
if (frameId === undefined || frameId.length > 256) {
|
||||
state.completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
return true;
|
||||
}
|
||||
const url = allowedSanitizedUrl(frame?.url, state.origins);
|
||||
if (url === undefined || url.origin === null) {
|
||||
removeFrame(frameId, state.frames, state.tools);
|
||||
state.completeness.exclude("webmcp_tools", "out_of_target_scope");
|
||||
return true;
|
||||
}
|
||||
state.frames.set(frameId, {
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
parentFrameId:
|
||||
(stringValue(frame?.parentId) ??
|
||||
state.frames.get(frameId)?.parentFrameId ??
|
||||
"") ||
|
||||
null,
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
const removeFrame = (
|
||||
frameId: string,
|
||||
frames: Map<string, FrameScopeFrame>,
|
||||
tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>,
|
||||
): void => {
|
||||
const pending = [frameId];
|
||||
const removed = new Set<string>();
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined || removed.has(current)) continue;
|
||||
removed.add(current);
|
||||
for (const [candidate, frame] of frames)
|
||||
if (frame.parentFrameId === current) pending.push(candidate);
|
||||
frames.delete(current);
|
||||
}
|
||||
for (const [key, tool] of tools)
|
||||
if (removed.has(tool.frame_id)) tools.delete(key);
|
||||
};
|
||||
|
||||
const assertStableAuthorizedFrame = async (
|
||||
context: DiscoveryContext,
|
||||
initialUrl: string | undefined,
|
||||
origins: ReadonlySet<string>,
|
||||
): Promise<void> => {
|
||||
const finalTree = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const finalUrl = mainFrameUrl(finalTree);
|
||||
if (allowedSanitizedUrl(finalUrl, origins) === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
if (finalUrl !== initialUrl)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_changed");
|
||||
};
|
||||
|
||||
const ingestWebMcpEvent = (
|
||||
event: CdpEvent,
|
||||
input: DiscoverWebMcpToolsInput,
|
||||
frames: ReadonlyMap<
|
||||
string,
|
||||
{ readonly url: string; readonly origin: string | null }
|
||||
>,
|
||||
tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>,
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): void => {
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return;
|
||||
if (event.method === "WebMCP.toolsRemoved") {
|
||||
for (const removed of recordsValue(params.tools)) {
|
||||
const name = stringValue(removed.name);
|
||||
const frameId = stringValue(removed.frameId);
|
||||
if (name === undefined || frameId === undefined) continue;
|
||||
for (const [key, tool] of tools)
|
||||
if (tool.name === name && tool.frame_id === frameId) tools.delete(key);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.method !== "WebMCP.toolsAdded") return;
|
||||
for (const declared of recordsValue(params.tools)) {
|
||||
const normalized = normalizeTool(declared, input, frames, completeness);
|
||||
if (normalized === undefined) continue;
|
||||
if (!tools.has(normalized.tool_key) && tools.size >= input.max_tools) {
|
||||
completeness.drop("webmcp_tools");
|
||||
continue;
|
||||
}
|
||||
tools.set(normalized.tool_key, normalized);
|
||||
}
|
||||
};
|
||||
|
||||
const normalizeTool = (
|
||||
value: UnknownRecord,
|
||||
input: DiscoverWebMcpToolsInput,
|
||||
frames: ReadonlyMap<
|
||||
string,
|
||||
{ readonly url: string; readonly origin: string | null }
|
||||
>,
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): WebMcpDiscovery["tools"]["items"][number] | undefined => {
|
||||
const frameId = stringValue(value.frameId);
|
||||
const name = stringValue(value.name);
|
||||
const frame = frameId === undefined ? undefined : frames.get(frameId);
|
||||
if (
|
||||
frameId === undefined ||
|
||||
name === undefined ||
|
||||
frame?.origin === null ||
|
||||
frame === undefined
|
||||
) {
|
||||
completeness.exclude("webmcp_tools", "out_of_target_scope");
|
||||
return undefined;
|
||||
}
|
||||
const description = boundedSensitiveText(
|
||||
stringValue(value.description) ?? "",
|
||||
4_096,
|
||||
).text;
|
||||
const annotations = recordValue(value.annotations);
|
||||
return {
|
||||
tool_key: toolKey(frame.url, name),
|
||||
name: boundedSensitiveText(name, 512).text,
|
||||
description,
|
||||
frame_id: frameId.slice(0, 256),
|
||||
frame_url: frame.url,
|
||||
owner_origin: frame.origin,
|
||||
declaration_kind:
|
||||
numberValue(value.backendNodeId) === undefined
|
||||
? "imperative"
|
||||
: "declarative",
|
||||
input_schema_shape: schemaShape(value.inputSchema, input, completeness),
|
||||
annotations: {
|
||||
read_only: booleanOrNull(annotations?.readOnly),
|
||||
untrusted_content: booleanOrNull(annotations?.untrustedContent),
|
||||
autosubmit: booleanOrNull(annotations?.autosubmit),
|
||||
},
|
||||
registration_source: registrationSource(
|
||||
recordValue(value.stackTrace),
|
||||
new Set(input.allowed_origins),
|
||||
),
|
||||
trust: "page-declared-untrusted",
|
||||
};
|
||||
};
|
||||
|
||||
const schemaShape = (
|
||||
value: unknown,
|
||||
input: DiscoverWebMcpToolsInput,
|
||||
completeness: CdpCaptureCompleteness,
|
||||
) => {
|
||||
if (recordValue(value) === undefined) return null;
|
||||
const encoded = JSON.stringify(value);
|
||||
const shape = inferJsonShape(encoded, {
|
||||
maximumBytes: input.max_schema_bytes,
|
||||
maximumNodes: input.max_schema_nodes,
|
||||
maximumDepth: input.max_schema_depth,
|
||||
});
|
||||
if (shape === null || shape.truncated) completeness.truncate("webmcp_tools");
|
||||
return shape;
|
||||
};
|
||||
|
||||
const registrationSource = (
|
||||
stack: UnknownRecord | undefined,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): WebMcpDiscovery["tools"]["items"][number]["registration_source"] => {
|
||||
const frame = recordsValue(stack?.callFrames)[0];
|
||||
const url = allowedSanitizedUrl(frame?.url, allowedOrigins);
|
||||
return frame === undefined || url === undefined
|
||||
? null
|
||||
: {
|
||||
url: url.url,
|
||||
line: integerOrNull(frame.lineNumber),
|
||||
column: integerOrNull(frame.columnNumber),
|
||||
};
|
||||
};
|
||||
|
||||
const result = (
|
||||
context: DiscoveryContext,
|
||||
frameTree: unknown,
|
||||
tools: ReadonlyMap<string, WebMcpDiscovery["tools"]["items"][number]>,
|
||||
completeness: CdpCaptureCompleteness,
|
||||
limitations: string[],
|
||||
available: boolean,
|
||||
): WebMcpDiscovery => {
|
||||
const targetUrl = mainFrameUrl(frameTree) ?? context.target.url;
|
||||
const sanitized = allowedSanitizedUrl(
|
||||
targetUrl,
|
||||
new Set(context.input.allowed_origins),
|
||||
);
|
||||
return {
|
||||
schema_version: 1,
|
||||
browser: context.discovery.version,
|
||||
target: {
|
||||
target_id: context.target.id,
|
||||
url: sanitized?.url ?? "[unsupported-url]",
|
||||
origin: sanitized?.origin ?? "",
|
||||
},
|
||||
status: available ? "available" : "unavailable",
|
||||
tools: {
|
||||
total: tools.size + completeness.droppedTotal,
|
||||
items: [...tools.values()].sort((left, right) =>
|
||||
left.tool_key.localeCompare(right.tool_key),
|
||||
),
|
||||
},
|
||||
completeness: completeness.snapshot(),
|
||||
limitations,
|
||||
};
|
||||
};
|
||||
|
||||
const toolKey = (frameUrl: string, name: string): string =>
|
||||
`webmcp_${createHash("sha256").update(`${frameUrl}\0${name}`).digest("hex")}`;
|
||||
|
||||
const booleanOrNull = (value: unknown): boolean | null =>
|
||||
typeof value === "boolean" ? value : null;
|
||||
|
||||
const integerOrNull = (value: unknown): number | null => {
|
||||
const number = numberValue(value);
|
||||
return number === undefined ? null : Math.max(0, Math.trunc(number));
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { isAbsolute, relative } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
/** Canonicalize operator roots before evaluating any Electron file target. */
|
||||
export const canonicalElectronRoots = async (
|
||||
roots: readonly string[],
|
||||
): Promise<readonly string[]> => {
|
||||
const canonical: string[] = [];
|
||||
for (const root of roots) canonical.push(await realpath(root));
|
||||
return [...new Set(canonical)].sort();
|
||||
};
|
||||
|
||||
/** Resolve one file URL and reject host, encoding, and symlink root escapes. */
|
||||
export const authorizedElectronFile = async (
|
||||
value: string,
|
||||
roots: readonly string[],
|
||||
): Promise<string | undefined> => {
|
||||
if (value.length > 65_536 || /%(?:2f|5c)/iu.test(value)) return undefined;
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
url.protocol !== "file:" ||
|
||||
url.hostname !== "" ||
|
||||
url.username !== "" ||
|
||||
url.password !== ""
|
||||
)
|
||||
return undefined;
|
||||
let path: string;
|
||||
try {
|
||||
path = fileURLToPath(url);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (!isAbsolute(path) || path.includes("\0")) return undefined;
|
||||
let canonical: string;
|
||||
try {
|
||||
canonical = await realpath(path);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
return roots.some((root) => withinRoot(root, canonical))
|
||||
? canonical
|
||||
: undefined;
|
||||
};
|
||||
|
||||
const withinRoot = (root: string, path: string): boolean => {
|
||||
const remainder = relative(root, path);
|
||||
return (
|
||||
remainder === "" || (!remainder.startsWith("..") && !isAbsolute(remainder))
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,222 @@
|
||||
import { inflateSync } from "node:zlib";
|
||||
|
||||
import type {
|
||||
CompareWebScreenshotsInput,
|
||||
WebScreenshotArtifact,
|
||||
WebScreenshotDiff,
|
||||
} from "../domain/webScreenshot.js";
|
||||
import { decodeCanonicalBase64 } from "../domain/webScreenshot.js";
|
||||
|
||||
interface DecodedPng {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
readonly rgba: Buffer;
|
||||
}
|
||||
|
||||
/** Compare two validated screenshots using bounded, deterministic RGBA metrics. */
|
||||
export const comparePngScreenshots = (
|
||||
input: CompareWebScreenshotsInput,
|
||||
): WebScreenshotDiff => {
|
||||
const before = decodePng(input.before, input.maximum_pixels);
|
||||
const after = decodePng(input.after, input.maximum_pixels);
|
||||
if (before.width !== after.width || before.height !== after.height)
|
||||
return {
|
||||
schema_version: 1,
|
||||
status: "dimension_mismatch",
|
||||
before: dimensions(before),
|
||||
after: dimensions(after),
|
||||
channel_threshold: input.channel_threshold,
|
||||
compared_pixels: 0,
|
||||
changed_pixels: null,
|
||||
changed_ratio: null,
|
||||
maximum_channel_delta: null,
|
||||
mean_absolute_channel_delta: null,
|
||||
limitations: limitations(),
|
||||
};
|
||||
let changedPixels = 0;
|
||||
let maximumDelta = 0;
|
||||
let totalDelta = 0;
|
||||
for (let offset = 0; offset < before.rgba.length; offset += 4) {
|
||||
let changed = false;
|
||||
for (let channel = 0; channel < 4; channel += 1) {
|
||||
const delta = Math.abs(
|
||||
(before.rgba[offset + channel] ?? 0) -
|
||||
(after.rgba[offset + channel] ?? 0),
|
||||
);
|
||||
totalDelta += delta;
|
||||
maximumDelta = Math.max(maximumDelta, delta);
|
||||
if (delta > input.channel_threshold) changed = true;
|
||||
}
|
||||
if (changed) changedPixels += 1;
|
||||
}
|
||||
const pixels = before.width * before.height;
|
||||
return {
|
||||
schema_version: 1,
|
||||
status: changedPixels === 0 ? "identical" : "different",
|
||||
before: dimensions(before),
|
||||
after: dimensions(after),
|
||||
channel_threshold: input.channel_threshold,
|
||||
compared_pixels: pixels,
|
||||
changed_pixels: changedPixels,
|
||||
changed_ratio: changedPixels / pixels,
|
||||
maximum_channel_delta: maximumDelta,
|
||||
mean_absolute_channel_delta: totalDelta / (pixels * 4),
|
||||
limitations: limitations(),
|
||||
};
|
||||
};
|
||||
|
||||
const decodePng = (
|
||||
artifact: WebScreenshotArtifact,
|
||||
maximumPixels: number,
|
||||
): DecodedPng => {
|
||||
const bytes = decodeCanonicalBase64(artifact.data_base64);
|
||||
if (bytes === undefined || !bytes.subarray(0, 8).equals(PNG_SIGNATURE))
|
||||
throw new TypeError("Invalid PNG signature");
|
||||
let offset = 8;
|
||||
let header: ReturnType<typeof parseHeader> | undefined;
|
||||
const compressed: Buffer[] = [];
|
||||
let sawEnd = false;
|
||||
while (offset < bytes.length) {
|
||||
if (offset + 12 > bytes.length) throw new TypeError("Truncated PNG chunk");
|
||||
const length = bytes.readUInt32BE(offset);
|
||||
const type = bytes.subarray(offset + 4, offset + 8).toString("ascii");
|
||||
const dataStart = offset + 8;
|
||||
const dataEnd = dataStart + length;
|
||||
if (dataEnd + 4 > bytes.length) throw new TypeError("Truncated PNG data");
|
||||
const data = bytes.subarray(dataStart, dataEnd);
|
||||
if (type === "IHDR") header = parseHeader(data, maximumPixels);
|
||||
else if (type === "IDAT") compressed.push(data);
|
||||
else if (type === "IEND") {
|
||||
sawEnd = true;
|
||||
break;
|
||||
}
|
||||
offset = dataEnd + 4;
|
||||
}
|
||||
if (header === undefined || !sawEnd || compressed.length === 0)
|
||||
throw new TypeError("Incomplete PNG");
|
||||
const rowBytes = header.width * header.channels;
|
||||
const expected = (rowBytes + 1) * header.height;
|
||||
const raw = inflateSync(Buffer.concat(compressed), {
|
||||
maxOutputLength: expected + 1,
|
||||
});
|
||||
if (raw.byteLength !== expected) throw new TypeError("Unexpected PNG size");
|
||||
return {
|
||||
width: header.width,
|
||||
height: header.height,
|
||||
rgba: unfilter(raw, header.width, header.height, header.channels),
|
||||
};
|
||||
};
|
||||
|
||||
const parseHeader = (data: Buffer, maximumPixels: number) => {
|
||||
if (data.byteLength !== 13) throw new TypeError("Invalid PNG header");
|
||||
const width = data.readUInt32BE(0);
|
||||
const height = data.readUInt32BE(4);
|
||||
const bitDepth = data[8];
|
||||
const colorType = data[9];
|
||||
if (
|
||||
width === 0 ||
|
||||
height === 0 ||
|
||||
width * height > maximumPixels ||
|
||||
bitDepth !== 8 ||
|
||||
(colorType !== 2 && colorType !== 6) ||
|
||||
data[10] !== 0 ||
|
||||
data[11] !== 0 ||
|
||||
data[12] !== 0
|
||||
)
|
||||
throw new TypeError("Unsupported or oversized PNG");
|
||||
return { width, height, channels: colorType === 6 ? 4 : 3 };
|
||||
};
|
||||
|
||||
const unfilter = (
|
||||
raw: Buffer,
|
||||
width: number,
|
||||
height: number,
|
||||
channels: number,
|
||||
): Buffer => {
|
||||
const rowBytes = width * channels;
|
||||
const decoded = Buffer.alloc(rowBytes * height);
|
||||
for (let row = 0; row < height; row += 1) {
|
||||
const rawOffset = row * (rowBytes + 1);
|
||||
const outputOffset = row * rowBytes;
|
||||
const filter = raw[rawOffset];
|
||||
if (filter === undefined || filter > 4)
|
||||
throw new TypeError("Unsupported PNG filter");
|
||||
for (let column = 0; column < rowBytes; column += 1) {
|
||||
const source = raw[rawOffset + 1 + column] ?? 0;
|
||||
const left =
|
||||
column >= channels
|
||||
? (decoded[outputOffset + column - channels] ?? 0)
|
||||
: 0;
|
||||
const above =
|
||||
row > 0 ? (decoded[outputOffset + column - rowBytes] ?? 0) : 0;
|
||||
const upperLeft =
|
||||
row > 0 && column >= channels
|
||||
? (decoded[outputOffset + column - rowBytes - channels] ?? 0)
|
||||
: 0;
|
||||
decoded[outputOffset + column] = applyFilter(
|
||||
filter,
|
||||
source,
|
||||
left,
|
||||
above,
|
||||
upperLeft,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (channels === 4) return decoded;
|
||||
const rgba = Buffer.alloc(width * height * 4);
|
||||
for (
|
||||
let source = 0, target = 0;
|
||||
source < decoded.length;
|
||||
source += 3, target += 4
|
||||
) {
|
||||
rgba[target] = decoded[source] ?? 0;
|
||||
rgba[target + 1] = decoded[source + 1] ?? 0;
|
||||
rgba[target + 2] = decoded[source + 2] ?? 0;
|
||||
rgba[target + 3] = 255;
|
||||
}
|
||||
return rgba;
|
||||
};
|
||||
|
||||
const applyFilter = (
|
||||
filter: number,
|
||||
source: number,
|
||||
left: number,
|
||||
above: number,
|
||||
upperLeft: number,
|
||||
): number => {
|
||||
switch (filter) {
|
||||
case 0:
|
||||
return source;
|
||||
case 1:
|
||||
return (source + left) & 0xff;
|
||||
case 2:
|
||||
return (source + above) & 0xff;
|
||||
case 3:
|
||||
return (source + Math.floor((left + above) / 2)) & 0xff;
|
||||
case 4:
|
||||
return (source + paeth(left, above, upperLeft)) & 0xff;
|
||||
default:
|
||||
throw new TypeError("Unsupported PNG filter");
|
||||
}
|
||||
};
|
||||
|
||||
const paeth = (left: number, above: number, upperLeft: number): number => {
|
||||
const prediction = left + above - upperLeft;
|
||||
const leftDistance = Math.abs(prediction - left);
|
||||
const aboveDistance = Math.abs(prediction - above);
|
||||
const upperLeftDistance = Math.abs(prediction - upperLeft);
|
||||
return leftDistance <= aboveDistance && leftDistance <= upperLeftDistance
|
||||
? left
|
||||
: aboveDistance <= upperLeftDistance
|
||||
? above
|
||||
: upperLeft;
|
||||
};
|
||||
|
||||
const dimensions = ({ width, height }: DecodedPng) => ({ width, height });
|
||||
|
||||
const limitations = (): string[] => [
|
||||
"Pixel comparison does not perform OCR, semantic layout analysis, or perceptual color correction.",
|
||||
"Only non-interlaced 8-bit RGB and RGBA PNG screenshots are accepted.",
|
||||
];
|
||||
|
||||
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
@@ -0,0 +1,35 @@
|
||||
const SECRET_ASSIGNMENT =
|
||||
/\b(authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret|cookie|session)\b\s*[:=]\s*(?:Bearer\s+[A-Za-z0-9._~+/=-]+|"[^"]*"|'[^']*'|[^\s,;]+)/giu;
|
||||
const BEARER = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
|
||||
const JWT = /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/gu;
|
||||
|
||||
/** Redact credential-shaped substrings before approved console text is retained. */
|
||||
export const redactSensitiveText = (value: string): string =>
|
||||
value
|
||||
.replace(SECRET_ASSIGNMENT, (_match, name: string) => `${name}=[REDACTED]`)
|
||||
.replace(BEARER, "Bearer [REDACTED]")
|
||||
.replace(JWT, "[REDACTED_JWT]");
|
||||
|
||||
/** Return a UTF-8-bounded prefix without splitting a code point. */
|
||||
export const boundedSensitiveText = (
|
||||
value: string,
|
||||
maximumBytes: number,
|
||||
): {
|
||||
readonly text: string;
|
||||
readonly bytes: number;
|
||||
readonly truncated: boolean;
|
||||
} => {
|
||||
const redacted = redactSensitiveText(value);
|
||||
const total = Buffer.byteLength(redacted);
|
||||
if (total <= maximumBytes)
|
||||
return { text: redacted, bytes: total, truncated: false };
|
||||
let text = "";
|
||||
let bytes = 0;
|
||||
for (const character of redacted) {
|
||||
const size = Buffer.byteLength(character);
|
||||
if (bytes + size > maximumBytes) break;
|
||||
text += character;
|
||||
bytes += size;
|
||||
}
|
||||
return { text, bytes, truncated: true };
|
||||
};
|
||||
@@ -0,0 +1,445 @@
|
||||
import { AnyMap, eachMapping } from "@jridgewell/trace-mapping";
|
||||
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import type {
|
||||
AnalyzeWebBundleInput,
|
||||
WebBundleAnalysis,
|
||||
} from "../domain/webBundleAnalysis.js";
|
||||
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
|
||||
|
||||
export interface WebSourceMapRequest {
|
||||
readonly scriptKey: string;
|
||||
readonly declaredUrl: string;
|
||||
readonly fetchUrl: string;
|
||||
}
|
||||
|
||||
interface SourceMapFetchHost {
|
||||
readonly fetch: typeof fetch;
|
||||
}
|
||||
|
||||
type SourceMaps = WebBundleAnalysis["observations"]["source_maps"];
|
||||
type SourceMapItem = SourceMaps["items"][number];
|
||||
|
||||
/** Fetch and validate approved source maps without browser credentials. */
|
||||
export const fetchWebSourceMaps = async (
|
||||
requests: readonly WebSourceMapRequest[],
|
||||
input: AnalyzeWebBundleInput,
|
||||
signal?: AbortSignal,
|
||||
host: SourceMapFetchHost = { fetch: globalThis.fetch },
|
||||
): Promise<SourceMaps> => {
|
||||
const items: SourceMapItem[] = [];
|
||||
let remainingBytes = input.analysis_limits.max_total_source_map_bytes;
|
||||
for (const request of requests.slice(
|
||||
0,
|
||||
input.analysis_limits.max_source_maps,
|
||||
)) {
|
||||
if (signal?.aborted === true) throw signal.reason;
|
||||
if (remainingBytes === 0) break;
|
||||
const fetched = await fetchOne(request, {
|
||||
input,
|
||||
maximumBytes: Math.min(
|
||||
input.analysis_limits.max_source_map_bytes,
|
||||
remainingBytes,
|
||||
),
|
||||
signal,
|
||||
host,
|
||||
});
|
||||
items.push(fetched.item);
|
||||
remainingBytes = Math.max(0, remainingBytes - fetched.bytesRead);
|
||||
}
|
||||
const included = items.filter(({ status }) => status === "included").length;
|
||||
const dropped = requests.length - items.length;
|
||||
const truncated =
|
||||
dropped > 0 || items.some(({ status }) => status === "truncated");
|
||||
return {
|
||||
status: truncated
|
||||
? "truncated"
|
||||
: items.length === 0
|
||||
? "unavailable"
|
||||
: included === items.length
|
||||
? "included"
|
||||
: included > 0
|
||||
? "partial"
|
||||
: "unavailable",
|
||||
requested: requests.length,
|
||||
processed: items.length,
|
||||
dropped,
|
||||
dropped_script_keys: requests
|
||||
.slice(items.length)
|
||||
.map(({ scriptKey }) => scriptKey),
|
||||
items,
|
||||
};
|
||||
};
|
||||
|
||||
interface SourceMapFetchResult {
|
||||
readonly item: SourceMapItem;
|
||||
readonly bytesRead: number;
|
||||
}
|
||||
|
||||
interface SourceMapFetchContext {
|
||||
readonly input: AnalyzeWebBundleInput;
|
||||
readonly maximumBytes: number;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly host: SourceMapFetchHost;
|
||||
}
|
||||
|
||||
const fetchOne = async (
|
||||
request: WebSourceMapRequest,
|
||||
context: SourceMapFetchContext,
|
||||
): Promise<SourceMapFetchResult> => {
|
||||
const { input, maximumBytes, signal, host } = context;
|
||||
const base = emptyItem(request);
|
||||
if (!approvedUrl(request.fetchUrl, input.allowed_origins))
|
||||
return {
|
||||
item: {
|
||||
...base,
|
||||
status: "policy_filtered",
|
||||
limitation:
|
||||
"Declared source-map URL is outside the approved exact origins.",
|
||||
},
|
||||
bytesRead: 0,
|
||||
};
|
||||
try {
|
||||
const response = await fetchFollowingApprovedRedirects(
|
||||
request.fetchUrl,
|
||||
input.allowed_origins,
|
||||
signal,
|
||||
host,
|
||||
);
|
||||
if (response === undefined)
|
||||
return {
|
||||
item: {
|
||||
...base,
|
||||
status: "policy_filtered",
|
||||
limitation: "A source-map redirect left the approved exact origins.",
|
||||
},
|
||||
bytesRead: 0,
|
||||
};
|
||||
if (!response.ok)
|
||||
return {
|
||||
item: {
|
||||
...base,
|
||||
status: "fetch_failed",
|
||||
limitation: `Source-map server returned HTTP ${String(response.status)}.`,
|
||||
},
|
||||
bytesRead: 0,
|
||||
};
|
||||
const body = await boundedResponseText(response, maximumBytes);
|
||||
return {
|
||||
item: normalizeSourceMap(request, body.text, input),
|
||||
bytesRead: body.bytes,
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
if (signal?.aborted === true) throw cause;
|
||||
return {
|
||||
item: {
|
||||
...base,
|
||||
status: isLimitError(cause) ? "truncated" : "fetch_failed",
|
||||
limitation: isLimitError(cause)
|
||||
? "Source-map response exceeded the remaining approved byte budget."
|
||||
: "Source-map fetch or validation failed.",
|
||||
},
|
||||
bytesRead: cause instanceof SourceMapByteLimitError ? cause.bytesRead : 0,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const fetchFollowingApprovedRedirects = async (
|
||||
initialUrl: string,
|
||||
allowedOrigins: readonly string[],
|
||||
signal: AbortSignal | undefined,
|
||||
host: SourceMapFetchHost,
|
||||
): Promise<Response | undefined> => {
|
||||
let current = initialUrl;
|
||||
for (let redirect = 0; redirect <= 5; redirect += 1) {
|
||||
if (!approvedUrl(current, allowedOrigins)) return undefined;
|
||||
const response = await timedFetch(current, signal, host);
|
||||
if (response.status < 300 || response.status >= 400) return response;
|
||||
const location = response.headers.get("location");
|
||||
if (location === null) return response;
|
||||
current = new URL(location, current).href;
|
||||
}
|
||||
throw new Error("source_map_redirect_limit");
|
||||
};
|
||||
|
||||
const timedFetch = async (
|
||||
url: string,
|
||||
signal: AbortSignal | undefined,
|
||||
host: SourceMapFetchHost,
|
||||
): Promise<Response> => {
|
||||
const timeout = AbortSignal.timeout(5_000);
|
||||
return await host.fetch(url, {
|
||||
method: "GET",
|
||||
headers: { Accept: "application/json, application/source-map+json;q=0.9" },
|
||||
redirect: "manual",
|
||||
credentials: "omit",
|
||||
referrerPolicy: "no-referrer",
|
||||
signal: signal === undefined ? timeout : AbortSignal.any([signal, timeout]),
|
||||
});
|
||||
};
|
||||
|
||||
const boundedResponseText = async (
|
||||
response: Response,
|
||||
maximumBytes: number,
|
||||
): Promise<{ readonly text: string; readonly bytes: number }> => {
|
||||
const declared = Number(response.headers.get("content-length"));
|
||||
if (Number.isFinite(declared) && declared > maximumBytes)
|
||||
throw new SourceMapByteLimitError(0);
|
||||
if (response.body === null) return { text: "", bytes: 0 };
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
for (;;) {
|
||||
const chunk = await reader.read();
|
||||
if (chunk.done) break;
|
||||
bytes += chunk.value.byteLength;
|
||||
if (bytes > maximumBytes) {
|
||||
await reader.cancel();
|
||||
throw new SourceMapByteLimitError(bytes);
|
||||
}
|
||||
text += decoder.decode(chunk.value, { stream: true });
|
||||
}
|
||||
text += decoder.decode();
|
||||
return { text, bytes };
|
||||
};
|
||||
|
||||
class SourceMapByteLimitError extends RangeError {
|
||||
constructor(readonly bytesRead: number) {
|
||||
super("source_map_bytes");
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeSourceMap = (
|
||||
request: WebSourceMapRequest,
|
||||
text: string,
|
||||
input: AnalyzeWebBundleInput,
|
||||
): SourceMapItem => {
|
||||
const base = emptyItem(request);
|
||||
if (!validSourceMapEnvelope(text))
|
||||
return {
|
||||
...base,
|
||||
status: "invalid",
|
||||
limitation: "Source-map JSON is not a bounded version 3 map.",
|
||||
};
|
||||
try {
|
||||
const map = new AnyMap(text, request.fetchUrl);
|
||||
if (map.sources.length > input.analysis_limits.max_original_sources)
|
||||
return {
|
||||
...base,
|
||||
status: "truncated",
|
||||
limitation: "Source map exceeds the original-source inventory limit.",
|
||||
};
|
||||
const resolvedBySource = new Map<string, string>();
|
||||
const originalSources = map.sources.map((source, index) => {
|
||||
const content = map.sourcesContent?.[index];
|
||||
const resolved =
|
||||
map.resolvedSources[index] ?? source ?? "[unknown-source]";
|
||||
if (source !== null) resolvedBySource.set(source, resolved);
|
||||
return {
|
||||
source: sanitizeSource(resolved),
|
||||
artifact:
|
||||
typeof content === "string"
|
||||
? createWebTextArtifact(content, sourceMediaType(source))
|
||||
: null,
|
||||
};
|
||||
});
|
||||
const mappings: SourceMapItem["mappings"] = [];
|
||||
let totalMappings = 0;
|
||||
eachMapping(map, (mapping) => {
|
||||
if (
|
||||
mapping.source === null ||
|
||||
mapping.originalLine === null ||
|
||||
mapping.originalColumn === null
|
||||
)
|
||||
return;
|
||||
totalMappings += 1;
|
||||
if (mappings.length >= input.analysis_limits.max_source_map_mappings)
|
||||
return;
|
||||
mappings.push({
|
||||
generated_line: mapping.generatedLine,
|
||||
generated_column: mapping.generatedColumn,
|
||||
source: sanitizeSource(
|
||||
resolvedBySource.get(mapping.source) ?? mapping.source,
|
||||
),
|
||||
original_line: mapping.originalLine,
|
||||
original_column: mapping.originalColumn,
|
||||
name: mapping.name?.slice(0, 1_024) ?? null,
|
||||
});
|
||||
});
|
||||
const modules = originalModuleEdges(
|
||||
originalSources,
|
||||
input.analysis_limits.max_findings,
|
||||
);
|
||||
const mappingTruncated = totalMappings > mappings.length;
|
||||
const limitations = [
|
||||
...(mappingTruncated
|
||||
? [
|
||||
`Mappings were truncated from ${String(totalMappings)} to ${String(mappings.length)}.`,
|
||||
]
|
||||
: []),
|
||||
...(modules.truncated
|
||||
? [
|
||||
`Original module edges were truncated to ${String(modules.edges.length)}.`,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
return {
|
||||
...base,
|
||||
status: mappingTruncated || modules.truncated ? "truncated" : "included",
|
||||
artifact: createWebTextArtifact(text, "application/source-map+json"),
|
||||
original_sources: originalSources,
|
||||
original_module_edges: modules.edges,
|
||||
mappings,
|
||||
limitation: limitations.length === 0 ? null : limitations.join(" "),
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
...base,
|
||||
status: "invalid",
|
||||
limitation: "Source-map mappings could not be decoded safely.",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const originalModuleEdges = (
|
||||
sources: SourceMapItem["original_sources"],
|
||||
maximum: number,
|
||||
): {
|
||||
readonly edges: SourceMapItem["original_module_edges"];
|
||||
readonly truncated: boolean;
|
||||
} => {
|
||||
const edges: SourceMapItem["original_module_edges"] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const source of sources) {
|
||||
if (source.artifact === null) continue;
|
||||
for (const detector of originalImportDetectors) {
|
||||
for (const match of source.artifact.text.matchAll(detector.pattern)) {
|
||||
const specifier = match[1]?.slice(0, 4_096);
|
||||
if (specifier === undefined) continue;
|
||||
const key = `${source.source}\0${detector.kind}\0${specifier}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
if (edges.length >= maximum) return { edges, truncated: true };
|
||||
edges.push({
|
||||
from_source: source.source,
|
||||
kind: detector.kind,
|
||||
specifier,
|
||||
resolved_source: resolveOriginalSource(specifier, source.source),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return { edges, truncated: false };
|
||||
};
|
||||
|
||||
const validSourceMapEnvelope = (text: string): boolean => {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (!isRecord(parsed) || parsed.version !== 3) return false;
|
||||
if (typeof parsed.mappings === "string")
|
||||
return Array.isArray(parsed.sources) && Array.isArray(parsed.names);
|
||||
if (!Array.isArray(parsed.sections) || parsed.sections.length > 10_000)
|
||||
return false;
|
||||
const pending: unknown[] = [...parsed.sections];
|
||||
let visited = 0;
|
||||
while (pending.length > 0) {
|
||||
const section = pending.pop();
|
||||
if (!isRecord(section) || !isRecord(section.offset) || !("map" in section))
|
||||
return false;
|
||||
visited += 1;
|
||||
if (visited > 10_000) return false;
|
||||
const map = section.map;
|
||||
if (!isRecord(map) || map.version !== 3) return false;
|
||||
if (Array.isArray(map.sections)) pending.push(...map.sections);
|
||||
else if (
|
||||
typeof map.mappings !== "string" ||
|
||||
!Array.isArray(map.sources) ||
|
||||
!Array.isArray(map.names)
|
||||
)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const approvedUrl = (
|
||||
value: string,
|
||||
allowedOrigins: readonly string[],
|
||||
): boolean => {
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
return (
|
||||
(parsed.protocol === "http:" || parsed.protocol === "https:") &&
|
||||
parsed.username === "" &&
|
||||
parsed.password === "" &&
|
||||
allowedOrigins.includes(parsed.origin)
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const emptyItem = (request: WebSourceMapRequest): SourceMapItem => ({
|
||||
script_key: request.scriptKey,
|
||||
declared_url: request.declaredUrl,
|
||||
status: "fetch_failed",
|
||||
artifact: null,
|
||||
original_sources: [],
|
||||
original_module_edges: [],
|
||||
mappings: [],
|
||||
limitation: null,
|
||||
});
|
||||
|
||||
const sanitizeSource = (value: string): string => {
|
||||
const bounded = value.slice(0, 4_096);
|
||||
try {
|
||||
const parsed = new URL(bounded);
|
||||
return parsed.protocol === "http:" || parsed.protocol === "https:"
|
||||
? sanitizeBrowserUrl(parsed.href).url
|
||||
: `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
|
||||
} catch {
|
||||
return bounded.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
}
|
||||
};
|
||||
|
||||
const resolveOriginalSource = (
|
||||
specifier: string,
|
||||
base: string,
|
||||
): string | null => {
|
||||
try {
|
||||
return sanitizeSource(new URL(specifier, base).href);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const sourceMediaType = (source: string | null): string =>
|
||||
source?.endsWith(".ts") || source?.endsWith(".tsx")
|
||||
? "text/typescript"
|
||||
: "text/javascript";
|
||||
|
||||
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const isLimitError = (value: unknown): value is RangeError =>
|
||||
value instanceof RangeError;
|
||||
|
||||
const originalImportDetectors = [
|
||||
{
|
||||
kind: "static_import" as const,
|
||||
pattern:
|
||||
/\b(?:import|export)\s+(?:[^'"\n]*?\s+from\s+)?["']([^"'\n]+)["']/gu,
|
||||
},
|
||||
{
|
||||
kind: "dynamic_import" as const,
|
||||
pattern: /\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)/gu,
|
||||
},
|
||||
{
|
||||
kind: "require" as const,
|
||||
pattern: /\brequire\s*\(\s*["']([^"'\n]+)["']\s*\)/gu,
|
||||
},
|
||||
] as const;
|
||||
Reference in New Issue
Block a user