mirror of
https://github.com/morluto/rea.git
synced 2026-11-18 20:53:00 +00:00
* refactor(native): bind producer_limits and max_input_bytes as the per-call controls of pwntools and Apple dispatch refusals producerLimitControl in src/domain/producerResourceLimits.ts names one producer budget as producer_limits.<field>; the shared provider outcome classifier now carries a resource signal's limit. Pwntools file-size, CPU and output refusals and the Apple dispatch input refusal bind their control, and their remediation no longer names CLI flags. * fix(native): report the selected output allowance as the omitted file_bytes default * fix(native): bind producer_limits.diagnostic_bytes as the pwntools command output-limit control * refactor(rust): bind producer_limits as the per-call control of Rust input and report refusals (#11458) * refactor(rust): bind producer_limits as the per-call control of Rust input and report refusals * test(rust): cover the complete-report refusal's producer_limits control * refactor(browser): bind caller-selectable browser deadlines as per-call controls instead of naming CLI flags (#11466) * refactor(rust): bind producer_limits as the per-call control of Rust input and report refusals * test(rust): cover the complete-report refusal's producer_limits control * refactor(browser): bind caller-selectable browser deadlines as per-call controls instead of naming CLI flags deadlineParameterLimit in src/domain/analysisResourceLimits.ts owns the millisecond deadline control that nativeDeadlineRecovery and the browser recoveries share. CDP command and discovery, web bundle per-script and total, network capture and source-map decode deadlines now carry it; browserDeadlineIncrease no longer takes CLI flag text. * fix(browser): record a per-script deadline's parameter control in partial web bundle results * refactor(providers): bind Wabt, SQLite, EVMole, Apktool and Go controls instead of naming CLI commands (#11472) * refactor(providers): bind Wabt, SQLite, EVMole and Apktool deadline and byte controls instead of naming CLI commands These remediation strings named rea commands and flags through template text the cli-option guard did not count. Wabt byte refusals and output limits bind max_input_bytes, max_tool_bytes or max_output_bytes while a larger value is selectable; SQLite worker_timeout_ms, EVMole timeout_ms and Apktool decode_timeout_ms bind through deadlineParameterLimit; the shared provider outcome classifier now carries an output limit's control. * refactor(go): bind Go analysis budgets as per-call controls instead of naming CLI flags * fix(providers): keep the typed primary when Wabt, EVMole or pwntools command cleanup fails * ci(guards): count template-built CLI option and command text outside the CLI layer (#11478) * refactor(providers): bind Wabt, SQLite, EVMole and Apktool deadline and byte controls instead of naming CLI commands These remediation strings named rea commands and flags through template text the cli-option guard did not count. Wabt byte refusals and output limits bind max_input_bytes, max_tool_bytes or max_output_bytes while a larger value is selectable; SQLite worker_timeout_ms, EVMole timeout_ms and Apktool decode_timeout_ms bind through deadlineParameterLimit; the shared provider outcome classifier now carries an output limit's control. * refactor(go): bind Go analysis budgets as per-call controls instead of naming CLI flags * fix(providers): keep the typed primary when Wabt, EVMole or pwntools command cleanup fails * ci(guards): count template-built CLI option and command text outside the CLI layer The cli-option-text-outside-cli pattern now also matches "(CLI ...", "on the CLI", "or use rea ..." and backticked `rea <command>` references, so remediation built from a template such as --${name} or rea inspect-... <path> is counted. Doctor.ts is exempt: setup and doctor run only through the CLI. The baseline records the newly counted pre-existing sites (22 -> 45 across 21 files). * ci(guards): extract the CLI text matcher, exempt host-only commands with written reasons, and test each spelling * ci(guards): exempt a host-only command and its own arguments in any matched CLI phrase * fix(native): bind producer_limits.output_bytes for oversized pwndbg debugger replies through one owner * fix(cli): name an Evidence target source failure's control by the source option that sets it * feat(cli): render the flags of result-recorded controls in the full-output envelope (#11507) * feat(cli): render the flags of result-recorded controls in the full-output envelope * fix(cli): collect result controls only for a full-output envelope, in its requested format, past undefined values * ci(guards): end a host-only command's arguments before the next CLI command * refactor(reverse): record the output budget that stopped a one-shot command as a parameter control (#11528) * fix(cli): read result controls only at positions the output schema declares as recorded controls * refactor(providers): record the controls that bounded Rust compiler paths and kernel module text instead of naming CLI options (#11532) * refactor(rust): record the control that bounded compiler-path coverage instead of naming CLI options * refactor(native): record the controls that omitted kernel module .modinfo text instead of naming CLI options (#11534) * fix(rust): describe compiler coverage from the retained result after report trimming * refactor(providers): record managed representation and JavaScript semantic ceiling controls instead of naming CLI options (#11537) * refactor(managed): record the representation budget on a resource-limit issue instead of naming its CLI option * refactor(javascript): record the semantic retention ceilings that stopped a graph instead of naming CLI options (#11540) * fix(cli): name a composed command's source options for the controls its result records * fix(cli): read result controls from the delivered Evidence when a summary wraps it * fix(rust): keep the report-byte control recorded when trimming omits every compiler path When the complete-report allowance left room for no compiler path, rustc_commit became null and its coverage.limit was lost, so --full-output could not name the option that raises the allowance. The report now records rustc_commit_omission { reason, limit } outside the dropped record, and the summary view carries it. * refactor(flutter): record the string-pool budgets that left a projection partial instead of naming the CLI option (#11541) * refactor(flutter): record the string-pool budgets that left a projection partial instead of naming the CLI option * test(flutter): assert the complete set of recorded string-pool budgets * feat(cli): name the options of controls a failure's partial Evidence records (#11557) meta.cli_controls was collected only from a successful result. A failure whose partial observation is Evidence of the command's own operation is now read the same way, at the positions the output schema declares as recorded controls; Evidence of another operation or a retained reference is not read. When --evidence_output publishes the partial, the delivery records it before replacing it. * refactor(javascript): record the evaluator budgets that limited sources instead of naming the CLI option (#11564) Per-value unknown reasons and the Electron wrapper limitation named --semantic-precision. The static examination now records the semantic_precision controls that limited a source (examination.controls), and analyze_javascript_application's semantic_graph.coverage.controls records every evaluator budget that limited any source (examination and semantic IR coverage), beside the retention ceilings. The CLI renders --semantic-precision from those records in meta.cli_controls; the reason texts name only the contract field.
597 lines
18 KiB
TypeScript
597 lines
18 KiB
TypeScript
import { request, type ClientRequest, type IncomingMessage } from "node:http";
|
|
import { isUtf8 } from "node:buffer";
|
|
|
|
import { z } from "zod";
|
|
|
|
import {
|
|
CDP_DISCOVERY_RESPONSE_TIMEOUT_MS,
|
|
cdpCommandTimeoutUnrelatedControl,
|
|
cdpDiscoveryTimeoutRecovery,
|
|
noRuntimeOverrideSentence,
|
|
} from "../domain/browserDeadline.js";
|
|
import {
|
|
AnalysisCancelledError,
|
|
cancelledBy,
|
|
carriedReason,
|
|
} from "../domain/analysisErrorCore.js";
|
|
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
|
import { BrowserObservationError } from "../domain/browserObservationError.js";
|
|
import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js";
|
|
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
|
import { urlDeclaresQueryOrFragment } from "../domain/urlComponents.js";
|
|
import { safeParseJson } from "../domain/safeJson.js";
|
|
import { WEB_RUNTIME_LIMITS } from "../domain/webRuntime.js";
|
|
import type { CdpConnection } from "./CdpConnection.js";
|
|
import { CdpMalformedReply } from "./protocol/CdpCommands.js";
|
|
import {
|
|
parseCdpDiscoveryTargets,
|
|
type CdpDiscoveryTarget,
|
|
} from "./CdpDiscoveryTargets.js";
|
|
|
|
const endpointVersionSchema = z.object({
|
|
Browser: z.string().min(1),
|
|
"Protocol-Version": z.string().min(1),
|
|
"User-Agent": z.string(),
|
|
"V8-Version": z.string(),
|
|
"WebKit-Version": z.string(),
|
|
webSocketDebuggerUrl: z.string().min(1),
|
|
});
|
|
|
|
/** Default per-response bounds for loopback CDP discovery documents. The byte budget has no runtime override. */
|
|
const CDP_DISCOVERY_RESPONSE_LIMITS = {
|
|
bytes: 8 * 1024 * 1024,
|
|
timeoutMs: CDP_DISCOVERY_RESPONSE_TIMEOUT_MS,
|
|
} as const;
|
|
|
|
const discoveryBudget = (phase: "response" | "browser-socket"): string =>
|
|
phase === "response"
|
|
? `The ${String(CDP_DISCOVERY_RESPONSE_LIMITS.bytes)}-byte discovery document budget`
|
|
: `The ${String(WEB_RUNTIME_LIMITS.protocolBytes)}-byte browser-socket message budget`;
|
|
|
|
const discoveryTimeout = (
|
|
operation: BrowserObservationOperation,
|
|
timeoutMs: number,
|
|
phase: "response" | "browser-socket",
|
|
): BrowserObservationError => {
|
|
const recovery = cdpDiscoveryTimeoutRecovery(
|
|
operation,
|
|
timeoutMs,
|
|
phase,
|
|
discoveryBudget(phase),
|
|
);
|
|
return new BrowserObservationError(operation, "timeout", {
|
|
detail: recovery.userMessage,
|
|
remediationAction: recovery.remediationAction,
|
|
limit: recovery.limit,
|
|
});
|
|
};
|
|
|
|
interface CdpDiscoveryResponseLimits {
|
|
readonly bytes: number;
|
|
readonly timeoutMs: number;
|
|
}
|
|
|
|
/** Validated direct CDP WebSocket bound to one discovered page target. */
|
|
interface CdpPageWebSocketEndpoint {
|
|
readonly scope: "page";
|
|
readonly targetId: string;
|
|
readonly url: string;
|
|
}
|
|
|
|
/** Validated CDP discovery socket and its command-routing scope. */
|
|
export type CdpWebSocketEndpoint =
|
|
| { readonly scope: "browser"; readonly url: string }
|
|
| CdpPageWebSocketEndpoint;
|
|
|
|
/** Bounded discovery target with an optional validated direct transport. */
|
|
export interface CdpEndpointTarget {
|
|
readonly id: string;
|
|
readonly type: string;
|
|
readonly title: string;
|
|
readonly url: string;
|
|
readonly attached: boolean | null;
|
|
readonly webSocket?: CdpPageWebSocketEndpoint;
|
|
}
|
|
|
|
export interface CdpEndpointDiscovery {
|
|
readonly limitations?: readonly string[];
|
|
readonly ambiguousTargetIds?: readonly string[];
|
|
readonly webSocket: CdpWebSocketEndpoint;
|
|
readonly version: {
|
|
readonly product: string;
|
|
readonly protocol_version: string;
|
|
readonly revision: string;
|
|
readonly user_agent: string;
|
|
readonly js_version: string;
|
|
};
|
|
readonly targets: readonly CdpEndpointTarget[];
|
|
}
|
|
|
|
/** Read CDP discovery endpoints without following redirects. */
|
|
export const discoverCdpEndpoint = async (
|
|
endpoint: string,
|
|
operation: BrowserObservationOperation,
|
|
signal?: AbortSignal,
|
|
timeoutMs: number = CDP_DISCOVERY_RESPONSE_LIMITS.timeoutMs,
|
|
): Promise<CdpEndpointDiscovery> => {
|
|
const limits: CdpDiscoveryResponseLimits = {
|
|
bytes: CDP_DISCOVERY_RESPONSE_LIMITS.bytes,
|
|
timeoutMs,
|
|
};
|
|
const versionInput = await readCdpJson(
|
|
new URL("/json/version", endpoint),
|
|
operation,
|
|
signal,
|
|
limits,
|
|
);
|
|
const targetsInput = await readCdpJson(
|
|
new URL("/json/list", endpoint),
|
|
operation,
|
|
signal,
|
|
limits,
|
|
);
|
|
const version = parseCdpEndpointValue(
|
|
endpointVersionSchema,
|
|
versionInput,
|
|
operation,
|
|
);
|
|
const { targets, limitations, ambiguousTargetIds } = parseCdpDiscoveryTargets(
|
|
targetsInput,
|
|
operation,
|
|
);
|
|
return {
|
|
limitations,
|
|
ambiguousTargetIds,
|
|
webSocket: safeCdpWebSocketEndpoint(
|
|
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: targets.map((target) => ({
|
|
id: target.id,
|
|
type: target.type,
|
|
title: sanitizeTargetTitle(target.title, target.url),
|
|
url: target.url,
|
|
attached: target.attached,
|
|
...targetWebSocket(endpoint, target, operation),
|
|
})),
|
|
};
|
|
};
|
|
|
|
/**
|
|
* Run browser-socket discovery work, including its WebSocket handshake, under
|
|
* the HTTP discovery deadline. Reaching the deadline is a timeout, not a
|
|
* caller cancellation, so the internal abort is not carried as its cause.
|
|
*/
|
|
export const withCdpDiscoveryDeadline = async <T>(
|
|
operation: BrowserObservationOperation,
|
|
signal: AbortSignal | undefined,
|
|
work: (deadlineSignal: AbortSignal) => Promise<T>,
|
|
timeoutMs: number = CDP_DISCOVERY_RESPONSE_LIMITS.timeoutMs,
|
|
): Promise<T> => {
|
|
const deadline = new AbortController();
|
|
let abortSource: "caller" | "deadline" | undefined;
|
|
let abortReason: unknown;
|
|
const abort = (source: "caller" | "deadline", reason: unknown): void => {
|
|
if (abortSource !== undefined) return;
|
|
abortSource = source;
|
|
abortReason = reason;
|
|
deadline.abort(reason);
|
|
};
|
|
const onCallerAbort = (): void => {
|
|
if (signal?.aborted === true) abort("caller", signal.reason);
|
|
};
|
|
const timer = setTimeout(
|
|
() => abort("deadline", new Error("CDP discovery deadline exceeded")),
|
|
timeoutMs,
|
|
);
|
|
signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
onCallerAbort();
|
|
try {
|
|
return await work(deadline.signal);
|
|
} catch (cause: unknown) {
|
|
if (cause === abortReason) {
|
|
if (abortSource === "caller")
|
|
throw cancelledBy(operation, carriedReason(abortReason));
|
|
if (abortSource === "deadline")
|
|
throw discoveryTimeout(operation, timeoutMs, "browser-socket");
|
|
}
|
|
// A concrete failure produced before cancellation remains authoritative.
|
|
if (cause instanceof AnalysisError) {
|
|
if (
|
|
abortSource === "deadline" &&
|
|
cause instanceof AnalysisCancelledError &&
|
|
cause.cause === abortReason
|
|
)
|
|
throw discoveryTimeout(operation, timeoutMs, "browser-socket");
|
|
throw cause;
|
|
}
|
|
throw cause;
|
|
} finally {
|
|
clearTimeout(timer);
|
|
signal?.removeEventListener("abort", onCallerAbort);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Read discovery facts over a browser socket that has no HTTP discovery.
|
|
* Each reply is bounded by the connection's protocol message limit; callers
|
|
* apply the discovery deadline through `signal`.
|
|
*/
|
|
export const discoverCdpBrowserSocket = async (
|
|
connection: Pick<CdpConnection, "send">,
|
|
url: string,
|
|
operation: BrowserObservationOperation,
|
|
signal?: AbortSignal,
|
|
): Promise<CdpEndpointDiscovery> => {
|
|
const version = await discoveryReply(
|
|
connection.send("Browser.getVersion", {}, undefined, signal),
|
|
operation,
|
|
);
|
|
const { targetInfos } = await discoveryReply(
|
|
connection.send("Target.getTargets", {}, undefined, signal),
|
|
operation,
|
|
);
|
|
const { targets, limitations, ambiguousTargetIds } = parseCdpDiscoveryTargets(
|
|
targetInfos,
|
|
operation,
|
|
"browser-socket",
|
|
);
|
|
return {
|
|
limitations,
|
|
ambiguousTargetIds,
|
|
webSocket: { scope: "browser", url },
|
|
version: {
|
|
product: version.product,
|
|
protocol_version: version.protocolVersion,
|
|
revision: version.revision,
|
|
user_agent: version.userAgent,
|
|
js_version: version.jsVersion,
|
|
},
|
|
targets: targets.map((target) => ({
|
|
id: target.id,
|
|
type: target.type,
|
|
title: sanitizeTargetTitle(target.title, target.url),
|
|
url: target.url,
|
|
attached: target.attached,
|
|
})),
|
|
};
|
|
};
|
|
|
|
/**
|
|
* Discovery answers the same question over HTTP and over a browser socket, so
|
|
* a malformed discovery reply is an invalid endpoint response on both paths.
|
|
*/
|
|
const discoveryReply = async <Reply>(
|
|
reply: Promise<Reply>,
|
|
operation: BrowserObservationOperation,
|
|
): Promise<Reply> => {
|
|
try {
|
|
return await reply;
|
|
} catch (cause: unknown) {
|
|
if (!(cause instanceof CdpMalformedReply)) throw cause;
|
|
throw new BrowserObservationError(operation, "invalid_endpoint_response", {
|
|
cause,
|
|
...(cause.detail === undefined ? {} : { detail: cause.detail }),
|
|
});
|
|
}
|
|
};
|
|
|
|
const sanitizeTargetTitle = (value: string, targetUrl: string): string => {
|
|
let url: URL;
|
|
try {
|
|
url = new URL(value);
|
|
} catch (cause: unknown) {
|
|
// Non-URL titles fall back to alias redaction.
|
|
void cause;
|
|
return sanitizeTargetUrlAlias(value, targetUrl);
|
|
}
|
|
return url.protocol === "http:" || url.protocol === "https:"
|
|
? sanitizeBrowserUrl(value).url
|
|
: sanitizeTargetUrlAlias(value, targetUrl);
|
|
};
|
|
|
|
const sanitizeTargetUrlAlias = (value: string, targetUrl: string): string => {
|
|
let parsed: URL;
|
|
try {
|
|
parsed = new URL(targetUrl);
|
|
} catch (cause: unknown) {
|
|
// Without a parseable target URL there is nothing to redact.
|
|
void cause;
|
|
return value;
|
|
}
|
|
const markers = [parsed.origin, `//${parsed.host}`, parsed.host];
|
|
if (parsed.pathname !== "/") markers.push(parsed.pathname);
|
|
const candidatePattern = new RegExp(
|
|
`(?:${markers.map(escapeRegExp).join("|")})[^\\s<>"']*`,
|
|
"gu",
|
|
);
|
|
return value.replace(candidatePattern, (candidate) =>
|
|
sanitizeSameOriginTitleUrl(candidate, parsed),
|
|
);
|
|
};
|
|
|
|
const sanitizeSameOriginTitleUrl = (candidate: string, target: URL): string => {
|
|
let parsed: URL;
|
|
try {
|
|
parsed = candidate.startsWith("//")
|
|
? new URL(`${target.protocol}${candidate}`)
|
|
: candidate.startsWith(target.host)
|
|
? new URL(`${target.protocol}//${candidate}`)
|
|
: new URL(candidate, target.origin);
|
|
} catch (cause: unknown) {
|
|
// Unparseable candidates are preserved verbatim.
|
|
void cause;
|
|
return candidate;
|
|
}
|
|
return parsed.origin === target.origin &&
|
|
(parsed.username !== "" || parsed.password !== "")
|
|
? sanitizeBrowserUrl(candidate).url
|
|
: candidate;
|
|
};
|
|
|
|
const escapeRegExp = (value: string): string =>
|
|
value.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
|
|
/** Select a browser attachment socket or a direct socket for one page target. */
|
|
export const cdpTargetWebSocket = (
|
|
discovery: CdpEndpointDiscovery,
|
|
target: CdpEndpointTarget,
|
|
operation: BrowserObservationOperation,
|
|
): CdpWebSocketEndpoint => {
|
|
const webSocket = availableCdpTargetWebSocket(discovery, target);
|
|
if (webSocket !== undefined) return webSocket;
|
|
throw new BrowserObservationError(operation, "invalid_endpoint_response");
|
|
};
|
|
|
|
/** Report whether discovery contains a validated transport for one target. */
|
|
export const hasCdpTargetWebSocket = (
|
|
discovery: CdpEndpointDiscovery,
|
|
target: CdpEndpointTarget,
|
|
): boolean => availableCdpTargetWebSocket(discovery, target) !== undefined;
|
|
|
|
const availableCdpTargetWebSocket = (
|
|
discovery: CdpEndpointDiscovery,
|
|
target: CdpEndpointTarget,
|
|
): CdpWebSocketEndpoint | undefined => {
|
|
if (discovery.webSocket.scope === "browser") return discovery.webSocket;
|
|
if (target.webSocket !== undefined) return target.webSocket;
|
|
return discovery.webSocket.targetId === target.id
|
|
? discovery.webSocket
|
|
: undefined;
|
|
};
|
|
|
|
/** Parse one CDP discovery value through its exact boundary schema. */
|
|
export const parseCdpEndpointValue = <Output>(
|
|
schema: z.ZodType<Output>,
|
|
input: unknown,
|
|
operation: BrowserObservationOperation,
|
|
): Output => {
|
|
const parsed = schema.safeParse(input);
|
|
if (!parsed.success)
|
|
throw new BrowserObservationError(operation, "invalid_endpoint_response", {
|
|
cause: parsed.error,
|
|
});
|
|
return parsed.data;
|
|
};
|
|
|
|
const safeCdpWebSocketEndpoint = (
|
|
endpoint: string,
|
|
reported: string,
|
|
operation: BrowserObservationOperation,
|
|
): CdpWebSocketEndpoint => {
|
|
let parsed: URL;
|
|
try {
|
|
parsed = new URL(reported);
|
|
} catch (cause: unknown) {
|
|
throw new BrowserObservationError(operation, "invalid_endpoint_response", {
|
|
cause,
|
|
});
|
|
}
|
|
const trustedEndpoint = new URL(endpoint);
|
|
const path = cdpWebSocketPath(parsed.pathname);
|
|
if (
|
|
parsed.protocol !== "ws:" ||
|
|
parsed.port !== trustedEndpoint.port ||
|
|
parsed.username !== "" ||
|
|
parsed.password !== "" ||
|
|
urlDeclaresQueryOrFragment(parsed) ||
|
|
path === undefined
|
|
)
|
|
throw new BrowserObservationError(operation, "invalid_endpoint_response");
|
|
parsed.hostname = trustedEndpoint.hostname;
|
|
return path.scope === "browser"
|
|
? { scope: "browser", url: parsed.href }
|
|
: { scope: "page", targetId: path.targetId, url: parsed.href };
|
|
};
|
|
|
|
const cdpWebSocketPath = (
|
|
pathname: string,
|
|
):
|
|
| { readonly scope: "browser" }
|
|
| { readonly scope: "page"; targetId: string }
|
|
| undefined => {
|
|
const browserId = pathIdentifier(pathname, "/devtools/browser/");
|
|
if (browserId !== undefined) return { scope: "browser" };
|
|
const targetId = pathIdentifier(pathname, "/devtools/page/");
|
|
return targetId === undefined ? undefined : { scope: "page", targetId };
|
|
};
|
|
|
|
const pathIdentifier = (
|
|
pathname: string,
|
|
prefix: string,
|
|
): string | undefined => {
|
|
if (!pathname.startsWith(prefix)) return undefined;
|
|
const identifier = pathname.slice(prefix.length);
|
|
return identifier.length > 0 && !identifier.includes("/")
|
|
? identifier
|
|
: undefined;
|
|
};
|
|
|
|
const targetWebSocket = (
|
|
endpoint: string,
|
|
target: CdpDiscoveryTarget,
|
|
operation: BrowserObservationOperation,
|
|
): { readonly webSocket?: CdpPageWebSocketEndpoint } => {
|
|
if (
|
|
typeof target.webSocketDebuggerUrl !== "string" ||
|
|
target.webSocketDebuggerUrl.length === 0
|
|
)
|
|
return {};
|
|
try {
|
|
const webSocket = safeCdpWebSocketEndpoint(
|
|
endpoint,
|
|
target.webSocketDebuggerUrl,
|
|
operation,
|
|
);
|
|
return webSocket.scope === "page" && webSocket.targetId === target.id
|
|
? { webSocket }
|
|
: {};
|
|
} catch (cause: unknown) {
|
|
// Endpoint validation failures mean no validated transport exists.
|
|
void cause;
|
|
return {};
|
|
}
|
|
};
|
|
|
|
/** Read one loopback CDP discovery document without redirects. */
|
|
export const readCdpJson = async (
|
|
url: URL,
|
|
operation: BrowserObservationOperation,
|
|
signal?: AbortSignal,
|
|
limits: CdpDiscoveryResponseLimits = CDP_DISCOVERY_RESPONSE_LIMITS,
|
|
): Promise<unknown> =>
|
|
await new Promise((resolve, reject) => {
|
|
if (signal?.aborted === true) {
|
|
reject(cancelledBy(operation, signal));
|
|
return;
|
|
}
|
|
let response: IncomingMessage | undefined;
|
|
let request_: ClientRequest | undefined;
|
|
let timer: NodeJS.Timeout | undefined;
|
|
let settled = false;
|
|
const removeAbort = (): void =>
|
|
signal?.removeEventListener("abort", onAbort);
|
|
const finish = (error?: Error, value?: unknown): void => {
|
|
if (settled) return;
|
|
settled = true;
|
|
if (timer !== undefined) clearTimeout(timer);
|
|
removeAbort();
|
|
if (error !== undefined) {
|
|
reject(error);
|
|
response?.destroy();
|
|
request_?.destroy();
|
|
} else resolve(value);
|
|
};
|
|
const onAbort = (): void => {
|
|
if (signal?.aborted === true) finish(cancelledBy(operation, signal));
|
|
};
|
|
request_ = request(
|
|
url,
|
|
{ method: "GET", headers: { Accept: "application/json" } },
|
|
(received) => {
|
|
response = received;
|
|
if (settled) {
|
|
received.destroy();
|
|
return;
|
|
}
|
|
if (received.statusCode !== 200) {
|
|
finish(
|
|
new BrowserObservationError(operation, "invalid_endpoint_response"),
|
|
);
|
|
return;
|
|
}
|
|
const chunks: Buffer[] = [];
|
|
let bytes = 0;
|
|
received.on("data", (chunk: Buffer) => {
|
|
if (settled) return;
|
|
bytes += chunk.byteLength;
|
|
if (bytes > limits.bytes) {
|
|
finish(
|
|
new BrowserObservationError(operation, "payload_limit", {
|
|
detail: noRuntimeOverrideSentence(
|
|
`CDP discovery response exceeds its ${String(limits.bytes)}-byte limit.`,
|
|
cdpCommandTimeoutUnrelatedControl(operation),
|
|
),
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
chunks.push(chunk);
|
|
});
|
|
received.on("end", () => {
|
|
if (settled) return;
|
|
const body = Buffer.concat(chunks, bytes);
|
|
if (!isUtf8(body)) {
|
|
finish(
|
|
new BrowserObservationError(
|
|
operation,
|
|
"invalid_endpoint_response",
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
const parsed = safeParseJson(body.toString("utf8"));
|
|
if (!parsed.ok) {
|
|
finish(
|
|
new BrowserObservationError(
|
|
operation,
|
|
"invalid_endpoint_response",
|
|
{ cause: parsed.cause },
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
finish(undefined, parsed.value);
|
|
});
|
|
received.on("aborted", () =>
|
|
finish(
|
|
new BrowserObservationError(operation, "invalid_endpoint_response"),
|
|
),
|
|
);
|
|
received.on("close", () => {
|
|
if (!settled && !received.complete)
|
|
finish(
|
|
new BrowserObservationError(
|
|
operation,
|
|
"invalid_endpoint_response",
|
|
),
|
|
);
|
|
});
|
|
received.on("error", (cause: unknown) =>
|
|
finish(endpointFailure(cause, operation, signal)),
|
|
);
|
|
},
|
|
);
|
|
request_.on("error", (cause: unknown) =>
|
|
finish(endpointFailure(cause, operation, signal)),
|
|
);
|
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
onAbort();
|
|
if (settled) return;
|
|
timer = setTimeout(
|
|
() => finish(discoveryTimeout(operation, limits.timeoutMs, "response")),
|
|
limits.timeoutMs,
|
|
);
|
|
request_.end();
|
|
});
|
|
|
|
const endpointFailure = (
|
|
cause: unknown,
|
|
operation: BrowserObservationOperation,
|
|
signal?: AbortSignal,
|
|
): AnalysisError => {
|
|
if (cause instanceof AnalysisError) return cause;
|
|
if (signal?.aborted === true) return cancelledBy(operation, signal);
|
|
return new BrowserObservationError(operation, "endpoint_unreachable", {
|
|
cause,
|
|
});
|
|
};
|