refactor: give Inspector its own capability directory (#869)
This commit is contained in:
@@ -1,34 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
authorizeRuntimeLocation,
|
||||
inspectorExclusionKey,
|
||||
} from "./JavaScriptRuntimeScope.js";
|
||||
|
||||
describe("runtime location authorization", () => {
|
||||
it("reports canonical exclusion reasons per denial case", async () => {
|
||||
expect(await authorizeRuntimeLocation("not a url")).toEqual({
|
||||
allowed: false,
|
||||
reason: "unsupported_url",
|
||||
});
|
||||
expect(await authorizeRuntimeLocation("ftp://example.test/app.js")).toEqual(
|
||||
{
|
||||
allowed: false,
|
||||
reason: "unsupported_url",
|
||||
},
|
||||
);
|
||||
expect(
|
||||
await authorizeRuntimeLocation("file:///outside-approved-scope.js"),
|
||||
).toEqual({ allowed: false, reason: "not_approved" });
|
||||
});
|
||||
|
||||
it("collapses every canonical denial onto the fixed wire bucket", () => {
|
||||
expect(inspectorExclusionKey("unsupported_url")).toBe(
|
||||
"unsupported_location",
|
||||
);
|
||||
expect(inspectorExclusionKey("not_approved")).toBe("unsupported_location");
|
||||
expect(inspectorExclusionKey("disallowed_origin")).toBe(
|
||||
"unsupported_location",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,112 +0,0 @@
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import {
|
||||
browserOriginSchema,
|
||||
sanitizeBrowserUrl,
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { BrowserExclusionReason } from "../domain/browserCompleteness.js";
|
||||
import type {
|
||||
JavaScriptRuntimeLocation,
|
||||
JavaScriptRuntimeTargetLocation,
|
||||
} from "../domain/javascriptRuntimeObservation.js";
|
||||
import { authorizedElectronFile } from "./ElectronFileScope.js";
|
||||
|
||||
export type RuntimeLocationDecision =
|
||||
| { readonly allowed: true; readonly location: JavaScriptRuntimeLocation }
|
||||
| {
|
||||
readonly allowed: false;
|
||||
readonly reason: BrowserExclusionReason;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wire bucket for inspector script exclusions. The V8 observation schemas
|
||||
* fix the `unsupported_location` key, so every canonical denial reason maps
|
||||
* onto it; the reason itself stays available on the decision for logs and
|
||||
* limitations text.
|
||||
*/
|
||||
export const inspectorExclusionKey = (
|
||||
reason: BrowserExclusionReason,
|
||||
): "unsupported_location" => {
|
||||
// Every canonical denial collapses onto the fixed V8 wire bucket.
|
||||
void reason;
|
||||
return "unsupported_location";
|
||||
};
|
||||
|
||||
/** Resolve a protocol location exposed by the explicitly selected Inspector endpoint. */
|
||||
export const authorizeRuntimeLocation = async (
|
||||
value: string,
|
||||
): Promise<RuntimeLocationDecision> => {
|
||||
if (value.startsWith("node:") && value.length > 0)
|
||||
return {
|
||||
allowed: true,
|
||||
location: { kind: "builtin", specifier: value },
|
||||
};
|
||||
if (value.startsWith("file:")) {
|
||||
const filePath = await authorizedElectronFile(value);
|
||||
return filePath === undefined
|
||||
? { allowed: false, reason: "not_approved" }
|
||||
: { allowed: true, location: { kind: "file", file_path: filePath } };
|
||||
}
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch (cause: unknown) {
|
||||
// Non-URL input is outside the authorized runtime scope.
|
||||
void cause;
|
||||
return { allowed: false, reason: "unsupported_url" };
|
||||
}
|
||||
if (!["http:", "https:"].includes(url.protocol))
|
||||
return { allowed: false, reason: "unsupported_url" };
|
||||
const parsedOrigin = browserOriginSchema.safeParse(url.origin);
|
||||
if (!parsedOrigin.success)
|
||||
return { allowed: false, reason: "unsupported_url" };
|
||||
return {
|
||||
allowed: true,
|
||||
location: {
|
||||
kind: "url",
|
||||
origin: parsedOrigin.data,
|
||||
sanitized_url: sanitizeBrowserUrl(value).url,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Interpret Node's lossy discovery metadata separately from scriptParsed URLs. */
|
||||
export const authorizeRuntimeTargetLocation = async (
|
||||
value: string,
|
||||
context: { readonly type: string; readonly product: string },
|
||||
): Promise<
|
||||
| {
|
||||
readonly allowed: true;
|
||||
readonly location: JavaScriptRuntimeTargetLocation;
|
||||
}
|
||||
| { readonly allowed: false; readonly reason: BrowserExclusionReason }
|
||||
> => {
|
||||
if (
|
||||
context.type !== "node" ||
|
||||
!/^node\.js\/v/iu.test(context.product) ||
|
||||
!value.startsWith("file://")
|
||||
)
|
||||
return authorizeRuntimeLocation(value);
|
||||
const reportedPath = value.slice("file://".length);
|
||||
if (!reportedPath.startsWith("/") && !/^[a-z]:[/\\_]/iu.test(reportedPath))
|
||||
return authorizeRuntimeLocation(value);
|
||||
|
||||
// Node concatenates the pathname, then replaces quotes and backslashes with
|
||||
// underscores. A remaining underscore cannot prove which pathname was used.
|
||||
if (process.platform !== "win32" && !/[_"\\]/u.test(reportedPath)) {
|
||||
if (reportedPath.startsWith("/")) {
|
||||
const decision = await authorizeRuntimeLocation(
|
||||
pathToFileURL(reportedPath).href,
|
||||
);
|
||||
if (decision.allowed) return decision;
|
||||
}
|
||||
}
|
||||
return {
|
||||
allowed: true,
|
||||
location: {
|
||||
kind: "unresolved",
|
||||
reported_url: value,
|
||||
reason: "unverifiable-file-location",
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -1,160 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import type {
|
||||
JavaScriptRuntimeLocation,
|
||||
JavaScriptRuntimeObservation,
|
||||
JavaScriptRuntimeTargetList,
|
||||
ObserveJavaScriptRuntimeInput,
|
||||
} from "../domain/javascriptRuntimeObservation.js";
|
||||
import {
|
||||
authorizeRuntimeLocation,
|
||||
inspectorExclusionKey,
|
||||
} from "./JavaScriptRuntimeScope.js";
|
||||
import type { CaptureState, ScriptDraft } from "./V8InspectorProvider.js";
|
||||
import type { AuthorizedV8InspectorTarget } from "./V8InspectorEndpoint.js";
|
||||
|
||||
type ExclusionReason = "unsupported_location";
|
||||
|
||||
/** Empty durable-location exclusion counters. */
|
||||
export const createInspectorExclusionCounts = (): Record<
|
||||
ExclusionReason,
|
||||
number
|
||||
> => ({
|
||||
unsupported_location: 0,
|
||||
});
|
||||
|
||||
/** Stable safety and protocol limitations shared by target-list Evidence. */
|
||||
export const describeInspectorTargetLimitations = (): string[] => [
|
||||
"REA attaches to an already-running exact target and never launches, resumes, evaluates, pauses, or mutates it.",
|
||||
"Only Runtime.enable and Debugger.enable are sent; source text, object values, EventEmitter activity, and Electron IPC are not inspected.",
|
||||
"The selected endpoint and target ID authorize observation; discovery file locations can remain unresolved and do not prove filesystem identity.",
|
||||
"Node discovery reports a best-effort pathname rather than an encoded file URL; lossy Windows paths and ambiguous underscores are preserved without guessing a file path.",
|
||||
"Every target exposed by the selected Inspector endpoint is eligible for observation; target IDs and locations are not authenticated as operating-system process identity.",
|
||||
"No runtime graph depth is traversed because passive Inspector events do not establish require/import caller edges.",
|
||||
];
|
||||
|
||||
interface FinalizeCaptureInput {
|
||||
readonly input: ObserveJavaScriptRuntimeInput;
|
||||
readonly runtime: JavaScriptRuntimeTargetList["runtime"];
|
||||
readonly target: AuthorizedV8InspectorTarget;
|
||||
readonly state: CaptureState;
|
||||
}
|
||||
|
||||
/** Canonically authorize, deduplicate, and sort one bounded raw capture. */
|
||||
export const finalizeInspectorCapture = async ({
|
||||
input,
|
||||
runtime,
|
||||
target,
|
||||
state,
|
||||
}: FinalizeCaptureInput): Promise<JavaScriptRuntimeObservation> => {
|
||||
const exclusions = createInspectorExclusionCounts();
|
||||
const scripts = new Map<
|
||||
string,
|
||||
JavaScriptRuntimeObservation["scripts"]["items"][number]
|
||||
>();
|
||||
for (const draft of state.scripts) {
|
||||
const decision = await authorizeRuntimeLocation(draft.rawUrl);
|
||||
if (!decision.allowed) {
|
||||
exclusions[inspectorExclusionKey(decision.reason)] += 1;
|
||||
continue;
|
||||
}
|
||||
const script = scriptFromDraft(draft, decision.location);
|
||||
scripts.set(script.script_key, script);
|
||||
}
|
||||
const items = [...scripts.values()].sort((left, right) =>
|
||||
left.script_key < right.script_key
|
||||
? -1
|
||||
: left.script_key > right.script_key
|
||||
? 1
|
||||
: 0,
|
||||
);
|
||||
const contexts = [...state.contexts.values()]
|
||||
.map((context) => ({
|
||||
context_key: context.contextKey,
|
||||
state: context.state,
|
||||
name: null,
|
||||
origin: context.origin,
|
||||
}))
|
||||
.sort((left, right) =>
|
||||
left.context_key < right.context_key
|
||||
? -1
|
||||
: left.context_key > right.context_key
|
||||
? 1
|
||||
: 0,
|
||||
);
|
||||
return {
|
||||
runtime,
|
||||
target: {
|
||||
target_id: target.id,
|
||||
protocol_type: target.type,
|
||||
attached: target.attached,
|
||||
location: target.location,
|
||||
runtime_kind: input.runtime_kind ?? "unknown",
|
||||
runtime_kind_authority:
|
||||
input.runtime_kind === undefined
|
||||
? "not-declared"
|
||||
: "caller-declared-unverified",
|
||||
},
|
||||
capture: {
|
||||
observation_ms: input.observation_ms,
|
||||
events_observed: state.eventsObserved,
|
||||
events_retained: state.eventsRetained,
|
||||
events_dropped: state.eventsDropped,
|
||||
metadata_bytes_retained: state.metadataBytes,
|
||||
truncated: state.truncated,
|
||||
truncation_reasons: [...state.truncationReasons].sort(),
|
||||
},
|
||||
scripts: {
|
||||
items,
|
||||
observed_total: state.scriptsObserved,
|
||||
excluded: {
|
||||
...exclusions,
|
||||
invalid_protocol_value: state.invalidScripts,
|
||||
},
|
||||
},
|
||||
execution_contexts: contexts,
|
||||
directly_observed: [
|
||||
"Debugger.scriptParsed established script presence within the bounded capture window.",
|
||||
"Runtime execution-context lifecycle events established context creation, destruction, or clearing.",
|
||||
],
|
||||
unavailable_without_instrumentation: [
|
||||
"require/import caller-to-callee edges",
|
||||
"EventEmitter emissions and listener invocation",
|
||||
"Electron IPC messages and handlers",
|
||||
"script unload events",
|
||||
],
|
||||
unknowns: [
|
||||
...(target.location.kind === "unresolved"
|
||||
? [
|
||||
"The discovery-reported file location cannot be verified; loaded script locations are resolved independently from Debugger.scriptParsed.",
|
||||
]
|
||||
: []),
|
||||
"Scripts collected before attachment may have been garbage-collected and therefore omitted.",
|
||||
"A bounded observation window cannot establish that an unobserved script or behavior never occurs.",
|
||||
"The declared Node/Electron process role is not authenticated by the Inspector protocol.",
|
||||
],
|
||||
limitations: describeInspectorTargetLimitations(),
|
||||
};
|
||||
};
|
||||
|
||||
const scriptFromDraft = (
|
||||
draft: ScriptDraft,
|
||||
location: JavaScriptRuntimeLocation,
|
||||
): JavaScriptRuntimeObservation["scripts"]["items"][number] => {
|
||||
const stable = JSON.stringify({
|
||||
location,
|
||||
execution_context_key: draft.executionContextKey,
|
||||
cdp_hash: draft.cdpHash,
|
||||
length: draft.length,
|
||||
is_module: draft.isModule,
|
||||
});
|
||||
return {
|
||||
script_key: `v8_script_${createHash("sha256").update(stable).digest("hex")}`,
|
||||
location,
|
||||
execution_context_key: draft.executionContextKey,
|
||||
cdp_hash: draft.cdpHash,
|
||||
length: draft.length,
|
||||
is_module: draft.isModule,
|
||||
status: "observed-loaded",
|
||||
};
|
||||
};
|
||||
@@ -1,113 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type {
|
||||
JavaScriptRuntimeTargetList,
|
||||
JavaScriptRuntimeTargetLocation,
|
||||
} from "../domain/javascriptRuntimeObservation.js";
|
||||
import { BrowserObservationError } from "../domain/browserObservationError.js";
|
||||
import { type BrowserObservationOperation } from "../domain/browserObservationErrors.js";
|
||||
import { parseCdpEndpointValue, readCdpJson } from "./CdpEndpoint.js";
|
||||
|
||||
const versionSchema = z
|
||||
.object({
|
||||
Browser: z.string().min(1),
|
||||
"Protocol-Version": z.string().min(1),
|
||||
"V8-Version": z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const targetSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
type: z.string().min(1),
|
||||
url: z.string(),
|
||||
attached: z.boolean().default(false),
|
||||
webSocketDebuggerUrl: z.string().min(1),
|
||||
})
|
||||
.passthrough();
|
||||
const targetsSchema = z.array(targetSchema);
|
||||
|
||||
export interface V8InspectorTarget {
|
||||
readonly id: string;
|
||||
readonly type: string;
|
||||
readonly url: string;
|
||||
readonly attached: boolean;
|
||||
readonly webSocketUrl: string;
|
||||
}
|
||||
|
||||
export interface V8InspectorDiscovery {
|
||||
readonly runtime: JavaScriptRuntimeTargetList["runtime"];
|
||||
readonly targets: readonly V8InspectorTarget[];
|
||||
}
|
||||
|
||||
/** Discover Node/Electron Inspector targets from one loopback endpoint. */
|
||||
export const discoverV8Inspector = async (
|
||||
endpoint: string,
|
||||
operation: BrowserObservationOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<V8InspectorDiscovery> => {
|
||||
const [versionInput, targetsInput] = await Promise.all([
|
||||
readCdpJson(new URL("/json/version", endpoint), operation, signal),
|
||||
readCdpJson(new URL("/json/list", endpoint), operation, signal),
|
||||
]);
|
||||
const version = parseCdpEndpointValue(versionSchema, versionInput, operation);
|
||||
const targets = parseCdpEndpointValue(targetsSchema, targetsInput, operation);
|
||||
return {
|
||||
runtime: {
|
||||
product: version.Browser,
|
||||
protocol_version: version["Protocol-Version"],
|
||||
v8_version: version["V8-Version"] ?? null,
|
||||
},
|
||||
targets: targets.map((target) => ({
|
||||
id: target.id,
|
||||
type: target.type,
|
||||
url: target.url,
|
||||
attached: target.attached,
|
||||
webSocketUrl: validatedInspectorWebSocket(
|
||||
endpoint,
|
||||
target.id,
|
||||
target.webSocketDebuggerUrl,
|
||||
operation,
|
||||
),
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
const validatedInspectorWebSocket = (
|
||||
endpoint: string,
|
||||
targetId: string,
|
||||
reported: string,
|
||||
operation: BrowserObservationOperation,
|
||||
): string => {
|
||||
let socket: URL;
|
||||
try {
|
||||
socket = new URL(reported);
|
||||
} catch (cause: unknown) {
|
||||
throw new BrowserObservationError(operation, "invalid_endpoint_response", {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
const trusted = new URL(endpoint);
|
||||
const allowedPaths = new Set([
|
||||
`/${targetId}`,
|
||||
`/devtools/node/${targetId}`,
|
||||
`/devtools/page/${targetId}`,
|
||||
]);
|
||||
if (
|
||||
socket.protocol !== "ws:" ||
|
||||
socket.port !== trusted.port ||
|
||||
socket.username !== "" ||
|
||||
socket.password !== "" ||
|
||||
socket.search !== "" ||
|
||||
socket.hash !== "" ||
|
||||
!allowedPaths.has(socket.pathname)
|
||||
)
|
||||
throw new BrowserObservationError(operation, "invalid_endpoint_response");
|
||||
socket.hostname = trusted.hostname;
|
||||
return socket.href;
|
||||
};
|
||||
|
||||
/** Authorized target plus its durable location. */
|
||||
export interface AuthorizedV8InspectorTarget extends V8InspectorTarget {
|
||||
readonly location: JavaScriptRuntimeTargetLocation;
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
closeInspectorConnection,
|
||||
inspectorCleanupError,
|
||||
} from "./V8InspectorProvider.js";
|
||||
|
||||
it("returns promptly on cancellation while a V8 socket close is hung", async () => {
|
||||
const controller = new AbortController();
|
||||
let closeStarted = false;
|
||||
const closing = closeInspectorConnection(
|
||||
{
|
||||
close: () => {
|
||||
closeStarted = true;
|
||||
return new Promise<void>(() => undefined);
|
||||
},
|
||||
},
|
||||
controller.signal,
|
||||
);
|
||||
|
||||
controller.abort();
|
||||
expect(closeStarted).toBe(true);
|
||||
await expect(closing).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("maps a rejected close to incomplete cleanup and preserves the primary failure", () => {
|
||||
const primary = new Error("observation failed");
|
||||
const cleanup = new Error("socket close failed");
|
||||
const error = inspectorCleanupError(primary, cleanup, true);
|
||||
|
||||
expect(error.reason).toBe("cleanup_failed");
|
||||
expect(error.cleanupIncomplete).toBe(true);
|
||||
expect(error.cleanupResources).toEqual(["browser_transport"]);
|
||||
expect(error.cause).toBeInstanceOf(AggregateError);
|
||||
if (!(error.cause instanceof AggregateError)) return;
|
||||
expect(error.cause.errors).toEqual([primary, cleanup]);
|
||||
});
|
||||
@@ -1,455 +0,0 @@
|
||||
import type {
|
||||
ExecutionOptions,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { JavaScriptRuntimeObservationPort } from "../application/JavaScriptRuntimeObservationPort.js";
|
||||
import {
|
||||
javascriptRuntimeObservationSchema,
|
||||
javascriptRuntimeTargetListSchema,
|
||||
type JavaScriptRuntimeObservation,
|
||||
type JavaScriptRuntimeTargetList,
|
||||
type ListJavaScriptRuntimeTargetsInput,
|
||||
type ObserveJavaScriptRuntimeInput,
|
||||
} from "../domain/javascriptRuntimeObservation.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { BrowserObservationError } from "../domain/browserObservationError.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { type BrowserObservationOperation } from "../domain/browserObservationErrors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
numberValue,
|
||||
recordValue,
|
||||
cdpStringValue,
|
||||
delayWithCancellation,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { CdpConnection, type CdpEvent } from "./CdpConnection.js";
|
||||
import {
|
||||
authorizeRuntimeTargetLocation,
|
||||
inspectorExclusionKey,
|
||||
} from "./JavaScriptRuntimeScope.js";
|
||||
import {
|
||||
createInspectorExclusionCounts,
|
||||
describeInspectorTargetLimitations,
|
||||
finalizeInspectorCapture,
|
||||
} from "./V8InspectorCaptureProjection.js";
|
||||
import {
|
||||
discoverV8Inspector,
|
||||
type AuthorizedV8InspectorTarget,
|
||||
type V8InspectorTarget,
|
||||
} from "./V8InspectorEndpoint.js";
|
||||
|
||||
/** Public identity committed by passive V8 Inspector observations. */
|
||||
export { V8_INSPECTOR_PROVIDER_IDENTITY } from "./providerIdentities.js";
|
||||
import { V8_INSPECTOR_PROVIDER_IDENTITY } from "./providerIdentities.js";
|
||||
|
||||
export interface ScriptDraft {
|
||||
readonly rawUrl: string;
|
||||
readonly executionContextKey: string | null;
|
||||
readonly cdpHash: string | null;
|
||||
readonly length: number;
|
||||
readonly isModule: boolean;
|
||||
}
|
||||
|
||||
export interface ContextDraft {
|
||||
readonly contextKey: string;
|
||||
state: "created" | "destroyed" | "cleared";
|
||||
readonly origin: string | null;
|
||||
}
|
||||
|
||||
export interface CaptureState {
|
||||
readonly scripts: ScriptDraft[];
|
||||
readonly contexts: Map<string, ContextDraft>;
|
||||
eventsObserved: number;
|
||||
eventsRetained: number;
|
||||
eventsDropped: number;
|
||||
metadataBytes: number;
|
||||
scriptsObserved: number;
|
||||
invalidScripts: number;
|
||||
truncated: boolean;
|
||||
readonly truncationReasons: Set<string>;
|
||||
}
|
||||
|
||||
/** Attach-only provider; sends only Runtime.enable and Debugger.enable. */
|
||||
export class V8InspectorProvider implements JavaScriptRuntimeObservationPort {
|
||||
identity(): ProviderIdentity {
|
||||
return V8_INSPECTOR_PROVIDER_IDENTITY;
|
||||
}
|
||||
|
||||
async listTargets(
|
||||
input: ListJavaScriptRuntimeTargetsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<JavaScriptRuntimeTargetList, AnalysisError>> {
|
||||
try {
|
||||
const discovery = await discoverV8Inspector(
|
||||
input.inspector_endpoint,
|
||||
"list_javascript_runtime_targets",
|
||||
options.signal,
|
||||
);
|
||||
const allowed: AuthorizedV8InspectorTarget[] = [];
|
||||
const excluded = createInspectorExclusionCounts();
|
||||
for (const target of discovery.targets) {
|
||||
const decision = await authorizeRuntimeTargetLocation(target.url, {
|
||||
type: target.type,
|
||||
product: discovery.runtime.product,
|
||||
});
|
||||
if (!decision.allowed) {
|
||||
excluded[inspectorExclusionKey(decision.reason)] += 1;
|
||||
continue;
|
||||
}
|
||||
if (decision.location.kind === "builtin") {
|
||||
excluded.unsupported_location += 1;
|
||||
continue;
|
||||
}
|
||||
allowed.push({ ...target, location: decision.location });
|
||||
}
|
||||
allowed.sort((left, right) =>
|
||||
left.id < right.id ? -1 : left.id > right.id ? 1 : 0,
|
||||
);
|
||||
return ok(
|
||||
javascriptRuntimeTargetListSchema.parse({
|
||||
runtime: discovery.runtime,
|
||||
targets: allowed.map(projectTarget),
|
||||
excluded: { ...excluded, unconnectable: 0 },
|
||||
limitations: describeInspectorTargetLimitations(),
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "list_javascript_runtime_targets"));
|
||||
}
|
||||
}
|
||||
|
||||
async observe(
|
||||
input: ObserveJavaScriptRuntimeInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<JavaScriptRuntimeObservation, AnalysisError>> {
|
||||
let connection: CdpConnection | undefined;
|
||||
let primaryFailure: unknown;
|
||||
let failed = false;
|
||||
let cleanupFailure: unknown;
|
||||
let cleanupFailed = false;
|
||||
let outcome:
|
||||
| Result<JavaScriptRuntimeObservation, AnalysisError>
|
||||
| undefined;
|
||||
try {
|
||||
const discovery = await discoverV8Inspector(
|
||||
input.inspector_endpoint,
|
||||
"observe_javascript_runtime",
|
||||
options.signal,
|
||||
);
|
||||
const target = await authorizedTarget(
|
||||
discovery.targets,
|
||||
input,
|
||||
discovery.runtime.product,
|
||||
);
|
||||
if (input.runtime_kind !== undefined)
|
||||
assertRuntimeKind(target, input.runtime_kind);
|
||||
connection = await CdpConnection.connect(
|
||||
target.webSocketUrl,
|
||||
"observe_javascript_runtime",
|
||||
options.signal,
|
||||
);
|
||||
const state = emptyCaptureState();
|
||||
const removeListener = connection.onEvent((event) =>
|
||||
ingestEvent(event, input, state),
|
||||
);
|
||||
try {
|
||||
await connection.send("Runtime.enable", {}, undefined, options.signal);
|
||||
await connection.send("Debugger.enable", {}, undefined, options.signal);
|
||||
await waitForCapture(connection, input.observation_ms, options.signal);
|
||||
} finally {
|
||||
removeListener();
|
||||
}
|
||||
const result = await finalizeInspectorCapture({
|
||||
input,
|
||||
runtime: discovery.runtime,
|
||||
target,
|
||||
state,
|
||||
});
|
||||
outcome = ok(javascriptRuntimeObservationSchema.parse(result));
|
||||
} catch (cause: unknown) {
|
||||
failed = true;
|
||||
primaryFailure = cause;
|
||||
outcome = err(providerError(cause, "observe_javascript_runtime"));
|
||||
} finally {
|
||||
if (connection !== undefined)
|
||||
try {
|
||||
await closeInspectorConnection(connection, options.signal);
|
||||
} catch (cause: unknown) {
|
||||
cleanupFailed = true;
|
||||
cleanupFailure = cause;
|
||||
}
|
||||
}
|
||||
if (cleanupFailed) {
|
||||
return err(inspectorCleanupError(primaryFailure, cleanupFailure, failed));
|
||||
}
|
||||
return (
|
||||
outcome ??
|
||||
err(
|
||||
new BrowserObservationError(
|
||||
"observe_javascript_runtime",
|
||||
"protocol_error",
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const closeInspectorConnection = async (
|
||||
connection: Pick<CdpConnection, "close">,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
const closing = connection.close();
|
||||
// best-effort cleanup: the race below observes the close; this only prevents
|
||||
// unhandled rejection when the caller abandons the close via cancellation.
|
||||
void closing.catch(() => undefined);
|
||||
// CdpConnection.close has its own one second transport bound. Do not make a
|
||||
// cancelled caller wait for that fallback.
|
||||
if (signal === undefined) return await closing;
|
||||
let onAbort: (() => void) | undefined;
|
||||
const cancelled = new Promise<void>((resolve) => {
|
||||
onAbort = () => resolve();
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal.aborted) onAbort();
|
||||
});
|
||||
try {
|
||||
await Promise.race([closing, cancelled]);
|
||||
} finally {
|
||||
if (onAbort !== undefined) signal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
};
|
||||
|
||||
export const inspectorCleanupError = (
|
||||
primaryFailure: unknown,
|
||||
cleanupFailure: unknown,
|
||||
hasPrimaryFailure: boolean,
|
||||
): BrowserObservationError => {
|
||||
const cause = hasPrimaryFailure
|
||||
? new AggregateError(
|
||||
[primaryFailure, cleanupFailure],
|
||||
"Inspector observation and cleanup both failed",
|
||||
)
|
||||
: cleanupFailure;
|
||||
return new BrowserObservationError(
|
||||
"observe_javascript_runtime",
|
||||
"cleanup_failed",
|
||||
{ cause },
|
||||
);
|
||||
};
|
||||
|
||||
const projectTarget = (target: AuthorizedV8InspectorTarget) => ({
|
||||
target_id: target.id,
|
||||
protocol_type: target.type,
|
||||
attached: target.attached,
|
||||
location: target.location,
|
||||
});
|
||||
|
||||
const authorizedTarget = async (
|
||||
targets: readonly V8InspectorTarget[],
|
||||
input: ObserveJavaScriptRuntimeInput,
|
||||
product: string,
|
||||
): Promise<AuthorizedV8InspectorTarget> => {
|
||||
const target = targets.find(({ id }) => id === input.target_id);
|
||||
if (target === undefined)
|
||||
throw new BrowserObservationError(
|
||||
"observe_javascript_runtime",
|
||||
"target_not_found",
|
||||
);
|
||||
const decision = await authorizeRuntimeTargetLocation(target.url, {
|
||||
type: target.type,
|
||||
product,
|
||||
});
|
||||
if (
|
||||
target.attached ||
|
||||
!decision.allowed ||
|
||||
decision.location.kind === "builtin"
|
||||
)
|
||||
throw new BrowserObservationError(
|
||||
"observe_javascript_runtime",
|
||||
"target_not_allowed",
|
||||
);
|
||||
return { ...target, location: decision.location };
|
||||
};
|
||||
|
||||
const assertRuntimeKind = (
|
||||
target: AuthorizedV8InspectorTarget,
|
||||
kind: ObserveJavaScriptRuntimeInput["runtime_kind"],
|
||||
): void => {
|
||||
const accepted =
|
||||
kind === "electron-preload" || kind === "electron-renderer"
|
||||
? target.type === "page"
|
||||
: target.type === "node";
|
||||
if (!accepted)
|
||||
throw new BrowserObservationError(
|
||||
"observe_javascript_runtime",
|
||||
"target_not_allowed",
|
||||
);
|
||||
};
|
||||
|
||||
const emptyCaptureState = (): CaptureState => ({
|
||||
scripts: [],
|
||||
contexts: new Map(),
|
||||
eventsObserved: 0,
|
||||
eventsRetained: 0,
|
||||
eventsDropped: 0,
|
||||
metadataBytes: 0,
|
||||
scriptsObserved: 0,
|
||||
invalidScripts: 0,
|
||||
truncated: false,
|
||||
truncationReasons: new Set(),
|
||||
});
|
||||
|
||||
const ingestEvent = (
|
||||
event: CdpEvent,
|
||||
input: ObserveJavaScriptRuntimeInput,
|
||||
state: CaptureState,
|
||||
): void => {
|
||||
if (
|
||||
event.method !== "Debugger.scriptParsed" &&
|
||||
event.method !== "Debugger.scriptFailedToParse" &&
|
||||
event.method !== "Runtime.executionContextCreated" &&
|
||||
event.method !== "Runtime.executionContextDestroyed" &&
|
||||
event.method !== "Runtime.executionContextsCleared"
|
||||
)
|
||||
return;
|
||||
state.eventsObserved += 1;
|
||||
if (event.method === "Debugger.scriptParsed") {
|
||||
ingestScript(event, input, state);
|
||||
return;
|
||||
}
|
||||
if (event.method === "Debugger.scriptFailedToParse") {
|
||||
state.invalidScripts += 1;
|
||||
retainEvent(state, 0);
|
||||
return;
|
||||
}
|
||||
ingestContext(event, input, state);
|
||||
};
|
||||
|
||||
const ingestScript = (
|
||||
event: CdpEvent,
|
||||
input: ObserveJavaScriptRuntimeInput,
|
||||
state: CaptureState,
|
||||
): void => {
|
||||
state.scriptsObserved += 1;
|
||||
const value = recordValue(event.params);
|
||||
const rawUrl = cdpStringValue(value?.url);
|
||||
if (rawUrl === undefined || rawUrl === "") {
|
||||
state.invalidScripts += 1;
|
||||
retainEvent(state, 0);
|
||||
return;
|
||||
}
|
||||
const draft: ScriptDraft = {
|
||||
rawUrl,
|
||||
executionContextKey: contextKey(value?.executionContextId),
|
||||
cdpHash: cdpStringValue(value?.hash) ?? null,
|
||||
length: nonnegativeInteger(value?.length),
|
||||
isModule: value?.isModule === true,
|
||||
};
|
||||
const bytes = metadataBytes(draft);
|
||||
retainEvent(state, bytes);
|
||||
state.scripts.push(draft);
|
||||
};
|
||||
|
||||
const ingestContext = (
|
||||
event: CdpEvent,
|
||||
input: ObserveJavaScriptRuntimeInput,
|
||||
state: CaptureState,
|
||||
): void => {
|
||||
if (event.method === "Runtime.executionContextsCleared") {
|
||||
for (const context of state.contexts.values()) context.state = "cleared";
|
||||
retainEvent(state, 0);
|
||||
return;
|
||||
}
|
||||
const parameters = recordValue(event.params);
|
||||
const runtimeContext =
|
||||
event.method === "Runtime.executionContextCreated"
|
||||
? recordValue(parameters?.context)
|
||||
: parameters;
|
||||
const key = contextKey(
|
||||
event.method === "Runtime.executionContextCreated"
|
||||
? runtimeContext?.id
|
||||
: runtimeContext?.executionContextId,
|
||||
);
|
||||
if (key === null) {
|
||||
retainEvent(state, 0);
|
||||
return;
|
||||
}
|
||||
const origin =
|
||||
event.method === "Runtime.executionContextCreated"
|
||||
? (cdpStringValue(runtimeContext?.origin) ?? null)
|
||||
: null;
|
||||
const draft: ContextDraft = {
|
||||
contextKey: key,
|
||||
state:
|
||||
event.method === "Runtime.executionContextCreated"
|
||||
? "created"
|
||||
: "destroyed",
|
||||
origin: origin === "" ? null : origin,
|
||||
};
|
||||
const bytes = metadataBytes(draft);
|
||||
retainEvent(state, bytes);
|
||||
state.contexts.set(key, draft);
|
||||
};
|
||||
|
||||
const retainEvent = (state: CaptureState, bytes: number): void => {
|
||||
state.metadataBytes += bytes;
|
||||
state.eventsRetained += 1;
|
||||
};
|
||||
|
||||
const waitForCapture = async (
|
||||
connection: CdpConnection,
|
||||
observationMs: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
let removeDisconnect = (): void => undefined;
|
||||
const disconnected = new Promise<never>((_resolve, reject) => {
|
||||
removeDisconnect = connection.onDisconnect(() =>
|
||||
reject(
|
||||
new BrowserObservationError(
|
||||
"observe_javascript_runtime",
|
||||
"disconnected",
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
try {
|
||||
await Promise.race([
|
||||
delayWithCancellation(
|
||||
observationMs,
|
||||
"observe_javascript_runtime",
|
||||
signal,
|
||||
),
|
||||
disconnected,
|
||||
]);
|
||||
} finally {
|
||||
removeDisconnect();
|
||||
}
|
||||
};
|
||||
|
||||
const metadataBytes = (value: object): number =>
|
||||
Buffer.byteLength(JSON.stringify(value));
|
||||
|
||||
const nonnegativeInteger = (value: unknown): number => {
|
||||
const parsed = numberValue(value);
|
||||
return parsed === undefined ? 0 : Math.max(0, Math.trunc(parsed));
|
||||
};
|
||||
|
||||
const contextKey = (value: unknown): string | null => {
|
||||
const identifier = numberValue(value);
|
||||
return identifier !== undefined && Number.isSafeInteger(identifier)
|
||||
? String(identifier)
|
||||
: null;
|
||||
};
|
||||
|
||||
const providerError = (
|
||||
cause: unknown,
|
||||
operation: BrowserObservationOperation,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
return new ProviderAdapterError(
|
||||
V8_INSPECTOR_PROVIDER_IDENTITY.id,
|
||||
operation,
|
||||
{
|
||||
cause,
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -29,10 +29,3 @@ export const PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY: ProviderIdentity =
|
||||
name: "REA Playwright active Electron observation provider",
|
||||
version: "1",
|
||||
});
|
||||
|
||||
/** Identity available without loading the V8InspectorProvider implementation. */
|
||||
export const V8_INSPECTOR_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
|
||||
id: "rea-v8-inspector",
|
||||
name: "REA passive Node/Electron V8 Inspector provider",
|
||||
version: "1",
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user