refactor(adapters): split oversized provider workflows
This commit is contained in:
@@ -5,7 +5,6 @@ import type {
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
@@ -13,6 +12,7 @@ import {
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { exclusionReasonForUrl } from "./CdpCaptureEventHelpers.js";
|
||||
import type { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
|
||||
export type CapturedResource = Omit<
|
||||
@@ -183,14 +183,14 @@ export const captureDom = (
|
||||
.map((value) => indexedString(strings, value).slice(0, 256))
|
||||
.slice(0, 200),
|
||||
});
|
||||
const metadata = domMetadata(
|
||||
const metadata = domMetadata({
|
||||
strings,
|
||||
attributeIndexes,
|
||||
attributes: attributeIndexes,
|
||||
documentUrl,
|
||||
nodeIndex,
|
||||
nodeName,
|
||||
allowedOrigins,
|
||||
);
|
||||
});
|
||||
for (const url of metadata.urls) {
|
||||
if (urls.length >= input.limits.max_resources) {
|
||||
completeness?.truncate("metadata");
|
||||
@@ -312,17 +312,29 @@ const numberArray = (value: unknown): readonly number[] =>
|
||||
})
|
||||
: [];
|
||||
|
||||
interface DomMetadataOptions {
|
||||
readonly strings: readonly string[];
|
||||
readonly attributes: readonly number[];
|
||||
readonly documentUrl: string;
|
||||
readonly nodeIndex: number;
|
||||
readonly nodeName: string;
|
||||
readonly allowedOrigins: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
const domMetadata = (
|
||||
strings: readonly string[],
|
||||
attributes: readonly number[],
|
||||
documentUrl: string,
|
||||
nodeIndex: number,
|
||||
nodeName: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
options: DomMetadataOptions,
|
||||
): {
|
||||
readonly urls: WebPageInspection["metadata"]["dom_urls"];
|
||||
readonly agentHints: WebPageInspection["metadata"]["agent_hints"];
|
||||
} => {
|
||||
const {
|
||||
strings,
|
||||
attributes,
|
||||
documentUrl,
|
||||
nodeIndex,
|
||||
nodeName,
|
||||
allowedOrigins,
|
||||
} = options;
|
||||
const pairs = new Map<string, string>();
|
||||
for (let index = 0; index + 1 < attributes.length; index += 2) {
|
||||
const name = indexedString(strings, attributes[index]).toLowerCase();
|
||||
@@ -403,15 +415,6 @@ const boundedUtf8 = (
|
||||
return { text, bytes, truncated: true };
|
||||
};
|
||||
|
||||
const exclusionReasonForUrl = (
|
||||
value: string | undefined,
|
||||
): "disallowed_origin" | "unsupported_url" | "unattributed_origin" =>
|
||||
value === undefined || value === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(value)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url";
|
||||
|
||||
const domUrlAttributes = [
|
||||
"href",
|
||||
"src",
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { inferJsonShape, type JsonShape } from "../domain/jsonShape.js";
|
||||
import {
|
||||
recordValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { decodeBase64, isJsonContentType } from "./CdpCaptureEventHelpers.js";
|
||||
import type { CdpCaptureEventsState } from "./CdpCaptureEventState.js";
|
||||
import type { NetworkState } from "./CdpCaptureEventTypes.js";
|
||||
|
||||
export const ingestResponseBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
requestId: string,
|
||||
value: unknown,
|
||||
): void => {
|
||||
const result = recordValue(value);
|
||||
const body = stringValue(result?.body);
|
||||
if (body === undefined) {
|
||||
invalidResponseBodyShape(state, requestId);
|
||||
return;
|
||||
}
|
||||
const decoded =
|
||||
result?.base64Encoded === true
|
||||
? decodeBase64(body)?.toString("utf8")
|
||||
: body;
|
||||
if (decoded === undefined) {
|
||||
invalidResponseBodyShape(state, requestId);
|
||||
return;
|
||||
}
|
||||
const inferred = inferBodyShape(state, decoded);
|
||||
updateResponseBodyShape(state, requestId, inferred.shape, inferred.truncated);
|
||||
};
|
||||
|
||||
export const requestBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
request: UnknownRecord,
|
||||
): NetworkState["body_shapes"] => {
|
||||
if (!state.input.include_json_body_shapes)
|
||||
return { status: "not_approved", request: null, response: null };
|
||||
const body = stringValue(request.postData);
|
||||
if (!isJsonContentType(recordValue(request.headers)) || body === undefined)
|
||||
return { status: "unavailable", request: null, response: null };
|
||||
const inferred = inferBodyShape(state, body);
|
||||
return {
|
||||
status: inferred.truncated
|
||||
? "truncated"
|
||||
: inferred.shape === null
|
||||
? "unavailable"
|
||||
: "included",
|
||||
request: inferred.shape,
|
||||
response: null,
|
||||
};
|
||||
};
|
||||
|
||||
export const updateResponseBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
requestId: string,
|
||||
response: JsonShape | null,
|
||||
truncated: boolean,
|
||||
): void => {
|
||||
const current = state.network.get(requestId);
|
||||
if (current === undefined) return;
|
||||
const request = current.body_shapes.request;
|
||||
const status =
|
||||
truncated || current.body_shapes.status === "truncated"
|
||||
? "truncated"
|
||||
: response !== null
|
||||
? "included"
|
||||
: request !== null
|
||||
? "partial"
|
||||
: "unavailable";
|
||||
state.network.set(requestId, {
|
||||
...current,
|
||||
body_shapes: { status, request, response },
|
||||
});
|
||||
};
|
||||
|
||||
const inferBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
text: string,
|
||||
): { readonly shape: JsonShape | null; readonly truncated: boolean } => {
|
||||
const bytes = Buffer.byteLength(text);
|
||||
const remaining =
|
||||
state.input.limits.max_total_json_body_bytes - state.jsonBodyBytes;
|
||||
if (bytes > state.input.limits.max_json_body_bytes || bytes > remaining) {
|
||||
state.completeness.truncate("json_body_shapes");
|
||||
return { shape: null, truncated: true };
|
||||
}
|
||||
state.jsonBodyBytes += bytes;
|
||||
const shape = inferJsonShape(text, {
|
||||
maximumBytes: state.input.limits.max_json_body_bytes,
|
||||
maximumNodes: state.input.limits.max_json_shape_nodes,
|
||||
maximumDepth: state.input.limits.max_json_shape_depth,
|
||||
});
|
||||
if (shape?.truncated === true)
|
||||
state.completeness.truncate("json_body_shapes");
|
||||
return { shape, truncated: shape?.truncated === true };
|
||||
};
|
||||
|
||||
const invalidResponseBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
requestId: string,
|
||||
): void => {
|
||||
updateResponseBodyShape(state, requestId, null, false);
|
||||
state.completeness.exclude("json_body_shapes", "invalid_protocol_value");
|
||||
};
|
||||
@@ -0,0 +1,457 @@
|
||||
import type { WebPageInspection } from "../domain/browserObservation.js";
|
||||
import { inferJsonShape } from "../domain/jsonShape.js";
|
||||
import { safeResponseMetadata } from "./CdpSafeMetadata.js";
|
||||
import { boundedSensitiveText } from "./SensitiveTextCapture.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { requestBodyShape } from "./CdpCaptureEventBodyShapes.js";
|
||||
import {
|
||||
consolePrimitive,
|
||||
decodeBase64,
|
||||
exclusionReasonForUrl,
|
||||
executionContextKey,
|
||||
firstCallFrame,
|
||||
initiatorLocation,
|
||||
integerOrNull,
|
||||
} from "./CdpCaptureEventHelpers.js";
|
||||
import type { CdpCaptureEventsState } from "./CdpCaptureEventState.js";
|
||||
import type { CapturedScript } from "./CdpCaptureEventTypes.js";
|
||||
|
||||
export const handleExecutionContextCreated = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const context = recordValue(params.context);
|
||||
const identifier = numberValue(context?.id);
|
||||
const frameId = stringValue(recordValue(context?.auxData)?.frameId);
|
||||
if (
|
||||
identifier === undefined ||
|
||||
!Number.isSafeInteger(identifier) ||
|
||||
frameId === undefined ||
|
||||
frameId.length > 256
|
||||
)
|
||||
return;
|
||||
const key = String(identifier);
|
||||
if (
|
||||
state.executionContextFrames.size >= state.input.limits.max_scripts &&
|
||||
!state.executionContextFrames.has(key)
|
||||
) {
|
||||
state.completeness.truncate("scripts");
|
||||
return;
|
||||
}
|
||||
state.executionContextFrames.set(key, frameId);
|
||||
};
|
||||
|
||||
export const handleExecutionContextDestroyed = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const key = executionContextKey(params.executionContextId);
|
||||
if (key !== null) state.executionContextFrames.delete(key);
|
||||
};
|
||||
|
||||
export const handleScriptParsed = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const scriptId = stringValue(params.scriptId);
|
||||
const rawUrl = stringValue(params.url) ?? "";
|
||||
const sanitized = allowedSanitizedUrl(rawUrl, state.allowedOrigins);
|
||||
if (scriptId === undefined || scriptId.length > 256) {
|
||||
state.completeness.exclude("scripts", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (sanitized === undefined) {
|
||||
state.completeness.exclude("scripts", exclusionReasonForUrl(rawUrl));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
state.scripts.size >= state.input.limits.max_scripts &&
|
||||
!state.scripts.has(scriptId)
|
||||
) {
|
||||
state.completeness.drop("scripts");
|
||||
return;
|
||||
}
|
||||
const sourceMap = sourceMapForScript(params.sourceMapURL, rawUrl, state);
|
||||
const script: CapturedScript = {
|
||||
scriptId,
|
||||
rawUrl,
|
||||
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: sourceMap.sanitized,
|
||||
sourceMapRawUrl: sourceMap.raw,
|
||||
executionContextKey: executionContextKey(params.executionContextId),
|
||||
};
|
||||
state.scripts.set(scriptId, script);
|
||||
};
|
||||
|
||||
const sourceMapForScript = (
|
||||
value: unknown,
|
||||
scriptUrl: string,
|
||||
state: CdpCaptureEventsState,
|
||||
): { readonly sanitized: string | null; readonly raw: string | null } => {
|
||||
const declaredUrl = stringValue(value);
|
||||
if (declaredUrl === undefined || declaredUrl === "")
|
||||
return { sanitized: null, raw: null };
|
||||
let rawUrl: string;
|
||||
try {
|
||||
rawUrl = new URL(declaredUrl, scriptUrl).href;
|
||||
} catch {
|
||||
state.completeness.exclude("source_maps", "unsupported_url");
|
||||
return { sanitized: null, raw: null };
|
||||
}
|
||||
const sanitized = allowedSanitizedUrl(rawUrl, state.allowedOrigins);
|
||||
if (sanitized !== undefined) return { sanitized: sanitized.url, raw: rawUrl };
|
||||
state.completeness.exclude("source_maps", exclusionReasonForUrl(rawUrl));
|
||||
return { sanitized: null, raw: null };
|
||||
};
|
||||
|
||||
export const handleRequestWillBeSent = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const request = recordValue(params.request);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
state.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (request === undefined) {
|
||||
state.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
state.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
const sanitized = allowedSanitizedUrl(request.url, state.allowedOrigins);
|
||||
if (sanitized === undefined) {
|
||||
state.completeness.exclude(
|
||||
"network_requests",
|
||||
exclusionReasonForUrl(stringValue(request.url)),
|
||||
);
|
||||
state.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
state.network.size >= state.input.limits.max_network_events &&
|
||||
!state.network.has(requestId)
|
||||
) {
|
||||
state.completeness.drop("network_requests");
|
||||
return;
|
||||
}
|
||||
const initiator = recordValue(params.initiator);
|
||||
const initiatorFrame = initiatorLocation(initiator);
|
||||
const rawInitiatorUrl = stringValue(initiatorFrame?.url);
|
||||
const initiatorUrl = allowedSanitizedUrl(
|
||||
rawInitiatorUrl,
|
||||
state.allowedOrigins,
|
||||
);
|
||||
if (rawInitiatorUrl !== undefined && initiatorUrl === undefined)
|
||||
state.completeness.exclude(
|
||||
"network_initiators",
|
||||
exclusionReasonForUrl(rawInitiatorUrl),
|
||||
);
|
||||
state.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(initiatorFrame?.lineNumber),
|
||||
column: integerOrNull(initiatorFrame?.columnNumber),
|
||||
},
|
||||
body_shapes: requestBodyShape(state, request),
|
||||
});
|
||||
};
|
||||
|
||||
export const handleResponseReceived = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
state.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
const current = state.network.get(requestId);
|
||||
const response = recordValue(params.response);
|
||||
if (current === undefined) return;
|
||||
const sanitized = allowedSanitizedUrl(response?.url, state.allowedOrigins);
|
||||
if (response === undefined || sanitized === undefined) {
|
||||
state.completeness.exclude(
|
||||
"network_requests",
|
||||
response === undefined
|
||||
? "invalid_protocol_value"
|
||||
: exclusionReasonForUrl(stringValue(response.url)),
|
||||
);
|
||||
state.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
state.network.set(requestId, {
|
||||
...current,
|
||||
status: numberValue(response.status) ?? null,
|
||||
mime_type: boundedText(response.mimeType, 256),
|
||||
});
|
||||
if (state.responseMetadata.length >= state.input.limits.max_network_events) {
|
||||
state.completeness.truncate("metadata");
|
||||
return;
|
||||
}
|
||||
const metadata = safeResponseMetadata(
|
||||
requestId,
|
||||
sanitized.url,
|
||||
response,
|
||||
state.allowedOrigins,
|
||||
);
|
||||
state.responseMetadata.push(metadata.response);
|
||||
state.agentHints.push(...metadata.agentHints);
|
||||
};
|
||||
|
||||
export const handleLoadingFinished = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) return;
|
||||
const current = state.network.get(requestId);
|
||||
if (current === undefined) return;
|
||||
state.network.set(requestId, {
|
||||
...current,
|
||||
encoded_data_length: Math.max(
|
||||
0,
|
||||
numberValue(params.encodedDataLength) ?? 0,
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
export const handleConsoleAPICalled = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const frame = firstCallFrame(recordValue(params.stackTrace));
|
||||
if (frame === undefined) {
|
||||
state.completeness.exclude("console_events", "unattributed_origin");
|
||||
return;
|
||||
}
|
||||
const source = allowedSanitizedUrl(frame.url, state.allowedOrigins);
|
||||
if (source === undefined) {
|
||||
state.completeness.exclude(
|
||||
"console_events",
|
||||
exclusionReasonForUrl(stringValue(frame.url)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (state.console.length >= state.input.limits.max_console_events) {
|
||||
state.completeness.drop("console_events");
|
||||
return;
|
||||
}
|
||||
const arguments_ = recordsValue(params.args);
|
||||
state.console.push({
|
||||
type: (stringValue(params.type) ?? "unknown").slice(0, 100),
|
||||
timestamp: numberValue(params.timestamp) ?? 0,
|
||||
argument_types: arguments_
|
||||
.map((argument) =>
|
||||
(stringValue(argument.type) ?? "unknown").slice(0, 100),
|
||||
)
|
||||
.slice(0, 100),
|
||||
url: source.url,
|
||||
line: integerOrNull(frame.lineNumber),
|
||||
column: integerOrNull(frame.columnNumber),
|
||||
text_capture: captureConsoleText(state, arguments_),
|
||||
});
|
||||
};
|
||||
|
||||
const captureConsoleText = (
|
||||
state: CdpCaptureEventsState,
|
||||
arguments_: readonly UnknownRecord[],
|
||||
): WebPageInspection["console"]["events"][number]["text_capture"] => {
|
||||
if (!state.input.include_console_text)
|
||||
return {
|
||||
status: "not_approved",
|
||||
values: [],
|
||||
retained_bytes: 0,
|
||||
truncated_values: 0,
|
||||
};
|
||||
const values: WebPageInspection["console"]["events"][number]["text_capture"]["values"] =
|
||||
[];
|
||||
let retainedBytes = 0;
|
||||
let truncatedValues = 0;
|
||||
for (const [argumentIndex, argument] of arguments_.entries()) {
|
||||
const primitive = consolePrimitive(argument);
|
||||
if (primitive === undefined) continue;
|
||||
const remaining =
|
||||
state.input.limits.max_total_console_text_bytes - state.consoleTextBytes;
|
||||
if (remaining <= 0) {
|
||||
truncatedValues += 1;
|
||||
continue;
|
||||
}
|
||||
const bounded = boundedSensitiveText(
|
||||
primitive.text,
|
||||
Math.min(state.input.limits.max_console_text_field_bytes, remaining),
|
||||
);
|
||||
values.push({
|
||||
argument_index: argumentIndex,
|
||||
type: primitive.type,
|
||||
text: bounded.text,
|
||||
});
|
||||
retainedBytes += bounded.bytes;
|
||||
state.consoleTextBytes += bounded.bytes;
|
||||
if (bounded.truncated) truncatedValues += 1;
|
||||
}
|
||||
if (truncatedValues > 0) state.completeness.truncate("console_text");
|
||||
return {
|
||||
status: truncatedValues > 0 ? "truncated" : "included",
|
||||
values,
|
||||
retained_bytes: retainedBytes,
|
||||
truncated_values: truncatedValues,
|
||||
};
|
||||
};
|
||||
|
||||
export const handleWebSocketFrame = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
direction: "sent" | "received",
|
||||
): void => {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (
|
||||
requestId === undefined ||
|
||||
requestId.length > 256 ||
|
||||
(!state.network.has(requestId) && !state.allowedWebSockets.has(requestId))
|
||||
)
|
||||
return;
|
||||
if (state.websockets.length >= state.input.limits.max_websocket_events) {
|
||||
state.completeness.drop("websocket_frames");
|
||||
return;
|
||||
}
|
||||
const response = recordValue(params.response);
|
||||
const payload = stringValue(response?.payloadData) ?? "";
|
||||
const opcode = Math.max(0, Math.trunc(numberValue(response?.opcode) ?? 0));
|
||||
const decoded = opcode === 1 ? undefined : decodeBase64(payload);
|
||||
if (opcode !== 1 && decoded === undefined)
|
||||
state.completeness.exclude("websocket_frames", "invalid_protocol_value");
|
||||
state.websockets.push({
|
||||
request_id: requestId,
|
||||
direction,
|
||||
opcode,
|
||||
payload_bytes:
|
||||
opcode === 1 ? Buffer.byteLength(payload) : (decoded?.byteLength ?? 0),
|
||||
payload_shape: captureWebSocketShape(state, payload, opcode),
|
||||
});
|
||||
};
|
||||
|
||||
const captureWebSocketShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
payload: string,
|
||||
opcode: number,
|
||||
): WebPageInspection["network"]["websocket_events"][number]["payload_shape"] => {
|
||||
if (!state.input.include_websocket_shapes) return null;
|
||||
if (opcode !== 1)
|
||||
return { format: "binary", json_shape: null, truncated: false };
|
||||
const bytes = Buffer.byteLength(payload);
|
||||
const remaining =
|
||||
state.input.limits.max_total_websocket_shape_bytes -
|
||||
state.websocketShapeBytes;
|
||||
if (
|
||||
bytes > state.input.limits.max_websocket_shape_bytes ||
|
||||
bytes > remaining
|
||||
) {
|
||||
state.completeness.truncate("websocket_shapes");
|
||||
return { format: "text", json_shape: null, truncated: true };
|
||||
}
|
||||
state.websocketShapeBytes += bytes;
|
||||
const shape = inferJsonShape(payload, {
|
||||
maximumBytes: state.input.limits.max_websocket_shape_bytes,
|
||||
maximumNodes: state.input.limits.max_json_shape_nodes,
|
||||
maximumDepth: state.input.limits.max_json_shape_depth,
|
||||
});
|
||||
if (shape?.truncated === true)
|
||||
state.completeness.truncate("websocket_shapes");
|
||||
return {
|
||||
format: shape === null ? "text" : "json",
|
||||
json_shape: shape,
|
||||
truncated: shape?.truncated === true,
|
||||
};
|
||||
};
|
||||
|
||||
export const handleWebSocketCreated = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const rawUrl = stringValue(params.url);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
state.completeness.exclude(
|
||||
"websocket_connections",
|
||||
"invalid_protocol_value",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (rawUrl === undefined) {
|
||||
state.completeness.exclude(
|
||||
"websocket_connections",
|
||||
"invalid_protocol_value",
|
||||
);
|
||||
return;
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
state.completeness.exclude("websocket_connections", "unsupported_url");
|
||||
return;
|
||||
}
|
||||
if (parsed.protocol === "ws:") parsed.protocol = "http:";
|
||||
else if (parsed.protocol === "wss:") parsed.protocol = "https:";
|
||||
else {
|
||||
state.completeness.exclude("websocket_connections", "unsupported_url");
|
||||
return;
|
||||
}
|
||||
if (!state.allowedOrigins.has(parsed.origin)) {
|
||||
state.completeness.exclude("websocket_connections", "disallowed_origin");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!state.allowedWebSockets.has(requestId) &&
|
||||
state.allowedWebSockets.size >= state.input.limits.max_websocket_events
|
||||
) {
|
||||
state.completeness.drop("websocket_connections");
|
||||
return;
|
||||
}
|
||||
state.allowedWebSockets.add(requestId);
|
||||
};
|
||||
|
||||
export const handleFrameNavigated = (
|
||||
state: CdpCaptureEventsState,
|
||||
params: UnknownRecord,
|
||||
): void => {
|
||||
const frame = recordValue(params.frame);
|
||||
if (stringValue(frame?.id) !== state.mainFrameId) return;
|
||||
state.navigationDuringCapture = true;
|
||||
const rawUrl = stringValue(frame?.url);
|
||||
if (
|
||||
isHttpUrl(rawUrl) &&
|
||||
allowedSanitizedUrl(rawUrl, state.allowedOrigins) === undefined
|
||||
)
|
||||
state.originViolation = true;
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
import {
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
export const firstCallFrame = (
|
||||
value: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => recordsValue(value?.callFrames)[0];
|
||||
|
||||
export const initiatorLocation = (
|
||||
initiator: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => {
|
||||
let stack = recordValue(initiator?.stack);
|
||||
for (let depth = 0; depth < 32 && stack !== undefined; depth += 1) {
|
||||
const frame = firstCallFrame(stack);
|
||||
if (frame !== undefined) return frame;
|
||||
stack = recordValue(stack.parent);
|
||||
}
|
||||
return stringValue(initiator?.url) === undefined ? undefined : initiator;
|
||||
};
|
||||
|
||||
export const exclusionReasonForUrl = (
|
||||
value: string | undefined,
|
||||
): "disallowed_origin" | "unsupported_url" | "unattributed_origin" =>
|
||||
value === undefined || value === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(value)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url";
|
||||
|
||||
export const integerOrNull = (value: unknown): number | null => {
|
||||
const number = numberValue(value);
|
||||
return number === undefined ? null : Math.max(0, Math.trunc(number));
|
||||
};
|
||||
|
||||
export const executionContextKey = (value: unknown): string | null => {
|
||||
const identifier = numberValue(value);
|
||||
return identifier !== undefined && Number.isSafeInteger(identifier)
|
||||
? String(identifier)
|
||||
: null;
|
||||
};
|
||||
|
||||
export const isJsonContentType = (
|
||||
headers: UnknownRecord | undefined,
|
||||
): boolean => {
|
||||
if (headers === undefined) return false;
|
||||
for (const [name, value] of Object.entries(headers))
|
||||
if (
|
||||
name.toLowerCase() === "content-type" &&
|
||||
isJsonMediaType(stringValue(value))
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
export const isJsonMediaType = (value: string | null | undefined): boolean => {
|
||||
const mediaType = value?.split(";", 1)[0]?.trim().toLowerCase();
|
||||
return (
|
||||
mediaType === "application/json" || mediaType?.endsWith("+json") === true
|
||||
);
|
||||
};
|
||||
|
||||
export const consolePrimitive = (
|
||||
value: UnknownRecord,
|
||||
): { readonly type: string; readonly text: string } | undefined => {
|
||||
const type = stringValue(value.type);
|
||||
switch (type) {
|
||||
case "string":
|
||||
return typeof value.value === "string"
|
||||
? { type, text: value.value }
|
||||
: undefined;
|
||||
case "boolean":
|
||||
return typeof value.value === "boolean"
|
||||
? { type, text: String(value.value) }
|
||||
: undefined;
|
||||
case "number":
|
||||
return typeof value.value === "number"
|
||||
? { type, text: String(value.value) }
|
||||
: typeof value.unserializableValue === "string"
|
||||
? { type, text: value.unserializableValue }
|
||||
: undefined;
|
||||
case "bigint":
|
||||
return typeof value.unserializableValue === "string"
|
||||
? { type, text: value.unserializableValue }
|
||||
: undefined;
|
||||
case "undefined":
|
||||
return { type, text: "undefined" };
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const BASE64 = /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/u;
|
||||
|
||||
export const decodeBase64 = (value: string): Buffer | undefined =>
|
||||
value.length % 4 === 0 && BASE64.test(value)
|
||||
? Buffer.from(value, "base64")
|
||||
: undefined;
|
||||
@@ -0,0 +1,26 @@
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import type { CapturedScript, NetworkState } from "./CdpCaptureEventTypes.js";
|
||||
|
||||
export interface CdpCaptureEventsState {
|
||||
readonly input: InspectWebPageInput;
|
||||
readonly allowedOrigins: ReadonlySet<string>;
|
||||
readonly scripts: Map<string, CapturedScript>;
|
||||
readonly executionContextFrames: Map<string, string>;
|
||||
readonly network: Map<string, NetworkState>;
|
||||
readonly allowedWebSockets: Set<string>;
|
||||
console: WebPageInspection["console"]["events"];
|
||||
websockets: WebPageInspection["network"]["websocket_events"];
|
||||
responseMetadata: WebPageInspection["metadata"]["responses"];
|
||||
agentHints: WebPageInspection["metadata"]["agent_hints"];
|
||||
readonly completeness: CdpCaptureCompleteness;
|
||||
originViolation: boolean;
|
||||
navigationDuringCapture: boolean;
|
||||
mainFrameId: string | undefined;
|
||||
consoleTextBytes: number;
|
||||
jsonBodyBytes: number;
|
||||
websocketShapeBytes: number;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { WebPageInspection } from "../domain/browserObservation.js";
|
||||
|
||||
export interface CapturedScript {
|
||||
readonly scriptId: string;
|
||||
readonly rawUrl: 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;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
readonly executionContextKey: string | null;
|
||||
}
|
||||
|
||||
export type NetworkState = WebPageInspection["network"]["requests"][number];
|
||||
+41
-633
@@ -2,48 +2,27 @@ import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import { inferJsonShape, type JsonShape } from "../domain/jsonShape.js";
|
||||
import type { CdpEvent } from "./CdpConnection.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import { safeResponseMetadata } from "./CdpSafeMetadata.js";
|
||||
import { boundedSensitiveText } from "./SensitiveTextCapture.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
isHttpUrl,
|
||||
numberValue,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import * as bodyShapes from "./CdpCaptureEventBodyShapes.js";
|
||||
import type { CdpCaptureEventsState } from "./CdpCaptureEventState.js";
|
||||
import type { CapturedScript, NetworkState } from "./CdpCaptureEventTypes.js";
|
||||
import * as handlers from "./CdpCaptureEventHandlers.js";
|
||||
import { isJsonMediaType } from "./CdpCaptureEventHelpers.js";
|
||||
import { recordValue } from "./CdpCaptureValues.js";
|
||||
|
||||
export interface CapturedScript {
|
||||
readonly scriptId: string;
|
||||
readonly rawUrl: 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;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
readonly executionContextKey: string | null;
|
||||
}
|
||||
|
||||
type NetworkState = WebPageInspection["network"]["requests"][number];
|
||||
export { type CapturedScript } from "./CdpCaptureEventTypes.js";
|
||||
|
||||
/** Bounded event accumulator that drops payload values at ingestion time. */
|
||||
export class CdpCaptureEvents {
|
||||
export class CdpCaptureEvents implements CdpCaptureEventsState {
|
||||
readonly scripts = new Map<string, CapturedScript>();
|
||||
readonly executionContextFrames = new Map<string, string>();
|
||||
readonly network = new Map<string, NetworkState>();
|
||||
readonly allowedWebSockets = new Set<string>();
|
||||
readonly console: WebPageInspection["console"]["events"] = [];
|
||||
readonly websockets: WebPageInspection["network"]["websocket_events"] = [];
|
||||
readonly responseMetadata: WebPageInspection["metadata"]["responses"] = [];
|
||||
readonly agentHints: WebPageInspection["metadata"]["agent_hints"] = [];
|
||||
console: WebPageInspection["console"]["events"] = [];
|
||||
websockets: WebPageInspection["network"]["websocket_events"] = [];
|
||||
responseMetadata: WebPageInspection["metadata"]["responses"] = [];
|
||||
agentHints: WebPageInspection["metadata"]["agent_hints"] = [];
|
||||
readonly completeness = new CdpCaptureCompleteness([
|
||||
"network_requests",
|
||||
"console_events",
|
||||
@@ -53,18 +32,21 @@ export class CdpCaptureEvents {
|
||||
]);
|
||||
originViolation = false;
|
||||
navigationDuringCapture = false;
|
||||
#mainFrameId: string | undefined;
|
||||
#consoleTextBytes = 0;
|
||||
#jsonBodyBytes = 0;
|
||||
#websocketShapeBytes = 0;
|
||||
mainFrameId: string | undefined = undefined;
|
||||
consoleTextBytes = 0;
|
||||
jsonBodyBytes = 0;
|
||||
websocketShapeBytes = 0;
|
||||
|
||||
constructor(
|
||||
private readonly input: InspectWebPageInput,
|
||||
private readonly allowedOrigins: ReadonlySet<string>,
|
||||
) {}
|
||||
readonly input: InspectWebPageInput;
|
||||
readonly allowedOrigins: ReadonlySet<string>;
|
||||
|
||||
constructor(input: InspectWebPageInput, allowedOrigins: ReadonlySet<string>) {
|
||||
this.input = input;
|
||||
this.allowedOrigins = allowedOrigins;
|
||||
}
|
||||
|
||||
beginAuthorizedFrame(frameId: string): void {
|
||||
this.#mainFrameId = frameId;
|
||||
this.mainFrameId = frameId;
|
||||
this.originViolation = false;
|
||||
this.navigationDuringCapture = false;
|
||||
this.scripts.clear();
|
||||
@@ -75,9 +57,9 @@ export class CdpCaptureEvents {
|
||||
this.websockets.length = 0;
|
||||
this.responseMetadata.length = 0;
|
||||
this.agentHints.length = 0;
|
||||
this.#consoleTextBytes = 0;
|
||||
this.#jsonBodyBytes = 0;
|
||||
this.#websocketShapeBytes = 0;
|
||||
this.consoleTextBytes = 0;
|
||||
this.jsonBodyBytes = 0;
|
||||
this.websocketShapeBytes = 0;
|
||||
this.completeness.reset();
|
||||
if (!this.input.include_console_text)
|
||||
this.completeness.exclude("console_text", "not_approved", null);
|
||||
@@ -88,7 +70,7 @@ export class CdpCaptureEvents {
|
||||
}
|
||||
|
||||
beginFinalCapture(frameId: string): void {
|
||||
this.#mainFrameId = frameId;
|
||||
this.mainFrameId = frameId;
|
||||
this.navigationDuringCapture = false;
|
||||
}
|
||||
|
||||
@@ -97,40 +79,40 @@ export class CdpCaptureEvents {
|
||||
if (params === undefined) return;
|
||||
switch (event.method) {
|
||||
case "Runtime.executionContextCreated":
|
||||
this.#executionContext(params);
|
||||
handlers.handleExecutionContextCreated(this, params);
|
||||
break;
|
||||
case "Runtime.executionContextDestroyed":
|
||||
this.#destroyExecutionContext(params);
|
||||
handlers.handleExecutionContextDestroyed(this, params);
|
||||
break;
|
||||
case "Runtime.executionContextsCleared":
|
||||
this.executionContextFrames.clear();
|
||||
break;
|
||||
case "Debugger.scriptParsed":
|
||||
this.#script(params);
|
||||
handlers.handleScriptParsed(this, params);
|
||||
break;
|
||||
case "Network.requestWillBeSent":
|
||||
this.#request(params);
|
||||
handlers.handleRequestWillBeSent(this, params);
|
||||
break;
|
||||
case "Network.responseReceived":
|
||||
this.#response(params);
|
||||
handlers.handleResponseReceived(this, params);
|
||||
break;
|
||||
case "Network.loadingFinished":
|
||||
this.#finished(params);
|
||||
handlers.handleLoadingFinished(this, params);
|
||||
break;
|
||||
case "Runtime.consoleAPICalled":
|
||||
this.#console(params);
|
||||
handlers.handleConsoleAPICalled(this, params);
|
||||
break;
|
||||
case "Page.frameNavigated":
|
||||
this.#frameNavigated(params);
|
||||
handlers.handleFrameNavigated(this, params);
|
||||
break;
|
||||
case "Network.webSocketCreated":
|
||||
this.#websocketCreated(params);
|
||||
handlers.handleWebSocketCreated(this, params);
|
||||
break;
|
||||
case "Network.webSocketFrameSent":
|
||||
this.#websocket(params, "sent");
|
||||
handlers.handleWebSocketFrame(this, params, "sent");
|
||||
break;
|
||||
case "Network.webSocketFrameReceived":
|
||||
this.#websocket(params, "received");
|
||||
handlers.handleWebSocketFrame(this, params, "received");
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -147,272 +129,6 @@ export class CdpCaptureEvents {
|
||||
: null;
|
||||
}
|
||||
|
||||
#executionContext(params: UnknownRecord): void {
|
||||
const context = recordValue(params.context);
|
||||
const identifier = numberValue(context?.id);
|
||||
const frameId = stringValue(recordValue(context?.auxData)?.frameId);
|
||||
if (
|
||||
identifier === undefined ||
|
||||
!Number.isSafeInteger(identifier) ||
|
||||
frameId === undefined ||
|
||||
frameId.length > 256
|
||||
)
|
||||
return;
|
||||
const key = String(identifier);
|
||||
if (
|
||||
this.executionContextFrames.size >= this.input.limits.max_scripts &&
|
||||
!this.executionContextFrames.has(key)
|
||||
) {
|
||||
this.completeness.truncate("scripts");
|
||||
return;
|
||||
}
|
||||
this.executionContextFrames.set(key, frameId);
|
||||
}
|
||||
|
||||
#destroyExecutionContext(params: UnknownRecord): void {
|
||||
const key = executionContextKey(params.executionContextId);
|
||||
if (key !== null) this.executionContextFrames.delete(key);
|
||||
}
|
||||
|
||||
#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) {
|
||||
this.completeness.exclude("scripts", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (sanitized === undefined) {
|
||||
this.completeness.exclude("scripts", exclusionReasonForUrl(rawUrl));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.scripts.size >= this.input.limits.max_scripts &&
|
||||
!this.scripts.has(scriptId)
|
||||
) {
|
||||
this.completeness.drop("scripts");
|
||||
return;
|
||||
}
|
||||
const sourceMap = this.#sourceMap(params.sourceMapURL, rawUrl);
|
||||
this.scripts.set(scriptId, {
|
||||
scriptId,
|
||||
rawUrl,
|
||||
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: sourceMap.sanitized,
|
||||
sourceMapRawUrl: sourceMap.raw,
|
||||
executionContextKey: executionContextKey(params.executionContextId),
|
||||
});
|
||||
}
|
||||
|
||||
#sourceMap(
|
||||
value: unknown,
|
||||
scriptUrl: string,
|
||||
): {
|
||||
readonly sanitized: string | null;
|
||||
readonly raw: string | null;
|
||||
} {
|
||||
const declaredUrl = stringValue(value);
|
||||
if (declaredUrl === undefined || declaredUrl === "")
|
||||
return { sanitized: null, raw: null };
|
||||
let rawUrl: string;
|
||||
try {
|
||||
rawUrl = new URL(declaredUrl, scriptUrl).href;
|
||||
} catch {
|
||||
this.completeness.exclude("source_maps", "unsupported_url");
|
||||
return { sanitized: null, raw: null };
|
||||
}
|
||||
const sanitized = allowedSanitizedUrl(rawUrl, this.allowedOrigins);
|
||||
if (sanitized !== undefined)
|
||||
return { sanitized: sanitized.url, raw: rawUrl };
|
||||
this.completeness.exclude("source_maps", exclusionReasonForUrl(rawUrl));
|
||||
return { sanitized: null, raw: null };
|
||||
}
|
||||
|
||||
#request(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const request = recordValue(params.request);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
this.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (request === undefined) {
|
||||
this.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
this.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
const sanitized = allowedSanitizedUrl(request.url, this.allowedOrigins);
|
||||
if (sanitized === undefined) {
|
||||
this.completeness.exclude(
|
||||
"network_requests",
|
||||
exclusionReasonForUrl(stringValue(request.url)),
|
||||
);
|
||||
this.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.network.size >= this.input.limits.max_network_events &&
|
||||
!this.network.has(requestId)
|
||||
) {
|
||||
this.completeness.drop("network_requests");
|
||||
return;
|
||||
}
|
||||
const initiator = recordValue(params.initiator);
|
||||
const initiatorFrame = initiatorLocation(initiator);
|
||||
const rawInitiatorUrl = stringValue(initiatorFrame?.url);
|
||||
const initiatorUrl = allowedSanitizedUrl(
|
||||
rawInitiatorUrl,
|
||||
this.allowedOrigins,
|
||||
);
|
||||
if (rawInitiatorUrl !== undefined && initiatorUrl === undefined)
|
||||
this.completeness.exclude(
|
||||
"network_initiators",
|
||||
exclusionReasonForUrl(rawInitiatorUrl),
|
||||
);
|
||||
this.network.set(requestId, {
|
||||
request_id: requestId,
|
||||
url: sanitized.url,
|
||||
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(initiatorFrame?.lineNumber),
|
||||
column: integerOrNull(initiatorFrame?.columnNumber),
|
||||
},
|
||||
body_shapes: this.#requestBodyShape(request),
|
||||
});
|
||||
}
|
||||
|
||||
#response(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
this.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
const current = this.network.get(requestId);
|
||||
const response = recordValue(params.response);
|
||||
if (current === undefined) return;
|
||||
const sanitized = allowedSanitizedUrl(response?.url, this.allowedOrigins);
|
||||
if (response === undefined || sanitized === undefined) {
|
||||
this.completeness.exclude(
|
||||
"network_requests",
|
||||
response === undefined
|
||||
? "invalid_protocol_value"
|
||||
: exclusionReasonForUrl(stringValue(response.url)),
|
||||
);
|
||||
this.network.delete(requestId);
|
||||
return;
|
||||
}
|
||||
this.network.set(requestId, {
|
||||
...current,
|
||||
status: numberValue(response.status) ?? null,
|
||||
mime_type: boundedText(response.mimeType, 256),
|
||||
});
|
||||
if (this.responseMetadata.length >= this.input.limits.max_network_events) {
|
||||
this.completeness.truncate("metadata");
|
||||
return;
|
||||
}
|
||||
const metadata = safeResponseMetadata(
|
||||
requestId,
|
||||
sanitized.url,
|
||||
response,
|
||||
this.allowedOrigins,
|
||||
);
|
||||
this.responseMetadata.push(metadata.response);
|
||||
this.agentHints.push(...metadata.agentHints);
|
||||
}
|
||||
|
||||
#finished(params: UnknownRecord): void {
|
||||
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));
|
||||
if (frame === undefined) {
|
||||
this.completeness.exclude("console_events", "unattributed_origin");
|
||||
return;
|
||||
}
|
||||
const source = allowedSanitizedUrl(frame.url, this.allowedOrigins);
|
||||
if (source === undefined) {
|
||||
this.completeness.exclude(
|
||||
"console_events",
|
||||
exclusionReasonForUrl(stringValue(frame.url)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (this.console.length >= this.input.limits.max_console_events) {
|
||||
this.completeness.drop("console_events");
|
||||
return;
|
||||
}
|
||||
const arguments_ = recordsValue(params.args);
|
||||
this.console.push({
|
||||
type: (stringValue(params.type) ?? "unknown").slice(0, 100),
|
||||
timestamp: numberValue(params.timestamp) ?? 0,
|
||||
argument_types: arguments_
|
||||
.map((argument) =>
|
||||
(stringValue(argument.type) ?? "unknown").slice(0, 100),
|
||||
)
|
||||
.slice(0, 100),
|
||||
url: source.url,
|
||||
line: integerOrNull(frame.lineNumber),
|
||||
column: integerOrNull(frame.columnNumber),
|
||||
text_capture: this.#consoleText(arguments_),
|
||||
});
|
||||
}
|
||||
|
||||
#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.completeness.drop("websocket_frames");
|
||||
return;
|
||||
}
|
||||
const response = recordValue(params.response);
|
||||
const payload = stringValue(response?.payloadData) ?? "";
|
||||
const opcode = Math.max(0, Math.trunc(numberValue(response?.opcode) ?? 0));
|
||||
const decoded = opcode === 1 ? undefined : decodeBase64(payload);
|
||||
if (opcode !== 1 && decoded === undefined)
|
||||
this.completeness.exclude("websocket_frames", "invalid_protocol_value");
|
||||
this.websockets.push({
|
||||
request_id: requestId,
|
||||
direction,
|
||||
opcode,
|
||||
payload_bytes:
|
||||
opcode === 1 ? Buffer.byteLength(payload) : (decoded?.byteLength ?? 0),
|
||||
payload_shape: this.#websocketShape(payload, opcode),
|
||||
});
|
||||
}
|
||||
|
||||
responseBodyRequestIds(): readonly string[] {
|
||||
if (!this.input.include_json_body_shapes) return [];
|
||||
return [...this.network.values()]
|
||||
@@ -421,319 +137,11 @@ export class CdpCaptureEvents {
|
||||
}
|
||||
|
||||
responseBodyUnavailable(requestId: string): void {
|
||||
this.#updateResponseShape(requestId, null, false);
|
||||
bodyShapes.updateResponseBodyShape(this, requestId, null, false);
|
||||
this.completeness.unavailable("json_body_shapes");
|
||||
}
|
||||
|
||||
ingestResponseBody(requestId: string, value: unknown): void {
|
||||
const result = recordValue(value);
|
||||
const body = stringValue(result?.body);
|
||||
if (body === undefined) {
|
||||
this.#invalidResponseBody(requestId);
|
||||
return;
|
||||
}
|
||||
const decoded =
|
||||
result?.base64Encoded === true
|
||||
? decodeBase64(body)?.toString("utf8")
|
||||
: body;
|
||||
if (decoded === undefined) {
|
||||
this.#invalidResponseBody(requestId);
|
||||
return;
|
||||
}
|
||||
const inferred = this.#inferBodyShape(decoded);
|
||||
this.#updateResponseShape(requestId, inferred.shape, inferred.truncated);
|
||||
}
|
||||
|
||||
#invalidResponseBody(requestId: string): void {
|
||||
this.#updateResponseShape(requestId, null, false);
|
||||
this.completeness.exclude("json_body_shapes", "invalid_protocol_value");
|
||||
}
|
||||
|
||||
#requestBodyShape(request: UnknownRecord): NetworkState["body_shapes"] {
|
||||
if (!this.input.include_json_body_shapes)
|
||||
return { status: "not_approved", request: null, response: null };
|
||||
const body = stringValue(request.postData);
|
||||
if (!isJsonContentType(recordValue(request.headers)) || body === undefined)
|
||||
return { status: "unavailable", request: null, response: null };
|
||||
const inferred = this.#inferBodyShape(body);
|
||||
return {
|
||||
status: inferred.truncated
|
||||
? "truncated"
|
||||
: inferred.shape === null
|
||||
? "unavailable"
|
||||
: "included",
|
||||
request: inferred.shape,
|
||||
response: null,
|
||||
};
|
||||
}
|
||||
|
||||
#inferBodyShape(text: string): {
|
||||
readonly shape: JsonShape | null;
|
||||
readonly truncated: boolean;
|
||||
} {
|
||||
const bytes = Buffer.byteLength(text);
|
||||
const remaining =
|
||||
this.input.limits.max_total_json_body_bytes - this.#jsonBodyBytes;
|
||||
if (bytes > this.input.limits.max_json_body_bytes || bytes > remaining) {
|
||||
this.completeness.truncate("json_body_shapes");
|
||||
return { shape: null, truncated: true };
|
||||
}
|
||||
this.#jsonBodyBytes += bytes;
|
||||
const shape = inferJsonShape(text, {
|
||||
maximumBytes: this.input.limits.max_json_body_bytes,
|
||||
maximumNodes: this.input.limits.max_json_shape_nodes,
|
||||
maximumDepth: this.input.limits.max_json_shape_depth,
|
||||
});
|
||||
if (shape?.truncated === true)
|
||||
this.completeness.truncate("json_body_shapes");
|
||||
return { shape, truncated: shape?.truncated === true };
|
||||
}
|
||||
|
||||
#updateResponseShape(
|
||||
requestId: string,
|
||||
response: JsonShape | null,
|
||||
truncated: boolean,
|
||||
): void {
|
||||
const current = this.network.get(requestId);
|
||||
if (current === undefined) return;
|
||||
const request = current.body_shapes.request;
|
||||
const status =
|
||||
truncated || current.body_shapes.status === "truncated"
|
||||
? "truncated"
|
||||
: response !== null
|
||||
? "included"
|
||||
: request !== null
|
||||
? "partial"
|
||||
: "unavailable";
|
||||
this.network.set(requestId, {
|
||||
...current,
|
||||
body_shapes: { status, request, response },
|
||||
});
|
||||
}
|
||||
|
||||
#consoleText(
|
||||
arguments_: readonly UnknownRecord[],
|
||||
): WebPageInspection["console"]["events"][number]["text_capture"] {
|
||||
if (!this.input.include_console_text)
|
||||
return {
|
||||
status: "not_approved",
|
||||
values: [],
|
||||
retained_bytes: 0,
|
||||
truncated_values: 0,
|
||||
};
|
||||
const values: WebPageInspection["console"]["events"][number]["text_capture"]["values"] =
|
||||
[];
|
||||
let retainedBytes = 0;
|
||||
let truncatedValues = 0;
|
||||
for (const [argumentIndex, argument] of arguments_.entries()) {
|
||||
const primitive = consolePrimitive(argument);
|
||||
if (primitive === undefined) continue;
|
||||
const remaining =
|
||||
this.input.limits.max_total_console_text_bytes - this.#consoleTextBytes;
|
||||
if (remaining <= 0) {
|
||||
truncatedValues += 1;
|
||||
continue;
|
||||
}
|
||||
const bounded = boundedSensitiveText(
|
||||
primitive.text,
|
||||
Math.min(this.input.limits.max_console_text_field_bytes, remaining),
|
||||
);
|
||||
values.push({
|
||||
argument_index: argumentIndex,
|
||||
type: primitive.type,
|
||||
text: bounded.text,
|
||||
});
|
||||
retainedBytes += bounded.bytes;
|
||||
this.#consoleTextBytes += bounded.bytes;
|
||||
if (bounded.truncated) truncatedValues += 1;
|
||||
}
|
||||
if (truncatedValues > 0) this.completeness.truncate("console_text");
|
||||
return {
|
||||
status: truncatedValues > 0 ? "truncated" : "included",
|
||||
values,
|
||||
retained_bytes: retainedBytes,
|
||||
truncated_values: truncatedValues,
|
||||
};
|
||||
}
|
||||
|
||||
#websocketShape(
|
||||
payload: string,
|
||||
opcode: number,
|
||||
): WebPageInspection["network"]["websocket_events"][number]["payload_shape"] {
|
||||
if (!this.input.include_websocket_shapes) return null;
|
||||
if (opcode !== 1)
|
||||
return { format: "binary", json_shape: null, truncated: false };
|
||||
const bytes = Buffer.byteLength(payload);
|
||||
const remaining =
|
||||
this.input.limits.max_total_websocket_shape_bytes -
|
||||
this.#websocketShapeBytes;
|
||||
if (
|
||||
bytes > this.input.limits.max_websocket_shape_bytes ||
|
||||
bytes > remaining
|
||||
) {
|
||||
this.completeness.truncate("websocket_shapes");
|
||||
return { format: "text", json_shape: null, truncated: true };
|
||||
}
|
||||
this.#websocketShapeBytes += bytes;
|
||||
const shape = inferJsonShape(payload, {
|
||||
maximumBytes: this.input.limits.max_websocket_shape_bytes,
|
||||
maximumNodes: this.input.limits.max_json_shape_nodes,
|
||||
maximumDepth: this.input.limits.max_json_shape_depth,
|
||||
});
|
||||
if (shape?.truncated === true)
|
||||
this.completeness.truncate("websocket_shapes");
|
||||
return {
|
||||
format: shape === null ? "text" : "json",
|
||||
json_shape: shape,
|
||||
truncated: shape?.truncated === true,
|
||||
};
|
||||
}
|
||||
|
||||
#websocketCreated(params: UnknownRecord): void {
|
||||
const requestId = stringValue(params.requestId);
|
||||
const rawUrl = stringValue(params.url);
|
||||
if (requestId === undefined || requestId.length > 256) {
|
||||
this.completeness.exclude(
|
||||
"websocket_connections",
|
||||
"invalid_protocol_value",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (rawUrl === undefined) {
|
||||
this.completeness.exclude(
|
||||
"websocket_connections",
|
||||
"invalid_protocol_value",
|
||||
);
|
||||
return;
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
this.completeness.exclude("websocket_connections", "unsupported_url");
|
||||
return;
|
||||
}
|
||||
if (parsed.protocol === "ws:") parsed.protocol = "http:";
|
||||
else if (parsed.protocol === "wss:") parsed.protocol = "https:";
|
||||
else {
|
||||
this.completeness.exclude("websocket_connections", "unsupported_url");
|
||||
return;
|
||||
}
|
||||
if (!this.allowedOrigins.has(parsed.origin)) {
|
||||
this.completeness.exclude("websocket_connections", "disallowed_origin");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!this.allowedWebSockets.has(requestId) &&
|
||||
this.allowedWebSockets.size >= this.input.limits.max_websocket_events
|
||||
) {
|
||||
this.completeness.drop("websocket_connections");
|
||||
return;
|
||||
}
|
||||
this.allowedWebSockets.add(requestId);
|
||||
}
|
||||
|
||||
#frameNavigated(params: UnknownRecord): void {
|
||||
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;
|
||||
bodyShapes.ingestResponseBodyShape(this, requestId, value);
|
||||
}
|
||||
}
|
||||
|
||||
const firstCallFrame = (
|
||||
value: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => recordsValue(value?.callFrames)[0];
|
||||
|
||||
const initiatorLocation = (
|
||||
initiator: UnknownRecord | undefined,
|
||||
): UnknownRecord | undefined => {
|
||||
let stack = recordValue(initiator?.stack);
|
||||
for (let depth = 0; depth < 32 && stack !== undefined; depth += 1) {
|
||||
const frame = firstCallFrame(stack);
|
||||
if (frame !== undefined) return frame;
|
||||
stack = recordValue(stack.parent);
|
||||
}
|
||||
return stringValue(initiator?.url) === undefined ? undefined : initiator;
|
||||
};
|
||||
|
||||
const exclusionReasonForUrl = (
|
||||
value: string | undefined,
|
||||
): "disallowed_origin" | "unsupported_url" | "unattributed_origin" =>
|
||||
value === undefined || value === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(value)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url";
|
||||
|
||||
const integerOrNull = (value: unknown): number | null => {
|
||||
const number = numberValue(value);
|
||||
return number === undefined ? null : Math.max(0, Math.trunc(number));
|
||||
};
|
||||
|
||||
const executionContextKey = (value: unknown): string | null => {
|
||||
const identifier = numberValue(value);
|
||||
return identifier !== undefined && Number.isSafeInteger(identifier)
|
||||
? String(identifier)
|
||||
: null;
|
||||
};
|
||||
|
||||
const isJsonContentType = (headers: UnknownRecord | undefined): boolean => {
|
||||
if (headers === undefined) return false;
|
||||
for (const [name, value] of Object.entries(headers))
|
||||
if (
|
||||
name.toLowerCase() === "content-type" &&
|
||||
isJsonMediaType(stringValue(value))
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
const isJsonMediaType = (value: string | null | undefined): boolean => {
|
||||
const mediaType = value?.split(";", 1)[0]?.trim().toLowerCase();
|
||||
return (
|
||||
mediaType === "application/json" || mediaType?.endsWith("+json") === true
|
||||
);
|
||||
};
|
||||
|
||||
const consolePrimitive = (
|
||||
value: UnknownRecord,
|
||||
): { readonly type: string; readonly text: string } | undefined => {
|
||||
const type = stringValue(value.type);
|
||||
switch (type) {
|
||||
case "string":
|
||||
return typeof value.value === "string"
|
||||
? { type, text: value.value }
|
||||
: undefined;
|
||||
case "boolean":
|
||||
return typeof value.value === "boolean"
|
||||
? { type, text: String(value.value) }
|
||||
: undefined;
|
||||
case "number":
|
||||
return typeof value.value === "number"
|
||||
? { type, text: String(value.value) }
|
||||
: typeof value.unserializableValue === "string"
|
||||
? { type, text: value.unserializableValue }
|
||||
: undefined;
|
||||
case "bigint":
|
||||
return typeof value.unserializableValue === "string"
|
||||
? { type, text: value.unserializableValue }
|
||||
: undefined;
|
||||
case "undefined":
|
||||
return { type, text: "undefined" };
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const BASE64 = /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/u;
|
||||
|
||||
const decodeBase64 = (value: string): Buffer | undefined =>
|
||||
value.length % 4 === 0 && BASE64.test(value)
|
||||
? Buffer.from(value, "base64")
|
||||
: undefined;
|
||||
|
||||
@@ -34,6 +34,14 @@ interface ObservationContext {
|
||||
type EndReason = WebObservationSession["window"]["end_reason"];
|
||||
type TimelineEvent = WebObservationSession["timeline"][number];
|
||||
|
||||
interface TimelineEntryOptions {
|
||||
readonly type: TimelineEvent["type"];
|
||||
readonly params: UnknownRecord;
|
||||
readonly rawUrl?: string | null;
|
||||
readonly requestId?: string | null;
|
||||
readonly detail?: string | null;
|
||||
}
|
||||
|
||||
/** Observe external user actions without rejecting approved same-origin navigation. */
|
||||
export const observeCdpSession = async (
|
||||
context: ObservationContext,
|
||||
@@ -190,7 +198,13 @@ class TimelineCapture {
|
||||
|
||||
targetTerminated(): void {
|
||||
if (this.#endReason !== undefined) return;
|
||||
this.#add("target_terminated", {}, null, null, "target_terminated");
|
||||
this.#add({
|
||||
type: "target_terminated",
|
||||
params: {},
|
||||
rawUrl: null,
|
||||
requestId: null,
|
||||
detail: "target_terminated",
|
||||
});
|
||||
this.end("target_terminated");
|
||||
}
|
||||
|
||||
@@ -203,13 +217,13 @@ class TimelineCapture {
|
||||
if (stringValue(params.frameId) !== this.mainFrameId) return;
|
||||
const reason = safeDetail(params.reason);
|
||||
this.#pendingReload = reason === "reload";
|
||||
this.#add(
|
||||
"navigation_requested",
|
||||
this.#add({
|
||||
type: "navigation_requested",
|
||||
params,
|
||||
stringValue(params.url),
|
||||
null,
|
||||
reason,
|
||||
);
|
||||
rawUrl: stringValue(params.url) ?? null,
|
||||
requestId: null,
|
||||
detail: reason,
|
||||
});
|
||||
}
|
||||
|
||||
#navigationCommitted(params: UnknownRecord): void {
|
||||
@@ -217,13 +231,13 @@ class TimelineCapture {
|
||||
if (stringValue(frame?.id) !== this.mainFrameId) return;
|
||||
const rawUrl = stringValue(frame?.url);
|
||||
const destination = scopedUrl(rawUrl, this.allowedOrigins);
|
||||
this.#add(
|
||||
this.#pendingReload ? "same_origin_reload" : "navigation_committed",
|
||||
{ ...params, frameId: frame?.id, loaderId: frame?.loaderId },
|
||||
rawUrl,
|
||||
null,
|
||||
safeDetail(frame?.transitionType),
|
||||
);
|
||||
this.#add({
|
||||
type: this.#pendingReload ? "same_origin_reload" : "navigation_committed",
|
||||
params: { ...params, frameId: frame?.id, loaderId: frame?.loaderId },
|
||||
rawUrl: rawUrl ?? null,
|
||||
requestId: null,
|
||||
detail: safeDetail(frame?.transitionType),
|
||||
});
|
||||
this.#pendingReload = false;
|
||||
if (destination.scope === "approved") this.finalUrl = destination.url;
|
||||
else {
|
||||
@@ -237,7 +251,13 @@ class TimelineCapture {
|
||||
if (stringValue(params.frameId) !== this.mainFrameId) return;
|
||||
const rawUrl = stringValue(params.url);
|
||||
const destination = scopedUrl(rawUrl, this.allowedOrigins);
|
||||
this.#add("same_document_navigation", params, rawUrl, null, null);
|
||||
this.#add({
|
||||
type: "same_document_navigation",
|
||||
params,
|
||||
rawUrl: rawUrl ?? null,
|
||||
requestId: null,
|
||||
detail: null,
|
||||
});
|
||||
if (destination.scope === "approved") this.finalUrl = destination.url;
|
||||
else {
|
||||
this.finalUrl = null;
|
||||
@@ -255,13 +275,13 @@ class TimelineCapture {
|
||||
const request = recordValue(params.request);
|
||||
const rawUrl = stringValue(request?.url);
|
||||
const destination = scopedUrl(rawUrl, this.allowedOrigins);
|
||||
this.#add(
|
||||
"redirect",
|
||||
this.#add({
|
||||
type: "redirect",
|
||||
params,
|
||||
rawUrl,
|
||||
stringValue(params.requestId) ?? null,
|
||||
null,
|
||||
);
|
||||
rawUrl: rawUrl ?? null,
|
||||
requestId: stringValue(params.requestId) ?? null,
|
||||
detail: null,
|
||||
});
|
||||
if (destination.scope !== "approved") {
|
||||
this.completeness.exclude("timeline", "out_of_target_scope");
|
||||
this.end("target_left_scope");
|
||||
@@ -271,27 +291,34 @@ class TimelineCapture {
|
||||
#loadingFailed(params: UnknownRecord): void {
|
||||
const frame = stringValue(params.frameId);
|
||||
if (frame !== undefined && frame !== this.mainFrameId) return;
|
||||
this.#add(
|
||||
"load_failed",
|
||||
this.#add({
|
||||
type: "load_failed",
|
||||
params,
|
||||
null,
|
||||
stringValue(params.requestId) ?? null,
|
||||
safeNetworkError(params.errorText),
|
||||
);
|
||||
rawUrl: null,
|
||||
requestId: stringValue(params.requestId) ?? null,
|
||||
detail: safeNetworkError(params.errorText),
|
||||
});
|
||||
}
|
||||
|
||||
#lifecycle(params: UnknownRecord): void {
|
||||
if (stringValue(params.frameId) !== this.mainFrameId) return;
|
||||
this.#add("lifecycle", params, null, null, safeDetail(params.name));
|
||||
this.#add({
|
||||
type: "lifecycle",
|
||||
params,
|
||||
rawUrl: null,
|
||||
requestId: null,
|
||||
detail: safeDetail(params.name),
|
||||
});
|
||||
}
|
||||
|
||||
#add(
|
||||
type: TimelineEvent["type"],
|
||||
params: UnknownRecord,
|
||||
rawUrl: string | null | undefined,
|
||||
requestId: string | null,
|
||||
detail: string | null,
|
||||
): void {
|
||||
#add(options: TimelineEntryOptions): void {
|
||||
const {
|
||||
type,
|
||||
params,
|
||||
rawUrl = null,
|
||||
requestId = null,
|
||||
detail = null,
|
||||
} = options;
|
||||
const destination =
|
||||
rawUrl == null ? null : scopedUrl(rawUrl, this.allowedOrigins);
|
||||
if (this.timeline.length >= this.maximum) {
|
||||
|
||||
+10
-208
@@ -7,11 +7,7 @@ import {
|
||||
BrowserObservationError,
|
||||
type BrowserObservationOperation,
|
||||
} from "../domain/errors.js";
|
||||
import {
|
||||
reconcileCapturedWebScript,
|
||||
stableWebResources,
|
||||
stableWebScriptKey,
|
||||
} from "../domain/webInventory.js";
|
||||
import { stableWebResources } from "../domain/webInventory.js";
|
||||
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
@@ -27,19 +23,14 @@ import {
|
||||
} from "./CdpCaptureDocuments.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
delayWithCancellation,
|
||||
isHttpUrl,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
requiredRecord,
|
||||
sourceExcluded,
|
||||
sourceResult,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { captureScripts } from "./CdpPageCaptureScripts.js";
|
||||
import { captureWorkers } from "./CdpPageCaptureWorkers.js";
|
||||
import type { WebSourceMapRequest } from "./WebSourceMapFetcher.js";
|
||||
|
||||
interface CaptureContext {
|
||||
export interface CaptureContext {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string | undefined;
|
||||
readonly operation: Extract<
|
||||
@@ -77,11 +68,6 @@ export interface CapturedPage {
|
||||
readonly sourceMapRequests: readonly WebSourceMapRequest[];
|
||||
}
|
||||
|
||||
interface CapturedScripts {
|
||||
readonly inventory: WebPageInspection["scripts"];
|
||||
readonly sourceMapRequests: readonly WebSourceMapRequest[];
|
||||
}
|
||||
|
||||
/** Capture and normalize one attached page without evaluating page JavaScript. */
|
||||
export const capturePage = async (
|
||||
context: CaptureContext,
|
||||
@@ -149,15 +135,15 @@ const captureAuthorizedPage = async (
|
||||
const accessibility = await accessibilityForFrames(state, frames);
|
||||
if (accessibility.total > accessibility.nodes.length)
|
||||
state.events.completeness.truncate("accessibility");
|
||||
const scripts = await captureScripts(
|
||||
const scripts = await captureScripts({
|
||||
context,
|
||||
state.events,
|
||||
resourceCapture.items,
|
||||
events: state.events,
|
||||
rawResources: resourceCapture.items,
|
||||
resources,
|
||||
new Set(frames.map((frame) => frame.frame_id)),
|
||||
);
|
||||
frameIds: new Set(frames.map((frame) => frame.frame_id)),
|
||||
});
|
||||
const workerCapture = await captureWorkers(
|
||||
state,
|
||||
{ context, allowedOrigins, limitations, events: state.events },
|
||||
new Set(frames.map((frame) => frame.frame_id)),
|
||||
);
|
||||
if (workerCapture.total > workerCapture.items.length)
|
||||
@@ -403,130 +389,6 @@ const accessibilityForFrames = async (
|
||||
return capture;
|
||||
};
|
||||
|
||||
const captureScripts = async (
|
||||
context: CaptureContext,
|
||||
events: CdpCaptureEvents,
|
||||
rawResources: readonly CapturedResource[],
|
||||
resources: WebPageInspection["resources"],
|
||||
frameIds: ReadonlySet<string>,
|
||||
): Promise<CapturedScripts> => {
|
||||
let totalSourceBytes = 0;
|
||||
const drafts: {
|
||||
readonly item: Omit<
|
||||
WebPageInspection["scripts"]["items"][number],
|
||||
"script_key"
|
||||
>;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
}[] = [];
|
||||
for (const script of events.scripts.values()) {
|
||||
let source: WebPageInspection["scripts"]["items"][number]["source"] =
|
||||
sourceExcluded("source capture was not approved");
|
||||
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",
|
||||
);
|
||||
events.completeness.truncate("script_sources");
|
||||
} else if (
|
||||
totalSourceBytes + script.length >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
source = sourceExcluded("total script source limit reached");
|
||||
events.completeness.truncate("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",
|
||||
);
|
||||
events.completeness.truncate("script_sources");
|
||||
} else {
|
||||
source = sourceResult(content);
|
||||
totalSourceBytes += bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
const inventoryScript = {
|
||||
frame_id: events.frameForScript(script, frameIds),
|
||||
url: script.url,
|
||||
cdp_hash: script.hash,
|
||||
length: script.length,
|
||||
is_module: script.isModule,
|
||||
language: script.language,
|
||||
source_map_url: script.sourceMapUrl,
|
||||
};
|
||||
drafts.push({
|
||||
item: {
|
||||
...inventoryScript,
|
||||
origin: script.origin,
|
||||
resource_reconciliation: reconcileCapturedWebScript(
|
||||
{ ...inventoryScript, rawUrl: script.rawUrl },
|
||||
rawResources,
|
||||
resources,
|
||||
),
|
||||
source,
|
||||
},
|
||||
sourceMapRawUrl: script.sourceMapRawUrl,
|
||||
});
|
||||
}
|
||||
if (!context.input.include_script_sources)
|
||||
events.completeness.exclude(
|
||||
"script_sources",
|
||||
"not_approved",
|
||||
events.scripts.size,
|
||||
);
|
||||
const keyed = drafts.map((draft) => ({
|
||||
...draft,
|
||||
base: stableWebScriptKey(draft.item),
|
||||
}));
|
||||
keyed.sort(
|
||||
(left, right) =>
|
||||
left.base.localeCompare(right.base) ||
|
||||
sourceDigest(left.item.source).localeCompare(
|
||||
sourceDigest(right.item.source),
|
||||
) ||
|
||||
(left.item.frame_id ?? "").localeCompare(right.item.frame_id ?? ""),
|
||||
);
|
||||
const totals = new Map<string, number>();
|
||||
for (const { base } of keyed) totals.set(base, (totals.get(base) ?? 0) + 1);
|
||||
const seen = new Map<string, number>();
|
||||
const sourceMapRequests: WebSourceMapRequest[] = [];
|
||||
const items = keyed.map(({ base, item, sourceMapRawUrl }) => {
|
||||
const occurrence = (seen.get(base) ?? 0) + 1;
|
||||
seen.set(base, occurrence);
|
||||
const scriptKey =
|
||||
totals.get(base) === 1 ? base : `${base}_${String(occurrence)}`;
|
||||
if (item.source_map_url !== null && sourceMapRawUrl !== null)
|
||||
sourceMapRequests.push({
|
||||
scriptKey,
|
||||
declaredUrl: item.source_map_url,
|
||||
fetchUrl: sourceMapRawUrl,
|
||||
});
|
||||
return { script_key: scriptKey, ...item };
|
||||
});
|
||||
return {
|
||||
inventory: { total: events.scripts.size, items },
|
||||
sourceMapRequests,
|
||||
};
|
||||
};
|
||||
|
||||
const sourceDigest = (
|
||||
source: WebPageInspection["scripts"]["items"][number]["source"],
|
||||
): string => (source.included ? source.artifact.sha256 : source.reason);
|
||||
|
||||
const publicResource = ({ rawUrl: _rawUrl, ...resource }: CapturedResource) =>
|
||||
resource;
|
||||
|
||||
@@ -542,66 +404,6 @@ const deduplicatedAgentHints = (
|
||||
});
|
||||
};
|
||||
|
||||
const captureWorkers = async (
|
||||
state: CaptureState,
|
||||
frameIds: ReadonlySet<string>,
|
||||
): Promise<{
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["workers"];
|
||||
}> => {
|
||||
const { context, allowedOrigins, limitations, events } = state;
|
||||
const completeness = events.completeness;
|
||||
const result = await optionalCdpCommand(
|
||||
{ ...context, sessionId: undefined },
|
||||
"Target.getTargets",
|
||||
{},
|
||||
limitations,
|
||||
);
|
||||
const items: WebPageInspection["workers"] = [];
|
||||
let total = 0;
|
||||
if (result === undefined) completeness.unavailable("workers");
|
||||
for (const target of recordsValue(recordValue(result)?.targetInfos)) {
|
||||
const type = stringValue(target.type) ?? "";
|
||||
const url = allowedSanitizedUrl(target.url, allowedOrigins);
|
||||
const relatedToPage =
|
||||
stringValue(target.openerId) === context.target.id ||
|
||||
(stringValue(target.parentFrameId) !== undefined &&
|
||||
frameIds.has(stringValue(target.parentFrameId) ?? ""));
|
||||
if (!type.includes("worker")) continue;
|
||||
if (!relatedToPage) {
|
||||
completeness.exclude("workers", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
if (url === undefined) {
|
||||
const rawUrl = stringValue(target.url);
|
||||
completeness.exclude(
|
||||
"workers",
|
||||
rawUrl === undefined || rawUrl === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(rawUrl)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
total += 1;
|
||||
if (items.length >= context.input.limits.max_workers) continue;
|
||||
items.push({
|
||||
target_id: (stringValue(target.targetId) ?? "").slice(0, 256),
|
||||
type: type.slice(0, 100),
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
attached: target.attached === true,
|
||||
opener_target_id: boundedText(target.openerId, 256) ?? null,
|
||||
parent_frame_id: boundedText(target.parentFrameId, 256) ?? null,
|
||||
});
|
||||
}
|
||||
return {
|
||||
total,
|
||||
items,
|
||||
};
|
||||
};
|
||||
|
||||
const normalizedTarget = (
|
||||
target: CdpEndpointTarget,
|
||||
currentUrl: string,
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import type { WebPageInspection } from "../domain/browserObservation.js";
|
||||
import {
|
||||
reconcileCapturedWebScript,
|
||||
stableWebScriptKey,
|
||||
} from "../domain/webInventory.js";
|
||||
import type { CapturedResource } from "./CdpCaptureDocuments.js";
|
||||
import type { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
import type { CapturedScript } from "./CdpCaptureEventTypes.js";
|
||||
import {
|
||||
requiredRecord,
|
||||
sourceExcluded,
|
||||
sourceResult,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import type { CaptureContext } from "./CdpPageCapture.js";
|
||||
import type { WebSourceMapRequest } from "./WebSourceMapFetcher.js";
|
||||
|
||||
export interface CapturedScripts {
|
||||
readonly inventory: WebPageInspection["scripts"];
|
||||
readonly sourceMapRequests: readonly WebSourceMapRequest[];
|
||||
}
|
||||
|
||||
export interface CaptureScriptsOptions {
|
||||
readonly context: CaptureContext;
|
||||
readonly events: CdpCaptureEvents;
|
||||
readonly rawResources: readonly CapturedResource[];
|
||||
readonly resources: WebPageInspection["resources"];
|
||||
readonly frameIds: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
interface ScriptDraftState {
|
||||
readonly context: CaptureContext;
|
||||
readonly events: CdpCaptureEvents;
|
||||
readonly frameIds: ReadonlySet<string>;
|
||||
readonly rawResources: readonly CapturedResource[];
|
||||
readonly resources: WebPageInspection["resources"];
|
||||
totalSourceBytes: number;
|
||||
}
|
||||
|
||||
type ScriptDraftItem = Omit<
|
||||
WebPageInspection["scripts"]["items"][number],
|
||||
"script_key"
|
||||
>;
|
||||
|
||||
export const captureScripts = async (
|
||||
options: CaptureScriptsOptions,
|
||||
): Promise<CapturedScripts> => {
|
||||
const { context, events, rawResources, resources, frameIds } = options;
|
||||
const state: ScriptDraftState = {
|
||||
context,
|
||||
events,
|
||||
frameIds,
|
||||
rawResources,
|
||||
resources,
|
||||
totalSourceBytes: 0,
|
||||
};
|
||||
const drafts: {
|
||||
readonly item: ScriptDraftItem;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
}[] = [];
|
||||
for (const script of events.scripts.values())
|
||||
drafts.push(await buildScriptDraft(script, state));
|
||||
if (!context.input.include_script_sources)
|
||||
events.completeness.exclude(
|
||||
"script_sources",
|
||||
"not_approved",
|
||||
events.scripts.size,
|
||||
);
|
||||
return keyAndBuildInventory(drafts, events.scripts.size);
|
||||
};
|
||||
|
||||
const buildScriptDraft = async (
|
||||
script: CapturedScript,
|
||||
state: ScriptDraftState,
|
||||
): Promise<{
|
||||
readonly item: ScriptDraftItem;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
}> => {
|
||||
let source: WebPageInspection["scripts"]["items"][number]["source"] = state
|
||||
.context.input.include_script_sources
|
||||
? await captureScriptSource(script, state)
|
||||
: sourceExcluded("source capture was not approved");
|
||||
const inventoryScript = {
|
||||
frame_id: state.events.frameForScript(script, state.frameIds),
|
||||
url: script.url,
|
||||
cdp_hash: script.hash,
|
||||
length: script.length,
|
||||
is_module: script.isModule,
|
||||
language: script.language,
|
||||
source_map_url: script.sourceMapUrl,
|
||||
};
|
||||
return {
|
||||
item: {
|
||||
...inventoryScript,
|
||||
origin: script.origin,
|
||||
resource_reconciliation: reconcileCapturedWebScript(
|
||||
{ ...inventoryScript, rawUrl: script.rawUrl },
|
||||
state.rawResources,
|
||||
state.resources,
|
||||
),
|
||||
source,
|
||||
},
|
||||
sourceMapRawUrl: script.sourceMapRawUrl,
|
||||
};
|
||||
};
|
||||
|
||||
const captureScriptSource = async (
|
||||
script: CapturedScript,
|
||||
state: ScriptDraftState,
|
||||
): Promise<WebPageInspection["scripts"]["items"][number]["source"]> => {
|
||||
const { context, events } = state;
|
||||
if (script.length > context.input.limits.max_script_source_bytes) {
|
||||
events.completeness.truncate("script_sources");
|
||||
return sourceExcluded("declared script length exceeds per-script limit");
|
||||
}
|
||||
if (
|
||||
state.totalSourceBytes + script.length >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
events.completeness.truncate("script_sources");
|
||||
return sourceExcluded("total script source limit reached");
|
||||
}
|
||||
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 ||
|
||||
state.totalSourceBytes + bytes >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
events.completeness.truncate("script_sources");
|
||||
return sourceExcluded("actual source exceeds configured byte limits");
|
||||
}
|
||||
state.totalSourceBytes += bytes;
|
||||
return sourceResult(content);
|
||||
};
|
||||
|
||||
const keyAndBuildInventory = (
|
||||
drafts: readonly {
|
||||
readonly item: ScriptDraftItem;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
}[],
|
||||
scriptCount: number,
|
||||
): CapturedScripts => {
|
||||
const keyed = drafts.map((draft) => ({
|
||||
...draft,
|
||||
base: stableWebScriptKey(draft.item),
|
||||
}));
|
||||
keyed.sort(
|
||||
(left, right) =>
|
||||
left.base.localeCompare(right.base) ||
|
||||
sourceDigest(left.item.source).localeCompare(
|
||||
sourceDigest(right.item.source),
|
||||
) ||
|
||||
(left.item.frame_id ?? "").localeCompare(right.item.frame_id ?? ""),
|
||||
);
|
||||
const totals = new Map<string, number>();
|
||||
for (const { base } of keyed) totals.set(base, (totals.get(base) ?? 0) + 1);
|
||||
const seen = new Map<string, number>();
|
||||
const sourceMapRequests: WebSourceMapRequest[] = [];
|
||||
const items = keyed.map(({ base, item, sourceMapRawUrl }) => {
|
||||
const occurrence = (seen.get(base) ?? 0) + 1;
|
||||
seen.set(base, occurrence);
|
||||
const scriptKey =
|
||||
totals.get(base) === 1 ? base : `${base}_${String(occurrence)}`;
|
||||
if (item.source_map_url !== null && sourceMapRawUrl !== null)
|
||||
sourceMapRequests.push({
|
||||
scriptKey,
|
||||
declaredUrl: item.source_map_url,
|
||||
fetchUrl: sourceMapRawUrl,
|
||||
});
|
||||
return { script_key: scriptKey, ...item };
|
||||
});
|
||||
return {
|
||||
inventory: { total: scriptCount, items },
|
||||
sourceMapRequests,
|
||||
};
|
||||
};
|
||||
|
||||
const sourceDigest = (
|
||||
source: WebPageInspection["scripts"]["items"][number]["source"],
|
||||
): string => (source.included ? source.artifact.sha256 : source.reason);
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { WebPageInspection } from "../domain/browserObservation.js";
|
||||
import type { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
isHttpUrl,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import type { CaptureContext } from "./CdpPageCapture.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
|
||||
interface CaptureWorkersInput {
|
||||
readonly context: CaptureContext;
|
||||
readonly allowedOrigins: ReadonlySet<string>;
|
||||
readonly limitations: string[];
|
||||
readonly events: CdpCaptureEvents;
|
||||
}
|
||||
|
||||
export const captureWorkers = async (
|
||||
input: CaptureWorkersInput,
|
||||
frameIds: ReadonlySet<string>,
|
||||
): Promise<{
|
||||
readonly total: number;
|
||||
readonly items: WebPageInspection["workers"];
|
||||
}> => {
|
||||
const { context, allowedOrigins, limitations, events } = input;
|
||||
const completeness = events.completeness;
|
||||
const result = await optionalCdpCommand(
|
||||
{ ...context, sessionId: undefined },
|
||||
"Target.getTargets",
|
||||
{},
|
||||
limitations,
|
||||
);
|
||||
const items: WebPageInspection["workers"] = [];
|
||||
let total = 0;
|
||||
if (result === undefined) completeness.unavailable("workers");
|
||||
for (const target of recordsValue(recordValue(result)?.targetInfos)) {
|
||||
const type = stringValue(target.type) ?? "";
|
||||
const url = allowedSanitizedUrl(target.url, allowedOrigins);
|
||||
const relatedToPage =
|
||||
stringValue(target.openerId) === context.target.id ||
|
||||
(stringValue(target.parentFrameId) !== undefined &&
|
||||
frameIds.has(stringValue(target.parentFrameId) ?? ""));
|
||||
if (!type.includes("worker")) continue;
|
||||
if (!relatedToPage) {
|
||||
completeness.exclude("workers", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
if (url === undefined) {
|
||||
const rawUrl = stringValue(target.url);
|
||||
completeness.exclude(
|
||||
"workers",
|
||||
rawUrl === undefined || rawUrl === ""
|
||||
? "unattributed_origin"
|
||||
: isHttpUrl(rawUrl)
|
||||
? "disallowed_origin"
|
||||
: "unsupported_url",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
total += 1;
|
||||
if (items.length >= context.input.limits.max_workers) continue;
|
||||
items.push({
|
||||
target_id: (stringValue(target.targetId) ?? "").slice(0, 256),
|
||||
type: type.slice(0, 100),
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
attached: target.attached === true,
|
||||
opener_target_id: boundedText(target.openerId, 256) ?? null,
|
||||
parent_frame_id: boundedText(target.parentFrameId, 256) ?? null,
|
||||
});
|
||||
}
|
||||
return { total, items };
|
||||
};
|
||||
@@ -74,7 +74,13 @@ export const discoverWebMcp = async (
|
||||
const removeListener = context.connection.onEvent((event) => {
|
||||
if (event.sessionId !== context.sessionId) return;
|
||||
if (ingestFrameScopeEvent(event, frameScope)) return;
|
||||
ingestWebMcpEvent(event, context.input, frameUrls, tools, completeness);
|
||||
ingestWebMcpEvent({
|
||||
event,
|
||||
input: context.input,
|
||||
frames: frameUrls,
|
||||
tools,
|
||||
completeness,
|
||||
});
|
||||
});
|
||||
await context.progress?.report({
|
||||
phase: "browser_observation",
|
||||
@@ -100,14 +106,14 @@ export const discoverWebMcp = async (
|
||||
context.signal,
|
||||
);
|
||||
await assertStableAuthorizedFrame(context, initialUrl, origins);
|
||||
return result(
|
||||
return buildWebMcpResult({
|
||||
context,
|
||||
frameTree,
|
||||
tools,
|
||||
completeness,
|
||||
limitations,
|
||||
available,
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
removeListener();
|
||||
await context.progress?.report({
|
||||
@@ -139,20 +145,35 @@ const ingestFrameScopeEvent = (
|
||||
): boolean => {
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return false;
|
||||
if (event.method === "Page.frameDetached") {
|
||||
const frameId = stringValue(params.frameId);
|
||||
if (frameId === undefined || frameId.length > 256)
|
||||
state.completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
else removeFrame(frameId, state.frames, state.tools);
|
||||
switch (event.method) {
|
||||
case "Page.frameDetached":
|
||||
return handleFrameDetached(params, state);
|
||||
case "Page.frameNavigated":
|
||||
return handleFrameUpdate(recordValue(params.frame), state);
|
||||
case "Page.navigatedWithinDocument":
|
||||
return handleFrameUpdate(params, state);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleFrameDetached = (
|
||||
params: UnknownRecord,
|
||||
state: FrameScopeState,
|
||||
): boolean => {
|
||||
const frameId = stringValue(params.frameId);
|
||||
if (frameId === undefined || frameId.length > 256) {
|
||||
state.completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
return true;
|
||||
}
|
||||
const frame =
|
||||
event.method === "Page.frameNavigated" ? recordValue(params.frame) : params;
|
||||
if (
|
||||
event.method !== "Page.frameNavigated" &&
|
||||
event.method !== "Page.navigatedWithinDocument"
|
||||
)
|
||||
return false;
|
||||
removeFrame(frameId, state.frames, state.tools);
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleFrameUpdate = (
|
||||
frame: UnknownRecord | undefined,
|
||||
state: FrameScopeState,
|
||||
): boolean => {
|
||||
const frameId = stringValue(frame?.id) ?? stringValue(frame?.frameId);
|
||||
if (frameId === undefined || frameId.length > 256) {
|
||||
state.completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
@@ -213,16 +234,19 @@ const assertStableAuthorizedFrame = async (
|
||||
throw new BrowserObservationError("inspect_web_page", "target_changed");
|
||||
};
|
||||
|
||||
const ingestWebMcpEvent = (
|
||||
event: CdpEvent,
|
||||
input: DiscoverWebMcpToolsInput,
|
||||
frames: ReadonlyMap<
|
||||
interface WebMcpIngestOptions {
|
||||
readonly event: CdpEvent;
|
||||
readonly input: DiscoverWebMcpToolsInput;
|
||||
readonly frames: ReadonlyMap<
|
||||
string,
|
||||
{ readonly url: string; readonly origin: string | null }
|
||||
>,
|
||||
tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>,
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): void => {
|
||||
>;
|
||||
readonly tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>;
|
||||
readonly completeness: CdpCaptureCompleteness;
|
||||
}
|
||||
|
||||
const ingestWebMcpEvent = (options: WebMcpIngestOptions): void => {
|
||||
const { event, input, frames, tools, completeness } = options;
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return;
|
||||
if (event.method === "WebMCP.toolsRemoved") {
|
||||
@@ -329,14 +353,21 @@ const registrationSource = (
|
||||
};
|
||||
};
|
||||
|
||||
const result = (
|
||||
context: DiscoveryContext,
|
||||
frameTree: unknown,
|
||||
tools: ReadonlyMap<string, WebMcpDiscovery["tools"]["items"][number]>,
|
||||
completeness: CdpCaptureCompleteness,
|
||||
limitations: string[],
|
||||
available: boolean,
|
||||
): WebMcpDiscovery => {
|
||||
interface WebMcpResultOptions {
|
||||
readonly context: DiscoveryContext;
|
||||
readonly frameTree: unknown;
|
||||
readonly tools: ReadonlyMap<
|
||||
string,
|
||||
WebMcpDiscovery["tools"]["items"][number]
|
||||
>;
|
||||
readonly completeness: CdpCaptureCompleteness;
|
||||
readonly limitations: string[];
|
||||
readonly available: boolean;
|
||||
}
|
||||
|
||||
const buildWebMcpResult = (options: WebMcpResultOptions): WebMcpDiscovery => {
|
||||
const { context, frameTree, tools, completeness, limitations, available } =
|
||||
options;
|
||||
const targetUrl = mainFrameUrl(frameTree) ?? context.target.url;
|
||||
const sanitized = allowedSanitizedUrl(
|
||||
targetUrl,
|
||||
|
||||
@@ -153,13 +153,13 @@ const unfilter = (
|
||||
row > 0 && column >= channels
|
||||
? (decoded[outputOffset + column - rowBytes - channels] ?? 0)
|
||||
: 0;
|
||||
decoded[outputOffset + column] = applyFilter(
|
||||
decoded[outputOffset + column] = applyFilter({
|
||||
filter,
|
||||
source,
|
||||
left,
|
||||
above,
|
||||
upperLeft,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
if (channels === 4) return decoded;
|
||||
@@ -177,13 +177,16 @@ const unfilter = (
|
||||
return rgba;
|
||||
};
|
||||
|
||||
const applyFilter = (
|
||||
filter: number,
|
||||
source: number,
|
||||
left: number,
|
||||
above: number,
|
||||
upperLeft: number,
|
||||
): number => {
|
||||
interface ApplyFilterOptions {
|
||||
readonly filter: number;
|
||||
readonly source: number;
|
||||
readonly left: number;
|
||||
readonly above: number;
|
||||
readonly upperLeft: number;
|
||||
}
|
||||
|
||||
const applyFilter = (options: ApplyFilterOptions): number => {
|
||||
const { filter, source, left, above, upperLeft } = options;
|
||||
switch (filter) {
|
||||
case 0:
|
||||
return source;
|
||||
|
||||
+48
-136
@@ -42,14 +42,10 @@ import {
|
||||
type GhidraSessionInfo,
|
||||
} from "./GhidraSessionValues.js";
|
||||
import { createGhidraTargetSnapshot } from "./GhidraTargetSnapshot.js";
|
||||
import {
|
||||
attachGhidraSocket,
|
||||
connectGhidraSocketOnce,
|
||||
} from "./GhidraSocketConnection.js";
|
||||
import {
|
||||
observeGhidraEndpoint,
|
||||
type GhidraEndpoint,
|
||||
} from "./GhidraTransport.js";
|
||||
import { connectGhidraSocket } from "./GhidraSocketConnection.js";
|
||||
import type { GhidraEndpoint } from "./GhidraTransport.js";
|
||||
import { GhidraWire } from "./GhidraClientWire.js";
|
||||
import { completeGhidraStartupHandshake } from "./GhidraClientStartup.js";
|
||||
|
||||
const SHUTDOWN_TIMEOUT_MS = 10_000;
|
||||
const SESSION_ROOT = tmpdir();
|
||||
@@ -75,11 +71,11 @@ export class GhidraClient {
|
||||
>
|
||||
> &
|
||||
GhidraClientOptions;
|
||||
readonly #logger: Logger;
|
||||
readonly #pending = new PendingOperations<
|
||||
number,
|
||||
Result<JsonValue, GhidraSessionError>
|
||||
>();
|
||||
readonly #logger: Logger;
|
||||
#socket: Socket | undefined;
|
||||
#detachSocket: (() => void) | undefined;
|
||||
#launch: GhidraLaunch | undefined;
|
||||
@@ -96,6 +92,7 @@ export class GhidraClient {
|
||||
#startPromise: Promise<GhidraStartResult> | undefined;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
readonly #failure = bindGhidraSessionFailure(() => this.#diagnostics());
|
||||
readonly #wire: GhidraWire;
|
||||
readonly #requestQueue: GhidraRequestQueue;
|
||||
readonly #responseRouter = new GhidraResponseRouter({
|
||||
pending: this.#pending,
|
||||
@@ -122,17 +119,26 @@ export class GhidraClient {
|
||||
};
|
||||
|
||||
constructor(options: GhidraClientOptions) {
|
||||
this.#logger = options.logger ?? silentLogger;
|
||||
this.#options = {
|
||||
...options,
|
||||
requestTimeoutMs: options.requestTimeoutMs ?? GHIDRA_REQUEST_TIMEOUT_MS,
|
||||
startupTimeoutMs: options.startupTimeoutMs ?? GHIDRA_STARTUP_TIMEOUT_MS,
|
||||
transport: options.transport ?? "unix-socket",
|
||||
};
|
||||
this.#logger = options.logger ?? silentLogger;
|
||||
this.#wire = new GhidraWire({
|
||||
getSocket: () => this.#socket,
|
||||
getToken: () => this.#token,
|
||||
nextId: () => this.#nextId++,
|
||||
pending: this.#pending,
|
||||
requestTimeoutMs: this.#options.requestTimeoutMs,
|
||||
logger: this.#logger,
|
||||
failure: this.#failure,
|
||||
});
|
||||
this.#requestQueue = new GhidraRequestQueue(
|
||||
GHIDRA_MAX_QUEUED_REQUESTS,
|
||||
(method, parameters, requestOptions) =>
|
||||
this.#request(method, parameters, requestOptions),
|
||||
this.#wire.request(method, parameters, requestOptions),
|
||||
(kind, message, timeoutMs) =>
|
||||
this.#failure(
|
||||
kind,
|
||||
@@ -176,7 +182,7 @@ export class GhidraClient {
|
||||
): Promise<Result<GhidraSessionInfo, GhidraSessionError>> {
|
||||
const started = await this.start(options.signal);
|
||||
if (!started.ok) return started;
|
||||
const result = await this.#request("ping", {}, options);
|
||||
const result = await this.#wire.request("ping", {}, options);
|
||||
if (!result.ok) return result;
|
||||
return this.#parseSessionInfo(result.value);
|
||||
}
|
||||
@@ -306,128 +312,38 @@ export class GhidraClient {
|
||||
await this.#cleanup();
|
||||
return err(failure);
|
||||
}
|
||||
const ping = await this.#request(
|
||||
"ping",
|
||||
{},
|
||||
{
|
||||
signal: deadline.signal,
|
||||
timeoutMs: deadline.remainingMs(),
|
||||
},
|
||||
);
|
||||
if (!ping.ok) {
|
||||
const failure = deadline.signal.aborted
|
||||
? this.#interruptionFailure(deadline)
|
||||
: ping.error;
|
||||
await this.#cleanup();
|
||||
return err(failure);
|
||||
}
|
||||
const parsed = this.#parseSessionInfo(ping.value);
|
||||
if (!parsed.ok || parsed.value.analysis_timed_out) {
|
||||
const failure = parsed.ok
|
||||
? this.#failure(
|
||||
"analysis_timeout",
|
||||
"Ghidra auto-analysis reached its per-file deadline",
|
||||
)
|
||||
: parsed.error;
|
||||
await this.#cleanup();
|
||||
return err(failure);
|
||||
}
|
||||
return parsed;
|
||||
return completeGhidraStartupHandshake({
|
||||
deadline,
|
||||
request: (method, params, requestOptions) =>
|
||||
this.#wire.request(method, params, requestOptions),
|
||||
parseSessionInfo: (value) => this.#parseSessionInfo(value),
|
||||
cleanup: () => this.#cleanup(),
|
||||
failure: this.#failure,
|
||||
startupTimeoutMs: this.#options.startupTimeoutMs,
|
||||
});
|
||||
}
|
||||
|
||||
async #connect(
|
||||
endpoint: GhidraEndpoint,
|
||||
deadline: ProviderStartupDeadline,
|
||||
): Promise<Result<undefined, GhidraSessionError>> {
|
||||
while (deadline.remainingMs() > 0) {
|
||||
if (deadline.signal.aborted)
|
||||
return err(this.#interruptionFailure(deadline));
|
||||
if (this.#closing)
|
||||
return err(this.#failure("cancelled", "Ghidra startup was closed"));
|
||||
if (this.#processSnapshot?.exitCode !== undefined)
|
||||
return err(
|
||||
this.#failure("process", "Ghidra exited before bridge startup"),
|
||||
);
|
||||
const observed = await observeGhidraEndpoint(endpoint);
|
||||
if (!observed.ok) return observed;
|
||||
if (observed.value === null) {
|
||||
if ((await deadline.wait(50)) === "aborted")
|
||||
return err(this.#interruptionFailure(deadline));
|
||||
continue;
|
||||
}
|
||||
const connected = await connectGhidraSocketOnce(
|
||||
observed.value,
|
||||
deadline.signal,
|
||||
);
|
||||
if (connected.ok) {
|
||||
this.#socket = connected.value;
|
||||
this.#detachSocket = attachGhidraSocket(connected.value, {
|
||||
data: this.#onSocketData,
|
||||
error: this.#onSocketError,
|
||||
close: this.#onSocketClose,
|
||||
});
|
||||
return ok(undefined);
|
||||
}
|
||||
if ((await deadline.wait(50)) === "aborted")
|
||||
return err(this.#interruptionFailure(deadline));
|
||||
}
|
||||
return err(
|
||||
this.#failure("timeout", "Ghidra startup deadline elapsed", undefined, {
|
||||
timeoutMs: this.#options.startupTimeoutMs,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async #request(
|
||||
method: string,
|
||||
params: JsonValue,
|
||||
options: GhidraRequestOptions,
|
||||
): Promise<Result<JsonValue, GhidraSessionError>> {
|
||||
const socket = this.#socket;
|
||||
const token = this.#token;
|
||||
if (socket === undefined || socket.destroyed || token === undefined)
|
||||
return err(this.#failure("process", "Ghidra bridge is unavailable"));
|
||||
if (options.signal?.aborted === true)
|
||||
return err(this.#failure("cancelled", "Ghidra request was cancelled"));
|
||||
const id = this.#nextId++;
|
||||
const timeoutMs = options.timeoutMs ?? this.#options.requestTimeoutMs;
|
||||
if (timeoutMs <= 0)
|
||||
return err(
|
||||
this.#failure("timeout", "Ghidra request deadline elapsed", undefined, {
|
||||
timeoutMs,
|
||||
}),
|
||||
);
|
||||
const response = this.#pending.wait(id, {
|
||||
timeoutMs,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
timeoutValue: () =>
|
||||
err(
|
||||
this.#failure(
|
||||
"timeout",
|
||||
"Ghidra bridge request timed out",
|
||||
undefined,
|
||||
{ timeoutMs },
|
||||
),
|
||||
),
|
||||
cancelledValue: () =>
|
||||
err(this.#failure("cancelled", "Ghidra request was cancelled")),
|
||||
});
|
||||
socket.write(
|
||||
`${JSON.stringify({ id, token, method, params })}\n`,
|
||||
(cause) => {
|
||||
if (cause !== undefined && cause !== null)
|
||||
this.#pending.settle(
|
||||
id,
|
||||
err(this.#failure("process", "Ghidra bridge write failed", cause)),
|
||||
);
|
||||
const connected = await connectGhidraSocket({
|
||||
endpoint,
|
||||
deadline,
|
||||
failure: this.#failure,
|
||||
isClosed: () => this.#closing,
|
||||
processExited: () => this.#processSnapshot?.exitCode !== undefined,
|
||||
startupTimeoutMs: this.#options.startupTimeoutMs,
|
||||
handlers: {
|
||||
data: this.#onSocketData,
|
||||
error: this.#onSocketError,
|
||||
close: this.#onSocketClose,
|
||||
},
|
||||
);
|
||||
const result = await response;
|
||||
this.#logger[result.ok ? "debug" : "warn"](
|
||||
{ method, status: result.ok ? "ok" : "error" },
|
||||
"Ghidra bridge request completed",
|
||||
);
|
||||
return result;
|
||||
});
|
||||
if (!connected.ok) return connected;
|
||||
this.#socket = connected.value.socket;
|
||||
this.#detachSocket = connected.value.detach;
|
||||
return ok(undefined);
|
||||
}
|
||||
|
||||
#parseSessionInfo(value: JsonValue) {
|
||||
@@ -473,15 +389,11 @@ export class GhidraClient {
|
||||
);
|
||||
const socket = this.#socket;
|
||||
if (socket !== undefined && !socket.destroyed) {
|
||||
const shutdown = await this.#request(
|
||||
"shutdown",
|
||||
{},
|
||||
{
|
||||
timeoutMs: SHUTDOWN_TIMEOUT_MS,
|
||||
},
|
||||
).catch(() =>
|
||||
err(this.#failure("process", "Ghidra shutdown request failed")),
|
||||
);
|
||||
const shutdown = await this.#wire
|
||||
.request("shutdown", {}, { timeoutMs: SHUTDOWN_TIMEOUT_MS })
|
||||
.catch(() =>
|
||||
err(this.#failure("process", "Ghidra shutdown request failed")),
|
||||
);
|
||||
if (!shutdown.ok || !isGhidraShutdownAcknowledgement(shutdown.value))
|
||||
this.#logger.warn(
|
||||
{ status: shutdown.ok ? "invalid-acknowledgement" : "failed" },
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
import type { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
|
||||
import type { GhidraRequestOptions } from "./GhidraClientTypes.js";
|
||||
import type {
|
||||
GhidraSessionError,
|
||||
GhidraSessionErrorOptions,
|
||||
GhidraSessionFailureKind,
|
||||
} from "./GhidraSessionError.js";
|
||||
import type { GhidraSessionInfo } from "./GhidraSessionValues.js";
|
||||
|
||||
/** Inputs needed to complete the post-connection bridge handshake. */
|
||||
export interface GhidraStartupHandshakeOptions {
|
||||
readonly deadline: ProviderStartupDeadline;
|
||||
readonly request: (
|
||||
method: string,
|
||||
params: JsonValue,
|
||||
options: GhidraRequestOptions,
|
||||
) => Promise<Result<JsonValue, GhidraSessionError>>;
|
||||
readonly parseSessionInfo: (
|
||||
value: JsonValue,
|
||||
) => Result<GhidraSessionInfo, GhidraSessionError>;
|
||||
readonly cleanup: () => Promise<void>;
|
||||
readonly failure: (
|
||||
kind: GhidraSessionFailureKind,
|
||||
message: string,
|
||||
cause?: unknown,
|
||||
options?: Pick<GhidraSessionErrorOptions, "timeoutMs" | "remoteCode">,
|
||||
) => GhidraSessionError;
|
||||
readonly startupTimeoutMs: number;
|
||||
}
|
||||
|
||||
/** Ping and validate the bridge after its socket is attached. */
|
||||
export async function completeGhidraStartupHandshake(
|
||||
options: GhidraStartupHandshakeOptions,
|
||||
): Promise<Result<GhidraSessionInfo, GhidraSessionError>> {
|
||||
const ping = await options.request(
|
||||
"ping",
|
||||
{},
|
||||
{
|
||||
signal: options.deadline.signal,
|
||||
timeoutMs: options.deadline.remainingMs(),
|
||||
},
|
||||
);
|
||||
if (!ping.ok) {
|
||||
const failure = options.deadline.signal.aborted
|
||||
? interruptionFailure(options)
|
||||
: ping.error;
|
||||
await options.cleanup();
|
||||
return err(failure);
|
||||
}
|
||||
const parsed = options.parseSessionInfo(ping.value);
|
||||
if (!parsed.ok || parsed.value.analysis_timed_out) {
|
||||
const failure = parsed.ok
|
||||
? options.failure(
|
||||
"analysis_timeout",
|
||||
"Ghidra auto-analysis reached its per-file deadline",
|
||||
)
|
||||
: parsed.error;
|
||||
await options.cleanup();
|
||||
return err(failure);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
const interruptionFailure = (
|
||||
options: GhidraStartupHandshakeOptions,
|
||||
): GhidraSessionError =>
|
||||
options.deadline.cancelled
|
||||
? options.failure("cancelled", "Ghidra startup was cancelled")
|
||||
: options.failure("timeout", "Ghidra startup deadline elapsed", undefined, {
|
||||
timeoutMs: options.startupTimeoutMs,
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { Socket } from "node:net";
|
||||
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { PendingOperations } from "../process/PendingOperations.js";
|
||||
import type { GhidraRequestOptions } from "./GhidraClientTypes.js";
|
||||
import type {
|
||||
GhidraSessionError,
|
||||
GhidraSessionErrorOptions,
|
||||
GhidraSessionFailureKind,
|
||||
} from "./GhidraSessionError.js";
|
||||
|
||||
/** Dependencies needed to write one authenticated line and await its reply. */
|
||||
export interface GhidraWireOptions {
|
||||
readonly getSocket: () => Socket | undefined;
|
||||
readonly getToken: () => string | undefined;
|
||||
readonly nextId: () => number;
|
||||
readonly pending: PendingOperations<
|
||||
number,
|
||||
Result<JsonValue, GhidraSessionError>
|
||||
>;
|
||||
readonly requestTimeoutMs: number;
|
||||
readonly logger: Logger;
|
||||
readonly failure: (
|
||||
kind: GhidraSessionFailureKind,
|
||||
message: string,
|
||||
cause?: unknown,
|
||||
options?: Pick<GhidraSessionErrorOptions, "timeoutMs" | "remoteCode">,
|
||||
) => GhidraSessionError;
|
||||
}
|
||||
|
||||
/** Owns the socket write and pending-reply lifecycle for one bridge session. */
|
||||
export class GhidraWire {
|
||||
readonly #options: GhidraWireOptions;
|
||||
|
||||
constructor(options: GhidraWireOptions) {
|
||||
this.#options = options;
|
||||
}
|
||||
|
||||
/** Write one authenticated request and return its correlated reply. */
|
||||
async request(
|
||||
method: string,
|
||||
params: JsonValue,
|
||||
options: GhidraRequestOptions,
|
||||
): Promise<Result<JsonValue, GhidraSessionError>> {
|
||||
const socket = this.#options.getSocket();
|
||||
const token = this.#options.getToken();
|
||||
if (socket === undefined || socket.destroyed || token === undefined)
|
||||
return err(
|
||||
this.#options.failure("process", "Ghidra bridge is unavailable"),
|
||||
);
|
||||
if (options.signal?.aborted === true)
|
||||
return err(
|
||||
this.#options.failure("cancelled", "Ghidra request was cancelled"),
|
||||
);
|
||||
const id = this.#options.nextId();
|
||||
const timeoutMs = options.timeoutMs ?? this.#options.requestTimeoutMs;
|
||||
if (timeoutMs <= 0)
|
||||
return err(
|
||||
this.#options.failure(
|
||||
"timeout",
|
||||
"Ghidra request deadline elapsed",
|
||||
undefined,
|
||||
{ timeoutMs },
|
||||
),
|
||||
);
|
||||
const response = this.#options.pending.wait(id, {
|
||||
timeoutMs,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
timeoutValue: () =>
|
||||
err(
|
||||
this.#options.failure(
|
||||
"timeout",
|
||||
"Ghidra bridge request timed out",
|
||||
undefined,
|
||||
{ timeoutMs },
|
||||
),
|
||||
),
|
||||
cancelledValue: () =>
|
||||
err(this.#options.failure("cancelled", "Ghidra request was cancelled")),
|
||||
});
|
||||
socket.write(
|
||||
`${JSON.stringify({ id, token, method, params })}\n`,
|
||||
(cause) => {
|
||||
if (cause !== undefined && cause !== null)
|
||||
this.#options.pending.settle(
|
||||
id,
|
||||
err(
|
||||
this.#options.failure(
|
||||
"process",
|
||||
"Ghidra bridge write failed",
|
||||
cause,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
const result = await response;
|
||||
this.#options.logger[result.ok ? "debug" : "warn"](
|
||||
{ method, status: result.ok ? "ok" : "error" },
|
||||
"Ghidra bridge request completed",
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+12
-193
@@ -24,28 +24,20 @@ import {
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import {
|
||||
ENHANCED_TOOL_CONTRACTS,
|
||||
OFFICIAL_TOOL_CONTRACTS,
|
||||
} from "../contracts/toolContracts.js";
|
||||
import { GhidraClient } from "./GhidraClient.js";
|
||||
import type { GhidraClientOptions } from "./GhidraClientTypes.js";
|
||||
import {
|
||||
GHIDRA_ANALYSIS_TIMEOUT_SECONDS,
|
||||
GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS,
|
||||
GHIDRA_DECOMPILE_TIMEOUT_SECONDS,
|
||||
GHIDRA_MAX_LINE_BYTES,
|
||||
GHIDRA_REQUEST_TIMEOUT_MS,
|
||||
GHIDRA_STARTUP_TIMEOUT_MS,
|
||||
} from "./GhidraDefaults.js";
|
||||
import {
|
||||
GHIDRA_FUNCTION_OPERATIONS,
|
||||
isGhidraFunctionOperation,
|
||||
parseGhidraFunctionInput,
|
||||
parseGhidraFunctionResult,
|
||||
} from "./GhidraFunctionValues.js";
|
||||
import {
|
||||
GHIDRA_INVENTORY_OPERATIONS,
|
||||
isGhidraInventoryOperation,
|
||||
parseGhidraInventoryInput,
|
||||
parseGhidraInventoryResult,
|
||||
@@ -59,191 +51,17 @@ import {
|
||||
import { GhidraHeadlessLauncher } from "./GhidraLauncher.js";
|
||||
import { resolveGhidraAnalysisProfile } from "./GhidraAnalysisProfile.js";
|
||||
import type { GhidraSessionError } from "./GhidraSessionError.js";
|
||||
import {
|
||||
CAPABILITIES,
|
||||
WINDOWS_P0_CAPABILITIES,
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS,
|
||||
healthLimitations,
|
||||
windowsP0Limitations,
|
||||
limitationsFor,
|
||||
} from "./GhidraProviderCapabilities.js";
|
||||
|
||||
/** Public identity committed by every Ghidra-backed observation. */
|
||||
export const GHIDRA_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
|
||||
id: "ghidra",
|
||||
name: "Ghidra",
|
||||
version: null,
|
||||
});
|
||||
|
||||
const providerContractByName = new Map(
|
||||
[...OFFICIAL_TOOL_CONTRACTS, ...ENHANCED_TOOL_CONTRACTS].map((contract) => [
|
||||
contract.name,
|
||||
contract,
|
||||
]),
|
||||
);
|
||||
|
||||
/** Provider-neutral read-only contracts implemented by the Ghidra adapter. */
|
||||
export const GHIDRA_PROVIDER_TOOL_CONTRACTS = Object.freeze(
|
||||
[...GHIDRA_INVENTORY_OPERATIONS, ...GHIDRA_FUNCTION_OPERATIONS].map(
|
||||
(operation) => {
|
||||
const contract = providerContractByName.get(operation);
|
||||
if (contract === undefined)
|
||||
throw new TypeError(
|
||||
`Missing provider-neutral contract for ${operation}`,
|
||||
);
|
||||
return contract;
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const PAGINATED_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"list_names",
|
||||
"list_procedures",
|
||||
"list_strings",
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
"procedure_references",
|
||||
"analyze_function",
|
||||
]);
|
||||
const SEARCH_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
]);
|
||||
const DECOMPILE_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"procedure_pseudo_code",
|
||||
"analyze_function",
|
||||
]);
|
||||
const healthLimitations = Object.freeze([
|
||||
"The session serves operations only after default Ghidra auto-analysis completes; an analysis timeout fails the open instead of exposing partial results.",
|
||||
"The imported Program and temporary project are ephemeral, read-only to REA, and deleted on close.",
|
||||
]);
|
||||
const windowsP0Limitations = Object.freeze([
|
||||
"Windows Ghidra P0 accepts approved native x86-64 PE applications only; DLL, managed, hostile, sensitive, and mutable-path targets are unsupported.",
|
||||
"The Windows bridge uses authenticated IPv4 loopback because Node path-based IPC does not expose Java AF_UNIX sockets; the endpoint file contains no bearer token.",
|
||||
"Windows P0 process-tree cleanup uses bounded taskkill termination and does not claim Job Object ownership, private DACL enforcement, or reparse-point-safe path authority.",
|
||||
]);
|
||||
|
||||
const limitationsFor = (operation: string): readonly string[] => {
|
||||
const common = [
|
||||
...healthLimitations,
|
||||
"Default-space addresses use lowercase 0x-prefixed hexadecimal; other address spaces use <percent-encoded-space>:0x<hex>.",
|
||||
];
|
||||
switch (operation) {
|
||||
case "list_documents":
|
||||
return [
|
||||
...common,
|
||||
"A headless Ghidra session contains exactly one imported Program, unlike Hopper's multi-document GUI session.",
|
||||
];
|
||||
case "list_names":
|
||||
return [
|
||||
...common,
|
||||
"The symbol inventory includes memory and external symbols, including dynamic symbols, but excludes variable and no-address namespace records.",
|
||||
];
|
||||
case "list_procedures":
|
||||
case "procedure_address":
|
||||
return [
|
||||
...common,
|
||||
"External functions and local thunks are distinct; procedure metadata identifies both and preserves a thunk target when Ghidra resolves one.",
|
||||
];
|
||||
case "list_strings":
|
||||
return [
|
||||
...common,
|
||||
"Only Ghidra-defined string Data is observed; charset is reported, while a non-missing terminator cannot distinguish a present terminator from a fixed or Pascal layout.",
|
||||
"Returned values are bounded to 1,024 Unicode code points and mark value_truncated instead of silently crossing the wire budget.",
|
||||
];
|
||||
case "list_segments":
|
||||
return [
|
||||
...common,
|
||||
"Memory-block end addresses are exclusive; permissions come from Ghidra MemoryBlock flags rather than inference from section names.",
|
||||
];
|
||||
case "search_procedures":
|
||||
case "search_strings":
|
||||
return [
|
||||
...common,
|
||||
"Literal search enforces 1,000,000 cumulative work units; regex mode also accepts only a conservative finite Java-regex subset with 10,000 static paths and 4,096 UTF-16 code units per candidate.",
|
||||
];
|
||||
case "procedure_pseudo_code":
|
||||
return [
|
||||
...common,
|
||||
"Pseudocode is Ghidra decompiler output, not original source and not text-equivalent to Hopper output; each decompile has a 30-second native deadline.",
|
||||
"External functions and functions without an analyzable body return null; other decompiler failures remain explicit.",
|
||||
];
|
||||
case "procedure_assembly":
|
||||
return [
|
||||
...common,
|
||||
"Assembly is Ghidra Listing text and fails rather than silently truncating when the 100,000-instruction or 1 MiB wire bound is exceeded.",
|
||||
];
|
||||
case "procedure_callers":
|
||||
case "procedure_callees":
|
||||
return [
|
||||
...common,
|
||||
"Only resolved Ghidra call references are returned; unresolved computed or indirect calls remain unknown, while function classifications distinguish thunks and externals.",
|
||||
];
|
||||
case "xrefs":
|
||||
return [
|
||||
...common,
|
||||
"The direct address list projects exact Ghidra references to one address but does not expose their kinds; procedure_references and analyze_function preserve available kind metadata.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
];
|
||||
case "procedure_references":
|
||||
return [
|
||||
...common,
|
||||
"Reference kinds are direct Ghidra ReferenceManager observations; unresolved computed flows without a target are absent and remain unknown.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
"Instruction scans stop at max_instructions; a truncated scan reports an unknown total and no false continuation.",
|
||||
];
|
||||
case "analyze_function":
|
||||
return [
|
||||
...common,
|
||||
"The dossier combines Ghidra FunctionManager, Listing, ReferenceManager, BasicBlockModel, and decompiler observations; provider-specific pseudocode and assembly are not cross-provider text invariants.",
|
||||
"Resolved reference metadata identifies computed, indirect, external, call, jump, and data edges; unresolved targetless flows remain unknown, and function classifications distinguish thunks and externals.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
"The Java bridge serializes one function request per Program through a bounded 32-request queue and applies a 30-second native decompilation deadline.",
|
||||
];
|
||||
default:
|
||||
return common;
|
||||
}
|
||||
};
|
||||
const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS.map((contract) =>
|
||||
Object.freeze({
|
||||
provider: GHIDRA_PROVIDER_IDENTITY,
|
||||
operation: contract.name,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: PAGINATED_OPERATIONS.has(contract.name)
|
||||
? ("offset" as const)
|
||||
: ("none" as const),
|
||||
exhaustive: !PAGINATED_OPERATIONS.has(contract.name),
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: true,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: true,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limits: Object.freeze({
|
||||
maxResults: PAGINATED_OPERATIONS.has(contract.name)
|
||||
? SEARCH_OPERATIONS.has(contract.name)
|
||||
? 100
|
||||
: 500
|
||||
: null,
|
||||
maxPayloadBytes: GHIDRA_MAX_LINE_BYTES,
|
||||
timeoutMs: DECOMPILE_OPERATIONS.has(contract.name)
|
||||
? GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS
|
||||
: GHIDRA_REQUEST_TIMEOUT_MS,
|
||||
}),
|
||||
limitations: Object.freeze(limitationsFor(contract.name)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const WINDOWS_P0_CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
CAPABILITIES.map((capability) =>
|
||||
Object.freeze({
|
||||
...capability,
|
||||
limitations: Object.freeze([
|
||||
...capability.limitations,
|
||||
...windowsP0Limitations,
|
||||
]),
|
||||
}),
|
||||
),
|
||||
);
|
||||
export { GHIDRA_PROVIDER_IDENTITY, GHIDRA_PROVIDER_TOOL_CONTRACTS };
|
||||
|
||||
const SUPPORTED_ARCHITECTURES = new Set(["x86", "x86_64", "arm", "arm64"]);
|
||||
const SUPPORTED_FORMATS = new Set(["elf", "pe", "mach-o"]);
|
||||
@@ -417,7 +235,8 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
if (!input.ok) return input;
|
||||
const called = await client.callTool(operation, input.value, {
|
||||
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(DECOMPILE_OPERATIONS.has(operation)
|
||||
...(operation === "procedure_pseudo_code" ||
|
||||
operation === "analyze_function"
|
||||
? { timeoutMs: GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS }
|
||||
: {}),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import type {
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import {
|
||||
ENHANCED_TOOL_CONTRACTS,
|
||||
OFFICIAL_TOOL_CONTRACTS,
|
||||
} from "../contracts/toolContracts.js";
|
||||
import {
|
||||
GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS,
|
||||
GHIDRA_MAX_LINE_BYTES,
|
||||
GHIDRA_REQUEST_TIMEOUT_MS,
|
||||
} from "./GhidraDefaults.js";
|
||||
import { GHIDRA_FUNCTION_OPERATIONS } from "./GhidraFunctionValues.js";
|
||||
import { GHIDRA_INVENTORY_OPERATIONS } from "./GhidraInventoryValues.js";
|
||||
|
||||
/** Public identity committed by every Ghidra-backed observation. */
|
||||
export const GHIDRA_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
|
||||
id: "ghidra",
|
||||
name: "Ghidra",
|
||||
version: null,
|
||||
});
|
||||
|
||||
const providerContractByName = new Map(
|
||||
[...OFFICIAL_TOOL_CONTRACTS, ...ENHANCED_TOOL_CONTRACTS].map((contract) => [
|
||||
contract.name,
|
||||
contract,
|
||||
]),
|
||||
);
|
||||
|
||||
/** Provider-neutral read-only contracts implemented by the Ghidra adapter. */
|
||||
export const GHIDRA_PROVIDER_TOOL_CONTRACTS = Object.freeze(
|
||||
[...GHIDRA_INVENTORY_OPERATIONS, ...GHIDRA_FUNCTION_OPERATIONS].map(
|
||||
(operation) => {
|
||||
const contract = providerContractByName.get(operation);
|
||||
if (contract === undefined)
|
||||
throw new TypeError(
|
||||
`Missing provider-neutral contract for ${operation}`,
|
||||
);
|
||||
return contract;
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const PAGINATED_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"list_names",
|
||||
"list_procedures",
|
||||
"list_strings",
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
"procedure_references",
|
||||
"analyze_function",
|
||||
]);
|
||||
const SEARCH_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
]);
|
||||
const DECOMPILE_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"procedure_pseudo_code",
|
||||
"analyze_function",
|
||||
]);
|
||||
|
||||
/** Health limitations shared by every Ghidra-backed capability. */
|
||||
export const healthLimitations = Object.freeze([
|
||||
"The session serves operations only after default Ghidra auto-analysis completes; an analysis timeout fails the open instead of exposing partial results.",
|
||||
"The imported Program and temporary project are ephemeral, read-only to REA, and deleted on close.",
|
||||
]);
|
||||
|
||||
/** Additional limitations applied to the experimental Windows x64 P0 boundary. */
|
||||
export const windowsP0Limitations = Object.freeze([
|
||||
"Windows Ghidra P0 accepts approved native x86-64 PE applications only; DLL, managed, hostile, sensitive, and mutable-path targets are unsupported.",
|
||||
"The Windows bridge uses authenticated IPv4 loopback because Node path-based IPC does not expose Java AF_UNIX sockets; the endpoint file contains no bearer token.",
|
||||
"Windows P0 process-tree cleanup uses bounded taskkill termination and does not claim Job Object ownership, private DACL enforcement, or reparse-point-safe path authority.",
|
||||
]);
|
||||
|
||||
/** Limitation text for one admitted operation, including the common base. */
|
||||
export const limitationsFor = (operation: string): readonly string[] => {
|
||||
const common = [
|
||||
...healthLimitations,
|
||||
"Default-space addresses use lowercase 0x-prefixed hexadecimal; other address spaces use <percent-encoded-space>:0x<hex>.",
|
||||
];
|
||||
switch (operation) {
|
||||
case "list_documents":
|
||||
return [
|
||||
...common,
|
||||
"A headless Ghidra session contains exactly one imported Program, unlike Hopper's multi-document GUI session.",
|
||||
];
|
||||
case "list_names":
|
||||
return [
|
||||
...common,
|
||||
"The symbol inventory includes memory and external symbols, including dynamic symbols, but excludes variable and no-address namespace records.",
|
||||
];
|
||||
case "list_procedures":
|
||||
case "procedure_address":
|
||||
return [
|
||||
...common,
|
||||
"External functions and local thunks are distinct; procedure metadata identifies both and preserves a thunk target when Ghidra resolves one.",
|
||||
];
|
||||
case "list_strings":
|
||||
return [
|
||||
...common,
|
||||
"Only Ghidra-defined string Data is observed; charset is reported, while a non-missing terminator cannot distinguish a present terminator from a fixed or Pascal layout.",
|
||||
"Returned values are bounded to 1,024 Unicode code points and mark value_truncated instead of silently crossing the wire budget.",
|
||||
];
|
||||
case "list_segments":
|
||||
return [
|
||||
...common,
|
||||
"Memory-block end addresses are exclusive; permissions come from Ghidra MemoryBlock flags rather than inference from section names.",
|
||||
];
|
||||
case "search_procedures":
|
||||
case "search_strings":
|
||||
return [
|
||||
...common,
|
||||
"Literal search enforces 1,000,000 cumulative work units; regex mode also accepts only a conservative finite Java-regex subset with 10,000 static paths and 4,096 UTF-16 code units per candidate.",
|
||||
];
|
||||
case "procedure_pseudo_code":
|
||||
return [
|
||||
...common,
|
||||
"Pseudocode is Ghidra decompiler output, not original source and not text-equivalent to Hopper output; each decompile has a 30-second native deadline.",
|
||||
"External functions and functions without an analyzable body return null; other decompiler failures remain explicit.",
|
||||
];
|
||||
case "procedure_assembly":
|
||||
return [
|
||||
...common,
|
||||
"Assembly is Ghidra Listing text and fails rather than silently truncating when the 100,000-instruction or 1 MiB wire bound is exceeded.",
|
||||
];
|
||||
case "procedure_callers":
|
||||
case "procedure_callees":
|
||||
return [
|
||||
...common,
|
||||
"Only resolved Ghidra call references are returned; unresolved computed or indirect calls remain unknown, while function classifications distinguish thunks and externals.",
|
||||
];
|
||||
case "xrefs":
|
||||
return [
|
||||
...common,
|
||||
"The direct address list projects exact Ghidra references to one address but does not expose their kinds; procedure_references and analyze_function preserve available kind metadata.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
];
|
||||
case "procedure_references":
|
||||
return [
|
||||
...common,
|
||||
"Reference kinds are direct Ghidra ReferenceManager observations; unresolved computed flows without a target are absent and remain unknown.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
"Instruction scans stop at max_instructions; a truncated scan reports an unknown total and no false continuation.",
|
||||
];
|
||||
case "analyze_function":
|
||||
return [
|
||||
...common,
|
||||
"The dossier combines Ghidra FunctionManager, Listing, ReferenceManager, BasicBlockModel, and decompiler observations; provider-specific pseudocode and assembly are not cross-provider text invariants.",
|
||||
"Resolved reference metadata identifies computed, indirect, external, call, jump, and data edges; unresolved targetless flows remain unknown, and function classifications distinguish thunks and externals.",
|
||||
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
|
||||
"The Java bridge serializes one function request per Program through a bounded 32-request queue and applies a 30-second native decompilation deadline.",
|
||||
];
|
||||
default:
|
||||
return common;
|
||||
}
|
||||
};
|
||||
|
||||
/** Provider-neutral capabilities advertised by every non-Windows Ghidra session. */
|
||||
export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS.map((contract) =>
|
||||
Object.freeze({
|
||||
provider: GHIDRA_PROVIDER_IDENTITY,
|
||||
operation: contract.name,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: PAGINATED_OPERATIONS.has(contract.name)
|
||||
? ("offset" as const)
|
||||
: ("none" as const),
|
||||
exhaustive: !PAGINATED_OPERATIONS.has(contract.name),
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: true,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: true,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limits: Object.freeze({
|
||||
maxResults: PAGINATED_OPERATIONS.has(contract.name)
|
||||
? SEARCH_OPERATIONS.has(contract.name)
|
||||
? 100
|
||||
: 500
|
||||
: null,
|
||||
maxPayloadBytes: GHIDRA_MAX_LINE_BYTES,
|
||||
timeoutMs: DECOMPILE_OPERATIONS.has(contract.name)
|
||||
? GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS
|
||||
: GHIDRA_REQUEST_TIMEOUT_MS,
|
||||
}),
|
||||
limitations: Object.freeze(limitationsFor(contract.name)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
/** Capabilities advertised for the experimental Windows x64 P0 boundary. */
|
||||
export const WINDOWS_P0_CAPABILITIES: readonly CapabilityDescriptor[] =
|
||||
Object.freeze(
|
||||
CAPABILITIES.map((capability) =>
|
||||
Object.freeze({
|
||||
...capability,
|
||||
limitations: Object.freeze([
|
||||
...capability.limitations,
|
||||
...windowsP0Limitations,
|
||||
]),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,8 +1,17 @@
|
||||
import { createConnection, type Socket } from "node:net";
|
||||
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { GhidraSessionError } from "./GhidraSessionError.js";
|
||||
import type { GhidraConnectTarget } from "./GhidraTransport.js";
|
||||
import type { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
|
||||
import {
|
||||
GhidraSessionError,
|
||||
type GhidraSessionErrorOptions,
|
||||
type GhidraSessionFailureKind,
|
||||
} from "./GhidraSessionError.js";
|
||||
import {
|
||||
type GhidraConnectTarget,
|
||||
type GhidraEndpoint,
|
||||
observeGhidraEndpoint,
|
||||
} from "./GhidraTransport.js";
|
||||
|
||||
/** Stable listeners attached for the lifetime of one bridge socket. */
|
||||
export interface GhidraSocketHandlers {
|
||||
@@ -11,6 +20,22 @@ export interface GhidraSocketHandlers {
|
||||
readonly close: () => void;
|
||||
}
|
||||
|
||||
/** Inputs needed to poll and attach one authenticated bridge socket. */
|
||||
export interface GhidraSocketConnectOptions {
|
||||
readonly endpoint: GhidraEndpoint;
|
||||
readonly deadline: ProviderStartupDeadline;
|
||||
readonly failure: (
|
||||
kind: GhidraSessionFailureKind,
|
||||
message: string,
|
||||
cause?: unknown,
|
||||
options?: Pick<GhidraSessionErrorOptions, "timeoutMs" | "remoteCode">,
|
||||
) => GhidraSessionError;
|
||||
readonly isClosed: () => boolean;
|
||||
readonly processExited: () => boolean;
|
||||
readonly startupTimeoutMs: number;
|
||||
readonly handlers: GhidraSocketHandlers;
|
||||
}
|
||||
|
||||
/** Attach decoded bridge listeners and return an idempotent detach callback. */
|
||||
export const attachGhidraSocket = (
|
||||
socket: Socket,
|
||||
@@ -27,6 +52,49 @@ export const attachGhidraSocket = (
|
||||
};
|
||||
};
|
||||
|
||||
/** Poll the endpoint and attach the first ready bridge socket. */
|
||||
export const connectGhidraSocket = async (
|
||||
options: GhidraSocketConnectOptions,
|
||||
): Promise<
|
||||
Result<
|
||||
{ readonly socket: Socket; readonly detach: () => void },
|
||||
GhidraSessionError
|
||||
>
|
||||
> => {
|
||||
while (options.deadline.remainingMs() > 0) {
|
||||
if (options.deadline.signal.aborted)
|
||||
return err(interruptionFailure(options));
|
||||
if (options.isClosed())
|
||||
return err(options.failure("cancelled", "Ghidra startup was closed"));
|
||||
if (options.processExited())
|
||||
return err(
|
||||
options.failure("process", "Ghidra exited before bridge startup"),
|
||||
);
|
||||
const observed = await observeGhidraEndpoint(options.endpoint);
|
||||
if (!observed.ok) return observed;
|
||||
if (observed.value === null) {
|
||||
if ((await options.deadline.wait(50)) === "aborted")
|
||||
return err(interruptionFailure(options));
|
||||
continue;
|
||||
}
|
||||
const connected = await connectGhidraSocketOnce(
|
||||
observed.value,
|
||||
options.deadline.signal,
|
||||
);
|
||||
if (connected.ok) {
|
||||
const detach = attachGhidraSocket(connected.value, options.handlers);
|
||||
return ok({ socket: connected.value, detach });
|
||||
}
|
||||
if ((await options.deadline.wait(50)) === "aborted")
|
||||
return err(interruptionFailure(options));
|
||||
}
|
||||
return err(
|
||||
options.failure("timeout", "Ghidra startup deadline elapsed", undefined, {
|
||||
timeoutMs: options.startupTimeoutMs,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
/** Open one abort-aware connection to an observed local Ghidra endpoint. */
|
||||
export const connectGhidraSocketOnce = (
|
||||
target: GhidraConnectTarget,
|
||||
@@ -76,3 +144,12 @@ export const connectGhidraSocketOnce = (
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal.aborted) onAbort();
|
||||
});
|
||||
|
||||
const interruptionFailure = (
|
||||
options: GhidraSocketConnectOptions,
|
||||
): GhidraSessionError =>
|
||||
options.deadline.cancelled
|
||||
? options.failure("cancelled", "Ghidra startup was cancelled")
|
||||
: options.failure("timeout", "Ghidra startup deadline elapsed", undefined, {
|
||||
timeoutMs: options.startupTimeoutMs,
|
||||
});
|
||||
|
||||
@@ -289,69 +289,103 @@ const normalizeFactorySource = (source: string): string =>
|
||||
? source.replace(/^\s*\d+\s*\(/u, "function(")
|
||||
: source;
|
||||
|
||||
interface ProjectionContext {
|
||||
readonly maximumDepth: number;
|
||||
readonly maximumNodes: number;
|
||||
nodes: number;
|
||||
}
|
||||
|
||||
const projectValue = (
|
||||
value: unknown,
|
||||
maximumDepth: number,
|
||||
maximumNodes: number,
|
||||
): unknown =>
|
||||
projectValueRecursive(value, 0, new Set(), {
|
||||
maximumDepth,
|
||||
maximumNodes,
|
||||
nodes: 0,
|
||||
});
|
||||
|
||||
const projectValueRecursive = (
|
||||
candidate: unknown,
|
||||
depth: number,
|
||||
ancestors: Set<object>,
|
||||
context: ProjectionContext,
|
||||
): unknown => {
|
||||
let nodes = 0;
|
||||
const visit = (
|
||||
candidate: unknown,
|
||||
depth: number,
|
||||
ancestors: Set<object>,
|
||||
): unknown => {
|
||||
nodes += 1;
|
||||
if (nodes > maximumNodes || depth > maximumDepth)
|
||||
throw new RangeError("Replay result projection limit exceeded");
|
||||
if (
|
||||
candidate === null ||
|
||||
typeof candidate === "string" ||
|
||||
typeof candidate === "boolean"
|
||||
)
|
||||
return candidate;
|
||||
if (typeof candidate === "number") {
|
||||
if (!Number.isFinite(candidate))
|
||||
throw new TypeError("Non-finite replay result number");
|
||||
return candidate;
|
||||
}
|
||||
if (typeof candidate !== "object")
|
||||
throw new TypeError(
|
||||
`Unsupported replay result type: ${typeof candidate}`,
|
||||
context.nodes += 1;
|
||||
if (context.nodes > context.maximumNodes || depth > context.maximumDepth)
|
||||
throw new RangeError("Replay result projection limit exceeded");
|
||||
const leaf = projectLeaf(candidate);
|
||||
if (leaf !== undefined) return leaf;
|
||||
if (typeof candidate !== "object" || candidate === null)
|
||||
throw new TypeError(`Unsupported replay result type: ${typeof candidate}`);
|
||||
if (types.isProxy(candidate))
|
||||
throw new TypeError("Proxy replay results are unavailable");
|
||||
if (ancestors.has(candidate)) throw new TypeError("Cyclic replay result");
|
||||
ancestors.add(candidate);
|
||||
try {
|
||||
assertSupportedPrototype(candidate);
|
||||
return projectComplexValue(candidate, depth, ancestors, context);
|
||||
} finally {
|
||||
ancestors.delete(candidate);
|
||||
}
|
||||
};
|
||||
|
||||
const projectLeaf = (candidate: unknown): unknown => {
|
||||
if (
|
||||
candidate === null ||
|
||||
typeof candidate === "string" ||
|
||||
typeof candidate === "boolean"
|
||||
)
|
||||
return candidate;
|
||||
if (typeof candidate === "number") {
|
||||
if (!Number.isFinite(candidate))
|
||||
throw new TypeError("Non-finite replay result number");
|
||||
return candidate;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const assertSupportedPrototype = (candidate: object): void => {
|
||||
if (Array.isArray(candidate)) return;
|
||||
const prototype = Object.getPrototypeOf(candidate) as object | null;
|
||||
if (prototype !== null && Object.getPrototypeOf(prototype) !== null)
|
||||
throw new TypeError("Unsupported replay result prototype");
|
||||
};
|
||||
|
||||
const projectComplexValue = (
|
||||
candidate: object,
|
||||
depth: number,
|
||||
ancestors: Set<object>,
|
||||
context: ProjectionContext,
|
||||
): unknown[] | Record<string, unknown> => {
|
||||
const descriptors = Object.getOwnPropertyDescriptors(candidate);
|
||||
const output: unknown[] | Record<string, unknown> = Array.isArray(candidate)
|
||||
? []
|
||||
: {};
|
||||
for (const [key, descriptor] of Object.entries(descriptors)) {
|
||||
if (key === "length" && Array.isArray(candidate)) continue;
|
||||
if (!("value" in descriptor))
|
||||
throw new TypeError("Replay result accessors are unavailable");
|
||||
if (Array.isArray(output)) {
|
||||
if (!/^\d+$/u.test(key))
|
||||
throw new TypeError("Replay arrays may only contain indexed values");
|
||||
output[Number(key)] = projectValueRecursive(
|
||||
descriptor.value,
|
||||
depth + 1,
|
||||
ancestors,
|
||||
context,
|
||||
);
|
||||
} else {
|
||||
output[key] = projectValueRecursive(
|
||||
descriptor.value,
|
||||
depth + 1,
|
||||
ancestors,
|
||||
context,
|
||||
);
|
||||
if (types.isProxy(candidate))
|
||||
throw new TypeError("Proxy replay results are unavailable");
|
||||
if (ancestors.has(candidate)) throw new TypeError("Cyclic replay result");
|
||||
ancestors.add(candidate);
|
||||
try {
|
||||
const descriptors = Object.getOwnPropertyDescriptors(candidate);
|
||||
const output: unknown[] | Record<string, unknown> = Array.isArray(
|
||||
candidate,
|
||||
)
|
||||
? []
|
||||
: {};
|
||||
if (!Array.isArray(candidate)) {
|
||||
const prototype = Object.getPrototypeOf(candidate) as object | null;
|
||||
if (prototype !== null && Object.getPrototypeOf(prototype) !== null)
|
||||
throw new TypeError("Unsupported replay result prototype");
|
||||
}
|
||||
for (const [key, descriptor] of Object.entries(descriptors)) {
|
||||
if (key === "length" && Array.isArray(candidate)) continue;
|
||||
if (!("value" in descriptor))
|
||||
throw new TypeError("Replay result accessors are unavailable");
|
||||
if (Array.isArray(output)) {
|
||||
if (!/^\d+$/u.test(key))
|
||||
throw new TypeError(
|
||||
"Replay arrays may only contain indexed values",
|
||||
);
|
||||
output[Number(key)] = visit(descriptor.value, depth + 1, ancestors);
|
||||
} else output[key] = visit(descriptor.value, depth + 1, ancestors);
|
||||
}
|
||||
return output;
|
||||
} finally {
|
||||
ancestors.delete(candidate);
|
||||
}
|
||||
};
|
||||
return visit(value, 0, new Set());
|
||||
}
|
||||
return output;
|
||||
};
|
||||
|
||||
const exceptionOutcome = (
|
||||
|
||||
@@ -1,27 +1,37 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { open, readFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import type {
|
||||
JavaScriptReplayPolicy,
|
||||
JavaScriptReplayRunner,
|
||||
PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import {
|
||||
digestBytes,
|
||||
digestJson,
|
||||
type JavaScriptReplayPolicy,
|
||||
type JavaScriptReplayRunner,
|
||||
type PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import type { ReplayExecutionResult } from "../domain/javascriptReplay.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import {
|
||||
buildLinuxX64ReplaySeccomp,
|
||||
linuxX64ReplaySeccompDigest,
|
||||
} from "./LinuxSeccompPolicy.js";
|
||||
import { linuxX64ReplaySeccompDigest } from "./LinuxSeccompPolicy.js";
|
||||
import { resolveLinuxRuntimeClosure } from "./LinuxRuntimeClosure.js";
|
||||
import {
|
||||
assertRuntimeCommitment,
|
||||
systemdArguments,
|
||||
temporaryFilterHandle,
|
||||
type RuntimeFile,
|
||||
} from "./LinuxJavaScriptReplaySandbox.js";
|
||||
import {
|
||||
boundedCollector,
|
||||
killUnit,
|
||||
observeCleanup,
|
||||
observeUnitResult,
|
||||
type CollectedProcess,
|
||||
} from "./ReplayProcessLifecycle.js";
|
||||
import {
|
||||
commitOutcomes,
|
||||
compareOutcomes,
|
||||
terminationResult,
|
||||
workerRequest,
|
||||
} from "./ReplayOutcome.js";
|
||||
import {
|
||||
parseReplayWorkerResponse,
|
||||
type WorkerProtocolOutcome,
|
||||
type WorkerProtocolResponse,
|
||||
} from "./ReplayWorkerProtocol.js";
|
||||
|
||||
@@ -36,544 +46,263 @@ export class LinuxJavaScriptReplayRunner implements JavaScriptReplayRunner {
|
||||
signal?: AbortSignal,
|
||||
): Promise<ReplayExecutionResult> {
|
||||
if (isAborted(signal))
|
||||
return terminationResult(prepared, "", "cancelled", {
|
||||
state: "complete",
|
||||
residual_resources: [],
|
||||
return terminationResult({
|
||||
prepared,
|
||||
stderr: "",
|
||||
termination: "cancelled",
|
||||
cleanup: { state: "complete", residual_resources: [] },
|
||||
});
|
||||
const unit = `rea-replay-${randomBytes(8).toString("hex")}.service`;
|
||||
const workerPath = prepared.publicPlan.runtime.worker.path;
|
||||
const closure = await resolveLinuxRuntimeClosure(policy.nodePath);
|
||||
assertRuntimeCommitment(prepared, closure);
|
||||
if (
|
||||
digestBytes(await readFile(workerPath)) !==
|
||||
prepared.publicPlan.runtime.worker.sha256
|
||||
)
|
||||
throw new TypeError("Replay worker changed after approval");
|
||||
if (
|
||||
linuxX64ReplaySeccompDigest() !==
|
||||
prepared.publicPlan.sandbox.seccomp_sha256
|
||||
)
|
||||
throw new TypeError("Replay seccomp policy changed after approval");
|
||||
const request = workerRequest(prepared);
|
||||
const encoded = Buffer.from(JSON.stringify(request));
|
||||
if (encoded.byteLength > prepared.publicPlan.limits.protocol_bytes)
|
||||
throw new RangeError(
|
||||
"Replay worker protocol input exceeds the committed limit",
|
||||
);
|
||||
const closure = await validateReplayCommitments(prepared, policy);
|
||||
const encoded = buildWorkerPayload(prepared);
|
||||
const filter = await temporaryFilterHandle();
|
||||
const arguments_ = systemdArguments(
|
||||
unit,
|
||||
policy,
|
||||
const replayProcess = launchReplayProcess({
|
||||
prepared,
|
||||
workerPath,
|
||||
policy,
|
||||
encoded,
|
||||
closure,
|
||||
filter.path,
|
||||
);
|
||||
let child: ReturnType<typeof spawn> | undefined;
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
let cancelled = false;
|
||||
let timedOut = false;
|
||||
let terminationRequest: Promise<void> | undefined;
|
||||
const requestTermination = (): void => {
|
||||
terminationRequest ??= killUnit(policy.systemctlPath, unit);
|
||||
child?.kill("SIGKILL");
|
||||
};
|
||||
const terminate = (): void => {
|
||||
cancelled = true;
|
||||
requestTermination();
|
||||
};
|
||||
filterPath: filter.path,
|
||||
unit,
|
||||
signal,
|
||||
});
|
||||
try {
|
||||
const completion = new Promise<CollectedProcess>((resolve, reject) => {
|
||||
child = spawn(policy.systemdRunPath, arguments_, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: {
|
||||
PATH: "/usr/bin:/bin",
|
||||
LANG: "C",
|
||||
LC_ALL: "C",
|
||||
TZ: "UTC",
|
||||
...(process.env.XDG_RUNTIME_DIR === undefined
|
||||
? {}
|
||||
: { XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR }),
|
||||
...(process.env.DBUS_SESSION_BUS_ADDRESS === undefined
|
||||
? {}
|
||||
: {
|
||||
DBUS_SESSION_BUS_ADDRESS:
|
||||
process.env.DBUS_SESSION_BUS_ADDRESS,
|
||||
}),
|
||||
},
|
||||
});
|
||||
const output = boundedCollector(
|
||||
prepared.publicPlan.limits.output_bytes,
|
||||
);
|
||||
const diagnostics = boundedCollector(
|
||||
prepared.publicPlan.limits.stderr_bytes,
|
||||
);
|
||||
child.stdout?.on("data", output.append);
|
||||
child.stderr?.on("data", diagnostics.append);
|
||||
child.once("error", reject);
|
||||
child.once("close", (code, signalName) =>
|
||||
resolve({
|
||||
code,
|
||||
signal: signalName,
|
||||
stdout: output.value(),
|
||||
stderr: diagnostics.value(),
|
||||
outputExceeded: output.exceeded(),
|
||||
}),
|
||||
);
|
||||
child.stdin?.end(encoded);
|
||||
});
|
||||
signal?.addEventListener("abort", terminate, { once: true });
|
||||
if (isAborted(signal)) terminate();
|
||||
timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
requestTermination();
|
||||
}, prepared.publicPlan.limits.wall_time_ms);
|
||||
timeout.unref();
|
||||
const collected = await completion;
|
||||
if (terminationRequest !== undefined) await terminationRequest;
|
||||
const collected = await replayProcess.completion;
|
||||
if (replayProcess.terminationRequest !== undefined)
|
||||
await replayProcess.terminationRequest;
|
||||
const unitResult = await observeUnitResult(policy.systemctlPath, unit);
|
||||
const cleanup = await observeCleanup(policy.systemctlPath, unit);
|
||||
if (cancelled || timedOut)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
cancelled ? "cancelled" : "timeout",
|
||||
cleanup,
|
||||
);
|
||||
if (collected.outputExceeded)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
"protocol_error",
|
||||
cleanup,
|
||||
"Worker stdout exceeded the committed bound",
|
||||
);
|
||||
if (collected.code !== 0)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
collected.code === 137 || unitResult === "oom-kill" ? "oom" : "crash",
|
||||
cleanup,
|
||||
);
|
||||
let response: WorkerProtocolResponse;
|
||||
try {
|
||||
response = parseReplayWorkerResponse(
|
||||
JSON.parse(collected.stdout),
|
||||
prepared.publicPlan.cases,
|
||||
prepared.publicPlan.right !== undefined,
|
||||
);
|
||||
} catch {
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
"protocol_error",
|
||||
cleanup,
|
||||
);
|
||||
}
|
||||
const outcomes = commitOutcomes(response.left);
|
||||
const right =
|
||||
response.right === undefined
|
||||
? undefined
|
||||
: commitOutcomes(response.right);
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [...outcomes, ...(right ?? [])],
|
||||
...(right === undefined
|
||||
? {}
|
||||
: { comparison: compareOutcomes(outcomes, right) }),
|
||||
stderr: collected.stderr,
|
||||
termination: "completed",
|
||||
return resolveReplayResult({
|
||||
prepared,
|
||||
collected,
|
||||
unitResult,
|
||||
cleanup,
|
||||
limitations: [
|
||||
"Controlled replay observes the isolated extracted modules, not the original application runtime.",
|
||||
"Network and host filesystem access were unavailable; unsupported dependencies may change behavior.",
|
||||
],
|
||||
reproducer: null,
|
||||
};
|
||||
cancelled: replayProcess.cancelled,
|
||||
timedOut: replayProcess.timedOut,
|
||||
});
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", terminate);
|
||||
if (timeout !== undefined) clearTimeout(timeout);
|
||||
if (child !== undefined && child.exitCode === null) {
|
||||
requestTermination();
|
||||
await terminationRequest;
|
||||
signal?.removeEventListener("abort", replayProcess.terminate);
|
||||
if (replayProcess.timeout !== undefined)
|
||||
clearTimeout(replayProcess.timeout);
|
||||
if (
|
||||
replayProcess.child !== undefined &&
|
||||
replayProcess.child.exitCode === null
|
||||
) {
|
||||
replayProcess.requestTermination();
|
||||
await replayProcess.terminationRequest;
|
||||
}
|
||||
await filter.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const workerRequest = (prepared: PreparedReplayPlan) => ({
|
||||
schemaVersion: 1,
|
||||
left: workerSide(prepared.publicPlan.left, prepared.leftSources),
|
||||
...(prepared.publicPlan.right === undefined ||
|
||||
prepared.rightSources === undefined
|
||||
? {}
|
||||
: { right: workerSide(prepared.publicPlan.right, prepared.rightSources) }),
|
||||
cases: prepared.publicPlan.cases.map((item) => ({
|
||||
caseId: item.case_id,
|
||||
arguments: item.arguments,
|
||||
inputSha256: item.sha256,
|
||||
})),
|
||||
determinism: {
|
||||
clockIso: prepared.publicPlan.determinism.clock_iso,
|
||||
randomSeed: prepared.publicPlan.determinism.random_seed,
|
||||
},
|
||||
limits: {
|
||||
resultDepth: prepared.publicPlan.limits.result_depth,
|
||||
resultNodes: prepared.publicPlan.limits.result_nodes,
|
||||
exceptionBytes: Math.min(
|
||||
64 * 1024,
|
||||
prepared.publicPlan.limits.output_bytes,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
const workerSide = (
|
||||
side: PreparedReplayPlan["publicPlan"]["left"],
|
||||
sources: Readonly<Record<string, string>>,
|
||||
) => ({
|
||||
modules: side.modules.map((module) => ({
|
||||
alias: module.alias,
|
||||
format: module.format,
|
||||
dependencies: module.dependencies,
|
||||
source: sources[module.alias] ?? "",
|
||||
})),
|
||||
entryAlias: side.entry_alias,
|
||||
entryExport: side.entry_export,
|
||||
});
|
||||
|
||||
const systemdArguments = (
|
||||
unit: string,
|
||||
const validateReplayCommitments = async (
|
||||
prepared: PreparedReplayPlan,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
prepared: PreparedReplayPlan,
|
||||
workerPath: string,
|
||||
closure: readonly RuntimeFile[],
|
||||
filterPath: string,
|
||||
): string[] => {
|
||||
const limits = prepared.publicPlan.limits;
|
||||
const descriptorPaths = [
|
||||
filterPath,
|
||||
...closure.map(({ sourcePath }) => sourcePath),
|
||||
workerPath,
|
||||
];
|
||||
const workerFd = descriptorPaths.length + 2;
|
||||
const wrapper = descriptorPaths
|
||||
.map((_, index) => `exec ${String(index + 3)}<"$1"; shift`)
|
||||
.concat('exec "$@"')
|
||||
.join("\n");
|
||||
return [
|
||||
"--user",
|
||||
"--pipe",
|
||||
"--wait",
|
||||
"--service-type=exec",
|
||||
"--quiet",
|
||||
`--unit=${unit}`,
|
||||
`--property=MemoryMax=${String(limits.memory_bytes)}`,
|
||||
"--property=MemorySwapMax=0",
|
||||
`--property=TasksMax=${String(limits.tasks)}`,
|
||||
`--property=CPUQuota=${String(limits.cpu_quota_percent)}%`,
|
||||
"--property=KillMode=control-group",
|
||||
"--property=SendSIGKILL=yes",
|
||||
"--",
|
||||
policy.shellPath,
|
||||
"-c",
|
||||
wrapper,
|
||||
"rea-replay-wrapper",
|
||||
...descriptorPaths,
|
||||
policy.bubblewrapPath,
|
||||
"--unshare-all",
|
||||
"--unshare-user",
|
||||
"--disable-userns",
|
||||
"--new-session",
|
||||
"--die-with-parent",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/work",
|
||||
"--setenv",
|
||||
"TMPDIR",
|
||||
"/tmp",
|
||||
"--setenv",
|
||||
"TZ",
|
||||
"UTC",
|
||||
"--setenv",
|
||||
"LANG",
|
||||
"C",
|
||||
"--setenv",
|
||||
"LC_ALL",
|
||||
"C",
|
||||
"--tmpfs",
|
||||
"/",
|
||||
"--dir",
|
||||
"/runtime",
|
||||
"--dir",
|
||||
"/work",
|
||||
"--size",
|
||||
String(limits.tmpfs_bytes),
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
...bindArguments(closure),
|
||||
"--ro-bind-fd",
|
||||
String(workerFd),
|
||||
"/runtime/worker.js",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--remount-ro",
|
||||
"/",
|
||||
"--chdir",
|
||||
"/work",
|
||||
"--seccomp",
|
||||
"3",
|
||||
"--",
|
||||
"/runtime/node",
|
||||
`--max-old-space-size=${String(Math.max(8, Math.floor(limits.memory_bytes / 1024 / 1024 / 2)))}`,
|
||||
"--experimental-vm-modules",
|
||||
"--permission",
|
||||
"--allow-fs-read=/runtime/worker.js",
|
||||
"/runtime/worker.js",
|
||||
];
|
||||
};
|
||||
|
||||
const bindArguments = (closure: readonly RuntimeFile[]): string[] => {
|
||||
const arguments_: string[] = [];
|
||||
const directories = new Set<string>();
|
||||
for (const [index, item] of closure.entries()) {
|
||||
const destination = item.destinationPath;
|
||||
let parent = dirname(destination);
|
||||
const chain: string[] = [];
|
||||
while (parent !== "/" && !directories.has(parent)) {
|
||||
chain.push(parent);
|
||||
parent = dirname(parent);
|
||||
}
|
||||
for (const directory of chain.reverse()) {
|
||||
directories.add(directory);
|
||||
arguments_.push("--dir", directory);
|
||||
}
|
||||
arguments_.push("--ro-bind-fd", String(index + 4), destination);
|
||||
}
|
||||
return arguments_;
|
||||
};
|
||||
|
||||
type RuntimeFile = Awaited<
|
||||
ReturnType<typeof resolveLinuxRuntimeClosure>
|
||||
>[number];
|
||||
|
||||
const assertRuntimeCommitment = (
|
||||
prepared: PreparedReplayPlan,
|
||||
closure: readonly RuntimeFile[],
|
||||
): void => {
|
||||
const observed = closure.map((item) => ({
|
||||
source_path: item.sourcePath,
|
||||
destination_path: item.destinationPath,
|
||||
sha256: item.sha256,
|
||||
}));
|
||||
): Promise<readonly RuntimeFile[]> => {
|
||||
const closure = await resolveLinuxRuntimeClosure(policy.nodePath);
|
||||
assertRuntimeCommitment(prepared, closure);
|
||||
const workerPath = prepared.publicPlan.runtime.worker.path;
|
||||
if (
|
||||
digestJson(observed) !==
|
||||
digestJson(prepared.publicPlan.runtime.read_only_files)
|
||||
digestBytes(await readFile(workerPath)) !==
|
||||
prepared.publicPlan.runtime.worker.sha256
|
||||
)
|
||||
throw new TypeError("Replay runtime closure changed after approval");
|
||||
throw new TypeError("Replay worker changed after approval");
|
||||
if (
|
||||
linuxX64ReplaySeccompDigest() !== prepared.publicPlan.sandbox.seccomp_sha256
|
||||
)
|
||||
throw new TypeError("Replay seccomp policy changed after approval");
|
||||
return closure;
|
||||
};
|
||||
|
||||
const temporaryFilterHandle = async () => {
|
||||
const { mkdtemp, writeFile, rm } = await import("node:fs/promises");
|
||||
const { tmpdir } = await import("node:os");
|
||||
const { join } = await import("node:path");
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-replay-filter-"));
|
||||
const path = join(directory, "seccomp.bpf");
|
||||
await writeFile(path, buildLinuxX64ReplaySeccomp(), { mode: 0o600 });
|
||||
const handle = await open(path, "r");
|
||||
return {
|
||||
path,
|
||||
handle,
|
||||
close: async () => {
|
||||
await handle.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
const buildWorkerPayload = (prepared: PreparedReplayPlan): Buffer => {
|
||||
const request = workerRequest(prepared);
|
||||
const encoded = Buffer.from(JSON.stringify(request));
|
||||
if (encoded.byteLength > prepared.publicPlan.limits.protocol_bytes)
|
||||
throw new RangeError(
|
||||
"Replay worker protocol input exceeds the committed limit",
|
||||
);
|
||||
return encoded;
|
||||
};
|
||||
|
||||
interface CollectedProcess {
|
||||
readonly code: number | null;
|
||||
readonly signal: NodeJS.Signals | null;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly outputExceeded: boolean;
|
||||
interface LaunchReplayProcessOptions {
|
||||
readonly prepared: PreparedReplayPlan;
|
||||
readonly policy: JavaScriptReplayPolicy;
|
||||
readonly encoded: Buffer;
|
||||
readonly closure: readonly RuntimeFile[];
|
||||
readonly filterPath: string;
|
||||
readonly unit: string;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
}
|
||||
|
||||
const boundedCollector = (maximum: number) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
let overflow = false;
|
||||
interface ReplayProcess {
|
||||
readonly child: ReturnType<typeof spawn>;
|
||||
readonly completion: Promise<CollectedProcess>;
|
||||
readonly timeout: NodeJS.Timeout;
|
||||
readonly terminate: () => void;
|
||||
readonly requestTermination: () => void;
|
||||
readonly terminationRequest: Promise<void> | undefined;
|
||||
readonly cancelled: boolean;
|
||||
readonly timedOut: boolean;
|
||||
}
|
||||
|
||||
const launchReplayProcess = (
|
||||
options: LaunchReplayProcessOptions,
|
||||
): ReplayProcess => {
|
||||
const { prepared, policy, encoded, closure, filterPath, unit, signal } =
|
||||
options;
|
||||
const arguments_ = systemdArguments({
|
||||
unit,
|
||||
policy,
|
||||
prepared,
|
||||
workerPath: prepared.publicPlan.runtime.worker.path,
|
||||
closure,
|
||||
filterPath,
|
||||
});
|
||||
let child: ReturnType<typeof spawn> | undefined;
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
let cancelled = false;
|
||||
let timedOut = false;
|
||||
let terminationRequest: Promise<void> | undefined;
|
||||
const requestTermination = (): void => {
|
||||
terminationRequest ??= killUnit(policy.systemctlPath, unit);
|
||||
child?.kill("SIGKILL");
|
||||
};
|
||||
const terminate = (): void => {
|
||||
cancelled = true;
|
||||
requestTermination();
|
||||
};
|
||||
const completion = new Promise<CollectedProcess>((resolve, reject) => {
|
||||
child = spawn(policy.systemdRunPath, arguments_, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: replayProcessEnvironment(),
|
||||
});
|
||||
const output = boundedCollector(prepared.publicPlan.limits.output_bytes);
|
||||
const diagnostics = boundedCollector(
|
||||
prepared.publicPlan.limits.stderr_bytes,
|
||||
);
|
||||
child.stdout?.on("data", output.append);
|
||||
child.stderr?.on("data", diagnostics.append);
|
||||
child.once("error", reject);
|
||||
child.once("close", (code, signalName) =>
|
||||
resolve({
|
||||
code,
|
||||
signal: signalName,
|
||||
stdout: output.value(),
|
||||
stderr: diagnostics.value(),
|
||||
outputExceeded: output.exceeded(),
|
||||
}),
|
||||
);
|
||||
child.stdin?.end(encoded);
|
||||
});
|
||||
signal?.addEventListener("abort", terminate, { once: true });
|
||||
if (isAborted(signal)) terminate();
|
||||
timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
requestTermination();
|
||||
}, prepared.publicPlan.limits.wall_time_ms);
|
||||
timeout.unref();
|
||||
if (child === undefined || timeout === undefined)
|
||||
throw new TypeError("Replay process was not launched");
|
||||
return {
|
||||
append: (chunk: Buffer) => {
|
||||
const retained = chunk.subarray(0, Math.max(0, maximum - bytes));
|
||||
if (retained.byteLength > 0) chunks.push(retained);
|
||||
bytes += retained.byteLength;
|
||||
if (retained.byteLength < chunk.byteLength) overflow = true;
|
||||
child,
|
||||
completion,
|
||||
timeout,
|
||||
terminate,
|
||||
requestTermination,
|
||||
get terminationRequest() {
|
||||
return terminationRequest;
|
||||
},
|
||||
get cancelled() {
|
||||
return cancelled;
|
||||
},
|
||||
get timedOut() {
|
||||
return timedOut;
|
||||
},
|
||||
value: () => Buffer.concat(chunks).toString("utf8"),
|
||||
exceeded: () => overflow,
|
||||
};
|
||||
};
|
||||
|
||||
const collect = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
maximum: number,
|
||||
) =>
|
||||
new Promise<{ code: number | null; stdout: string; stderr: string }>(
|
||||
(resolve, reject) => {
|
||||
const child = spawn(executable, [...arguments_], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const stdout = boundedCollector(maximum);
|
||||
const stderr = boundedCollector(maximum);
|
||||
const timeout = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
||||
timeout.unref();
|
||||
child.stdout?.on("data", stdout.append);
|
||||
child.stderr?.on("data", stderr.append);
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
resolve({ code, stdout: stdout.value(), stderr: stderr.value() });
|
||||
});
|
||||
},
|
||||
);
|
||||
const replayProcessEnvironment = (): NodeJS.ProcessEnv => ({
|
||||
PATH: "/usr/bin:/bin",
|
||||
LANG: "C",
|
||||
LC_ALL: "C",
|
||||
TZ: "UTC",
|
||||
...(process.env.XDG_RUNTIME_DIR === undefined
|
||||
? {}
|
||||
: { XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR }),
|
||||
...(process.env.DBUS_SESSION_BUS_ADDRESS === undefined
|
||||
? {}
|
||||
: { DBUS_SESSION_BUS_ADDRESS: process.env.DBUS_SESSION_BUS_ADDRESS }),
|
||||
});
|
||||
|
||||
const killUnit = async (systemctl: string, unit: string): Promise<void> => {
|
||||
try {
|
||||
await collect(
|
||||
systemctl,
|
||||
["--user", "kill", "--kill-whom=all", "--signal=SIGKILL", unit],
|
||||
4096,
|
||||
);
|
||||
} catch {
|
||||
/* cleanup continues */
|
||||
}
|
||||
};
|
||||
interface ResolveReplayResultOptions {
|
||||
readonly prepared: PreparedReplayPlan;
|
||||
readonly collected: CollectedProcess;
|
||||
readonly unitResult: string;
|
||||
readonly cleanup: ReplayExecutionResult["cleanup"];
|
||||
readonly cancelled: boolean;
|
||||
readonly timedOut: boolean;
|
||||
}
|
||||
|
||||
const observeCleanup = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<ReplayExecutionResult["cleanup"]> => {
|
||||
try {
|
||||
const state = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=ActiveState", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
if (
|
||||
state.code !== 0 ||
|
||||
state.stdout.trim() === "inactive" ||
|
||||
state.stdout.trim() === "failed" ||
|
||||
state.stdout.trim().length === 0
|
||||
) {
|
||||
await collect(systemctl, ["--user", "reset-failed", unit], 4096);
|
||||
return { state: "complete", residual_resources: [] };
|
||||
}
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
} catch {
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
}
|
||||
};
|
||||
|
||||
const observeUnitResult = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<string> => {
|
||||
try {
|
||||
const result = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=Result", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
return result.stdout.trim();
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
};
|
||||
|
||||
const commitOutcomes = (
|
||||
outcomes: readonly WorkerProtocolOutcome[],
|
||||
): ReplayExecutionResult["outcomes"] =>
|
||||
outcomes.map((outcome) => {
|
||||
const semantic =
|
||||
outcome.value === undefined ? (outcome.exception ?? null) : outcome.value;
|
||||
return {
|
||||
case_id: outcome.case_id,
|
||||
outcome: outcome.outcome,
|
||||
...(outcome.value === undefined
|
||||
? {}
|
||||
: { value: jsonValueSchema.parse(outcome.value) }),
|
||||
...(outcome.exception === undefined
|
||||
? {}
|
||||
: { exception: outcome.exception }),
|
||||
input_sha256: outcome.input_sha256,
|
||||
output_sha256: digestJson(semantic),
|
||||
truncated: false,
|
||||
};
|
||||
});
|
||||
|
||||
const compareOutcomes = (
|
||||
left: ReplayExecutionResult["outcomes"],
|
||||
right: ReplayExecutionResult["outcomes"],
|
||||
): NonNullable<ReplayExecutionResult["comparison"]> =>
|
||||
left.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status:
|
||||
right[index] === undefined
|
||||
? "unknown"
|
||||
: item.outcome === right[index].outcome &&
|
||||
item.output_sha256 === right[index].output_sha256
|
||||
? "equal"
|
||||
: "changed",
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
}));
|
||||
|
||||
const terminationResult = (
|
||||
prepared: PreparedReplayPlan,
|
||||
stderr: string,
|
||||
termination: "timeout" | "oom" | "crash" | "cancelled" | "protocol_error",
|
||||
cleanup: ReplayExecutionResult["cleanup"],
|
||||
limitation?: string,
|
||||
const resolveReplayResult = (
|
||||
options: ResolveReplayResultOptions,
|
||||
): ReplayExecutionResult => {
|
||||
const outcomes = prepared.publicPlan.cases.map((item) => ({
|
||||
case_id: item.case_id,
|
||||
outcome: termination,
|
||||
input_sha256: item.sha256,
|
||||
output_sha256: null,
|
||||
truncated: termination === "protocol_error",
|
||||
}));
|
||||
const differential = prepared.publicPlan.right !== undefined;
|
||||
const { prepared, collected, unitResult, cleanup, cancelled, timedOut } =
|
||||
options;
|
||||
if (cancelled || timedOut)
|
||||
return terminationResult({
|
||||
prepared,
|
||||
stderr: collected.stderr,
|
||||
termination: cancelled ? "cancelled" : "timeout",
|
||||
cleanup,
|
||||
});
|
||||
if (collected.outputExceeded)
|
||||
return terminationResult({
|
||||
prepared,
|
||||
stderr: collected.stderr,
|
||||
termination: "protocol_error",
|
||||
cleanup,
|
||||
limitation: "Worker stdout exceeded the committed bound",
|
||||
});
|
||||
if (collected.code !== 0)
|
||||
return terminationResult({
|
||||
prepared,
|
||||
stderr: collected.stderr,
|
||||
termination:
|
||||
collected.code === 137 || unitResult === "oom-kill" ? "oom" : "crash",
|
||||
cleanup,
|
||||
});
|
||||
let response: WorkerProtocolResponse;
|
||||
try {
|
||||
const rawResponse: unknown = JSON.parse(collected.stdout);
|
||||
response = parseReplayWorkerResponse(
|
||||
rawResponse,
|
||||
prepared.publicPlan.cases,
|
||||
prepared.publicPlan.right !== undefined,
|
||||
);
|
||||
} catch {
|
||||
return terminationResult({
|
||||
prepared,
|
||||
stderr: collected.stderr,
|
||||
termination: "protocol_error",
|
||||
cleanup,
|
||||
});
|
||||
}
|
||||
const outcomes = commitOutcomes(response.left);
|
||||
const right =
|
||||
response.right === undefined ? undefined : commitOutcomes(response.right);
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [...outcomes, ...(differential ? outcomes : [])],
|
||||
...(differential
|
||||
? {
|
||||
comparison: outcomes.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status: "unknown" as const,
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
stderr,
|
||||
termination,
|
||||
outcomes: [...outcomes, ...(right ?? [])],
|
||||
...(right === undefined
|
||||
? {}
|
||||
: { comparison: compareOutcomes(outcomes, right) }),
|
||||
stderr: collected.stderr,
|
||||
termination: "completed",
|
||||
cleanup,
|
||||
limitations: [
|
||||
limitation ??
|
||||
`Replay terminated with ${termination}; the requested functional result remains unknown.`,
|
||||
"Controlled replay observes the isolated extracted modules, not the original application runtime.",
|
||||
"Network and host filesystem access were unavailable; unsupported dependencies may change behavior.",
|
||||
],
|
||||
reproducer: null,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { open } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import {
|
||||
digestJson,
|
||||
type JavaScriptReplayPolicy,
|
||||
type PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import { buildLinuxX64ReplaySeccomp } from "./LinuxSeccompPolicy.js";
|
||||
import { resolveLinuxRuntimeClosure } from "./LinuxRuntimeClosure.js";
|
||||
|
||||
export type RuntimeFile = Awaited<
|
||||
ReturnType<typeof resolveLinuxRuntimeClosure>
|
||||
>[number];
|
||||
|
||||
export interface SandboxArgumentsOptions {
|
||||
readonly unit: string;
|
||||
readonly policy: JavaScriptReplayPolicy;
|
||||
readonly prepared: PreparedReplayPlan;
|
||||
readonly workerPath: string;
|
||||
readonly closure: readonly RuntimeFile[];
|
||||
readonly filterPath: string;
|
||||
}
|
||||
|
||||
export const assertRuntimeCommitment = (
|
||||
prepared: PreparedReplayPlan,
|
||||
closure: readonly RuntimeFile[],
|
||||
): void => {
|
||||
const observed = closure.map((item) => ({
|
||||
source_path: item.sourcePath,
|
||||
destination_path: item.destinationPath,
|
||||
sha256: item.sha256,
|
||||
}));
|
||||
if (
|
||||
digestJson(observed) !==
|
||||
digestJson(prepared.publicPlan.runtime.read_only_files)
|
||||
)
|
||||
throw new TypeError("Replay runtime closure changed after approval");
|
||||
};
|
||||
|
||||
export const temporaryFilterHandle = async () => {
|
||||
const { mkdtemp, writeFile, rm } = await import("node:fs/promises");
|
||||
const { tmpdir } = await import("node:os");
|
||||
const { join } = await import("node:path");
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-replay-filter-"));
|
||||
const path = join(directory, "seccomp.bpf");
|
||||
await writeFile(path, buildLinuxX64ReplaySeccomp(), { mode: 0o600 });
|
||||
const handle = await open(path, "r");
|
||||
return {
|
||||
path,
|
||||
handle,
|
||||
close: async () => {
|
||||
await handle.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const systemdArguments = (
|
||||
options: SandboxArgumentsOptions,
|
||||
): string[] => {
|
||||
const { unit, policy, prepared, workerPath, closure, filterPath } = options;
|
||||
const limits = prepared.publicPlan.limits;
|
||||
const descriptorPaths = [
|
||||
filterPath,
|
||||
...closure.map(({ sourcePath }) => sourcePath),
|
||||
workerPath,
|
||||
];
|
||||
const workerFd = descriptorPaths.length + 2;
|
||||
const wrapper = descriptorPaths
|
||||
.map((_, index) => `exec ${String(index + 3)}<"$1"; shift`)
|
||||
.concat('exec "$@"')
|
||||
.join("\n");
|
||||
return [
|
||||
"--user",
|
||||
"--pipe",
|
||||
"--wait",
|
||||
"--service-type=exec",
|
||||
"--quiet",
|
||||
`--unit=${unit}`,
|
||||
`--property=MemoryMax=${String(limits.memory_bytes)}`,
|
||||
"--property=MemorySwapMax=0",
|
||||
`--property=TasksMax=${String(limits.tasks)}`,
|
||||
`--property=CPUQuota=${String(limits.cpu_quota_percent)}%`,
|
||||
"--property=KillMode=control-group",
|
||||
"--property=SendSIGKILL=yes",
|
||||
"--",
|
||||
policy.shellPath,
|
||||
"-c",
|
||||
wrapper,
|
||||
"rea-replay-wrapper",
|
||||
...descriptorPaths,
|
||||
policy.bubblewrapPath,
|
||||
"--unshare-all",
|
||||
"--unshare-user",
|
||||
"--disable-userns",
|
||||
"--new-session",
|
||||
"--die-with-parent",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/work",
|
||||
"--setenv",
|
||||
"TMPDIR",
|
||||
"/tmp",
|
||||
"--setenv",
|
||||
"TZ",
|
||||
"UTC",
|
||||
"--setenv",
|
||||
"LANG",
|
||||
"C",
|
||||
"--setenv",
|
||||
"LC_ALL",
|
||||
"C",
|
||||
"--tmpfs",
|
||||
"/",
|
||||
"--dir",
|
||||
"/runtime",
|
||||
"--dir",
|
||||
"/work",
|
||||
"--size",
|
||||
String(limits.tmpfs_bytes),
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
...bindArguments(closure),
|
||||
"--ro-bind-fd",
|
||||
String(workerFd),
|
||||
"/runtime/worker.js",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--remount-ro",
|
||||
"/",
|
||||
"--chdir",
|
||||
"/work",
|
||||
"--seccomp",
|
||||
"3",
|
||||
"--",
|
||||
"/runtime/node",
|
||||
`--max-old-space-size=${String(
|
||||
Math.max(8, Math.floor(limits.memory_bytes / 1024 / 1024 / 2)),
|
||||
)}`,
|
||||
"--experimental-vm-modules",
|
||||
"--permission",
|
||||
"--allow-fs-read=/runtime/worker.js",
|
||||
"/runtime/worker.js",
|
||||
];
|
||||
};
|
||||
|
||||
const bindArguments = (closure: readonly RuntimeFile[]): string[] => {
|
||||
const arguments_: string[] = [];
|
||||
const directories = new Set<string>();
|
||||
for (const [index, item] of closure.entries()) {
|
||||
const destination = item.destinationPath;
|
||||
let parent = dirname(destination);
|
||||
const chain: string[] = [];
|
||||
while (parent !== "/" && !directories.has(parent)) {
|
||||
chain.push(parent);
|
||||
parent = dirname(parent);
|
||||
}
|
||||
for (const directory of chain.reverse()) {
|
||||
directories.add(directory);
|
||||
arguments_.push("--dir", directory);
|
||||
}
|
||||
arguments_.push("--ro-bind-fd", String(index + 4), destination);
|
||||
}
|
||||
return arguments_;
|
||||
};
|
||||
@@ -0,0 +1,135 @@
|
||||
import {
|
||||
digestJson,
|
||||
type PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import type { ReplayExecutionResult } from "../domain/javascriptReplay.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import type { WorkerProtocolOutcome } from "./ReplayWorkerProtocol.js";
|
||||
|
||||
export const workerRequest = (prepared: PreparedReplayPlan) => ({
|
||||
schemaVersion: 1,
|
||||
left: workerSide(prepared.publicPlan.left, prepared.leftSources),
|
||||
...(prepared.publicPlan.right === undefined ||
|
||||
prepared.rightSources === undefined
|
||||
? {}
|
||||
: { right: workerSide(prepared.publicPlan.right, prepared.rightSources) }),
|
||||
cases: prepared.publicPlan.cases.map((item) => ({
|
||||
caseId: item.case_id,
|
||||
arguments: item.arguments,
|
||||
inputSha256: item.sha256,
|
||||
})),
|
||||
determinism: {
|
||||
clockIso: prepared.publicPlan.determinism.clock_iso,
|
||||
randomSeed: prepared.publicPlan.determinism.random_seed,
|
||||
},
|
||||
limits: {
|
||||
resultDepth: prepared.publicPlan.limits.result_depth,
|
||||
resultNodes: prepared.publicPlan.limits.result_nodes,
|
||||
exceptionBytes: Math.min(
|
||||
64 * 1024,
|
||||
prepared.publicPlan.limits.output_bytes,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
const workerSide = (
|
||||
side: PreparedReplayPlan["publicPlan"]["left"],
|
||||
sources: Readonly<Record<string, string>>,
|
||||
) => ({
|
||||
modules: side.modules.map((module) => ({
|
||||
alias: module.alias,
|
||||
format: module.format,
|
||||
dependencies: module.dependencies,
|
||||
source: sources[module.alias] ?? "",
|
||||
})),
|
||||
entryAlias: side.entry_alias,
|
||||
entryExport: side.entry_export,
|
||||
});
|
||||
|
||||
export const commitOutcomes = (
|
||||
outcomes: readonly WorkerProtocolOutcome[],
|
||||
): ReplayExecutionResult["outcomes"] =>
|
||||
outcomes.map((outcome) => {
|
||||
const semantic =
|
||||
outcome.value === undefined ? (outcome.exception ?? null) : outcome.value;
|
||||
return {
|
||||
case_id: outcome.case_id,
|
||||
outcome: outcome.outcome,
|
||||
...(outcome.value === undefined
|
||||
? {}
|
||||
: { value: jsonValueSchema.parse(outcome.value) }),
|
||||
...(outcome.exception === undefined
|
||||
? {}
|
||||
: { exception: outcome.exception }),
|
||||
input_sha256: outcome.input_sha256,
|
||||
output_sha256: digestJson(semantic),
|
||||
truncated: false,
|
||||
};
|
||||
});
|
||||
|
||||
export const compareOutcomes = (
|
||||
left: ReplayExecutionResult["outcomes"],
|
||||
right: ReplayExecutionResult["outcomes"],
|
||||
): NonNullable<ReplayExecutionResult["comparison"]> =>
|
||||
left.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status:
|
||||
right[index] === undefined
|
||||
? "unknown"
|
||||
: item.outcome === right[index].outcome &&
|
||||
item.output_sha256 === right[index].output_sha256
|
||||
? "equal"
|
||||
: "changed",
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
}));
|
||||
|
||||
export interface TerminationResultOptions {
|
||||
readonly prepared: PreparedReplayPlan;
|
||||
readonly stderr: string;
|
||||
readonly termination:
|
||||
| "timeout"
|
||||
| "oom"
|
||||
| "crash"
|
||||
| "cancelled"
|
||||
| "protocol_error";
|
||||
readonly cleanup: ReplayExecutionResult["cleanup"];
|
||||
readonly limitation?: string;
|
||||
}
|
||||
|
||||
export const terminationResult = (
|
||||
options: TerminationResultOptions,
|
||||
): ReplayExecutionResult => {
|
||||
const { prepared, stderr, termination, cleanup, limitation } = options;
|
||||
const outcomes = prepared.publicPlan.cases.map((item) => ({
|
||||
case_id: item.case_id,
|
||||
outcome: termination,
|
||||
input_sha256: item.sha256,
|
||||
output_sha256: null,
|
||||
truncated: termination === "protocol_error",
|
||||
}));
|
||||
const differential = prepared.publicPlan.right !== undefined;
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [...outcomes, ...(differential ? outcomes : [])],
|
||||
...(differential
|
||||
? {
|
||||
comparison: outcomes.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status: "unknown" as const,
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
stderr,
|
||||
termination,
|
||||
cleanup,
|
||||
limitations: [
|
||||
limitation ??
|
||||
`Replay terminated with ${termination}; the requested functional result remains unknown.`,
|
||||
],
|
||||
reproducer: null,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import type { ReplayExecutionResult } from "../domain/javascriptReplay.js";
|
||||
|
||||
export interface CollectedProcess {
|
||||
readonly code: number | null;
|
||||
readonly signal: NodeJS.Signals | null;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly outputExceeded: boolean;
|
||||
}
|
||||
|
||||
export const boundedCollector = (maximum: number) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
let overflow = false;
|
||||
return {
|
||||
append: (chunk: Buffer) => {
|
||||
const retained = chunk.subarray(0, Math.max(0, maximum - bytes));
|
||||
if (retained.byteLength > 0) chunks.push(retained);
|
||||
bytes += retained.byteLength;
|
||||
if (retained.byteLength < chunk.byteLength) overflow = true;
|
||||
},
|
||||
value: () => Buffer.concat(chunks).toString("utf8"),
|
||||
exceeded: () => overflow,
|
||||
};
|
||||
};
|
||||
|
||||
export const collect = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
maximum: number,
|
||||
) =>
|
||||
new Promise<{ code: number | null; stdout: string; stderr: string }>(
|
||||
(resolve, reject) => {
|
||||
const child = spawn(executable, [...arguments_], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const stdout = boundedCollector(maximum);
|
||||
const stderr = boundedCollector(maximum);
|
||||
const timeout = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
||||
timeout.unref();
|
||||
child.stdout?.on("data", stdout.append);
|
||||
child.stderr?.on("data", stderr.append);
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
resolve({ code, stdout: stdout.value(), stderr: stderr.value() });
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const killUnit = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<void> => {
|
||||
try {
|
||||
await collect(
|
||||
systemctl,
|
||||
["--user", "kill", "--kill-whom=all", "--signal=SIGKILL", unit],
|
||||
4096,
|
||||
);
|
||||
} catch {
|
||||
/* cleanup continues */
|
||||
}
|
||||
};
|
||||
|
||||
export const observeCleanup = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<ReplayExecutionResult["cleanup"]> => {
|
||||
try {
|
||||
const state = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=ActiveState", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
const activeState = state.stdout.trim();
|
||||
if (
|
||||
state.code !== 0 ||
|
||||
activeState === "inactive" ||
|
||||
activeState === "failed" ||
|
||||
activeState.length === 0
|
||||
) {
|
||||
await collect(systemctl, ["--user", "reset-failed", unit], 4096);
|
||||
return { state: "complete", residual_resources: [] };
|
||||
}
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
} catch {
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
}
|
||||
};
|
||||
|
||||
export const observeUnitResult = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<string> => {
|
||||
try {
|
||||
const result = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=Result", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
return result.stdout.trim();
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user