feat: add passive website reverse engineering
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import type { ProviderIdentity } from "./AnalysisProvider.js";
|
||||
import {
|
||||
createEvidence,
|
||||
type Evidence,
|
||||
type EvidenceObservation,
|
||||
} from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import type {
|
||||
BrowserTargetList,
|
||||
InspectWebPageInput,
|
||||
ListBrowserTargetsInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
|
||||
type BrowserEvidenceInput = ListBrowserTargetsInput | InspectWebPageInput;
|
||||
type BrowserEvidenceResult = BrowserTargetList | WebPageInspection;
|
||||
|
||||
/** Create Evidence v2 for a policy-scoped external browser observation. */
|
||||
export const createBrowserEvidence = (
|
||||
operation: "list_browser_targets" | "inspect_web_page",
|
||||
input: BrowserEvidenceInput,
|
||||
result: BrowserEvidenceResult,
|
||||
provider: ProviderIdentity,
|
||||
): Evidence =>
|
||||
createEvidence(undefined, provider, {
|
||||
predicateType:
|
||||
operation === "list_browser_targets"
|
||||
? "rea.browser-target-list/v1"
|
||||
: "rea.web-page-inspection/v1",
|
||||
operation,
|
||||
parameters: browserParameters(input),
|
||||
result: jsonValueSchema.parse(result),
|
||||
confidence: "observed",
|
||||
authority: "external-service",
|
||||
environment:
|
||||
"target" in result
|
||||
? {
|
||||
id: `${result.browser.product}@${result.browser.revision}`,
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
isolation: "none",
|
||||
}
|
||||
: null,
|
||||
limitations: result.limitations,
|
||||
});
|
||||
|
||||
const browserParameters = (
|
||||
input: BrowserEvidenceInput,
|
||||
): EvidenceObservation["parameters"] => ({
|
||||
cdp_endpoint: input.cdp_endpoint,
|
||||
allowed_origins: input.allowed_origins,
|
||||
...("target_id" in input
|
||||
? {
|
||||
target_id: input.target_id,
|
||||
observation_ms: input.observation_ms,
|
||||
include_script_sources: input.include_script_sources,
|
||||
include_storage_keys: input.include_storage_keys,
|
||||
limits: input.limits,
|
||||
}
|
||||
: { offset: input.offset, limit: input.limit }),
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type {
|
||||
BrowserTargetList,
|
||||
InspectWebPageInput,
|
||||
ListBrowserTargetsInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type { ProviderIdentity } from "./AnalysisProvider.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
|
||||
/** Provider-neutral application boundary for passive browser observation. */
|
||||
export interface BrowserObservationPort {
|
||||
identity(): ProviderIdentity;
|
||||
listTargets(
|
||||
input: ListBrowserTargetsInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<BrowserTargetList, AnalysisError>>;
|
||||
inspectPage(
|
||||
input: InspectWebPageInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebPageInspection, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
ListBrowserTargetsInput,
|
||||
} from "../domain/browserObservation.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { BrowserObservationPort } from "./BrowserObservationPort.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import { createBrowserEvidence } from "./BrowserEvidence.js";
|
||||
|
||||
type ScopedBrowserInput = Pick<
|
||||
ListBrowserTargetsInput,
|
||||
"cdp_endpoint" | "allowed_origins"
|
||||
> & { readonly target_id?: string };
|
||||
|
||||
/** Authorize and execute one policy-scoped target discovery observation. */
|
||||
export const listBrowserTargets = async (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ListBrowserTargetsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(
|
||||
browser,
|
||||
authority,
|
||||
input,
|
||||
"list_browser_targets",
|
||||
);
|
||||
if (!ready.ok) return ready;
|
||||
const result = await ready.value.listTargets(input, options);
|
||||
return result.ok
|
||||
? ok(
|
||||
createBrowserEvidence(
|
||||
"list_browser_targets",
|
||||
input,
|
||||
result.value,
|
||||
ready.value.identity(),
|
||||
),
|
||||
)
|
||||
: result;
|
||||
};
|
||||
|
||||
/** Authorize and execute one policy-scoped passive page inspection. */
|
||||
export const inspectWebPage = async (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: InspectWebPageInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(browser, authority, input, "inspect_web_page");
|
||||
if (!ready.ok) return ready;
|
||||
const result = await ready.value.inspectPage(input, options);
|
||||
return result.ok
|
||||
? ok(
|
||||
createBrowserEvidence(
|
||||
"inspect_web_page",
|
||||
input,
|
||||
result.value,
|
||||
ready.value.identity(),
|
||||
),
|
||||
)
|
||||
: result;
|
||||
};
|
||||
|
||||
const prepare = async (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ScopedBrowserInput,
|
||||
operation: "list_browser_targets" | "inspect_web_page",
|
||||
): Promise<Result<BrowserObservationPort, AnalysisError>> => {
|
||||
if (authority === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-cdp-browser",
|
||||
operation,
|
||||
"browser observation permission policy is not configured",
|
||||
),
|
||||
);
|
||||
const authorized = await authority.authorize(
|
||||
{
|
||||
capability: "browser_observe",
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
origins: [input.cdp_endpoint, ...input.allowed_origins],
|
||||
network: browserNetworkScope(input.allowed_origins),
|
||||
mount: false,
|
||||
operation_identity: `${operation}:${input.target_id ?? input.cdp_endpoint}`,
|
||||
},
|
||||
"read",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
return browser === undefined
|
||||
? err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-cdp-browser",
|
||||
operation,
|
||||
"browser observation provider is not configured",
|
||||
),
|
||||
)
|
||||
: ok(browser);
|
||||
};
|
||||
|
||||
const browserNetworkScope = (
|
||||
allowedOrigins: readonly string[],
|
||||
): "loopback" | "external" =>
|
||||
allowedOrigins.every((origin) => {
|
||||
const hostname = new URL(origin).hostname;
|
||||
return hostname === "127.0.0.1" || hostname === "[::1]";
|
||||
})
|
||||
? "loopback"
|
||||
: "external";
|
||||
@@ -54,6 +54,7 @@ export const buildCapabilityInventory = (
|
||||
policy: {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly evidenceFileRoots: number;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
},
|
||||
) => {
|
||||
const status = statusSchema.parse(sessionStatus);
|
||||
@@ -97,6 +98,7 @@ const availabilityFor = (
|
||||
policy: {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly evidenceFileRoots: number;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
},
|
||||
): {
|
||||
readonly reason: ToolAvailabilityReason;
|
||||
@@ -113,6 +115,14 @@ const availabilityFor = (
|
||||
reason: "policy_disabled",
|
||||
remediation: "Configure or grant an evidence_read root.",
|
||||
};
|
||||
if (kind === "browser-provider")
|
||||
return policy.browserObservationEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "policy_disabled",
|
||||
remediation:
|
||||
"Enable browser observation and configure exact CDP endpoint and page origins.",
|
||||
};
|
||||
if (kind === "session") return { reason: "available", remediation: null };
|
||||
if (!targetOpen)
|
||||
return {
|
||||
|
||||
@@ -12,6 +12,7 @@ const grantSchema = z.object({
|
||||
grant_id: z.string().min(1),
|
||||
capability: z.enum([
|
||||
"process_capture",
|
||||
"browser_observe",
|
||||
"evidence_read",
|
||||
"evidence_write",
|
||||
"investigation_input",
|
||||
@@ -26,6 +27,7 @@ const grantSchema = z.object({
|
||||
roots: z.array(z.string()),
|
||||
executables: z.array(z.string()),
|
||||
environment_names: z.array(z.string()),
|
||||
origins: z.array(z.string()).optional(),
|
||||
network: z.enum(["none", "loopback", "external"]),
|
||||
mount: z.boolean(),
|
||||
lifetime: z.literal("project"),
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import type { BrowserObservationPort } from "../application/BrowserObservationPort.js";
|
||||
import type { ProviderIdentity } from "../application/AnalysisProvider.js";
|
||||
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
|
||||
import {
|
||||
browserTargetListSchema,
|
||||
sanitizeBrowserUrl,
|
||||
webPageInspectionSchema,
|
||||
type BrowserTargetList,
|
||||
type InspectWebPageInput,
|
||||
type ListBrowserTargetsInput,
|
||||
type WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
BrowserObservationError,
|
||||
ProviderAdapterError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import {
|
||||
discoverCdpEndpoint,
|
||||
type CdpEndpointDiscovery,
|
||||
type CdpEndpointTarget,
|
||||
} from "./CdpEndpoint.js";
|
||||
import { capturePage } from "./CdpPageCapture.js";
|
||||
|
||||
const IDENTITY: ProviderIdentity = {
|
||||
id: "rea-cdp-browser",
|
||||
name: "REA Chrome DevTools Protocol observation provider",
|
||||
version: "1",
|
||||
};
|
||||
|
||||
/** Passive, origin-scoped browser observation through a user-owned CDP endpoint. */
|
||||
export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
identity(): ProviderIdentity {
|
||||
return IDENTITY;
|
||||
}
|
||||
|
||||
async listTargets(
|
||||
input: ListBrowserTargetsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<BrowserTargetList, AnalysisError>> {
|
||||
try {
|
||||
const discovery = await discoverCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
"list_browser_targets",
|
||||
options.signal,
|
||||
);
|
||||
const allowedOrigins = new Set(input.allowed_origins);
|
||||
const selected = selectTargets(discovery, allowedOrigins);
|
||||
const items = selected.allowed.slice(
|
||||
input.offset,
|
||||
input.offset + input.limit,
|
||||
);
|
||||
const nextOffset = input.offset + items.length;
|
||||
return ok(
|
||||
browserTargetListSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: discovery.version,
|
||||
targets: {
|
||||
items,
|
||||
offset: input.offset,
|
||||
limit: input.limit,
|
||||
total: selected.allowed.length,
|
||||
next_offset:
|
||||
nextOffset < selected.allowed.length ? nextOffset : null,
|
||||
has_more: nextOffset < selected.allowed.length,
|
||||
},
|
||||
excluded: selected.excluded,
|
||||
limitations: [
|
||||
"Only page targets whose current URL matches an approved exact origin are listed.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "list_browser_targets"));
|
||||
}
|
||||
}
|
||||
|
||||
async inspectPage(
|
||||
input: InspectWebPageInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<WebPageInspection, AnalysisError>> {
|
||||
let connection: CdpConnection | undefined;
|
||||
let sessionId: string | undefined;
|
||||
try {
|
||||
const discovery = await discoverCdpEndpoint(
|
||||
input.cdp_endpoint,
|
||||
"inspect_web_page",
|
||||
options.signal,
|
||||
);
|
||||
const target = authorizeTarget(discovery, input);
|
||||
connection = await CdpConnection.connect(
|
||||
discovery.browserWebSocketUrl,
|
||||
options.signal,
|
||||
);
|
||||
const attached = await connection.send(
|
||||
"Target.attachToTarget",
|
||||
{ targetId: target.id, flatten: true },
|
||||
undefined,
|
||||
options.signal,
|
||||
);
|
||||
sessionId = attachedSessionId(attached);
|
||||
const result = await capturePage({
|
||||
connection,
|
||||
sessionId,
|
||||
discovery,
|
||||
target,
|
||||
input,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options.progress === undefined
|
||||
? {}
|
||||
: { progress: options.progress }),
|
||||
});
|
||||
return ok(webPageInspectionSchema.parse(result));
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "inspect_web_page"));
|
||||
} finally {
|
||||
if (connection !== undefined) {
|
||||
if (sessionId !== undefined)
|
||||
await bestEffortCleanup(connection, sessionId);
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const selectTargets = (
|
||||
discovery: CdpEndpointDiscovery,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): {
|
||||
readonly allowed: readonly BrowserTargetList["targets"]["items"][number][];
|
||||
readonly excluded: BrowserTargetList["excluded"];
|
||||
} => {
|
||||
const allowed = [];
|
||||
let disallowedOrigin = 0;
|
||||
let unsupportedUrl = 0;
|
||||
let nonPage = 0;
|
||||
for (const target of discovery.targets) {
|
||||
if (target.type !== "page") {
|
||||
nonPage += 1;
|
||||
continue;
|
||||
}
|
||||
const url = sanitizeBrowserUrl(target.url);
|
||||
if (url.origin === null) {
|
||||
unsupportedUrl += 1;
|
||||
continue;
|
||||
}
|
||||
if (!allowedOrigins.has(url.origin)) {
|
||||
disallowedOrigin += 1;
|
||||
continue;
|
||||
}
|
||||
allowed.push({
|
||||
target_id: target.id,
|
||||
type: target.type,
|
||||
title: target.title.slice(0, 16_384),
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
attached: target.attached,
|
||||
});
|
||||
}
|
||||
allowed.sort((left, right) => left.target_id.localeCompare(right.target_id));
|
||||
return {
|
||||
allowed,
|
||||
excluded: {
|
||||
disallowed_origin: disallowedOrigin,
|
||||
unsupported_url: unsupportedUrl,
|
||||
non_page: nonPage,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const authorizeTarget = (
|
||||
discovery: CdpEndpointDiscovery,
|
||||
input: InspectWebPageInput,
|
||||
): CdpEndpointTarget => {
|
||||
const target = discovery.targets.find(
|
||||
(candidate) => candidate.id === input.target_id,
|
||||
);
|
||||
if (target === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_found");
|
||||
const origin = sanitizeBrowserUrl(target.url).origin;
|
||||
if (
|
||||
target.type !== "page" ||
|
||||
origin === null ||
|
||||
!input.allowed_origins.includes(origin)
|
||||
)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
return target;
|
||||
};
|
||||
|
||||
const attachedSessionId = (value: unknown): string => {
|
||||
if (typeof value !== "object" || value === null || !("sessionId" in value))
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
if (typeof value.sessionId !== "string" || value.sessionId.length > 256)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
return value.sessionId;
|
||||
};
|
||||
|
||||
const bestEffortCleanup = async (
|
||||
connection: CdpConnection,
|
||||
sessionId: string,
|
||||
): Promise<void> => {
|
||||
for (const method of [
|
||||
"Network.disable",
|
||||
"Debugger.disable",
|
||||
"Runtime.disable",
|
||||
"Page.disable",
|
||||
]) {
|
||||
try {
|
||||
await connection.send(method, {}, sessionId);
|
||||
} catch {
|
||||
// Cleanup continues so detach is still attempted.
|
||||
}
|
||||
}
|
||||
try {
|
||||
await connection.send("Target.detachFromTarget", { sessionId });
|
||||
} catch {
|
||||
// Closing REA's socket is the final non-destructive cleanup boundary.
|
||||
}
|
||||
};
|
||||
|
||||
const providerError = (
|
||||
cause: unknown,
|
||||
operation: "list_browser_targets" | "inspect_web_page",
|
||||
): AnalysisError =>
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderAdapterError(IDENTITY.id, operation, { cause });
|
||||
@@ -0,0 +1,198 @@
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
requiredRecord,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
/** Normalize allowed frames while retaining a bounded prefix and total count. */
|
||||
export const captureFrames = (
|
||||
result: unknown,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
maximum: number,
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["frames"];
|
||||
} => {
|
||||
const root = recordValue(requiredRecord(result).frameTree);
|
||||
if (root === undefined) return { total: 0, items: [] };
|
||||
const items: WebPageInspection["frames"] = [];
|
||||
let total = 0;
|
||||
for (const tree of walkFrameTrees(root)) {
|
||||
const frame = recordValue(tree.frame);
|
||||
const frameId = stringValue(frame?.id);
|
||||
const sanitized = allowedSanitizedUrl(frame?.url, allowedOrigins);
|
||||
if (
|
||||
frame === undefined ||
|
||||
frameId === undefined ||
|
||||
frameId.length > 256 ||
|
||||
sanitized === undefined ||
|
||||
sanitized.origin === null
|
||||
)
|
||||
continue;
|
||||
total += 1;
|
||||
if (items.length >= maximum) continue;
|
||||
items.push({
|
||||
frame_id: frameId,
|
||||
parent_frame_id:
|
||||
(stringValue(frame.parentId) ?? "").slice(0, 256) || null,
|
||||
url: sanitized.url,
|
||||
origin: sanitized.origin,
|
||||
});
|
||||
}
|
||||
return { total, items };
|
||||
};
|
||||
|
||||
/** Read the current main-frame URL from an untrusted Page.getFrameTree result. */
|
||||
export const mainFrameUrl = (result: unknown): string | undefined =>
|
||||
stringValue(
|
||||
recordValue(recordValue(requiredRecord(result).frameTree)?.frame)?.url,
|
||||
);
|
||||
|
||||
/** Normalize allowed resources while retaining a bounded prefix and total count. */
|
||||
export const captureResources = (
|
||||
result: unknown,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
maximum: number,
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["resources"];
|
||||
} => {
|
||||
const root = recordValue(requiredRecord(result).frameTree);
|
||||
if (root === undefined) return { total: 0, items: [] };
|
||||
const items: WebPageInspection["resources"] = [];
|
||||
let total = 0;
|
||||
for (const tree of walkFrameTrees(root)) {
|
||||
for (const resource of recordsValue(tree.resources)) {
|
||||
const url = allowedSanitizedUrl(resource.url, allowedOrigins);
|
||||
if (url === undefined || url.origin === null) continue;
|
||||
total += 1;
|
||||
if (items.length >= maximum) continue;
|
||||
const contentSize = numberValue(resource.contentSize);
|
||||
items.push({
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
type: (stringValue(resource.type) ?? "Other").slice(0, 100),
|
||||
mime_type: (stringValue(resource.mimeType) ?? "").slice(0, 256),
|
||||
content_size:
|
||||
contentSize === undefined ? null : Math.max(0, contentSize),
|
||||
});
|
||||
}
|
||||
}
|
||||
return { total, items };
|
||||
};
|
||||
|
||||
const walkFrameTrees = function* (
|
||||
root: UnknownRecord,
|
||||
): Generator<UnknownRecord> {
|
||||
const pending = [root];
|
||||
while (pending.length > 0) {
|
||||
const tree = pending.pop();
|
||||
if (tree === undefined) return;
|
||||
const children = recordsValue(tree.childFrames);
|
||||
for (let index = children.length - 1; index >= 0; index -= 1) {
|
||||
const child = children[index];
|
||||
if (child !== undefined) pending.push(child);
|
||||
}
|
||||
yield tree;
|
||||
}
|
||||
};
|
||||
|
||||
export const captureDom = (
|
||||
result: unknown,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
input: InspectWebPageInput,
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly nodes: WebPageInspection["dom"]["nodes"];
|
||||
} => {
|
||||
const root = requiredRecord(result);
|
||||
const strings = Array.isArray(root.strings)
|
||||
? root.strings.map((value) => stringValue(value) ?? "")
|
||||
: [];
|
||||
const nodes: WebPageInspection["dom"]["nodes"] = [];
|
||||
let total = 0;
|
||||
for (const document of recordsValue(root.documents)) {
|
||||
const documentUrl = indexedString(strings, document.documentURL);
|
||||
if (allowedSanitizedUrl(documentUrl, allowedOrigins) === undefined)
|
||||
continue;
|
||||
const documentNodes = recordValue(document.nodes);
|
||||
if (documentNodes === undefined) continue;
|
||||
const nodeTypes = numberArray(documentNodes.nodeType);
|
||||
const nodeNames = numberArray(documentNodes.nodeName);
|
||||
const nodeValues = numberArray(documentNodes.nodeValue);
|
||||
const parents = numberArray(documentNodes.parentIndex);
|
||||
const attributes = Array.isArray(documentNodes.attributes)
|
||||
? documentNodes.attributes
|
||||
: [];
|
||||
const baseIndex = nodes.length;
|
||||
total += nodeTypes.length;
|
||||
for (
|
||||
let index = 0;
|
||||
index < nodeTypes.length && nodes.length < input.limits.max_dom_nodes;
|
||||
index += 1
|
||||
) {
|
||||
const attributeIndexes = numberArray(attributes[index]);
|
||||
const parent = Math.trunc(parents[index] ?? -1);
|
||||
nodes.push({
|
||||
index: nodes.length,
|
||||
parent_index: parent < 0 ? -1 : baseIndex + parent,
|
||||
node_type: Math.max(0, Math.trunc(nodeTypes[index] ?? 0)),
|
||||
node_name: indexedString(strings, nodeNames[index]).slice(0, 256),
|
||||
node_value_length: indexedString(strings, nodeValues[index]).length,
|
||||
attribute_names: attributeIndexes
|
||||
.filter((_value, attributeIndex) => attributeIndex % 2 === 0)
|
||||
.map((value) => indexedString(strings, value).slice(0, 256))
|
||||
.slice(0, 200),
|
||||
});
|
||||
}
|
||||
}
|
||||
return { total, nodes };
|
||||
};
|
||||
|
||||
export const captureAccessibility = (
|
||||
results: readonly unknown[],
|
||||
maximum: number,
|
||||
): {
|
||||
readonly total: number;
|
||||
readonly nodes: WebPageInspection["accessibility"]["nodes"];
|
||||
} => {
|
||||
const all = results.flatMap((result) =>
|
||||
recordsValue(requiredRecord(result).nodes),
|
||||
);
|
||||
return {
|
||||
total: all.length,
|
||||
nodes: all.slice(0, maximum).map((node) => ({
|
||||
node_id: (stringValue(node.nodeId) ?? "").slice(0, 256),
|
||||
parent_id: (stringValue(node.parentId) ?? "").slice(0, 256) || null,
|
||||
role: axText(node.role),
|
||||
name: axText(node.name),
|
||||
description: axText(node.description),
|
||||
ignored: node.ignored === true,
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
const axText = (value: unknown): string | null =>
|
||||
boundedText(recordValue(value)?.value, 1_024);
|
||||
|
||||
const indexedString = (strings: readonly string[], index: unknown): string => {
|
||||
const integer = numberValue(index);
|
||||
return integer === undefined ? "" : (strings[Math.trunc(integer)] ?? "");
|
||||
};
|
||||
|
||||
const numberArray = (value: unknown): readonly number[] =>
|
||||
Array.isArray(value)
|
||||
? value.flatMap((item) => {
|
||||
const number = numberValue(item);
|
||||
return number === undefined ? [] : [number];
|
||||
})
|
||||
: [];
|
||||
@@ -0,0 +1,300 @@
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { CdpEvent } from "./CdpConnection.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
export interface CapturedScript {
|
||||
readonly scriptId: string;
|
||||
readonly url: string;
|
||||
readonly origin: string | null;
|
||||
readonly hash: string;
|
||||
readonly length: number;
|
||||
readonly isModule: boolean;
|
||||
readonly language: string | null;
|
||||
readonly sourceMapUrl: string | null;
|
||||
}
|
||||
|
||||
type NetworkState = WebPageInspection["network"]["requests"][number];
|
||||
|
||||
/** Bounded event accumulator that drops payload values at ingestion time. */
|
||||
export class CdpCaptureEvents {
|
||||
readonly scripts = new Map<string, CapturedScript>();
|
||||
readonly network = new Map<string, NetworkState>();
|
||||
readonly allowedWebSockets = new Set<string>();
|
||||
readonly console: WebPageInspection["console"]["events"] = [];
|
||||
readonly websockets: WebPageInspection["network"]["websocket_events"] = [];
|
||||
dropped = 0;
|
||||
originViolation = false;
|
||||
navigationDuringCapture = false;
|
||||
#mainFrameId: string | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly input: InspectWebPageInput,
|
||||
private readonly allowedOrigins: ReadonlySet<string>,
|
||||
) {}
|
||||
|
||||
beginAuthorizedFrame(frameId: string): void {
|
||||
this.#mainFrameId = frameId;
|
||||
this.originViolation = false;
|
||||
this.navigationDuringCapture = false;
|
||||
this.dropped = 0;
|
||||
this.scripts.clear();
|
||||
this.network.clear();
|
||||
this.allowedWebSockets.clear();
|
||||
this.console.length = 0;
|
||||
this.websockets.length = 0;
|
||||
}
|
||||
|
||||
beginFinalCapture(frameId: string): void {
|
||||
this.#mainFrameId = frameId;
|
||||
this.navigationDuringCapture = false;
|
||||
}
|
||||
|
||||
ingest(event: CdpEvent): void {
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return;
|
||||
switch (event.method) {
|
||||
case "Debugger.scriptParsed":
|
||||
this.#script(params);
|
||||
break;
|
||||
case "Network.requestWillBeSent":
|
||||
this.#request(params);
|
||||
break;
|
||||
case "Network.responseReceived":
|
||||
this.#response(params);
|
||||
break;
|
||||
case "Network.loadingFinished":
|
||||
this.#finished(params);
|
||||
break;
|
||||
case "Runtime.consoleAPICalled":
|
||||
this.#console(params);
|
||||
break;
|
||||
case "Page.frameNavigated":
|
||||
this.#frameNavigated(params);
|
||||
break;
|
||||
case "Network.webSocketCreated":
|
||||
this.#websocketCreated(params);
|
||||
break;
|
||||
case "Network.webSocketFrameSent":
|
||||
this.#websocket(params, "sent");
|
||||
break;
|
||||
case "Network.webSocketFrameReceived":
|
||||
this.#websocket(params, "received");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#script(params: UnknownRecord): void {
|
||||
const scriptId = stringValue(params.scriptId);
|
||||
const rawUrl = stringValue(params.url) ?? "";
|
||||
const sanitized = allowedSanitizedUrl(rawUrl, this.allowedOrigins);
|
||||
if (
|
||||
scriptId === undefined ||
|
||||
scriptId.length > 256 ||
|
||||
sanitized === undefined
|
||||
)
|
||||
return;
|
||||
if (
|
||||
this.scripts.size >= this.input.limits.max_scripts &&
|
||||
!this.scripts.has(scriptId)
|
||||
) {
|
||||
this.dropped += 1;
|
||||
return;
|
||||
}
|
||||
this.scripts.set(scriptId, {
|
||||
scriptId,
|
||||
url: sanitized.url,
|
||||
origin: sanitized.origin,
|
||||
hash: (stringValue(params.hash) ?? "").slice(0, 512),
|
||||
length: Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
Math.trunc(numberValue(params.length) ?? 0),
|
||||
),
|
||||
),
|
||||
isModule: params.isModule === true,
|
||||
language: boundedText(params.scriptLanguage, 100),
|
||||
sourceMapUrl: this.#sourceMap(params.sourceMapURL),
|
||||
});
|
||||
}
|
||||
|
||||
#sourceMap(value: unknown): string | null {
|
||||
const sanitized = allowedSanitizedUrl(value, this.allowedOrigins);
|
||||
return sanitized?.url ?? null;
|
||||
}
|
||||
|
||||
#request(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const request = recordValue(params.request);
|
||||
const sanitized = allowedSanitizedUrl(request?.url, this.allowedOrigins);
|
||||
if (
|
||||
requestId === undefined ||
|
||||
requestId.length > 256 ||
|
||||
request === undefined ||
|
||||
sanitized === undefined
|
||||
)
|
||||
return;
|
||||
if (
|
||||
this.network.size >= this.input.limits.max_network_events &&
|
||||
!this.network.has(requestId)
|
||||
) {
|
||||
this.dropped += 1;
|
||||
return;
|
||||
}
|
||||
const initiator = recordValue(params.initiator);
|
||||
const initiatorUrl = allowedSanitizedUrl(
|
||||
firstCallFrame(initiator)?.url,
|
||||
this.allowedOrigins,
|
||||
);
|
||||
this.network.set(requestId, {
|
||||
request_id: requestId,
|
||||
url: sanitized.url,
|
||||
origin: sanitized.origin ?? "",
|
||||
method: (stringValue(request.method) ?? "GET").slice(0, 32),
|
||||
resource_type: boundedText(params.type, 100),
|
||||
status: null,
|
||||
mime_type: null,
|
||||
encoded_data_length: null,
|
||||
initiator: {
|
||||
type: (stringValue(initiator?.type) ?? "other").slice(0, 100),
|
||||
url: initiatorUrl?.url ?? null,
|
||||
line: integerOrNull(firstCallFrame(initiator)?.lineNumber),
|
||||
column: integerOrNull(firstCallFrame(initiator)?.columnNumber),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
#response(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) return;
|
||||
const current = this.network.get(requestId);
|
||||
const response = recordValue(params.response);
|
||||
if (current === undefined || response === undefined) return;
|
||||
this.network.set(requestId, {
|
||||
...current,
|
||||
status: numberValue(response.status) ?? null,
|
||||
mime_type: boundedText(response.mimeType, 256),
|
||||
});
|
||||
}
|
||||
|
||||
#finished(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) return;
|
||||
const current = this.network.get(requestId);
|
||||
if (current === undefined) return;
|
||||
this.network.set(requestId, {
|
||||
...current,
|
||||
encoded_data_length: Math.max(
|
||||
0,
|
||||
numberValue(params.encodedDataLength) ?? 0,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
#console(params: UnknownRecord): void {
|
||||
const frame = firstCallFrame(recordValue(params.stackTrace));
|
||||
const source = allowedSanitizedUrl(frame?.url, this.allowedOrigins);
|
||||
if (frame === undefined || source === undefined) return;
|
||||
if (this.console.length >= this.input.limits.max_console_events) {
|
||||
this.dropped += 1;
|
||||
return;
|
||||
}
|
||||
this.console.push({
|
||||
type: (stringValue(params.type) ?? "unknown").slice(0, 100),
|
||||
timestamp: numberValue(params.timestamp) ?? 0,
|
||||
argument_types: recordsValue(params.args)
|
||||
.map((argument) =>
|
||||
(stringValue(argument.type) ?? "unknown").slice(0, 100),
|
||||
)
|
||||
.slice(0, 100),
|
||||
url: source?.url ?? null,
|
||||
line: integerOrNull(frame?.lineNumber),
|
||||
column: integerOrNull(frame?.columnNumber),
|
||||
});
|
||||
}
|
||||
|
||||
#websocket(params: UnknownRecord, direction: "sent" | "received"): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (
|
||||
requestId === undefined ||
|
||||
requestId.length > 256 ||
|
||||
(!this.network.has(requestId) && !this.allowedWebSockets.has(requestId))
|
||||
)
|
||||
return;
|
||||
if (this.websockets.length >= this.input.limits.max_websocket_events) {
|
||||
this.dropped += 1;
|
||||
return;
|
||||
}
|
||||
const response = recordValue(params.response);
|
||||
const payload = stringValue(response?.payloadData) ?? "";
|
||||
this.websockets.push({
|
||||
request_id: requestId,
|
||||
direction,
|
||||
opcode: Math.max(0, Math.trunc(numberValue(response?.opcode) ?? 0)),
|
||||
payload_bytes: Buffer.byteLength(payload),
|
||||
});
|
||||
}
|
||||
|
||||
#websocketCreated(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const rawUrl = stringValue(params.url);
|
||||
if (
|
||||
requestId === undefined ||
|
||||
requestId.length > 256 ||
|
||||
rawUrl === undefined
|
||||
)
|
||||
return;
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (parsed.protocol === "ws:") parsed.protocol = "http:";
|
||||
else if (parsed.protocol === "wss:") parsed.protocol = "https:";
|
||||
else return;
|
||||
if (
|
||||
this.allowedOrigins.has(parsed.origin) &&
|
||||
(this.allowedWebSockets.has(requestId) ||
|
||||
this.allowedWebSockets.size < this.input.limits.max_websocket_events)
|
||||
)
|
||||
this.allowedWebSockets.add(requestId);
|
||||
else if (this.allowedOrigins.has(parsed.origin)) this.dropped += 1;
|
||||
}
|
||||
|
||||
#frameNavigated(params: UnknownRecord): void {
|
||||
const frame = recordValue(params.frame);
|
||||
if (stringValue(frame?.id) !== this.#mainFrameId) return;
|
||||
this.navigationDuringCapture = true;
|
||||
const rawUrl = stringValue(frame?.url);
|
||||
if (
|
||||
isHttpUrl(rawUrl) &&
|
||||
allowedSanitizedUrl(rawUrl, this.allowedOrigins) === undefined
|
||||
)
|
||||
this.originViolation = true;
|
||||
}
|
||||
}
|
||||
|
||||
const firstCallFrame = (
|
||||
value: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => {
|
||||
const callFrames = recordsValue(value?.callFrames);
|
||||
return callFrames[0];
|
||||
};
|
||||
|
||||
const integerOrNull = (value: unknown): number | null => {
|
||||
const number = numberValue(value);
|
||||
return number === undefined ? null : Math.max(0, Math.trunc(number));
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
import {
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
/** Capture redacted, bounded storage metadata for one authorized origin. */
|
||||
export const captureStorage = async (
|
||||
context: {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string;
|
||||
readonly input: InspectWebPageInput;
|
||||
readonly signal?: AbortSignal;
|
||||
},
|
||||
origin: string,
|
||||
limitations: string[],
|
||||
): Promise<{
|
||||
readonly value: WebPageInspection["storage"];
|
||||
readonly truncated: boolean;
|
||||
}> => {
|
||||
const quota = recordValue(
|
||||
await optionalCdpCommand(
|
||||
context,
|
||||
"Storage.getUsageAndQuota",
|
||||
{ origin },
|
||||
limitations,
|
||||
),
|
||||
);
|
||||
const local = context.input.include_storage_keys
|
||||
? await storageKeys(context, origin, true, limitations)
|
||||
: [];
|
||||
const session = context.input.include_storage_keys
|
||||
? await storageKeys(context, origin, false, limitations)
|
||||
: [];
|
||||
const indexed = context.input.include_storage_keys
|
||||
? stringArray(
|
||||
recordValue(
|
||||
await optionalCdpCommand(
|
||||
context,
|
||||
"IndexedDB.requestDatabaseNames",
|
||||
{ securityOrigin: origin },
|
||||
limitations,
|
||||
),
|
||||
)?.databaseNames,
|
||||
)
|
||||
: [];
|
||||
const caches = context.input.include_storage_keys
|
||||
? recordsValue(
|
||||
recordValue(
|
||||
await optionalCdpCommand(
|
||||
context,
|
||||
"CacheStorage.requestCacheNames",
|
||||
{ securityOrigin: origin },
|
||||
limitations,
|
||||
),
|
||||
)?.caches,
|
||||
).flatMap((cache) => {
|
||||
const name = stringValue(cache.cacheName);
|
||||
return name === undefined ? [] : [name.slice(0, 1_024)];
|
||||
})
|
||||
: [];
|
||||
const maximum = context.input.limits.max_storage_keys;
|
||||
return {
|
||||
value: {
|
||||
origin,
|
||||
usage_bytes: numberValue(quota?.usage) ?? null,
|
||||
quota_bytes: numberValue(quota?.quota) ?? null,
|
||||
local_storage_keys: local.slice(0, maximum),
|
||||
session_storage_keys: session.slice(0, maximum),
|
||||
indexed_db_names: indexed.slice(0, maximum),
|
||||
cache_names: caches.slice(0, maximum),
|
||||
values_redacted: true,
|
||||
},
|
||||
truncated: [local, session, indexed, caches].some(
|
||||
(items) => items.length > maximum,
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const storageKeys = async (
|
||||
context: Parameters<typeof captureStorage>[0],
|
||||
origin: string,
|
||||
isLocalStorage: boolean,
|
||||
limitations: string[],
|
||||
): Promise<readonly string[]> => {
|
||||
const result = recordValue(
|
||||
await optionalCdpCommand(
|
||||
context,
|
||||
"DOMStorage.getDOMStorageItems",
|
||||
{ storageId: { securityOrigin: origin, isLocalStorage } },
|
||||
limitations,
|
||||
),
|
||||
);
|
||||
return Array.isArray(result?.entries)
|
||||
? result.entries.flatMap((entry) => {
|
||||
if (!Array.isArray(entry)) return [];
|
||||
const key = stringValue(entry[0]);
|
||||
return key === undefined ? [] : [key.slice(0, 1_024)];
|
||||
})
|
||||
: [];
|
||||
};
|
||||
|
||||
const stringArray = (value: unknown): readonly string[] =>
|
||||
Array.isArray(value)
|
||||
? value.flatMap((item) => {
|
||||
const text = stringValue(item);
|
||||
return text === undefined ? [] : [text.slice(0, 1_024)];
|
||||
})
|
||||
: [];
|
||||
@@ -0,0 +1,98 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
BrowserObservationError,
|
||||
} from "../domain/errors.js";
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
|
||||
export type UnknownRecord = Readonly<Record<string, unknown>>;
|
||||
|
||||
const isRecord = (value: unknown): value is UnknownRecord =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
export const recordValue = (value: unknown): UnknownRecord | undefined =>
|
||||
isRecord(value) ? value : undefined;
|
||||
|
||||
export const recordsValue = (value: unknown): readonly UnknownRecord[] =>
|
||||
Array.isArray(value)
|
||||
? value.flatMap((item) => {
|
||||
const record = recordValue(item);
|
||||
return record === undefined ? [] : [record];
|
||||
})
|
||||
: [];
|
||||
|
||||
export const stringValue = (value: unknown): string | undefined =>
|
||||
typeof value === "string" ? value : undefined;
|
||||
|
||||
export const numberValue = (value: unknown): number | undefined =>
|
||||
typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
|
||||
export const requiredRecord = (value: unknown): UnknownRecord => {
|
||||
const record = recordValue(value);
|
||||
if (record === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
return record;
|
||||
};
|
||||
|
||||
export const boundedText = (value: unknown, maximum = 1_024): string | null => {
|
||||
const text = stringValue(value);
|
||||
return text === undefined ? null : text.slice(0, maximum);
|
||||
};
|
||||
|
||||
export const isHttpUrl = (value: string | undefined): boolean => {
|
||||
if (value === undefined) return false;
|
||||
try {
|
||||
const protocol = new URL(value).protocol;
|
||||
return protocol === "http:" || protocol === "https:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const allowedSanitizedUrl = (
|
||||
value: unknown,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): ReturnType<typeof sanitizeBrowserUrl> | undefined => {
|
||||
const text = stringValue(value);
|
||||
if (text === undefined) return undefined;
|
||||
const sanitized = sanitizeBrowserUrl(text);
|
||||
return sanitized.origin !== null && allowedOrigins.has(sanitized.origin)
|
||||
? sanitized
|
||||
: undefined;
|
||||
};
|
||||
|
||||
export const sourceResult = (
|
||||
source: string,
|
||||
): { included: true; sha256: string; bytes: number; content: string } => ({
|
||||
included: true,
|
||||
sha256: createHash("sha256").update(source).digest("hex"),
|
||||
bytes: Buffer.byteLength(source),
|
||||
content: source,
|
||||
});
|
||||
|
||||
export const sourceExcluded = (
|
||||
reason: string,
|
||||
): { included: false; reason: string } => ({ included: false, reason });
|
||||
|
||||
export const delayWithCancellation = async (
|
||||
durationMs: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
if (durationMs === 0) return;
|
||||
if (signal?.aborted === true)
|
||||
throw new AnalysisCancelledError("inspect_web_page");
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
resolve();
|
||||
}, durationMs);
|
||||
const onAbort = (): void => {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
reject(new AnalysisCancelledError("inspect_web_page"));
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal?.aborted === true) onAbort();
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,252 @@
|
||||
import WebSocket, { type RawData } from "ws";
|
||||
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisError,
|
||||
AnalysisTimeoutError,
|
||||
BrowserObservationError,
|
||||
} from "../domain/errors.js";
|
||||
|
||||
export interface CdpEvent {
|
||||
readonly method: string;
|
||||
readonly params: unknown;
|
||||
readonly sessionId?: string;
|
||||
}
|
||||
|
||||
interface PendingCommand {
|
||||
readonly resolve: (value: unknown) => void;
|
||||
readonly reject: (error: AnalysisError) => void;
|
||||
readonly timer: ReturnType<typeof setTimeout>;
|
||||
readonly removeAbort: () => void;
|
||||
}
|
||||
|
||||
const CONNECT_TIMEOUT_MS = 5_000;
|
||||
const COMMAND_TIMEOUT_MS = 5_000;
|
||||
const MAX_PAYLOAD_BYTES = 16 * 1_024 * 1_024;
|
||||
const MAX_PENDING_COMMANDS = 128;
|
||||
|
||||
/** Correlated, bounded JSON-RPC transport for a browser-level CDP socket. */
|
||||
export class CdpConnection {
|
||||
readonly #pending = new Map<number, PendingCommand>();
|
||||
readonly #listeners = new Set<(event: CdpEvent) => void>();
|
||||
#nextId = 1;
|
||||
#closed = false;
|
||||
#protocolFailed = false;
|
||||
|
||||
private constructor(private readonly socket: WebSocket) {
|
||||
socket.on("message", (data) => this.#receive(data));
|
||||
socket.on("close", () => this.#failPending("disconnected"));
|
||||
socket.on("error", () => this.#failPending("disconnected"));
|
||||
}
|
||||
|
||||
/** Connect to one already-validated loopback browser WebSocket. */
|
||||
static async connect(
|
||||
url: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CdpConnection> {
|
||||
if (signal?.aborted === true)
|
||||
throw new AnalysisCancelledError("inspect_web_page");
|
||||
const socket = new WebSocket(url, {
|
||||
handshakeTimeout: CONNECT_TIMEOUT_MS,
|
||||
maxPayload: MAX_PAYLOAD_BYTES,
|
||||
perMessageDeflate: false,
|
||||
});
|
||||
await waitForOpen(socket, signal);
|
||||
return new CdpConnection(socket);
|
||||
}
|
||||
|
||||
/** Subscribe to validated CDP event envelopes. */
|
||||
onEvent(listener: (event: CdpEvent) => void): () => void {
|
||||
this.#listeners.add(listener);
|
||||
return () => this.#listeners.delete(listener);
|
||||
}
|
||||
|
||||
/** Execute one bounded command, optionally within a flat target session. */
|
||||
async send(
|
||||
method: string,
|
||||
params: Readonly<Record<string, unknown>> = {},
|
||||
sessionId?: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<unknown> {
|
||||
if (this.#protocolFailed)
|
||||
throw new BrowserObservationError("inspect_web_page", "protocol_error");
|
||||
if (this.#closed || this.socket.readyState !== WebSocket.OPEN)
|
||||
throw new BrowserObservationError("inspect_web_page", "disconnected");
|
||||
if (this.#pending.size >= MAX_PENDING_COMMANDS)
|
||||
throw new BrowserObservationError("inspect_web_page", "payload_limit");
|
||||
if (signal?.aborted === true)
|
||||
throw new AnalysisCancelledError("inspect_web_page");
|
||||
const id = this.#nextId;
|
||||
this.#nextId += 1;
|
||||
return await new Promise((resolve, reject) => {
|
||||
const onAbort = (): void => {
|
||||
const pending = this.#pending.get(id);
|
||||
if (pending === undefined) return;
|
||||
clearTimeout(pending.timer);
|
||||
pending.removeAbort();
|
||||
this.#pending.delete(id);
|
||||
reject(new AnalysisCancelledError("inspect_web_page"));
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
this.#pending.delete(id);
|
||||
reject(
|
||||
new AnalysisTimeoutError("inspect_web_page", COMMAND_TIMEOUT_MS),
|
||||
);
|
||||
}, COMMAND_TIMEOUT_MS);
|
||||
this.#pending.set(id, {
|
||||
resolve,
|
||||
reject,
|
||||
timer,
|
||||
removeAbort: () => signal?.removeEventListener("abort", onAbort),
|
||||
});
|
||||
this.socket.send(
|
||||
JSON.stringify({
|
||||
id,
|
||||
method,
|
||||
params,
|
||||
...(sessionId ? { sessionId } : {}),
|
||||
}),
|
||||
(error) => {
|
||||
if (error === undefined || error === null) return;
|
||||
const pending = this.#pending.get(id);
|
||||
if (pending === undefined) return;
|
||||
this.#complete(id, pending);
|
||||
reject(
|
||||
new BrowserObservationError("inspect_web_page", "disconnected", {
|
||||
cause: error,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Close only REA's socket; never close the browser or selected page. */
|
||||
async close(): Promise<void> {
|
||||
if (this.#closed) return;
|
||||
this.#closed = true;
|
||||
this.#failPending("disconnected");
|
||||
if (this.socket.readyState === WebSocket.CLOSED) return;
|
||||
await new Promise<void>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.socket.terminate();
|
||||
resolve();
|
||||
}, 1_000);
|
||||
this.socket.once("close", () => {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
});
|
||||
this.socket.close();
|
||||
});
|
||||
}
|
||||
|
||||
#receive(data: RawData): void {
|
||||
let message: unknown;
|
||||
try {
|
||||
message = JSON.parse(rawText(data));
|
||||
} catch {
|
||||
this.#failPending("protocol_error");
|
||||
return;
|
||||
}
|
||||
if (!isRecord(message)) {
|
||||
this.#failPending("protocol_error");
|
||||
return;
|
||||
}
|
||||
if ("id" in message && typeof message.id === "number") {
|
||||
this.#receiveResponse(message, message.id);
|
||||
return;
|
||||
}
|
||||
if ("method" in message && typeof message.method === "string") {
|
||||
const event: CdpEvent = {
|
||||
method: message.method,
|
||||
params: "params" in message ? message.params : {},
|
||||
...(typeof message.sessionId === "string"
|
||||
? { sessionId: message.sessionId }
|
||||
: {}),
|
||||
};
|
||||
for (const listener of this.#listeners) listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
#receiveResponse(message: Record<string, unknown>, id: number): void {
|
||||
const pending = this.#pending.get(id);
|
||||
if (pending === undefined) return;
|
||||
this.#complete(id, pending);
|
||||
if ("error" in message) {
|
||||
pending.reject(
|
||||
new BrowserObservationError("inspect_web_page", "protocol_error"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.resolve("result" in message ? message.result : {});
|
||||
}
|
||||
|
||||
#complete(id: number, pending: PendingCommand): void {
|
||||
clearTimeout(pending.timer);
|
||||
pending.removeAbort();
|
||||
this.#pending.delete(id);
|
||||
}
|
||||
|
||||
#failPending(reason: "disconnected" | "protocol_error"): void {
|
||||
if (reason === "disconnected") this.#closed = true;
|
||||
else this.#protocolFailed = true;
|
||||
for (const [id, pending] of this.#pending) {
|
||||
this.#complete(id, pending);
|
||||
pending.reject(new BrowserObservationError("inspect_web_page", reason));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const rawText = (data: RawData): string =>
|
||||
Array.isArray(data)
|
||||
? Buffer.concat(data).toString("utf8")
|
||||
: Buffer.isBuffer(data)
|
||||
? data.toString("utf8")
|
||||
: Buffer.from(data).toString("utf8");
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const waitForOpen = async (
|
||||
socket: WebSocket,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> =>
|
||||
await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
socket.terminate();
|
||||
reject(new AnalysisTimeoutError("inspect_web_page", CONNECT_TIMEOUT_MS));
|
||||
}, CONNECT_TIMEOUT_MS);
|
||||
const onOpen = (): void => {
|
||||
cleanup();
|
||||
resolve();
|
||||
};
|
||||
const onFailure = (cause: unknown): void => {
|
||||
cleanup();
|
||||
reject(
|
||||
signal?.aborted === true
|
||||
? new AnalysisCancelledError("inspect_web_page")
|
||||
: new BrowserObservationError(
|
||||
"inspect_web_page",
|
||||
"endpoint_unreachable",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
socket.terminate();
|
||||
onFailure(new AnalysisCancelledError("inspect_web_page"));
|
||||
};
|
||||
const cleanup = (): void => {
|
||||
clearTimeout(timer);
|
||||
socket.off("open", onOpen);
|
||||
socket.off("error", onFailure);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
};
|
||||
socket.once("open", onOpen);
|
||||
socket.once("error", onFailure);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal?.aborted === true) onAbort();
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
import { request } from "node:http";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisError,
|
||||
AnalysisTimeoutError,
|
||||
BrowserObservationError,
|
||||
} from "../domain/errors.js";
|
||||
|
||||
const HTTP_TIMEOUT_MS = 5_000;
|
||||
const MAX_VERSION_BYTES = 64 * 1_024;
|
||||
const MAX_TARGET_LIST_BYTES = 2 * 1_024 * 1_024;
|
||||
|
||||
const endpointVersionSchema = z.object({
|
||||
Browser: z.string().min(1).max(1_024),
|
||||
"Protocol-Version": z.string().min(1).max(100),
|
||||
"User-Agent": z.string().max(16_384),
|
||||
"V8-Version": z.string().max(1_024),
|
||||
"WebKit-Version": z.string().max(1_024),
|
||||
webSocketDebuggerUrl: z.string().min(1).max(2_048),
|
||||
});
|
||||
|
||||
const endpointTargetSchema = z.object({
|
||||
id: z.string().min(1).max(256),
|
||||
type: z.string().min(1).max(100),
|
||||
title: z.string().max(16_384).default(""),
|
||||
url: z.string().max(65_536),
|
||||
attached: z.boolean().default(false),
|
||||
});
|
||||
const endpointTargetsSchema = z.array(endpointTargetSchema).max(1_000);
|
||||
|
||||
export type CdpEndpointTarget = z.infer<typeof endpointTargetSchema>;
|
||||
|
||||
export interface CdpEndpointDiscovery {
|
||||
readonly browserWebSocketUrl: string;
|
||||
readonly version: {
|
||||
readonly product: string;
|
||||
readonly protocol_version: string;
|
||||
readonly revision: string;
|
||||
readonly user_agent: string;
|
||||
readonly js_version: string;
|
||||
};
|
||||
readonly targets: readonly CdpEndpointTarget[];
|
||||
}
|
||||
|
||||
type BrowserOperation = "list_browser_targets" | "inspect_web_page";
|
||||
|
||||
/** Read bounded CDP discovery endpoints without following redirects. */
|
||||
export const discoverCdpEndpoint = async (
|
||||
endpoint: string,
|
||||
operation: BrowserOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CdpEndpointDiscovery> => {
|
||||
const versionInput = await readJson(
|
||||
new URL("/json/version", endpoint),
|
||||
MAX_VERSION_BYTES,
|
||||
operation,
|
||||
signal,
|
||||
);
|
||||
const targetsInput = await readJson(
|
||||
new URL("/json/list", endpoint),
|
||||
MAX_TARGET_LIST_BYTES,
|
||||
operation,
|
||||
signal,
|
||||
);
|
||||
const version = parseEndpointValue(
|
||||
endpointVersionSchema,
|
||||
versionInput,
|
||||
operation,
|
||||
);
|
||||
const targets = parseEndpointValue(
|
||||
endpointTargetsSchema,
|
||||
targetsInput,
|
||||
operation,
|
||||
);
|
||||
return {
|
||||
browserWebSocketUrl: safeBrowserWebSocketUrl(
|
||||
endpoint,
|
||||
version.webSocketDebuggerUrl,
|
||||
operation,
|
||||
),
|
||||
version: {
|
||||
product: version.Browser,
|
||||
protocol_version: version["Protocol-Version"],
|
||||
revision: version["WebKit-Version"],
|
||||
user_agent: version["User-Agent"],
|
||||
js_version: version["V8-Version"],
|
||||
},
|
||||
targets,
|
||||
};
|
||||
};
|
||||
|
||||
const parseEndpointValue = <Output>(
|
||||
schema: z.ZodType<Output>,
|
||||
input: unknown,
|
||||
operation: BrowserOperation,
|
||||
): Output => {
|
||||
const parsed = schema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
throw new BrowserObservationError(operation, "invalid_endpoint_response", {
|
||||
cause: parsed.error,
|
||||
});
|
||||
return parsed.data;
|
||||
};
|
||||
|
||||
const safeBrowserWebSocketUrl = (
|
||||
endpoint: string,
|
||||
reported: string,
|
||||
operation: BrowserOperation,
|
||||
): string => {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(reported);
|
||||
} catch (cause: unknown) {
|
||||
throw new BrowserObservationError(operation, "invalid_endpoint_response", {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
const trustedEndpoint = new URL(endpoint);
|
||||
if (
|
||||
parsed.protocol !== "ws:" ||
|
||||
parsed.port !== trustedEndpoint.port ||
|
||||
parsed.username !== "" ||
|
||||
parsed.password !== "" ||
|
||||
parsed.search !== "" ||
|
||||
parsed.hash !== "" ||
|
||||
!parsed.pathname.startsWith("/devtools/browser/")
|
||||
)
|
||||
throw new BrowserObservationError(operation, "invalid_endpoint_response");
|
||||
parsed.hostname = trustedEndpoint.hostname;
|
||||
return parsed.href;
|
||||
};
|
||||
|
||||
const readJson = async (
|
||||
url: URL,
|
||||
maximumBytes: number,
|
||||
operation: BrowserOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<unknown> =>
|
||||
await new Promise((resolve, reject) => {
|
||||
if (signal?.aborted === true) {
|
||||
reject(new AnalysisCancelledError(operation));
|
||||
return;
|
||||
}
|
||||
const request_ = request(
|
||||
url,
|
||||
{ method: "GET", signal, headers: { Accept: "application/json" } },
|
||||
(response) => {
|
||||
if (response.statusCode !== 200) {
|
||||
response.resume();
|
||||
reject(
|
||||
new BrowserObservationError(operation, "invalid_endpoint_response"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
response.on("data", (chunk: Buffer) => {
|
||||
bytes += chunk.length;
|
||||
if (bytes > maximumBytes) {
|
||||
response.destroy(
|
||||
new BrowserObservationError(operation, "payload_limit"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
response.on("end", () => {
|
||||
try {
|
||||
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||
} catch (cause: unknown) {
|
||||
reject(
|
||||
new BrowserObservationError(
|
||||
operation,
|
||||
"invalid_endpoint_response",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
response.on("error", (cause: unknown) =>
|
||||
reject(endpointFailure(cause, operation, signal)),
|
||||
);
|
||||
},
|
||||
);
|
||||
request_.setTimeout(HTTP_TIMEOUT_MS, () =>
|
||||
request_.destroy(new AnalysisTimeoutError(operation, HTTP_TIMEOUT_MS)),
|
||||
);
|
||||
request_.on("error", (cause: unknown) =>
|
||||
reject(endpointFailure(cause, operation, signal)),
|
||||
);
|
||||
request_.end();
|
||||
});
|
||||
|
||||
const endpointFailure = (
|
||||
cause: unknown,
|
||||
operation: BrowserOperation,
|
||||
signal?: AbortSignal,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (signal?.aborted === true) return new AnalysisCancelledError(operation);
|
||||
return new BrowserObservationError(operation, "endpoint_unreachable", {
|
||||
cause,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import { BrowserObservationError } from "../domain/errors.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
|
||||
/** Execute an optional CDP method while preserving transport and cancellation failures. */
|
||||
export const optionalCdpCommand = async (
|
||||
context: {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string | undefined;
|
||||
readonly signal?: AbortSignal;
|
||||
},
|
||||
method: string,
|
||||
parameters: Readonly<Record<string, unknown>>,
|
||||
limitations: string[],
|
||||
): Promise<unknown | undefined> => {
|
||||
try {
|
||||
return await context.connection.send(
|
||||
method,
|
||||
parameters,
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
!(cause instanceof BrowserObservationError) ||
|
||||
cause.reason !== "protocol_error"
|
||||
)
|
||||
throw cause;
|
||||
limitations.push(`${method} was unavailable from this browser target.`);
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,446 @@
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import { BrowserObservationError } from "../domain/errors.js";
|
||||
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
import { captureStorage } from "./CdpCaptureStorage.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
import {
|
||||
captureAccessibility,
|
||||
captureDom,
|
||||
captureFrames,
|
||||
captureResources,
|
||||
mainFrameUrl,
|
||||
} from "./CdpCaptureDocuments.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
delayWithCancellation,
|
||||
isHttpUrl,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
requiredRecord,
|
||||
sourceExcluded,
|
||||
sourceResult,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
interface CaptureContext {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string;
|
||||
readonly discovery: CdpEndpointDiscovery;
|
||||
readonly target: CdpEndpointTarget;
|
||||
readonly input: InspectWebPageInput;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly progress?: ProgressReporter;
|
||||
}
|
||||
|
||||
interface CaptureState {
|
||||
readonly context: CaptureContext;
|
||||
readonly events: CdpCaptureEvents;
|
||||
readonly allowedOrigins: ReadonlySet<string>;
|
||||
readonly limitations: string[];
|
||||
readonly truncatedSections: Set<string>;
|
||||
readonly startedAt: string;
|
||||
}
|
||||
|
||||
interface CapturedSections {
|
||||
readonly attachedUrl: string;
|
||||
readonly frames: WebPageInspection["frames"];
|
||||
readonly dom: ReturnType<typeof captureDom>;
|
||||
readonly accessibility: ReturnType<typeof captureAccessibility>;
|
||||
readonly scripts: WebPageInspection["scripts"];
|
||||
readonly resources: WebPageInspection["resources"];
|
||||
readonly workers: WebPageInspection["workers"];
|
||||
readonly storage: WebPageInspection["storage"];
|
||||
}
|
||||
|
||||
/** Capture and normalize one attached page without evaluating page JavaScript. */
|
||||
export const capturePage = async (
|
||||
context: CaptureContext,
|
||||
): Promise<WebPageInspection> => {
|
||||
const allowedOrigins = new Set(context.input.allowed_origins);
|
||||
const events = new CdpCaptureEvents(context.input, allowedOrigins);
|
||||
const removeListener = context.connection.onEvent((event) =>
|
||||
events.ingest(event),
|
||||
);
|
||||
const state: CaptureState = {
|
||||
context,
|
||||
events,
|
||||
allowedOrigins,
|
||||
limitations: [
|
||||
"Observation starts when REA attaches; prior network and console activity is unavailable.",
|
||||
"Network headers, request bodies, response bodies, cookies, storage values, console values, and WebSocket payloads are not retained.",
|
||||
"Source maps are reported only as declarative URLs and are not fetched.",
|
||||
"URL-less scripts and console events without an allowed source URL are excluded because their origin cannot be proven.",
|
||||
],
|
||||
truncatedSections: new Set<string>(),
|
||||
startedAt: new Date().toISOString(),
|
||||
};
|
||||
try {
|
||||
return await captureAuthorizedPage(state);
|
||||
} finally {
|
||||
removeListener();
|
||||
}
|
||||
};
|
||||
|
||||
const captureAuthorizedPage = async (
|
||||
state: CaptureState,
|
||||
): Promise<WebPageInspection> => {
|
||||
const { context, allowedOrigins, limitations, truncatedSections } = state;
|
||||
const { connection, sessionId, input, signal } = context;
|
||||
await authorizeObservationWindow(state);
|
||||
const frameResult = await authorizedFrameTree(context, allowedOrigins);
|
||||
const attachedUrl = mainFrameUrl(frameResult) ?? "";
|
||||
const frameCapture = captureFrames(
|
||||
frameResult,
|
||||
allowedOrigins,
|
||||
input.limits.max_frames,
|
||||
);
|
||||
const frames = frameCapture.items;
|
||||
if (frameCapture.total > frames.length) truncatedSections.add("frames");
|
||||
const captureFrame = frames[0];
|
||||
if (captureFrame === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
state.events.beginFinalCapture(captureFrame.frame_id);
|
||||
const resourceCapture = captureResources(
|
||||
await connection.send("Page.getResourceTree", {}, sessionId, signal),
|
||||
allowedOrigins,
|
||||
input.limits.max_resources,
|
||||
);
|
||||
if (resourceCapture.total > resourceCapture.items.length)
|
||||
truncatedSections.add("resources");
|
||||
const dom = await capturePageDom(state);
|
||||
if (dom.total > dom.nodes.length) truncatedSections.add("dom");
|
||||
const accessibility = await accessibilityForFrames(
|
||||
context,
|
||||
frames,
|
||||
limitations,
|
||||
);
|
||||
if (accessibility.total > accessibility.nodes.length)
|
||||
truncatedSections.add("accessibility");
|
||||
const scripts = await captureScripts(
|
||||
context,
|
||||
state.events,
|
||||
truncatedSections,
|
||||
);
|
||||
const workerCapture = await captureWorkers(
|
||||
context,
|
||||
allowedOrigins,
|
||||
limitations,
|
||||
);
|
||||
if (workerCapture.total > workerCapture.items.length)
|
||||
truncatedSections.add("workers");
|
||||
const storageCapture = await captureStorage(
|
||||
context,
|
||||
frames[0]?.origin ?? new URL(attachedUrl).origin,
|
||||
limitations,
|
||||
);
|
||||
if (storageCapture.truncated) truncatedSections.add("storage_keys");
|
||||
if (state.events.dropped > 0) truncatedSections.add("events");
|
||||
const completedFrameResult = await authorizedFrameTree(
|
||||
context,
|
||||
allowedOrigins,
|
||||
);
|
||||
const completedUrl = mainFrameUrl(completedFrameResult) ?? "";
|
||||
if (state.events.originViolation)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
if (state.events.navigationDuringCapture || completedUrl !== attachedUrl)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_changed");
|
||||
await report(context.progress, 3, "Normalizing browser evidence");
|
||||
return normalizedInspection(state, {
|
||||
attachedUrl,
|
||||
frames,
|
||||
dom,
|
||||
accessibility,
|
||||
scripts,
|
||||
resources: resourceCapture.items,
|
||||
workers: workerCapture.items,
|
||||
storage: storageCapture.value,
|
||||
});
|
||||
};
|
||||
|
||||
const authorizeObservationWindow = async (
|
||||
state: CaptureState,
|
||||
): Promise<void> => {
|
||||
const { context, allowedOrigins, events } = state;
|
||||
const { connection, sessionId, signal } = context;
|
||||
await report(context.progress, 1, "Enabling passive CDP domains");
|
||||
await connection.send("Page.enable", {}, sessionId, signal);
|
||||
const initialFrameResult = await authorizedFrameTree(context, allowedOrigins);
|
||||
const mainFrame = captureFrames(initialFrameResult, allowedOrigins, 1)
|
||||
.items[0];
|
||||
if (mainFrame === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
events.beginAuthorizedFrame(mainFrame.frame_id);
|
||||
await enableObservationDomains(connection, sessionId, signal);
|
||||
await report(context.progress, 2, "Observing page events");
|
||||
await delayWithCancellation(context.input.observation_ms, signal);
|
||||
if (events.originViolation)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
};
|
||||
|
||||
const capturePageDom = async (
|
||||
state: CaptureState,
|
||||
): Promise<ReturnType<typeof captureDom>> => {
|
||||
const { context, allowedOrigins } = state;
|
||||
const result = await context.connection.send(
|
||||
"DOMSnapshot.captureSnapshot",
|
||||
{
|
||||
computedStyles: [],
|
||||
includePaintOrder: false,
|
||||
includeDOMRects: false,
|
||||
},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
return captureDom(result, allowedOrigins, context.input);
|
||||
};
|
||||
|
||||
const normalizedInspection = (
|
||||
state: CaptureState,
|
||||
captured: CapturedSections,
|
||||
): WebPageInspection => ({
|
||||
schema_version: 1,
|
||||
browser: state.context.discovery.version,
|
||||
target: normalizedTarget(
|
||||
state.context.target,
|
||||
captured.attachedUrl,
|
||||
state.allowedOrigins,
|
||||
),
|
||||
capture_window: {
|
||||
started_at: state.startedAt,
|
||||
ended_at: new Date().toISOString(),
|
||||
observation_ms: state.context.input.observation_ms,
|
||||
},
|
||||
completeness: {
|
||||
status: state.truncatedSections.size === 0 ? "complete" : "truncated",
|
||||
truncated_sections: [...state.truncatedSections].sort(),
|
||||
dropped_events: state.events.dropped,
|
||||
},
|
||||
frames: [...captured.frames],
|
||||
dom: { total_nodes: captured.dom.total, nodes: [...captured.dom.nodes] },
|
||||
accessibility: {
|
||||
total_nodes: captured.accessibility.total,
|
||||
nodes: [...captured.accessibility.nodes],
|
||||
},
|
||||
scripts: captured.scripts,
|
||||
resources: [...captured.resources],
|
||||
network: {
|
||||
requests: [...state.events.network.values()],
|
||||
websocket_events: [...state.events.websockets],
|
||||
coverage_started_at: state.startedAt,
|
||||
prior_activity_available: false,
|
||||
},
|
||||
console: {
|
||||
events: [...state.events.console],
|
||||
coverage_started_at: state.startedAt,
|
||||
prior_activity_available: false,
|
||||
},
|
||||
workers: [...captured.workers],
|
||||
storage: captured.storage,
|
||||
limitations: state.limitations,
|
||||
});
|
||||
|
||||
const authorizedFrameTree = async (
|
||||
context: CaptureContext,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): Promise<unknown> => {
|
||||
for (let attempt = 0; attempt < 80; attempt += 1) {
|
||||
const result = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const currentUrl = mainFrameUrl(result);
|
||||
if (allowedSanitizedUrl(currentUrl, allowedOrigins) !== undefined)
|
||||
return result;
|
||||
if (isHttpUrl(currentUrl))
|
||||
throw new BrowserObservationError(
|
||||
"inspect_web_page",
|
||||
"target_not_allowed",
|
||||
);
|
||||
await delayWithCancellation(25, context.signal);
|
||||
}
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
};
|
||||
|
||||
const enableObservationDomains = async (
|
||||
connection: CdpConnection,
|
||||
sessionId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
await connection.send("Runtime.enable", {}, sessionId, signal);
|
||||
await connection.send(
|
||||
"Debugger.enable",
|
||||
{ maxScriptsCacheSize: 4 * 1_024 * 1_024 },
|
||||
sessionId,
|
||||
signal,
|
||||
);
|
||||
await connection.send(
|
||||
"Network.enable",
|
||||
{
|
||||
maxTotalBufferSize: 4 * 1_024 * 1_024,
|
||||
maxResourceBufferSize: 1_024 * 1_024,
|
||||
},
|
||||
sessionId,
|
||||
signal,
|
||||
);
|
||||
};
|
||||
|
||||
const accessibilityForFrames = async (
|
||||
context: CaptureContext,
|
||||
frames: readonly { readonly frame_id: string }[],
|
||||
limitations: string[],
|
||||
): Promise<ReturnType<typeof captureAccessibility>> => {
|
||||
const nodes: WebPageInspection["accessibility"]["nodes"] = [];
|
||||
let total = 0;
|
||||
for (const frame of frames) {
|
||||
const result = await optionalCdpCommand(
|
||||
context,
|
||||
"Accessibility.getFullAXTree",
|
||||
{ depth: 32, frameId: frame.frame_id },
|
||||
limitations,
|
||||
);
|
||||
if (result === undefined) continue;
|
||||
const capture = captureAccessibility(
|
||||
[result],
|
||||
Math.max(0, context.input.limits.max_ax_nodes - nodes.length),
|
||||
);
|
||||
total += capture.total;
|
||||
nodes.push(...capture.nodes);
|
||||
}
|
||||
return { total, nodes };
|
||||
};
|
||||
|
||||
const captureScripts = async (
|
||||
context: CaptureContext,
|
||||
events: CdpCaptureEvents,
|
||||
truncatedSections: Set<string>,
|
||||
): Promise<WebPageInspection["scripts"]> => {
|
||||
let totalSourceBytes = 0;
|
||||
const items: WebPageInspection["scripts"]["items"] = [];
|
||||
for (const script of events.scripts.values()) {
|
||||
let source: WebPageInspection["scripts"]["items"][number]["source"] =
|
||||
sourceExcluded("source capture was not approved");
|
||||
if (context.input.include_script_sources) {
|
||||
if (script.length > context.input.limits.max_script_source_bytes) {
|
||||
source = sourceExcluded(
|
||||
"declared script length exceeds per-script limit",
|
||||
);
|
||||
truncatedSections.add("script_sources");
|
||||
} else if (
|
||||
totalSourceBytes + script.length >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
source = sourceExcluded("total script source limit reached");
|
||||
truncatedSections.add("script_sources");
|
||||
} else {
|
||||
const result = requiredRecord(
|
||||
await context.connection.send(
|
||||
"Debugger.getScriptSource",
|
||||
{ scriptId: script.scriptId },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
),
|
||||
);
|
||||
const content = stringValue(result.scriptSource) ?? "";
|
||||
const bytes = Buffer.byteLength(content);
|
||||
if (
|
||||
bytes > context.input.limits.max_script_source_bytes ||
|
||||
totalSourceBytes + bytes >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
source = sourceExcluded(
|
||||
"actual source exceeds configured byte limits",
|
||||
);
|
||||
truncatedSections.add("script_sources");
|
||||
} else {
|
||||
source = sourceResult(content);
|
||||
totalSourceBytes += bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
items.push({
|
||||
script_id: script.scriptId,
|
||||
url: script.url,
|
||||
origin: script.origin,
|
||||
cdp_hash: script.hash,
|
||||
length: script.length,
|
||||
is_module: script.isModule,
|
||||
language: script.language,
|
||||
source_map_url: script.sourceMapUrl,
|
||||
source,
|
||||
});
|
||||
}
|
||||
return { total: events.scripts.size, items };
|
||||
};
|
||||
|
||||
const captureWorkers = async (
|
||||
context: CaptureContext,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
limitations: string[],
|
||||
): Promise<{
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["workers"];
|
||||
}> => {
|
||||
const result = await optionalCdpCommand(
|
||||
{ ...context, sessionId: undefined },
|
||||
"Target.getTargets",
|
||||
{},
|
||||
limitations,
|
||||
);
|
||||
const items: WebPageInspection["workers"] = [];
|
||||
let total = 0;
|
||||
for (const target of recordsValue(recordValue(result)?.targetInfos)) {
|
||||
const type = stringValue(target.type) ?? "";
|
||||
const url = allowedSanitizedUrl(target.url, allowedOrigins);
|
||||
if (!type.includes("worker") || url === undefined) continue;
|
||||
total += 1;
|
||||
if (items.length >= context.input.limits.max_workers) continue;
|
||||
items.push({
|
||||
target_id: (stringValue(target.targetId) ?? "").slice(0, 256),
|
||||
type: type.slice(0, 100),
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
attached: target.attached === true,
|
||||
});
|
||||
}
|
||||
return {
|
||||
total,
|
||||
items,
|
||||
};
|
||||
};
|
||||
|
||||
const normalizedTarget = (
|
||||
target: CdpEndpointTarget,
|
||||
currentUrl: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): WebPageInspection["target"] => {
|
||||
const url = allowedSanitizedUrl(currentUrl, allowedOrigins);
|
||||
return {
|
||||
target_id: target.id,
|
||||
type: target.type,
|
||||
title: target.title.slice(0, 16_384),
|
||||
url: url?.url ?? "[unsupported-url]",
|
||||
origin: url?.origin ?? "",
|
||||
attached: target.attached,
|
||||
};
|
||||
};
|
||||
|
||||
const report = async (
|
||||
progress: ProgressReporter | undefined,
|
||||
completed: number,
|
||||
message: string,
|
||||
): Promise<void> =>
|
||||
await progress?.report({
|
||||
phase: "browser_observation",
|
||||
completed,
|
||||
total: 3,
|
||||
message,
|
||||
...(completed === 3 ? { terminal: true } : {}),
|
||||
});
|
||||
@@ -36,6 +36,8 @@ export const CLI_COMMAND_NAMES = [
|
||||
"capture-process",
|
||||
"compare-process-captures",
|
||||
"policy",
|
||||
"list-browser-targets",
|
||||
"inspect-web-page",
|
||||
] as const;
|
||||
|
||||
const toolCatalog = TOOL_CONTRACTS.map((contract) => ({
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
import { projectReferenceSourceImportError } from "./application/ReferenceSourceImportTypes.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import { registerPolicyCommands } from "./cliPolicyCommands.js";
|
||||
import { registerBrowserCommands } from "./cliBrowserCommands.js";
|
||||
|
||||
/**
|
||||
* Build the one-shot Incur CLI without starting Hopper at import time.
|
||||
@@ -73,6 +74,7 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
registerReferenceSourceCommand(cli, logger);
|
||||
registerProcessCommands(cli, logger);
|
||||
registerPolicyCommands(cli, logger);
|
||||
registerBrowserCommands(cli, logger);
|
||||
return cli;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { Cli, z } from "incur";
|
||||
|
||||
import {
|
||||
inspectWebPage,
|
||||
listBrowserTargets,
|
||||
} from "./application/BrowserObservationService.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import { CdpBrowserProvider } from "./browser/CdpBrowserProvider.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import {
|
||||
inspectWebPageInputSchema,
|
||||
listBrowserTargetsInputSchema,
|
||||
} from "./domain/browserObservation.js";
|
||||
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
|
||||
import type { JsonValue } from "./domain/jsonValue.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
|
||||
const browserScopeOptions = {
|
||||
allowedOrigins: z
|
||||
.array(z.string().min(1))
|
||||
.optional()
|
||||
.describe(
|
||||
"Exact origins to observe; defaults to REA_BROWSER_ALLOWED_ORIGINS_JSON",
|
||||
),
|
||||
approved: z.boolean().default(false).describe("Approve passive observation"),
|
||||
};
|
||||
|
||||
/** Register CLI equivalents of the passive browser MCP tools. */
|
||||
export const registerBrowserCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
registerTargetList(cli, logger);
|
||||
registerPageInspection(cli, logger);
|
||||
};
|
||||
|
||||
const registerTargetList = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command("list-browser-targets", {
|
||||
description: "List approved pages from a user-owned loopback CDP browser",
|
||||
args: z.object({
|
||||
endpoint: z.string().describe("Configured loopback CDP HTTP endpoint"),
|
||||
}),
|
||||
options: z.object({
|
||||
...browserScopeOptions,
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(200).default(100),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "list-browser-targets", async () => {
|
||||
const context = await browserContext();
|
||||
if (!context.ok) return context.error;
|
||||
const parsed = listBrowserTargetsInputSchema.safeParse({
|
||||
cdp_endpoint: args.endpoint,
|
||||
allowed_origins:
|
||||
options.allowedOrigins ?? context.allowedBrowserOrigins,
|
||||
approved: options.approved,
|
||||
offset: options.offset,
|
||||
limit: options.limit,
|
||||
});
|
||||
if (!parsed.success)
|
||||
return cliError(new AnalysisInputError("list_browser_targets"));
|
||||
const result = await listBrowserTargets(
|
||||
context.provider,
|
||||
context.authority,
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const registerPageInspection = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command("inspect-web-page", {
|
||||
description: "Passively inspect one approved page through CDP",
|
||||
args: z.object({
|
||||
endpoint: z.string().describe("Configured loopback CDP HTTP endpoint"),
|
||||
targetId: z.string().describe("Target ID from list-browser-targets"),
|
||||
}),
|
||||
options: z.object({
|
||||
...browserScopeOptions,
|
||||
observationMs: z.number().int().min(0).max(10_000).default(500),
|
||||
includeScriptSources: z.boolean().default(false),
|
||||
includeStorageKeys: z.boolean().default(false),
|
||||
maxFrames: z.number().int().min(1).max(1_000).default(200),
|
||||
maxDomNodes: z.number().int().min(1).max(10_000).default(2_000),
|
||||
maxAxNodes: z.number().int().min(1).max(10_000).default(2_000),
|
||||
maxScripts: z.number().int().min(1).max(1_000).default(200),
|
||||
maxResources: z.number().int().min(1).max(10_000).default(2_000),
|
||||
maxWorkers: z.number().int().min(1).max(5_000).default(500),
|
||||
maxStorageKeys: z.number().int().min(1).max(10_000).default(1_000),
|
||||
maxScriptSourceBytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(4 * 1_024 * 1_024)
|
||||
.default(1_024 * 1_024),
|
||||
maxTotalScriptSourceBytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16 * 1_024 * 1_024)
|
||||
.default(4 * 1_024 * 1_024),
|
||||
maxNetworkEvents: z.number().int().min(1).max(10_000).default(1_000),
|
||||
maxConsoleEvents: z.number().int().min(1).max(2_000).default(200),
|
||||
maxWebsocketEvents: z.number().int().min(1).max(5_000).default(500),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "inspect-web-page", async () => {
|
||||
const context = await browserContext();
|
||||
if (!context.ok) return context.error;
|
||||
const parsed = inspectWebPageInputSchema.safeParse({
|
||||
cdp_endpoint: args.endpoint,
|
||||
allowed_origins:
|
||||
options.allowedOrigins ?? context.allowedBrowserOrigins,
|
||||
approved: options.approved,
|
||||
target_id: args.targetId,
|
||||
observation_ms: options.observationMs,
|
||||
include_script_sources: options.includeScriptSources,
|
||||
include_storage_keys: options.includeStorageKeys,
|
||||
limits: {
|
||||
max_frames: options.maxFrames,
|
||||
max_dom_nodes: options.maxDomNodes,
|
||||
max_ax_nodes: options.maxAxNodes,
|
||||
max_scripts: options.maxScripts,
|
||||
max_resources: options.maxResources,
|
||||
max_workers: options.maxWorkers,
|
||||
max_storage_keys: options.maxStorageKeys,
|
||||
max_script_source_bytes: options.maxScriptSourceBytes,
|
||||
max_total_script_source_bytes: options.maxTotalScriptSourceBytes,
|
||||
max_network_events: options.maxNetworkEvents,
|
||||
max_console_events: options.maxConsoleEvents,
|
||||
max_websocket_events: options.maxWebsocketEvents,
|
||||
},
|
||||
});
|
||||
if (!parsed.success)
|
||||
return cliError(new AnalysisInputError("inspect_web_page"));
|
||||
const result = await inspectWebPage(
|
||||
context.provider,
|
||||
context.authority,
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const browserContext = async () => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok) return { ok: false as const, error: cliError(config.error) };
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok)
|
||||
return { ok: false as const, error: cliError(authority.error) };
|
||||
return {
|
||||
ok: true as const,
|
||||
authority: authority.value,
|
||||
provider: new CdpBrowserProvider(),
|
||||
allowedBrowserOrigins: config.value.browserAllowedOrigins,
|
||||
};
|
||||
};
|
||||
|
||||
const cliError = (
|
||||
error: Parameters<typeof projectAnalysisError>[0],
|
||||
): JsonValue => ({
|
||||
error: "Browser observation failed",
|
||||
...projectAnalysisError(error),
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import type { Logger } from "./logger.js";
|
||||
|
||||
const capabilitySchema = z.enum([
|
||||
"process_capture",
|
||||
"browser_observe",
|
||||
"evidence_read",
|
||||
"evidence_write",
|
||||
"investigation_input",
|
||||
@@ -43,6 +44,7 @@ export const registerPolicyCommands = (
|
||||
root: z.string().optional(),
|
||||
executable: z.string().optional(),
|
||||
environmentNames: z.array(z.string()).default([]),
|
||||
origins: z.array(z.string()).default([]),
|
||||
network: z.enum(["none", "loopback", "external"]).default("none"),
|
||||
mount: z.boolean().default(false),
|
||||
write: z.boolean().default(false),
|
||||
@@ -102,6 +104,7 @@ const explain = async (
|
||||
readonly root?: string | undefined;
|
||||
readonly executable?: string | undefined;
|
||||
readonly environmentNames: readonly string[];
|
||||
readonly origins: readonly string[];
|
||||
readonly network: "none" | "loopback" | "external";
|
||||
readonly mount: boolean;
|
||||
readonly write: boolean;
|
||||
@@ -115,6 +118,7 @@ const explain = async (
|
||||
roots: options.root === undefined ? [] : [options.root],
|
||||
executables: options.executable === undefined ? [] : [options.executable],
|
||||
environment_names: options.environmentNames,
|
||||
origins: options.origins,
|
||||
network: options.network,
|
||||
mount: options.mount,
|
||||
operation_identity: `policy_explain:${capability}`,
|
||||
|
||||
@@ -10,6 +10,10 @@ import type {
|
||||
PermissionCeiling,
|
||||
PermissionGrant,
|
||||
} from "./domain/permissionPolicy.js";
|
||||
import {
|
||||
browserEndpointSchema,
|
||||
browserOriginSchema,
|
||||
} from "./domain/browserObservation.js";
|
||||
|
||||
const DEFAULT_HOPPER_LAUNCHER_PATH =
|
||||
"/Applications/Hopper Disassembler.app/Contents/MacOS/hopper";
|
||||
@@ -31,6 +35,9 @@ export interface AppConfig {
|
||||
readonly investigationInputRoots: readonly string[];
|
||||
readonly analysisSnapshotFilePolicy: EvidenceFilePolicy;
|
||||
readonly referenceSourcePolicy: ReferenceSourcePolicy;
|
||||
readonly browserObservationEnabled: boolean;
|
||||
readonly browserCdpEndpoints: readonly string[];
|
||||
readonly browserAllowedOrigins: readonly string[];
|
||||
readonly permissionCeilings: readonly PermissionCeiling[];
|
||||
readonly administratorPermissionGrants: readonly PermissionGrant[];
|
||||
readonly permissionProjectRoot: string | undefined;
|
||||
@@ -66,6 +73,9 @@ const environmentSchema = z
|
||||
REA_ANALYSIS_SNAPSHOT_ROOTS_JSON: z.string().default("[]"),
|
||||
REA_REFERENCE_ROOTS_JSON: z.string().default("[]"),
|
||||
REA_REFERENCE_SECRET_PATTERNS_JSON: z.string().default("[]"),
|
||||
REA_BROWSER_OBSERVE_ENABLED: z.enum(["true", "false"]).default("false"),
|
||||
REA_BROWSER_CDP_ENDPOINTS_JSON: z.string().default("[]"),
|
||||
REA_BROWSER_ALLOWED_ORIGINS_JSON: z.string().default("[]"),
|
||||
REA_PERMISSION_PROJECT_ROOT: z.string().min(1).optional(),
|
||||
REA_PERMISSION_PROJECT_STORE: z.string().min(1).optional(),
|
||||
})
|
||||
@@ -100,6 +110,29 @@ const parseStringArray = (
|
||||
}
|
||||
};
|
||||
|
||||
const parseBrowserArray = (
|
||||
encoded: string,
|
||||
name: string,
|
||||
itemSchema: z.ZodType<string>,
|
||||
maximum: number,
|
||||
): Result<readonly string[], ConfigurationError> => {
|
||||
try {
|
||||
const parsed = z
|
||||
.array(itemSchema)
|
||||
.max(maximum)
|
||||
.safeParse(JSON.parse(encoded));
|
||||
return parsed.success
|
||||
? ok([...new Set(parsed.data)].sort())
|
||||
: err(
|
||||
new ConfigurationError(`${name} must encode valid browser scopes`, {
|
||||
cause: parsed.error,
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(new ConfigurationError(`${name} must be valid JSON`, { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
const filePolicy = (roots: readonly string[]): EvidenceFilePolicy => ({
|
||||
roots,
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
@@ -117,6 +150,7 @@ const permissionScope = (
|
||||
roots,
|
||||
executables: options.executables ?? [],
|
||||
environment_names: options.environment_names ?? [],
|
||||
...(options.origins === undefined ? {} : { origins: options.origins }),
|
||||
network: options.network ?? "none",
|
||||
mount: options.mount ?? false,
|
||||
});
|
||||
@@ -218,6 +252,20 @@ export const parseConfig = (
|
||||
"REA_REFERENCE_SECRET_PATTERNS_JSON",
|
||||
);
|
||||
if (!secretPatterns.ok) return secretPatterns;
|
||||
const browserEndpoints = parseBrowserArray(
|
||||
parsedEnvironment.data.REA_BROWSER_CDP_ENDPOINTS_JSON,
|
||||
"REA_BROWSER_CDP_ENDPOINTS_JSON",
|
||||
browserEndpointSchema,
|
||||
16,
|
||||
);
|
||||
if (!browserEndpoints.ok) return browserEndpoints;
|
||||
const browserOrigins = parseBrowserArray(
|
||||
parsedEnvironment.data.REA_BROWSER_ALLOWED_ORIGINS_JSON,
|
||||
"REA_BROWSER_ALLOWED_ORIGINS_JSON",
|
||||
browserOriginSchema,
|
||||
32,
|
||||
);
|
||||
if (!browserOrigins.ok) return browserOrigins;
|
||||
const permissionCeilings = [
|
||||
...(parsedEnvironment.data.REA_PROCESS_CAPTURE_ENABLED === "true"
|
||||
? [
|
||||
@@ -241,6 +289,14 @@ export const parseConfig = (
|
||||
permissionScope("snapshot_write", analysisSnapshotRoots.value),
|
||||
permissionScope("artifact_extract", ["/"]),
|
||||
permissionScope("reference_read", referenceRoots.value),
|
||||
...(parsedEnvironment.data.REA_BROWSER_OBSERVE_ENABLED === "true"
|
||||
? [
|
||||
permissionScope("browser_observe", [], {
|
||||
origins: [...browserEndpoints.value, ...browserOrigins.value],
|
||||
network: browserNetworkScope(browserOrigins.value),
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(parsedEnvironment.data.REA_ARTIFACT_NATIVE_MOUNT_ENABLED === "true"
|
||||
? [permissionScope("native_mount", [], { mount: true })]
|
||||
: []),
|
||||
@@ -276,9 +332,23 @@ export const parseConfig = (
|
||||
maxDepth: 32,
|
||||
maxPathBytes: 4_096,
|
||||
},
|
||||
browserObservationEnabled:
|
||||
parsedEnvironment.data.REA_BROWSER_OBSERVE_ENABLED === "true",
|
||||
browserCdpEndpoints: browserEndpoints.value,
|
||||
browserAllowedOrigins: browserOrigins.value,
|
||||
permissionCeilings,
|
||||
administratorPermissionGrants: administratorGrants(permissionCeilings),
|
||||
permissionProjectRoot: parsedEnvironment.data.REA_PERMISSION_PROJECT_ROOT,
|
||||
permissionProjectStore: parsedEnvironment.data.REA_PERMISSION_PROJECT_STORE,
|
||||
});
|
||||
};
|
||||
|
||||
const browserNetworkScope = (
|
||||
origins: readonly string[],
|
||||
): "loopback" | "external" =>
|
||||
origins.every((origin) => {
|
||||
const hostname = new URL(origin).hostname;
|
||||
return hostname === "127.0.0.1" || hostname === "[::1]";
|
||||
})
|
||||
? "loopback"
|
||||
: "external";
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { ToolContract } from "./toolContracts.js";
|
||||
import { evidenceSchema } from "../domain/evidence.js";
|
||||
import {
|
||||
browserTargetListSchema,
|
||||
inspectWebPageInputSchema,
|
||||
listBrowserTargetsInputSchema,
|
||||
webPageInspectionSchema,
|
||||
} from "../domain/browserObservation.js";
|
||||
|
||||
const evidenceResult = (schema: typeof browserTargetListSchema) =>
|
||||
evidenceSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: schema });
|
||||
const listOutputSchema = evidenceResult(browserTargetListSchema);
|
||||
const inspectionOutputSchema = evidenceSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: webPageInspectionSchema });
|
||||
|
||||
const endpoint = "http://127.0.0.1:9222";
|
||||
const origin = "https://app.example.test";
|
||||
|
||||
/** Origin-scoped, passive browser reverse-engineering contracts. */
|
||||
export const BROWSER_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "list_browser_targets",
|
||||
description:
|
||||
"List bounded page targets from an approved user-owned loopback Chrome DevTools Protocol endpoint. Only targets whose current URL matches an approved exact origin are returned; URL credentials, query values, and fragments are redacted.",
|
||||
kind: "browser-provider",
|
||||
inputSchema: listBrowserTargetsInputSchema,
|
||||
outputSchema: listOutputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: true,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: true,
|
||||
},
|
||||
examples: [
|
||||
{
|
||||
title: "List approved browser page targets",
|
||||
input: {
|
||||
cdp_endpoint: endpoint,
|
||||
allowed_origins: [origin],
|
||||
approved: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "inspect_web_page",
|
||||
description:
|
||||
"Passively inspect one approved page target through CDP without evaluating JavaScript, navigating, clicking, closing, or mutating the page. Returns bounded DOM structure, accessibility, scripts, resources, attach-window network and console metadata, workers, and redacted storage inventory as Evidence v2.",
|
||||
kind: "browser-provider",
|
||||
inputSchema: inspectWebPageInputSchema,
|
||||
outputSchema: inspectionOutputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: true,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: true,
|
||||
},
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect one approved browser page",
|
||||
input: {
|
||||
cdp_endpoint: endpoint,
|
||||
allowed_origins: [origin],
|
||||
approved: true,
|
||||
target_id: "TARGET_ID_FROM_LIST_BROWSER_TARGETS",
|
||||
observation_ms: 500,
|
||||
include_script_sources: false,
|
||||
include_storage_keys: false,
|
||||
limits: {
|
||||
max_frames: 200,
|
||||
max_dom_nodes: 2_000,
|
||||
max_ax_nodes: 2_000,
|
||||
max_scripts: 200,
|
||||
max_resources: 2_000,
|
||||
max_workers: 500,
|
||||
max_storage_keys: 1_000,
|
||||
max_script_source_bytes: 1_048_576,
|
||||
max_total_script_source_bytes: 4_194_304,
|
||||
max_network_events: 1_000,
|
||||
max_console_events: 200,
|
||||
max_websocket_events: 500,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -36,6 +36,7 @@ const scopeSchema = z
|
||||
roots: z.array(z.string()),
|
||||
executables: z.array(z.string()),
|
||||
environment_names: z.array(z.string()),
|
||||
origins: z.array(z.string()).optional(),
|
||||
network: z.enum(["none", "loopback", "external"]),
|
||||
mount: z.boolean(),
|
||||
})
|
||||
@@ -45,6 +46,7 @@ const missingScopeSchema = z
|
||||
roots: z.array(z.string()).optional(),
|
||||
executables: z.array(z.string()).optional(),
|
||||
environment_names: z.array(z.string()).optional(),
|
||||
origins: z.array(z.string()).optional(),
|
||||
network: z.enum(["none", "loopback", "external"]).optional(),
|
||||
mount: z.literal(true).optional(),
|
||||
})
|
||||
|
||||
@@ -22,6 +22,7 @@ export type ToolKind =
|
||||
| "enhanced"
|
||||
| "native-provider"
|
||||
| "artifact-provider"
|
||||
| "browser-provider"
|
||||
| "session";
|
||||
|
||||
/** Single source of truth for a public MCP tool. */
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
import { TOOL_EXAMPLE_OVERRIDES } from "./toolContractExamples.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "./browserToolContracts.js";
|
||||
import {
|
||||
closeBinaryInputSchema,
|
||||
openBinaryInputSchema,
|
||||
@@ -512,15 +513,12 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
),
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
/**
|
||||
* Complete ordered public inventory used by registration and verification.
|
||||
* Keep this collection at 68 tools unless a deliberate contract change updates
|
||||
* snapshots, package verification, and real-Hopper verification together.
|
||||
*/
|
||||
/** Complete ordered public inventory used by registration and verification. */
|
||||
export const TOOL_CONTRACTS = [
|
||||
...OFFICIAL_TOOL_CONTRACTS,
|
||||
...ENHANCED_TOOL_CONTRACTS,
|
||||
...NATIVE_TOOL_CONTRACTS,
|
||||
...ARTIFACT_TOOL_CONTRACTS,
|
||||
...BROWSER_TOOL_CONTRACTS,
|
||||
...SESSION_TOOL_CONTRACTS,
|
||||
] as const;
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const parseExactOrigin = (value: string): string | undefined => {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
(url.protocol !== "http:" && url.protocol !== "https:") ||
|
||||
url.hostname.includes("*") ||
|
||||
url.username !== "" ||
|
||||
url.password !== "" ||
|
||||
url.pathname !== "/" ||
|
||||
url.search !== "" ||
|
||||
url.hash !== ""
|
||||
)
|
||||
return undefined;
|
||||
return url.origin;
|
||||
};
|
||||
|
||||
const MAX_BROWSER_URL_CHARS = 65_536;
|
||||
const MAX_SANITIZED_BROWSER_URL_CHARS = 131_072;
|
||||
const MAX_QUERY_PARAMETER_NAMES = 256;
|
||||
const MAX_QUERY_PARAMETER_NAME_CHARS = 256;
|
||||
|
||||
/** Exact normalized HTTP(S) authority used for browser observation scope. */
|
||||
export const browserOriginSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(2_048)
|
||||
.transform((value, context) => {
|
||||
const origin = parseExactOrigin(value);
|
||||
if (origin === undefined) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Expected one exact HTTP(S) origin without a path or wildcard",
|
||||
});
|
||||
return z.NEVER;
|
||||
}
|
||||
return origin;
|
||||
});
|
||||
|
||||
const isLiteralLoopback = (hostname: string): boolean =>
|
||||
hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
|
||||
|
||||
/** Loopback-only HTTP endpoint accepted for a user-owned CDP browser. */
|
||||
export const browserEndpointSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(2_048)
|
||||
.transform((value, context) => {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
context.addIssue({ code: "custom", message: "Invalid CDP endpoint URL" });
|
||||
return z.NEVER;
|
||||
}
|
||||
if (
|
||||
url.protocol !== "http:" ||
|
||||
!isLiteralLoopback(url.hostname) ||
|
||||
url.port === "" ||
|
||||
url.username !== "" ||
|
||||
url.password !== "" ||
|
||||
url.pathname !== "/" ||
|
||||
url.search !== "" ||
|
||||
url.hash !== ""
|
||||
) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"CDP endpoint must be an explicit-port HTTP URL on 127.0.0.1 or ::1",
|
||||
});
|
||||
return z.NEVER;
|
||||
}
|
||||
return url.origin;
|
||||
});
|
||||
|
||||
const allowedOriginsSchema = z
|
||||
.array(browserOriginSchema)
|
||||
.min(1)
|
||||
.max(32)
|
||||
.transform((origins) => [...new Set(origins)].sort());
|
||||
|
||||
const approvedBrowserInput = {
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
allowed_origins: allowedOriginsSchema,
|
||||
approved: z
|
||||
.literal(true)
|
||||
.describe("Explicit approval for browser observation"),
|
||||
};
|
||||
|
||||
/** Public input for bounded discovery of allowed page targets. */
|
||||
export const listBrowserTargetsInputSchema = z.object({
|
||||
...approvedBrowserInput,
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(200).default(100),
|
||||
});
|
||||
|
||||
const browserInspectionLimitsSchema = z.object({
|
||||
max_frames: z.number().int().min(1).max(1_000).default(200),
|
||||
max_dom_nodes: z.number().int().min(1).max(10_000).default(2_000),
|
||||
max_ax_nodes: z.number().int().min(1).max(10_000).default(2_000),
|
||||
max_scripts: z.number().int().min(1).max(1_000).default(200),
|
||||
max_resources: z.number().int().min(1).max(10_000).default(2_000),
|
||||
max_workers: z.number().int().min(1).max(5_000).default(500),
|
||||
max_storage_keys: z.number().int().min(1).max(10_000).default(1_000),
|
||||
max_script_source_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(4 * 1_024 * 1_024)
|
||||
.default(1_024 * 1_024),
|
||||
max_total_script_source_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16 * 1_024 * 1_024)
|
||||
.default(4 * 1_024 * 1_024),
|
||||
max_network_events: z.number().int().min(1).max(10_000).default(1_000),
|
||||
max_console_events: z.number().int().min(1).max(2_000).default(200),
|
||||
max_websocket_events: z.number().int().min(1).max(5_000).default(500),
|
||||
});
|
||||
|
||||
const DEFAULT_BROWSER_INSPECTION_LIMITS = {
|
||||
max_frames: 200,
|
||||
max_dom_nodes: 2_000,
|
||||
max_ax_nodes: 2_000,
|
||||
max_scripts: 200,
|
||||
max_resources: 2_000,
|
||||
max_workers: 500,
|
||||
max_storage_keys: 1_000,
|
||||
max_script_source_bytes: 1_024 * 1_024,
|
||||
max_total_script_source_bytes: 4 * 1_024 * 1_024,
|
||||
max_network_events: 1_000,
|
||||
max_console_events: 200,
|
||||
max_websocket_events: 500,
|
||||
} as const;
|
||||
|
||||
/** Public input for one passive, bounded inspection of an existing page. */
|
||||
export const inspectWebPageInputSchema = z
|
||||
.object({
|
||||
...approvedBrowserInput,
|
||||
target_id: z.string().trim().min(1).max(256),
|
||||
observation_ms: z.number().int().min(0).max(10_000).default(500),
|
||||
include_script_sources: z.boolean().default(false),
|
||||
include_storage_keys: z.boolean().default(false),
|
||||
limits: browserInspectionLimitsSchema.default(
|
||||
DEFAULT_BROWSER_INSPECTION_LIMITS,
|
||||
),
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
if (
|
||||
input.limits.max_script_source_bytes >
|
||||
input.limits.max_total_script_source_bytes
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["limits", "max_script_source_bytes"],
|
||||
message: "Per-script source limit cannot exceed the total source limit",
|
||||
});
|
||||
});
|
||||
|
||||
export type ListBrowserTargetsInput = z.infer<
|
||||
typeof listBrowserTargetsInputSchema
|
||||
>;
|
||||
export type InspectWebPageInput = z.infer<typeof inspectWebPageInputSchema>;
|
||||
|
||||
const sanitizedBrowserUrlSchema = z.object({
|
||||
url: z.string().max(MAX_SANITIZED_BROWSER_URL_CHARS),
|
||||
origin: z.string().max(2_048).nullable(),
|
||||
query_parameter_names: z
|
||||
.array(z.string().max(MAX_QUERY_PARAMETER_NAME_CHARS))
|
||||
.max(MAX_QUERY_PARAMETER_NAMES),
|
||||
redacted: z.boolean(),
|
||||
});
|
||||
export type SanitizedBrowserUrl = z.infer<typeof sanitizedBrowserUrlSchema>;
|
||||
|
||||
/** Remove credentials and query values before a browser URL becomes durable. */
|
||||
export const sanitizeBrowserUrl = (value: string): SanitizedBrowserUrl => {
|
||||
let parsed: URL;
|
||||
const wasTruncated = value.length > MAX_BROWSER_URL_CHARS;
|
||||
try {
|
||||
parsed = new URL(value.slice(0, MAX_BROWSER_URL_CHARS));
|
||||
} catch {
|
||||
return {
|
||||
url: "[unsupported-url]",
|
||||
origin: null,
|
||||
query_parameter_names: [],
|
||||
redacted: true,
|
||||
};
|
||||
}
|
||||
const hadCredentials = parsed.username !== "" || parsed.password !== "";
|
||||
const hadFragment = parsed.hash !== "";
|
||||
const names = [
|
||||
...new Set(
|
||||
[...parsed.searchParams.keys()].map((name) =>
|
||||
name.slice(0, MAX_QUERY_PARAMETER_NAME_CHARS),
|
||||
),
|
||||
),
|
||||
]
|
||||
.sort()
|
||||
.slice(0, MAX_QUERY_PARAMETER_NAMES);
|
||||
parsed.username = "";
|
||||
parsed.password = "";
|
||||
parsed.hash = "";
|
||||
parsed.search = "";
|
||||
for (const name of names) parsed.searchParams.append(name, "[REDACTED]");
|
||||
return {
|
||||
url: parsed.href,
|
||||
origin: parsed.origin === "null" ? null : parsed.origin,
|
||||
query_parameter_names: names,
|
||||
redacted: wasTruncated || hadCredentials || hadFragment || names.length > 0,
|
||||
};
|
||||
};
|
||||
|
||||
const browserVersionSchema = z.object({
|
||||
product: z.string(),
|
||||
protocol_version: z.string(),
|
||||
revision: z.string(),
|
||||
user_agent: z.string(),
|
||||
js_version: z.string(),
|
||||
});
|
||||
|
||||
const browserTargetSchema = z.object({
|
||||
target_id: z.string(),
|
||||
type: z.string(),
|
||||
title: z.string(),
|
||||
url: z.string(),
|
||||
origin: z.string(),
|
||||
attached: z.boolean(),
|
||||
});
|
||||
|
||||
/** Bounded and policy-filtered browser target discovery result. */
|
||||
export const browserTargetListSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
browser: browserVersionSchema,
|
||||
targets: z.object({
|
||||
items: z.array(browserTargetSchema),
|
||||
offset: z.number().int().min(0),
|
||||
limit: z.number().int().min(1),
|
||||
total: z.number().int().min(0),
|
||||
next_offset: z.number().int().min(0).nullable(),
|
||||
has_more: z.boolean(),
|
||||
}),
|
||||
excluded: z.object({
|
||||
disallowed_origin: z.number().int().min(0),
|
||||
unsupported_url: z.number().int().min(0),
|
||||
non_page: z.number().int().min(0),
|
||||
}),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export type BrowserTargetList = z.infer<typeof browserTargetListSchema>;
|
||||
|
||||
const browserFrameSchema = z.object({
|
||||
frame_id: z.string(),
|
||||
parent_frame_id: z.string().nullable(),
|
||||
url: z.string(),
|
||||
origin: z.string().nullable(),
|
||||
});
|
||||
const browserDomNodeSchema = z.object({
|
||||
index: z.number().int().min(0),
|
||||
parent_index: z.number().int().min(-1),
|
||||
node_type: z.number().int().min(0),
|
||||
node_name: z.string(),
|
||||
node_value_length: z.number().int().min(0),
|
||||
attribute_names: z.array(z.string()),
|
||||
});
|
||||
const browserAxNodeSchema = z.object({
|
||||
node_id: z.string(),
|
||||
parent_id: z.string().nullable(),
|
||||
role: z.string().nullable(),
|
||||
name: z.string().nullable(),
|
||||
description: z.string().nullable(),
|
||||
ignored: z.boolean(),
|
||||
});
|
||||
const browserScriptSourceSchema = z.discriminatedUnion("included", [
|
||||
z.object({ included: z.literal(false), reason: z.string() }),
|
||||
z.object({
|
||||
included: z.literal(true),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
bytes: z.number().int().min(0),
|
||||
content: z.string(),
|
||||
}),
|
||||
]);
|
||||
const browserScriptSchema = z.object({
|
||||
script_id: z.string(),
|
||||
url: z.string(),
|
||||
origin: z.string().nullable(),
|
||||
cdp_hash: z.string(),
|
||||
length: z.number().int().min(0),
|
||||
is_module: z.boolean(),
|
||||
language: z.string().nullable(),
|
||||
source_map_url: z.string().nullable(),
|
||||
source: browserScriptSourceSchema,
|
||||
});
|
||||
const browserResourceSchema = z.object({
|
||||
url: z.string(),
|
||||
origin: z.string().nullable(),
|
||||
type: z.string(),
|
||||
mime_type: z.string(),
|
||||
content_size: z.number().min(0).nullable(),
|
||||
});
|
||||
const browserNetworkRequestSchema = z.object({
|
||||
request_id: z.string(),
|
||||
url: z.string(),
|
||||
origin: z.string().nullable(),
|
||||
method: z.string(),
|
||||
resource_type: z.string().nullable(),
|
||||
status: z.number().nullable(),
|
||||
mime_type: z.string().nullable(),
|
||||
encoded_data_length: z.number().min(0).nullable(),
|
||||
initiator: z.object({
|
||||
type: z.string(),
|
||||
url: z.string().nullable(),
|
||||
line: z.number().int().min(0).nullable(),
|
||||
column: z.number().int().min(0).nullable(),
|
||||
}),
|
||||
});
|
||||
const browserConsoleEventSchema = z.object({
|
||||
type: z.string(),
|
||||
timestamp: z.number(),
|
||||
argument_types: z.array(z.string()),
|
||||
url: z.string().nullable(),
|
||||
line: z.number().int().min(0).nullable(),
|
||||
column: z.number().int().min(0).nullable(),
|
||||
});
|
||||
const browserWebSocketEventSchema = z.object({
|
||||
request_id: z.string(),
|
||||
direction: z.enum(["sent", "received"]),
|
||||
opcode: z.number().int().min(0),
|
||||
payload_bytes: z.number().int().min(0),
|
||||
});
|
||||
const browserWorkerSchema = z.object({
|
||||
target_id: z.string(),
|
||||
type: z.string(),
|
||||
url: z.string(),
|
||||
origin: z.string().nullable(),
|
||||
attached: z.boolean(),
|
||||
});
|
||||
|
||||
/** Provider-neutral normalized result for one passive web-page observation. */
|
||||
export const webPageInspectionSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
browser: browserVersionSchema,
|
||||
target: browserTargetSchema,
|
||||
capture_window: z.object({
|
||||
started_at: z.iso.datetime(),
|
||||
ended_at: z.iso.datetime(),
|
||||
observation_ms: z.number().int().min(0),
|
||||
}),
|
||||
completeness: z.object({
|
||||
status: z.enum(["complete", "truncated"]),
|
||||
truncated_sections: z.array(z.string()),
|
||||
dropped_events: z.number().int().min(0),
|
||||
}),
|
||||
frames: z.array(browserFrameSchema),
|
||||
dom: z.object({
|
||||
total_nodes: z.number().int().min(0),
|
||||
nodes: z.array(browserDomNodeSchema),
|
||||
}),
|
||||
accessibility: z.object({
|
||||
total_nodes: z.number().int().min(0),
|
||||
nodes: z.array(browserAxNodeSchema),
|
||||
}),
|
||||
scripts: z.object({
|
||||
total: z.number().int().min(0),
|
||||
items: z.array(browserScriptSchema),
|
||||
}),
|
||||
resources: z.array(browserResourceSchema),
|
||||
network: z.object({
|
||||
requests: z.array(browserNetworkRequestSchema),
|
||||
websocket_events: z.array(browserWebSocketEventSchema),
|
||||
coverage_started_at: z.iso.datetime(),
|
||||
prior_activity_available: z.literal(false),
|
||||
}),
|
||||
console: z.object({
|
||||
events: z.array(browserConsoleEventSchema),
|
||||
coverage_started_at: z.iso.datetime(),
|
||||
prior_activity_available: z.literal(false),
|
||||
}),
|
||||
workers: z.array(browserWorkerSchema),
|
||||
storage: z.object({
|
||||
origin: z.string(),
|
||||
usage_bytes: z.number().min(0).nullable(),
|
||||
quota_bytes: z.number().min(0).nullable(),
|
||||
local_storage_keys: z.array(z.string()),
|
||||
session_storage_keys: z.array(z.string()),
|
||||
indexed_db_names: z.array(z.string()),
|
||||
cache_names: z.array(z.string()),
|
||||
values_redacted: z.literal(true),
|
||||
}),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export type WebPageInspection = z.infer<typeof webPageInspectionSchema>;
|
||||
@@ -20,6 +20,7 @@ const ANALYSIS_ERROR_TAGS = [
|
||||
"AnalysisTimeoutError",
|
||||
"ProviderSelectionError",
|
||||
"ProviderAdapterError",
|
||||
"BrowserObservationError",
|
||||
"ArtifactOperationError",
|
||||
"ProcessCaptureError",
|
||||
"EvidenceIntegrityError",
|
||||
@@ -143,6 +144,27 @@ export class ProviderAdapterError extends AnalysisError {
|
||||
}
|
||||
}
|
||||
|
||||
/** A bounded passive browser observation failed at its CDP boundary. */
|
||||
export class BrowserObservationError extends AnalysisError {
|
||||
readonly _tag = "BrowserObservationError";
|
||||
|
||||
constructor(
|
||||
readonly operation: "list_browser_targets" | "inspect_web_page",
|
||||
readonly reason:
|
||||
| "endpoint_unreachable"
|
||||
| "invalid_endpoint_response"
|
||||
| "target_not_found"
|
||||
| "target_not_allowed"
|
||||
| "target_changed"
|
||||
| "protocol_error"
|
||||
| "disconnected"
|
||||
| "payload_limit",
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(`Browser observation ${operation} failed: ${reason}`, options);
|
||||
}
|
||||
}
|
||||
|
||||
/** Artifact inventory or extraction failed a typed safety boundary. */
|
||||
export class ArtifactOperationError extends AnalysisError {
|
||||
readonly _tag = "ArtifactOperationError";
|
||||
@@ -424,6 +446,21 @@ export const projectAnalysisError = (
|
||||
|
||||
const errorCode = (error: AnalysisError): AnalysisErrorProjection["code"] => {
|
||||
if (error instanceof PermissionRequiredError) return "permission_required";
|
||||
if (error instanceof BrowserObservationError) {
|
||||
if (error.reason === "payload_limit") return "truncated";
|
||||
if (
|
||||
error.reason === "target_not_found" ||
|
||||
error.reason === "target_not_allowed" ||
|
||||
error.reason === "target_changed"
|
||||
)
|
||||
return "target_unavailable";
|
||||
if (
|
||||
error.reason === "endpoint_unreachable" ||
|
||||
error.reason === "disconnected"
|
||||
)
|
||||
return "provider_unavailable";
|
||||
return "unreadable_output";
|
||||
}
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return error.reason === "integrity" && error.artifactDetails !== undefined
|
||||
? "artifact_integrity_mismatch"
|
||||
@@ -501,6 +538,8 @@ const errorCode = (error: AnalysisError): AnalysisErrorProjection["code"] => {
|
||||
case "ProviderAdapterError":
|
||||
case "HopperRemoteError":
|
||||
return "execution_failure";
|
||||
case "BrowserObservationError":
|
||||
throw new TypeError("Unhandled specialized browser error");
|
||||
case "ArtifactOperationError":
|
||||
case "EvidenceFileError":
|
||||
case "InvestigationWorkspaceError":
|
||||
@@ -552,6 +591,8 @@ const errorDetails = (
|
||||
return { provider_id: error.providerId, operation: error.operation };
|
||||
if (error instanceof ProviderAdapterError)
|
||||
return { provider_id: error.providerId, operation: error.operation };
|
||||
if (error instanceof BrowserObservationError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
if (error instanceof HopperRemoteError)
|
||||
return { provider_code: error.code, diagnostic_type: error.diagnosticType };
|
||||
if (error instanceof HopperProcessError && error.failureCode !== undefined)
|
||||
@@ -577,6 +618,7 @@ const scopeDetails = (
|
||||
roots: [...scope.roots],
|
||||
executables: [...scope.executables],
|
||||
environment_names: [...scope.environment_names],
|
||||
...(scope.origins === undefined ? {} : { origins: [...scope.origins] }),
|
||||
network: scope.network,
|
||||
mount: scope.mount,
|
||||
});
|
||||
@@ -591,6 +633,7 @@ const missingScopeDetails = (
|
||||
...(scope.environment_names === undefined
|
||||
? {}
|
||||
: { environment_names: [...scope.environment_names] }),
|
||||
...(scope.origins === undefined ? {} : { origins: [...scope.origins] }),
|
||||
...(scope.network === undefined ? {} : { network: scope.network }),
|
||||
...(scope.mount === undefined ? {} : { mount: scope.mount }),
|
||||
});
|
||||
@@ -616,6 +659,17 @@ const errorCategory = (
|
||||
if (error instanceof PermissionRequiredError) return "permission_required";
|
||||
if (error._tag === "ProcessCaptureError")
|
||||
return error.userCategory ?? "execution_failure";
|
||||
if (error instanceof BrowserObservationError) {
|
||||
if (error.reason === "payload_limit") return "truncated";
|
||||
if (
|
||||
error.reason === "target_not_found" ||
|
||||
error.reason === "target_not_allowed" ||
|
||||
error.reason === "target_changed" ||
|
||||
error.reason === "endpoint_unreachable" ||
|
||||
error.reason === "disconnected"
|
||||
)
|
||||
return "unavailable";
|
||||
}
|
||||
if (
|
||||
error instanceof HopperRemoteError &&
|
||||
error.diagnosticType === "authorization"
|
||||
@@ -799,6 +853,7 @@ const KNOWN_ERROR_TAGS = {
|
||||
AnalysisTimeoutError: true,
|
||||
ProviderSelectionError: true,
|
||||
ProviderAdapterError: true,
|
||||
BrowserObservationError: true,
|
||||
ArtifactOperationError: true,
|
||||
ProcessCaptureError: true,
|
||||
EvidenceIntegrityError: true,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { err, ok, type Result } from "./result.js";
|
||||
/** Local capabilities governed by the shared REA permission policy. */
|
||||
export type PermissionCapability =
|
||||
| "process_capture"
|
||||
| "browser_observe"
|
||||
| "evidence_read"
|
||||
| "evidence_write"
|
||||
| "investigation_input"
|
||||
@@ -25,6 +26,7 @@ export interface PermissionScope {
|
||||
readonly roots: readonly string[];
|
||||
readonly executables: readonly string[];
|
||||
readonly environment_names: readonly string[];
|
||||
readonly origins?: readonly string[] | undefined;
|
||||
readonly network: PermissionNetwork;
|
||||
readonly mount: boolean;
|
||||
}
|
||||
@@ -50,6 +52,7 @@ export interface MissingPermissionScope {
|
||||
readonly roots?: readonly string[];
|
||||
readonly executables?: readonly string[];
|
||||
readonly environment_names?: readonly string[];
|
||||
readonly origins?: readonly string[];
|
||||
readonly network?: PermissionNetwork;
|
||||
readonly mount?: true;
|
||||
}
|
||||
@@ -220,6 +223,9 @@ const normalizeScope = (scope: PermissionScope): PermissionScope => ({
|
||||
roots: uniqueSorted(scope.roots.map((path) => resolve(path))),
|
||||
executables: uniqueSorted(scope.executables.map((path) => resolve(path))),
|
||||
environment_names: uniqueSorted(scope.environment_names),
|
||||
...(scope.origins === undefined
|
||||
? {}
|
||||
: { origins: uniqueSorted(scope.origins) }),
|
||||
network: scope.network,
|
||||
mount: scope.mount,
|
||||
});
|
||||
@@ -253,6 +259,10 @@ const missingFromScopes = (
|
||||
const environmentNames = request.environment_names.filter(
|
||||
(name) => !relevant.some((scope) => scope.environment_names.includes(name)),
|
||||
);
|
||||
const origins = (request.origins ?? []).filter(
|
||||
(origin) =>
|
||||
!relevant.some((scope) => (scope.origins ?? []).includes(origin)),
|
||||
);
|
||||
const network =
|
||||
request.network === "none" ||
|
||||
relevant.some(
|
||||
@@ -270,6 +280,7 @@ const missingFromScopes = (
|
||||
...(environmentNames.length === 0
|
||||
? {}
|
||||
: { environment_names: environmentNames }),
|
||||
...(origins.length === 0 ? {} : { origins }),
|
||||
...(network === undefined ? {} : { network }),
|
||||
...(mount === undefined ? {} : { mount }),
|
||||
};
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/** Generated from package.json and package-lock.json; do not edit. */
|
||||
export const PACKAGE_METADATA = {
|
||||
name: "rea-agents",
|
||||
version: "1.3.0",
|
||||
version: "1.4.0",
|
||||
serverSdkVersion: "2.0.0-beta.4",
|
||||
clientSdkVersion: "2.0.0-beta.4",
|
||||
coreSdkVersion: "2.0.0-beta.4",
|
||||
skillVersion: "12",
|
||||
skillVersion: "13",
|
||||
} as const;
|
||||
|
||||
@@ -15,6 +15,7 @@ import { createLogger } from "./logger.js";
|
||||
import { projectAnalysisError } from "./domain/errors.js";
|
||||
import { readProjectPermissionStore } from "./application/ProjectPermissionStore.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import { CdpBrowserProvider } from "./browser/CdpBrowserProvider.js";
|
||||
|
||||
const MCP_CONNECTION_LOST =
|
||||
"REA lost its MCP client connection. Restart REA from your MCP client.";
|
||||
@@ -80,6 +81,7 @@ export const run = async (
|
||||
}
|
||||
|
||||
const session = createBinarySession(config.value, logger);
|
||||
const browserObservation = new CdpBrowserProvider();
|
||||
if (config.value.hopperTargetPath !== undefined) {
|
||||
const opened = await session.open(config.value.hopperTargetPath, {
|
||||
targetKind: config.value.hopperTargetKind,
|
||||
@@ -126,11 +128,16 @@ export const run = async (
|
||||
investigationInputRoots: runtimeInvestigationRoots,
|
||||
analysisSnapshotFilePolicy: runtimeSnapshotPolicy,
|
||||
permissionAuthority: permissionAuthority.value,
|
||||
browserObservation,
|
||||
artifactIntegrityContinueEnabled: () =>
|
||||
currentConfig.artifactIntegrityContinueEnabled,
|
||||
availabilityPolicy: () => ({
|
||||
processCaptureEnabled: currentConfig.processExecutionPolicy.enabled,
|
||||
evidenceFileRoots: currentConfig.evidenceFilePolicy.roots.length,
|
||||
browserObservationEnabled:
|
||||
currentConfig.browserObservationEnabled &&
|
||||
currentConfig.browserCdpEndpoints.length > 0 &&
|
||||
currentConfig.browserAllowedOrigins.length > 0,
|
||||
}),
|
||||
});
|
||||
liveServers.add(server);
|
||||
|
||||
@@ -15,6 +15,8 @@ import { registerGuidedPrompts } from "./registerPrompts.js";
|
||||
import { registerEvidenceResources } from "./registerEvidenceResources.js";
|
||||
import { createServerIdentity } from "../serverIdentity.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import type { BrowserObservationPort } from "../application/BrowserObservationPort.js";
|
||||
import { registerBrowserTools } from "./registerBrowserTools.js";
|
||||
|
||||
export interface CreateServerOptions {
|
||||
readonly logger?: Logger;
|
||||
@@ -23,10 +25,12 @@ export interface CreateServerOptions {
|
||||
readonly investigationInputRoots?: readonly string[];
|
||||
readonly analysisSnapshotFilePolicy?: EvidenceFilePolicy;
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
readonly browserObservation?: BrowserObservationPort;
|
||||
readonly artifactIntegrityContinueEnabled?: () => boolean;
|
||||
readonly availabilityPolicy?: () => {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly evidenceFileRoots: number;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -136,6 +140,12 @@ export const createServer = (
|
||||
? {}
|
||||
: { permissionAuthority: options.permissionAuthority }),
|
||||
});
|
||||
registerBrowserTools(server, {
|
||||
logger: toolLogger,
|
||||
browser: options.browserObservation,
|
||||
permissionAuthority: options.permissionAuthority,
|
||||
recordEvidence,
|
||||
});
|
||||
registerGuidedPrompts(server, analysis, session);
|
||||
if (session !== undefined) {
|
||||
registerEvidenceResources(server, session);
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { BrowserObservationPort } from "../application/BrowserObservationPort.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import {
|
||||
inspectWebPage,
|
||||
listBrowserTargets,
|
||||
} from "../application/BrowserObservationService.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "../contracts/browserToolContracts.js";
|
||||
import {
|
||||
inspectWebPageInputSchema,
|
||||
listBrowserTargetsInputSchema,
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
|
||||
interface BrowserToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly browser: BrowserObservationPort | undefined;
|
||||
readonly permissionAuthority: PermissionAuthority | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
}
|
||||
|
||||
/** Register browser tools even when policy/provider availability denies execution. */
|
||||
export const registerBrowserTools = (
|
||||
server: McpServer,
|
||||
options: BrowserToolRegistration,
|
||||
): void => {
|
||||
const [listContract, inspectContract] = BROWSER_TOOL_CONTRACTS;
|
||||
server.registerTool(
|
||||
listContract.name,
|
||||
toolRegistrationOptions(listContract),
|
||||
async (input, context) => {
|
||||
const parsed = listBrowserTargetsInputSchema.parse(input);
|
||||
const result = await logToolExecution(
|
||||
options.logger,
|
||||
listContract.name,
|
||||
() =>
|
||||
listBrowserTargets(
|
||||
options.browser,
|
||||
options.permissionAuthority,
|
||||
parsed,
|
||||
{ signal: context.mcpReq.signal },
|
||||
),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, listContract);
|
||||
return evidenceResult(options, listContract, result.value);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
inspectContract.name,
|
||||
toolRegistrationOptions(inspectContract),
|
||||
async (input, context) => {
|
||||
const parsed = inspectWebPageInputSchema.parse(input);
|
||||
const result = await logToolExecution(
|
||||
options.logger,
|
||||
inspectContract.name,
|
||||
() =>
|
||||
inspectWebPage(options.browser, options.permissionAuthority, parsed, {
|
||||
signal: context.mcpReq.signal,
|
||||
progress: mcpProgressReporter(context),
|
||||
}),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, inspectContract);
|
||||
return evidenceResult(options, inspectContract, result.value);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const evidenceResult = (
|
||||
options: BrowserToolRegistration,
|
||||
contract: (typeof BROWSER_TOOL_CONTRACTS)[number],
|
||||
evidence: import("../domain/evidence.js").Evidence,
|
||||
) => {
|
||||
const recorded = options.recordEvidence?.(evidence);
|
||||
return recorded !== undefined && !recorded.ok
|
||||
? toCallToolResult(recorded, contract)
|
||||
: toCallToolResult({ ok: true, value: evidence }, contract, {
|
||||
evidenceResourcesAvailable: recorded !== undefined,
|
||||
});
|
||||
};
|
||||
@@ -19,6 +19,7 @@ export const registerSessionStatusTool = (
|
||||
availabilityPolicy: () => {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly evidenceFileRoots: number;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
},
|
||||
): void => {
|
||||
server.registerTool(
|
||||
|
||||
@@ -432,6 +432,7 @@ interface LifecycleToolRegistration {
|
||||
readonly availabilityPolicy: () => {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly evidenceFileRoots: number;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
};
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
}
|
||||
@@ -592,6 +593,7 @@ export interface SessionToolOptions {
|
||||
readonly availabilityPolicy?: () => {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly evidenceFileRoots: number;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -638,6 +640,7 @@ export const registerSessionTools = (
|
||||
(() => ({
|
||||
processCaptureEnabled: processPolicy.enabled,
|
||||
evidenceFileRoots: evidenceFilePolicy.roots.length,
|
||||
browserObservationEnabled: false,
|
||||
})),
|
||||
...(options.permissionAuthority === undefined
|
||||
? {}
|
||||
|
||||
Reference in New Issue
Block a user