feat(runtime): add passive V8 Inspector observation

This commit is contained in:
morluto
2026-07-24 13:16:35 +00:00
parent f27dd745b8
commit 8271650945
17 changed files with 2539 additions and 0 deletions
+60
View File
@@ -0,0 +1,60 @@
import {
browserOriginSchema,
sanitizeBrowserUrl,
} from "../domain/browserObservation.js";
import type { JavaScriptRuntimeLocation } from "../domain/javascriptRuntimeObservation.js";
import {
authorizedElectronFile,
canonicalElectronRoots,
} from "./ElectronFileScope.js";
export type RuntimeLocationDecision =
| { readonly allowed: true; readonly location: JavaScriptRuntimeLocation }
| {
readonly allowed: false;
readonly reason:
| "outside_file_roots"
| "outside_origins"
| "unsupported_location";
};
/** Canonicalize exact filesystem scopes before Inspector attachment. */
export const canonicalRuntimeRoots = canonicalElectronRoots;
/** Authorize one protocol URL without retaining an out-of-scope value. */
export const authorizeRuntimeLocation = async (
value: string,
roots: readonly string[],
origins: readonly string[],
): Promise<RuntimeLocationDecision> => {
if (value.startsWith("node:") && value.length <= 4_096)
return {
allowed: true,
location: { kind: "builtin", specifier: value },
};
if (value.startsWith("file:")) {
const filePath = await authorizedElectronFile(value, roots);
return filePath === undefined
? { allowed: false, reason: "outside_file_roots" }
: { allowed: true, location: { kind: "file", file_path: filePath } };
}
let url: URL;
try {
url = new URL(value);
} catch {
return { allowed: false, reason: "unsupported_location" };
}
if (!["http:", "https:"].includes(url.protocol))
return { allowed: false, reason: "unsupported_location" };
const parsedOrigin = browserOriginSchema.safeParse(url.origin);
if (!parsedOrigin.success || !origins.includes(parsedOrigin.data))
return { allowed: false, reason: "outside_origins" };
return {
allowed: true,
location: {
kind: "url",
origin: parsedOrigin.data,
sanitized_url: sanitizeBrowserUrl(value).url,
},
};
};
+145
View File
@@ -0,0 +1,145 @@
import { createHash } from "node:crypto";
import type {
JavaScriptRuntimeLocation,
JavaScriptRuntimeObservation,
JavaScriptRuntimeTargetList,
ObserveJavaScriptRuntimeInput,
} from "../domain/javascriptRuntimeObservation.js";
import { authorizeRuntimeLocation } from "./JavaScriptRuntimeScope.js";
import type { CaptureState, ScriptDraft } from "./V8InspectorProvider.js";
import type { AuthorizedV8InspectorTarget } from "./V8InspectorEndpoint.js";
type ExclusionReason =
| "outside_file_roots"
| "outside_origins"
| "unsupported_location";
/** Empty durable-location exclusion counters. */
export const v8ExclusionCounts = (): Record<ExclusionReason, number> => ({
outside_file_roots: 0,
outside_origins: 0,
unsupported_location: 0,
});
/** Stable safety and protocol limitations shared by target-list Evidence. */
export const v8TargetLimitations = (): 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.",
"Target IDs and locations are authorized, but the Inspector protocol does not authenticate an operating-system process ID or Electron role.",
"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 roots: readonly string[];
readonly state: CaptureState;
}
/** Canonically authorize, deduplicate, and sort one bounded raw capture. */
export const finalizeV8InspectorCapture = async ({
input,
runtime,
target,
roots,
state,
}: FinalizeCaptureInput): Promise<JavaScriptRuntimeObservation> => {
const exclusions = v8ExclusionCounts();
const scripts = new Map<
string,
JavaScriptRuntimeObservation["scripts"]["items"][number]
>();
for (const draft of state.scripts) {
const decision = await authorizeRuntimeLocation(
draft.rawUrl,
roots,
input.allowed_origins,
);
if (!decision.allowed) {
exclusions[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.localeCompare(right.script_key),
);
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.localeCompare(right.context_key));
return {
schema_version: 1,
runtime,
target: {
target_id: target.id,
protocol_type: target.type,
attached: target.attached,
location: target.location,
runtime_kind: input.runtime_kind,
runtime_kind_authority: "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: [
"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: v8TargetLimitations(),
};
};
const scriptFromDraft = (
draft: ScriptDraft,
location: JavaScriptRuntimeLocation,
): JavaScriptRuntimeObservation["scripts"]["items"][number] => {
const stable = JSON.stringify({
location,
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",
};
};
+141
View File
@@ -0,0 +1,141 @@
import { z } from "zod";
import type {
JavaScriptRuntimeTargetList,
JavaScriptRuntimeLocation,
} from "../domain/javascriptRuntimeObservation.js";
import {
BrowserObservationError,
type BrowserObservationOperation,
} from "../domain/errors.js";
import { readBoundedCdpJson } from "./CdpEndpoint.js";
const MAX_VERSION_BYTES = 64 * 1_024;
const MAX_TARGET_LIST_BYTES = 2 * 1_024 * 1_024;
const versionSchema = z
.object({
Browser: z.string().min(1).max(1_024),
"Protocol-Version": z.string().min(1).max(100),
"V8-Version": z.string().max(1_024).optional(),
})
.passthrough();
const targetSchema = z
.object({
id: z.string().min(1).max(256),
type: z.string().min(1).max(100),
url: z.string().max(65_536),
attached: z.boolean().default(false),
webSocketDebuggerUrl: z.string().min(1).max(2_048),
})
.passthrough();
const targetsSchema = z.array(targetSchema).max(1_000);
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 bounded 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([
readBoundedCdpJson(
new URL("/json/version", endpoint),
MAX_VERSION_BYTES,
operation,
signal,
),
readBoundedCdpJson(
new URL("/json/list", endpoint),
MAX_TARGET_LIST_BYTES,
operation,
signal,
),
]);
const version = parse(versionSchema, versionInput, operation);
const targets = parse(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 parse = <Output>(
schema: z.ZodType<Output>,
input: unknown,
operation: BrowserObservationOperation,
): Output => {
const parsed = schema.safeParse(input);
if (!parsed.success)
throw new BrowserObservationError(operation, "invalid_endpoint_response", {
cause: parsed.error,
});
return parsed.data;
};
const 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: JavaScriptRuntimeLocation;
}
+437
View File
@@ -0,0 +1,437 @@
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,
BrowserObservationError,
ProviderAdapterError,
type BrowserObservationOperation,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import {
boundedText,
numberValue,
recordValue,
stringValue,
delayWithCancellation,
} from "./CdpCaptureValues.js";
import { CdpConnection, type CdpEvent } from "./CdpConnection.js";
import {
authorizeRuntimeLocation,
canonicalRuntimeRoots,
} from "./JavaScriptRuntimeScope.js";
import {
finalizeV8InspectorCapture,
v8ExclusionCounts,
v8TargetLimitations,
} from "./V8InspectorCaptureProjection.js";
import {
discoverV8Inspector,
type AuthorizedV8InspectorTarget,
type V8InspectorTarget,
} from "./V8InspectorEndpoint.js";
/** Public identity committed by passive V8 Inspector observations. */
export const V8_INSPECTOR_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
id: "rea-v8-inspector",
name: "REA passive Node/Electron V8 Inspector provider",
version: "1",
});
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 roots = await canonicalRuntimeRoots(input.allowed_file_roots);
const discovery = await discoverV8Inspector(
input.inspector_endpoint,
"list_javascript_runtime_targets",
options.signal,
);
const allowed: AuthorizedV8InspectorTarget[] = [];
const excluded = v8ExclusionCounts();
for (const target of discovery.targets) {
const decision = await authorizeRuntimeLocation(
target.url,
roots,
input.allowed_origins,
);
if (!decision.allowed) {
excluded[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.localeCompare(right.id));
const items = allowed
.slice(input.offset, input.offset + input.limit)
.map(projectTarget);
const nextOffset = input.offset + items.length;
return ok(
javascriptRuntimeTargetListSchema.parse({
schema_version: 1,
runtime: discovery.runtime,
targets: {
items,
offset: input.offset,
limit: input.limit,
total: allowed.length,
next_offset: nextOffset < allowed.length ? nextOffset : null,
has_more: nextOffset < allowed.length,
},
excluded: { ...excluded, unconnectable: 0 },
limitations: v8TargetLimitations(),
}),
);
} 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;
try {
const roots = await canonicalRuntimeRoots(input.allowed_file_roots);
const discovery = await discoverV8Inspector(
input.inspector_endpoint,
"observe_javascript_runtime",
options.signal,
);
const target = await authorizedTarget(discovery.targets, input, roots);
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 finalizeV8InspectorCapture({
input,
runtime: discovery.runtime,
target,
roots,
state,
});
return ok(javascriptRuntimeObservationSchema.parse(result));
} catch (cause: unknown) {
return err(providerError(cause, "observe_javascript_runtime"));
} finally {
await connection?.close();
}
}
}
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,
roots: readonly 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 authorizeRuntimeLocation(
target.url,
roots,
input.allowed_origins,
);
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 (state.eventsObserved > input.limits.max_events) {
drop(state, "max_events");
return;
}
if (event.method === "Debugger.scriptParsed") {
ingestScript(event, input, state);
return;
}
if (event.method === "Debugger.scriptFailedToParse") {
state.invalidScripts += 1;
retainEvent(state, 0, input);
return;
}
ingestContext(event, input, state);
};
const ingestScript = (
event: CdpEvent,
input: ObserveJavaScriptRuntimeInput,
state: CaptureState,
): void => {
state.scriptsObserved += 1;
const value = recordValue(event.params);
const rawUrl = stringValue(value?.url);
if (
rawUrl === undefined ||
rawUrl === "" ||
Buffer.byteLength(rawUrl) > input.limits.max_location_bytes
) {
state.invalidScripts += 1;
retainEvent(state, 0, input);
return;
}
if (state.scripts.length >= input.limits.max_scripts) {
drop(state, "max_scripts");
return;
}
const draft: ScriptDraft = {
rawUrl,
executionContextKey: contextKey(value?.executionContextId),
cdpHash: boundedText(value?.hash, 512),
length: nonnegativeInteger(value?.length),
isModule: value?.isModule === true,
};
const bytes = metadataBytes(draft);
if (!retainEvent(state, bytes, input)) return;
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, input);
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, input);
return;
}
if (
state.contexts.size >= input.limits.max_execution_contexts &&
!state.contexts.has(key)
) {
drop(state, "max_execution_contexts");
return;
}
const origin =
event.method === "Runtime.executionContextCreated"
? boundedText(runtimeContext?.origin, 4_096)
: null;
const draft: ContextDraft = {
contextKey: key,
state:
event.method === "Runtime.executionContextCreated"
? "created"
: "destroyed",
origin:
origin !== null && input.allowed_origins.includes(origin) ? origin : null,
};
const bytes = metadataBytes(draft);
if (!retainEvent(state, bytes, input)) return;
state.contexts.set(key, draft);
};
const retainEvent = (
state: CaptureState,
bytes: number,
input: ObserveJavaScriptRuntimeInput,
): boolean => {
if (state.metadataBytes + bytes > input.limits.max_total_metadata_bytes) {
drop(state, "max_total_metadata_bytes");
return false;
}
state.metadataBytes += bytes;
state.eventsRetained += 1;
return true;
};
const drop = (state: CaptureState, reason: string): void => {
state.eventsDropped += 1;
state.truncated = true;
state.truncationReasons.add(reason);
};
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,
},
);
};