feat(runtime): add passive V8 Inspector observation
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import type { ProviderIdentity } from "./AnalysisProvider.js";
|
||||
import {
|
||||
createEvidence,
|
||||
type Evidence,
|
||||
type EvidenceObservation,
|
||||
} from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import type {
|
||||
JavaScriptRuntimeObservation,
|
||||
JavaScriptRuntimeTargetList,
|
||||
ListJavaScriptRuntimeTargetsInput,
|
||||
ObserveJavaScriptRuntimeInput,
|
||||
} from "../domain/javascriptRuntimeObservation.js";
|
||||
|
||||
type RuntimeObservationOperation =
|
||||
| "list_javascript_runtime_targets"
|
||||
| "observe_javascript_runtime";
|
||||
|
||||
/** Create deterministic Evidence v2 for one passive Inspector operation. */
|
||||
export const createJavaScriptRuntimeObservationEvidence = (
|
||||
operation: RuntimeObservationOperation,
|
||||
input: ListJavaScriptRuntimeTargetsInput | ObserveJavaScriptRuntimeInput,
|
||||
result: JavaScriptRuntimeTargetList | JavaScriptRuntimeObservation,
|
||||
provider: ProviderIdentity,
|
||||
): Evidence =>
|
||||
createEvidence(undefined, provider, {
|
||||
predicateType:
|
||||
operation === "list_javascript_runtime_targets"
|
||||
? "rea.javascript-runtime-target-list/v1"
|
||||
: "rea.javascript-runtime-observation/v1",
|
||||
operation,
|
||||
parameters: parameters(input),
|
||||
result: jsonValueSchema.parse(result),
|
||||
rawResult: null,
|
||||
confidence: "observed",
|
||||
authority: "external-service",
|
||||
environment: {
|
||||
id: `${result.runtime.product}@${result.runtime.protocol_version}`,
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
isolation: "none",
|
||||
},
|
||||
limitations: result.limitations,
|
||||
});
|
||||
|
||||
const parameters = (
|
||||
input: ListJavaScriptRuntimeTargetsInput | ObserveJavaScriptRuntimeInput,
|
||||
): EvidenceObservation["parameters"] => ({
|
||||
inspector_endpoint: input.inspector_endpoint,
|
||||
allowed_file_roots: input.allowed_file_roots,
|
||||
allowed_origins: input.allowed_origins,
|
||||
...("target_id" in input
|
||||
? {
|
||||
target_id: input.target_id,
|
||||
runtime_kind: input.runtime_kind,
|
||||
observation_ms: input.observation_ms,
|
||||
limits: input.limits,
|
||||
}
|
||||
: { offset: input.offset, limit: input.limit }),
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { ExecutionOptions, ProviderIdentity } from "./AnalysisProvider.js";
|
||||
import type {
|
||||
JavaScriptRuntimeObservation,
|
||||
JavaScriptRuntimeTargetList,
|
||||
ListJavaScriptRuntimeTargetsInput,
|
||||
ObserveJavaScriptRuntimeInput,
|
||||
} from "../domain/javascriptRuntimeObservation.js";
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
|
||||
/** Provider-neutral boundary for passive Node/Electron Inspector observation. */
|
||||
export interface JavaScriptRuntimeObservationPort {
|
||||
identity(): ProviderIdentity;
|
||||
listTargets(
|
||||
input: ListJavaScriptRuntimeTargetsInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<JavaScriptRuntimeTargetList, AnalysisError>>;
|
||||
observe(
|
||||
input: ObserveJavaScriptRuntimeInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<JavaScriptRuntimeObservation, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { JavaScriptRuntimeObservationPort } from "./JavaScriptRuntimeObservationPort.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import { createJavaScriptRuntimeObservationEvidence } from "./JavaScriptRuntimeObservationEvidence.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type {
|
||||
ListJavaScriptRuntimeTargetsInput,
|
||||
ObserveJavaScriptRuntimeInput,
|
||||
} from "../domain/javascriptRuntimeObservation.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Authorize and list attachable Node/Electron Inspector targets. */
|
||||
export const listJavaScriptRuntimeTargets = async (
|
||||
provider: JavaScriptRuntimeObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ListJavaScriptRuntimeTargetsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(
|
||||
provider,
|
||||
authority,
|
||||
input,
|
||||
"list_javascript_runtime_targets",
|
||||
);
|
||||
if (!ready.ok) return ready;
|
||||
const result = await ready.value.listTargets(input, options);
|
||||
return result.ok
|
||||
? ok(
|
||||
createJavaScriptRuntimeObservationEvidence(
|
||||
"list_javascript_runtime_targets",
|
||||
input,
|
||||
result.value,
|
||||
ready.value.identity(),
|
||||
),
|
||||
)
|
||||
: result;
|
||||
};
|
||||
|
||||
/** Authorize one bounded attach-only Inspector observation. */
|
||||
export const observeJavaScriptRuntime = async (
|
||||
provider: JavaScriptRuntimeObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ObserveJavaScriptRuntimeInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(
|
||||
provider,
|
||||
authority,
|
||||
input,
|
||||
"observe_javascript_runtime",
|
||||
);
|
||||
if (!ready.ok) return ready;
|
||||
const result = await ready.value.observe(input, options);
|
||||
return result.ok
|
||||
? ok(
|
||||
createJavaScriptRuntimeObservationEvidence(
|
||||
"observe_javascript_runtime",
|
||||
input,
|
||||
result.value,
|
||||
ready.value.identity(),
|
||||
),
|
||||
)
|
||||
: result;
|
||||
};
|
||||
|
||||
const prepare = async (
|
||||
provider: JavaScriptRuntimeObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ListJavaScriptRuntimeTargetsInput | ObserveJavaScriptRuntimeInput,
|
||||
operation: "list_javascript_runtime_targets" | "observe_javascript_runtime",
|
||||
): Promise<Result<JavaScriptRuntimeObservationPort, AnalysisError>> => {
|
||||
if (authority === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-v8-inspector",
|
||||
operation,
|
||||
"V8 Inspector observation permission policy is not configured",
|
||||
),
|
||||
);
|
||||
const authorized = await authority.authorize(
|
||||
{
|
||||
capability: "v8_inspector_observe",
|
||||
roots: input.allowed_file_roots,
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
origins: [input.inspector_endpoint, ...input.allowed_origins],
|
||||
network: "loopback",
|
||||
mount: false,
|
||||
operation_identity: `${operation}:${"target_id" in input ? input.target_id : input.inspector_endpoint}`,
|
||||
},
|
||||
"read",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
return provider === undefined
|
||||
? err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-v8-inspector",
|
||||
operation,
|
||||
"V8 Inspector observation provider is not configured",
|
||||
),
|
||||
)
|
||||
: ok(provider);
|
||||
};
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -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",
|
||||
};
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,204 @@
|
||||
import { Cli, z } from "incur";
|
||||
|
||||
import {
|
||||
listJavaScriptRuntimeTargets,
|
||||
observeJavaScriptRuntime,
|
||||
} from "./application/JavaScriptRuntimeObservationService.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import { V8InspectorProvider } from "./browser/V8InspectorProvider.js";
|
||||
import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import {
|
||||
javascriptRuntimeKindSchema,
|
||||
listJavaScriptRuntimeTargetsInputSchema,
|
||||
observeJavaScriptRuntimeInputSchema,
|
||||
} from "./domain/javascriptRuntimeObservation.js";
|
||||
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
|
||||
import type { JsonValue } from "./domain/jsonValue.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
|
||||
const scopeOptions = {
|
||||
allowedFileRoots: z
|
||||
.array(z.string().min(1))
|
||||
.optional()
|
||||
.describe("Exact roots; defaults to REA_V8_INSPECTOR_FILE_ROOTS_JSON"),
|
||||
allowedOrigins: z
|
||||
.array(z.string().min(1))
|
||||
.optional()
|
||||
.describe(
|
||||
"Exact origins; defaults to REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON",
|
||||
),
|
||||
approved: z.boolean().default(false).describe("Approve passive attachment"),
|
||||
};
|
||||
|
||||
const listOptionsSchema = z.object({
|
||||
...scopeOptions,
|
||||
offset: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.default(0)
|
||||
.describe("Zero-based target offset"),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(200)
|
||||
.default(100)
|
||||
.describe("Maximum targets to return"),
|
||||
});
|
||||
|
||||
const observeOptionsSchema = z.object({
|
||||
...scopeOptions,
|
||||
runtimeKind: javascriptRuntimeKindSchema.describe(
|
||||
"Declared target role; Inspector cannot authenticate the Electron role",
|
||||
),
|
||||
observationMs: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(10_000)
|
||||
.default(100)
|
||||
.describe("Bounded observation window in milliseconds"),
|
||||
maxEvents: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(50_000)
|
||||
.default(10_000)
|
||||
.describe("Maximum retained protocol events"),
|
||||
maxScripts: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(10_000)
|
||||
.default(2_000)
|
||||
.describe("Maximum retained scripts"),
|
||||
maxExecutionContexts: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(5_000)
|
||||
.default(1_000)
|
||||
.describe("Maximum retained execution contexts"),
|
||||
maxLocationBytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(64)
|
||||
.max(65_536)
|
||||
.default(16_384)
|
||||
.describe("Maximum bytes in one protocol location"),
|
||||
maxTotalMetadataBytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1_024)
|
||||
.max(32 * 1_024 * 1_024)
|
||||
.default(4 * 1_024 * 1_024)
|
||||
.describe("Maximum retained metadata bytes"),
|
||||
});
|
||||
|
||||
/** Register CLI equivalents of passive V8 Inspector tools. */
|
||||
export const registerJavaScriptRuntimeObservationCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.listJavaScriptRuntimeTargets, {
|
||||
description: "List approved Node/Electron V8 Inspector targets",
|
||||
args: z.object({
|
||||
endpoint: z.string().describe("Configured literal-loopback endpoint"),
|
||||
}),
|
||||
options: listOptionsSchema,
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(
|
||||
logger,
|
||||
CLI_COMMANDS.listJavaScriptRuntimeTargets,
|
||||
async () => {
|
||||
const context = await runtimeContext();
|
||||
if (!context.ok) return context.error;
|
||||
const parsed = listJavaScriptRuntimeTargetsInputSchema.safeParse({
|
||||
inspector_endpoint: args.endpoint,
|
||||
allowed_file_roots:
|
||||
options.allowedFileRoots ?? context.allowedFileRoots,
|
||||
allowed_origins: options.allowedOrigins ?? context.allowedOrigins,
|
||||
approved: options.approved,
|
||||
offset: options.offset,
|
||||
limit: options.limit,
|
||||
});
|
||||
if (!parsed.success)
|
||||
return inputError("list_javascript_runtime_targets");
|
||||
const result = await listJavaScriptRuntimeTargets(
|
||||
context.provider,
|
||||
context.authority,
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
},
|
||||
),
|
||||
});
|
||||
|
||||
cli.command(CLI_COMMANDS.observeJavaScriptRuntime, {
|
||||
description: "Passively observe one exact Node/Electron Inspector target",
|
||||
args: z.object({
|
||||
endpoint: z.string().describe("Configured literal-loopback endpoint"),
|
||||
targetId: z
|
||||
.string()
|
||||
.describe("Target from list-javascript-runtime-targets"),
|
||||
}),
|
||||
options: observeOptionsSchema,
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.observeJavaScriptRuntime, async () => {
|
||||
const context = await runtimeContext();
|
||||
if (!context.ok) return context.error;
|
||||
const parsed = observeJavaScriptRuntimeInputSchema.safeParse({
|
||||
inspector_endpoint: args.endpoint,
|
||||
allowed_file_roots:
|
||||
options.allowedFileRoots ?? context.allowedFileRoots,
|
||||
allowed_origins: options.allowedOrigins ?? context.allowedOrigins,
|
||||
target_id: args.targetId,
|
||||
runtime_kind: options.runtimeKind,
|
||||
approved: options.approved,
|
||||
observation_ms: options.observationMs,
|
||||
limits: {
|
||||
max_events: options.maxEvents,
|
||||
max_scripts: options.maxScripts,
|
||||
max_execution_contexts: options.maxExecutionContexts,
|
||||
max_location_bytes: options.maxLocationBytes,
|
||||
max_total_metadata_bytes: options.maxTotalMetadataBytes,
|
||||
},
|
||||
});
|
||||
if (!parsed.success) return inputError("observe_javascript_runtime");
|
||||
const result = await observeJavaScriptRuntime(
|
||||
context.provider,
|
||||
context.authority,
|
||||
parsed.data,
|
||||
);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const runtimeContext = async () => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok) return { ok: false as const, error: cliError(config.error) };
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok)
|
||||
return { ok: false as const, error: cliError(authority.error) };
|
||||
return {
|
||||
ok: true as const,
|
||||
authority: authority.value,
|
||||
provider: new V8InspectorProvider(),
|
||||
allowedFileRoots: config.value.v8InspectorFileRoots,
|
||||
allowedOrigins: config.value.v8InspectorAllowedOrigins,
|
||||
};
|
||||
};
|
||||
|
||||
const inputError = (operation: string): JsonValue =>
|
||||
cliError(new AnalysisInputError(operation));
|
||||
|
||||
const cliError = (
|
||||
error: Parameters<typeof projectAnalysisError>[0],
|
||||
): JsonValue => ({
|
||||
error: "JavaScript runtime observation failed",
|
||||
...projectAnalysisError(error),
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { ToolContract } from "./toolContracts.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import { evidenceResultOf } from "./toolOutputSchemas.js";
|
||||
import {
|
||||
javascriptRuntimeObservationSchema,
|
||||
javascriptRuntimeTargetListSchema,
|
||||
listJavaScriptRuntimeTargetsInputSchema,
|
||||
observeJavaScriptRuntimeInputSchema,
|
||||
} from "../domain/javascriptRuntimeObservation.js";
|
||||
|
||||
const root = "/opt/example-app";
|
||||
const endpoint = "http://127.0.0.1:9229";
|
||||
|
||||
/** Passive Node/Electron V8 Inspector discovery and observation contracts. */
|
||||
export const JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "list_javascript_runtime_targets",
|
||||
...toolContractMetadata("list_javascript_runtime_targets"),
|
||||
description:
|
||||
"List attachable Node/Electron V8 Inspector targets from one approved literal-loopback endpoint. Only targets inside exact canonical file roots or exact HTTP(S) origins are retained; excluded target locations never enter Evidence.",
|
||||
kind: "runtime-provider",
|
||||
inputSchema: listJavaScriptRuntimeTargetsInputSchema,
|
||||
outputSchema: evidenceResultOf(javascriptRuntimeTargetListSchema),
|
||||
examples: [
|
||||
{
|
||||
title: "List approved Node Inspector targets",
|
||||
input: {
|
||||
inspector_endpoint: endpoint,
|
||||
allowed_file_roots: [root],
|
||||
allowed_origins: [],
|
||||
approved: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "observe_javascript_runtime",
|
||||
...toolContractMetadata("observe_javascript_runtime"),
|
||||
description:
|
||||
"Attach passively to one exact approved Node/Electron V8 Inspector target and capture bounded Debugger.scriptParsed plus Runtime execution-context events. REA sends only Runtime.enable and Debugger.enable: it never evaluates, pauses, resumes, reads source, or instruments the target. require/import edges, EventEmitter activity, and Electron IPC remain explicit unknowns; reconcile the returned Evidence with static Application Graph Evidence using reconcile_javascript_runtime.",
|
||||
kind: "runtime-provider",
|
||||
inputSchema: observeJavaScriptRuntimeInputSchema,
|
||||
outputSchema: evidenceResultOf(javascriptRuntimeObservationSchema),
|
||||
examples: [
|
||||
{
|
||||
title: "Observe one approved Node runtime",
|
||||
input: {
|
||||
inspector_endpoint: endpoint,
|
||||
allowed_file_roots: [root],
|
||||
allowed_origins: [],
|
||||
target_id: "TARGET_ID_FROM_LIST_JAVASCRIPT_RUNTIME_TARGETS",
|
||||
runtime_kind: "node",
|
||||
approved: true,
|
||||
observation_ms: 100,
|
||||
limits: {
|
||||
max_events: 10_000,
|
||||
max_scripts: 2_000,
|
||||
max_execution_contexts: 1_000,
|
||||
max_location_bytes: 16_384,
|
||||
max_total_metadata_bytes: 4_194_304,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -0,0 +1,216 @@
|
||||
import { isAbsolute, resolve } from "node:path";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
browserEndpointSchema,
|
||||
browserOriginSchema,
|
||||
} from "./browserObservation.js";
|
||||
|
||||
const boundedTextSchema = z.string().min(1).max(4_096);
|
||||
|
||||
const runtimeFileRootsSchema = z
|
||||
.array(
|
||||
z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(16_384)
|
||||
.refine(isAbsolute, "Runtime file roots must be absolute paths")
|
||||
.overwrite(resolve),
|
||||
)
|
||||
.max(32)
|
||||
.overwrite((roots) => [...new Set(roots)].sort())
|
||||
.default([]);
|
||||
|
||||
const runtimeOriginsSchema = z
|
||||
.array(browserOriginSchema)
|
||||
.max(32)
|
||||
.overwrite((origins) => [...new Set(origins)].sort())
|
||||
.default([]);
|
||||
|
||||
const approvedRuntimeScope = {
|
||||
inspector_endpoint: browserEndpointSchema,
|
||||
allowed_file_roots: runtimeFileRootsSchema,
|
||||
allowed_origins: runtimeOriginsSchema,
|
||||
approved: z.literal(true),
|
||||
};
|
||||
|
||||
const requireRuntimeScope = (
|
||||
input: {
|
||||
readonly allowed_file_roots: readonly string[];
|
||||
readonly allowed_origins: readonly string[];
|
||||
},
|
||||
context: z.RefinementCtx,
|
||||
): void => {
|
||||
if (
|
||||
input.allowed_file_roots.length === 0 &&
|
||||
input.allowed_origins.length === 0
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["allowed_file_roots"],
|
||||
message: "At least one exact file root or HTTP(S) origin is required",
|
||||
});
|
||||
};
|
||||
|
||||
/** Input for listing approved Node/Electron V8 Inspector targets. */
|
||||
export const listJavaScriptRuntimeTargetsInputSchema = z
|
||||
.strictObject({
|
||||
...approvedRuntimeScope,
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(200).default(100),
|
||||
})
|
||||
.superRefine(requireRuntimeScope);
|
||||
export type ListJavaScriptRuntimeTargetsInput = z.infer<
|
||||
typeof listJavaScriptRuntimeTargetsInputSchema
|
||||
>;
|
||||
|
||||
export const javascriptRuntimeKindSchema = z.enum([
|
||||
"node",
|
||||
"electron-main",
|
||||
"electron-preload",
|
||||
"electron-renderer",
|
||||
]);
|
||||
|
||||
export const javascriptRuntimeObservationLimitsSchema = z.strictObject({
|
||||
max_events: z.number().int().min(1).max(50_000).default(10_000),
|
||||
max_scripts: z.number().int().min(1).max(10_000).default(2_000),
|
||||
max_execution_contexts: z.number().int().min(1).max(5_000).default(1_000),
|
||||
max_location_bytes: z.number().int().min(64).max(65_536).default(16_384),
|
||||
max_total_metadata_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1_024)
|
||||
.max(32 * 1_024 * 1_024)
|
||||
.default(4 * 1_024 * 1_024),
|
||||
});
|
||||
|
||||
/** Input for one bounded, attach-only V8 Inspector observation. */
|
||||
export const observeJavaScriptRuntimeInputSchema = z
|
||||
.strictObject({
|
||||
...approvedRuntimeScope,
|
||||
target_id: z.string().trim().min(1).max(256),
|
||||
runtime_kind: javascriptRuntimeKindSchema,
|
||||
observation_ms: z.number().int().min(0).max(10_000).default(100),
|
||||
limits: javascriptRuntimeObservationLimitsSchema.default({
|
||||
max_events: 10_000,
|
||||
max_scripts: 2_000,
|
||||
max_execution_contexts: 1_000,
|
||||
max_location_bytes: 16_384,
|
||||
max_total_metadata_bytes: 4 * 1_024 * 1_024,
|
||||
}),
|
||||
})
|
||||
.superRefine(requireRuntimeScope);
|
||||
export type ObserveJavaScriptRuntimeInput = z.infer<
|
||||
typeof observeJavaScriptRuntimeInputSchema
|
||||
>;
|
||||
|
||||
export const javascriptRuntimeVersionSchema = z.strictObject({
|
||||
product: z.string().min(1).max(1_024),
|
||||
protocol_version: z.string().min(1).max(100),
|
||||
v8_version: z.string().max(1_024).nullable(),
|
||||
});
|
||||
|
||||
export const javascriptRuntimeLocationSchema = z.discriminatedUnion("kind", [
|
||||
z.strictObject({
|
||||
kind: z.literal("file"),
|
||||
file_path: z.string().min(1).max(16_384),
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("url"),
|
||||
origin: z.string().min(1).max(2_048),
|
||||
sanitized_url: z.string().min(1).max(65_536),
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("builtin"),
|
||||
specifier: z.string().min(1).max(4_096),
|
||||
}),
|
||||
]);
|
||||
export type JavaScriptRuntimeLocation = z.infer<
|
||||
typeof javascriptRuntimeLocationSchema
|
||||
>;
|
||||
|
||||
const javascriptRuntimeTargetSchema = z.strictObject({
|
||||
target_id: z.string().min(1).max(256),
|
||||
protocol_type: z.string().min(1).max(100),
|
||||
attached: z.boolean(),
|
||||
location: javascriptRuntimeLocationSchema,
|
||||
});
|
||||
|
||||
/** Root/origin-filtered V8 Inspector target inventory. */
|
||||
export const javascriptRuntimeTargetListSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
runtime: javascriptRuntimeVersionSchema,
|
||||
targets: z.strictObject({
|
||||
items: z.array(javascriptRuntimeTargetSchema),
|
||||
offset: z.number().int().min(0),
|
||||
limit: z.number().int().min(1),
|
||||
total: z.number().int().min(0),
|
||||
next_offset: z.number().int().min(0).nullable(),
|
||||
has_more: z.boolean(),
|
||||
}),
|
||||
excluded: z.strictObject({
|
||||
outside_file_roots: z.number().int().min(0),
|
||||
outside_origins: z.number().int().min(0),
|
||||
unsupported_location: z.number().int().min(0),
|
||||
unconnectable: z.number().int().min(0),
|
||||
}),
|
||||
limitations: z.array(boundedTextSchema).max(100),
|
||||
});
|
||||
export type JavaScriptRuntimeTargetList = z.infer<
|
||||
typeof javascriptRuntimeTargetListSchema
|
||||
>;
|
||||
|
||||
const javascriptRuntimeScriptSchema = z.strictObject({
|
||||
script_key: z.string().regex(/^v8_script_[a-f0-9]{64}$/u),
|
||||
location: javascriptRuntimeLocationSchema,
|
||||
execution_context_key: z.string().max(64).nullable(),
|
||||
cdp_hash: z.string().max(512).nullable(),
|
||||
length: z.number().int().min(0),
|
||||
is_module: z.boolean(),
|
||||
status: z.literal("observed-loaded"),
|
||||
});
|
||||
|
||||
const javascriptRuntimeContextSchema = z.strictObject({
|
||||
context_key: z.string().min(1).max(64),
|
||||
state: z.enum(["created", "destroyed", "cleared"]),
|
||||
name: z.string().max(1_024).nullable(),
|
||||
origin: z.string().max(4_096).nullable(),
|
||||
});
|
||||
|
||||
/** Deterministic passive script/context snapshot from one bounded window. */
|
||||
export const javascriptRuntimeObservationSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
runtime: javascriptRuntimeVersionSchema,
|
||||
target: javascriptRuntimeTargetSchema.extend({
|
||||
runtime_kind: javascriptRuntimeKindSchema,
|
||||
runtime_kind_authority: z.literal("caller-declared-unverified"),
|
||||
}),
|
||||
capture: z.strictObject({
|
||||
observation_ms: z.number().int().min(0),
|
||||
events_observed: z.number().int().min(0),
|
||||
events_retained: z.number().int().min(0),
|
||||
events_dropped: z.number().int().min(0),
|
||||
metadata_bytes_retained: z.number().int().min(0),
|
||||
truncated: z.boolean(),
|
||||
truncation_reasons: z.array(boundedTextSchema).max(20),
|
||||
}),
|
||||
scripts: z.strictObject({
|
||||
items: z.array(javascriptRuntimeScriptSchema),
|
||||
observed_total: z.number().int().min(0),
|
||||
excluded: z.strictObject({
|
||||
outside_file_roots: z.number().int().min(0),
|
||||
outside_origins: z.number().int().min(0),
|
||||
unsupported_location: z.number().int().min(0),
|
||||
invalid_protocol_value: z.number().int().min(0),
|
||||
}),
|
||||
}),
|
||||
execution_contexts: z.array(javascriptRuntimeContextSchema),
|
||||
directly_observed: z.array(boundedTextSchema).max(20),
|
||||
unavailable_without_instrumentation: z.array(boundedTextSchema).max(20),
|
||||
unknowns: z.array(boundedTextSchema).max(100),
|
||||
limitations: z.array(boundedTextSchema).max(100),
|
||||
});
|
||||
export type JavaScriptRuntimeObservation = z.infer<
|
||||
typeof javascriptRuntimeObservationSchema
|
||||
>;
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { JavaScriptRuntimeObservationPort } from "../application/JavaScriptRuntimeObservationPort.js";
|
||||
import {
|
||||
listJavaScriptRuntimeTargets,
|
||||
observeJavaScriptRuntime,
|
||||
} from "../application/JavaScriptRuntimeObservationService.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "../contracts/javascriptRuntimeObservationToolContracts.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
listJavaScriptRuntimeTargetsInputSchema,
|
||||
observeJavaScriptRuntimeInputSchema,
|
||||
} from "../domain/javascriptRuntimeObservation.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { safeParseToolInput } from "./toolInputValidation.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
|
||||
interface RuntimeToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly runtime: JavaScriptRuntimeObservationPort | undefined;
|
||||
readonly permissionAuthority: PermissionAuthority | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
}
|
||||
|
||||
interface RuntimeToolSpec<Schema extends z.ZodType> {
|
||||
readonly contract: ToolContract;
|
||||
readonly schema: Schema;
|
||||
readonly execute: (
|
||||
parsed: z.output<Schema>,
|
||||
signal: AbortSignal,
|
||||
) => Promise<Result<Evidence, AnalysisError>>;
|
||||
}
|
||||
|
||||
/** Register passive Inspector tools even when policy keeps them unavailable. */
|
||||
export const registerJavaScriptRuntimeObservationTools = (
|
||||
server: McpServer,
|
||||
options: RuntimeToolRegistration,
|
||||
): void => {
|
||||
const [listContract, observeContract] =
|
||||
JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS;
|
||||
registerRuntimeTool(server, options, {
|
||||
contract: listContract,
|
||||
schema: listJavaScriptRuntimeTargetsInputSchema,
|
||||
execute: (parsed, signal) =>
|
||||
listJavaScriptRuntimeTargets(
|
||||
options.runtime,
|
||||
options.permissionAuthority,
|
||||
parsed,
|
||||
{ signal },
|
||||
),
|
||||
});
|
||||
registerRuntimeTool(server, options, {
|
||||
contract: observeContract,
|
||||
schema: observeJavaScriptRuntimeInputSchema,
|
||||
execute: (parsed, signal) =>
|
||||
observeJavaScriptRuntime(
|
||||
options.runtime,
|
||||
options.permissionAuthority,
|
||||
parsed,
|
||||
{ signal },
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const registerRuntimeTool = <Schema extends z.ZodType>(
|
||||
server: McpServer,
|
||||
options: RuntimeToolRegistration,
|
||||
spec: RuntimeToolSpec<Schema>,
|
||||
): void => {
|
||||
server.registerTool(
|
||||
spec.contract.name,
|
||||
toolRegistrationOptions(spec.contract),
|
||||
async (input, context) => {
|
||||
const parsed = safeParseToolInput(spec.schema, input, spec.contract.name);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, spec.contract);
|
||||
const result = await logToolExecution(
|
||||
options.logger,
|
||||
spec.contract.name,
|
||||
() => spec.execute(parsed.value, context.mcpReq.signal),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, spec.contract);
|
||||
const recorded = options.recordEvidence?.(result.value);
|
||||
return recorded !== undefined && !recorded.ok
|
||||
? toCallToolResult(recorded, spec.contract)
|
||||
: toCallToolResult({ ok: true, value: result.value }, spec.contract, {
|
||||
evidenceResourcesAvailable: recorded !== undefined,
|
||||
});
|
||||
},
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user