feat(electron): reconcile static artifacts with passive runtime
This commit is contained in:
@@ -32,6 +32,13 @@ export const JAVASCRIPT_APPLICATION_PROVIDER = {
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for static/passive-runtime JavaScript reconciliation. */
|
||||
export const JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER = {
|
||||
id: "rea-javascript-runtime-reconciliation",
|
||||
name: "REA JavaScript runtime reconciliation",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic cross-artifact comparisons. */
|
||||
export const ARTIFACT_COMPARISON_PROVIDER = {
|
||||
id: "rea-artifact-comparison",
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import {
|
||||
createEvidence,
|
||||
type Evidence,
|
||||
type EvidenceObservation,
|
||||
} from "../domain/evidence.js";
|
||||
import type {
|
||||
JavaScriptRuntimeReconciliationResult,
|
||||
ReconcileJavaScriptRuntimeInput,
|
||||
} from "../domain/javascriptRuntimeReconciliationSchemas.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER } from "./InvestigationProviders.js";
|
||||
|
||||
/** Create derived Evidence v2 for one exact set of static/runtime inputs. */
|
||||
export const createJavaScriptRuntimeReconciliationEvidence = (
|
||||
input: ReconcileJavaScriptRuntimeInput,
|
||||
result: JavaScriptRuntimeReconciliationResult,
|
||||
): Evidence =>
|
||||
createEvidence(undefined, JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER, {
|
||||
predicateType: "rea.javascript-runtime-reconciliation/v1",
|
||||
operation: "reconcile_javascript_runtime",
|
||||
parameters: parameters(input),
|
||||
result: jsonValueSchema.parse(result),
|
||||
rawResult: null,
|
||||
confidence: "inferred",
|
||||
authority: "analyst-inference",
|
||||
environment: null,
|
||||
limitations: result.limitations,
|
||||
evidenceLinks: result.evidence_links,
|
||||
});
|
||||
|
||||
const parameters = (
|
||||
input: ReconcileJavaScriptRuntimeInput,
|
||||
): EvidenceObservation["parameters"] => ({
|
||||
static_layers: input.static_layers.map((layer) => ({
|
||||
role: layer.role,
|
||||
evidence_id: layer.analysis.evidence_id,
|
||||
runtime_mappings: layer.runtime_mappings,
|
||||
})),
|
||||
runtime_evidence_ids: input.runtime_observations.map(
|
||||
({ evidence_id: id }) => id,
|
||||
),
|
||||
limits: input.limits,
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { reconcileJavaScriptRuntime } from "../domain/javascriptRuntimeReconciliation.js";
|
||||
import { reconcileJavaScriptRuntimeInputSchema } from "../domain/javascriptRuntimeReconciliationSchemas.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { createJavaScriptRuntimeReconciliationEvidence } from "./JavaScriptRuntimeReconciliationEvidence.js";
|
||||
|
||||
const OPERATION = "reconcile_javascript_runtime" as const;
|
||||
|
||||
/** Derive a combined JAG from verified static and passive-runtime Evidence. */
|
||||
export const reconcileJavaScriptRuntimeEvidence = (
|
||||
rawInput: unknown,
|
||||
): Result<Evidence, AnalysisError> => {
|
||||
const parsed = reconcileJavaScriptRuntimeInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success) return err(new AnalysisInputError(OPERATION));
|
||||
try {
|
||||
const result = reconcileJavaScriptRuntime(parsed.data);
|
||||
return ok(
|
||||
createJavaScriptRuntimeReconciliationEvidence(parsed.data, result),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
cause instanceof z.ZodError || cause instanceof TypeError
|
||||
? new AnalysisInputError(OPERATION)
|
||||
: new AnalysisProtocolError(
|
||||
"JavaScript runtime reconciliation produced an invalid result",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -29,6 +29,7 @@ export interface CapturedScript {
|
||||
readonly language: string | null;
|
||||
readonly sourceMapUrl: string | null;
|
||||
readonly sourceMapRawUrl: string | null;
|
||||
readonly executionContextKey: string | null;
|
||||
}
|
||||
|
||||
type NetworkState = WebPageInspection["network"]["requests"][number];
|
||||
@@ -36,6 +37,7 @@ type NetworkState = WebPageInspection["network"]["requests"][number];
|
||||
/** Bounded event accumulator that drops payload values at ingestion time. */
|
||||
export class CdpCaptureEvents {
|
||||
readonly scripts = new Map<string, CapturedScript>();
|
||||
readonly executionContextFrames = new Map<string, string>();
|
||||
readonly network = new Map<string, NetworkState>();
|
||||
readonly allowedWebSockets = new Set<string>();
|
||||
readonly console: WebPageInspection["console"]["events"] = [];
|
||||
@@ -66,6 +68,7 @@ export class CdpCaptureEvents {
|
||||
this.originViolation = false;
|
||||
this.navigationDuringCapture = false;
|
||||
this.scripts.clear();
|
||||
this.executionContextFrames.clear();
|
||||
this.network.clear();
|
||||
this.allowedWebSockets.clear();
|
||||
this.console.length = 0;
|
||||
@@ -93,6 +96,15 @@ export class CdpCaptureEvents {
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return;
|
||||
switch (event.method) {
|
||||
case "Runtime.executionContextCreated":
|
||||
this.#executionContext(params);
|
||||
break;
|
||||
case "Runtime.executionContextDestroyed":
|
||||
this.#destroyExecutionContext(params);
|
||||
break;
|
||||
case "Runtime.executionContextsCleared":
|
||||
this.executionContextFrames.clear();
|
||||
break;
|
||||
case "Debugger.scriptParsed":
|
||||
this.#script(params);
|
||||
break;
|
||||
@@ -123,6 +135,45 @@ export class CdpCaptureEvents {
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve a transient execution context to one already authorized frame. */
|
||||
frameForScript(
|
||||
script: CapturedScript,
|
||||
allowedFrameIds: ReadonlySet<string>,
|
||||
): string | null {
|
||||
if (script.executionContextKey === null) return null;
|
||||
const frameId = this.executionContextFrames.get(script.executionContextKey);
|
||||
return frameId !== undefined && allowedFrameIds.has(frameId)
|
||||
? frameId
|
||||
: null;
|
||||
}
|
||||
|
||||
#executionContext(params: UnknownRecord): void {
|
||||
const context = recordValue(params.context);
|
||||
const identifier = numberValue(context?.id);
|
||||
const frameId = stringValue(recordValue(context?.auxData)?.frameId);
|
||||
if (
|
||||
identifier === undefined ||
|
||||
!Number.isSafeInteger(identifier) ||
|
||||
frameId === undefined ||
|
||||
frameId.length > 256
|
||||
)
|
||||
return;
|
||||
const key = String(identifier);
|
||||
if (
|
||||
this.executionContextFrames.size >= this.input.limits.max_scripts &&
|
||||
!this.executionContextFrames.has(key)
|
||||
) {
|
||||
this.completeness.truncate("scripts");
|
||||
return;
|
||||
}
|
||||
this.executionContextFrames.set(key, frameId);
|
||||
}
|
||||
|
||||
#destroyExecutionContext(params: UnknownRecord): void {
|
||||
const key = executionContextKey(params.executionContextId);
|
||||
if (key !== null) this.executionContextFrames.delete(key);
|
||||
}
|
||||
|
||||
#script(params: UnknownRecord): void {
|
||||
const scriptId = stringValue(params.scriptId);
|
||||
const rawUrl = stringValue(params.url) ?? "";
|
||||
@@ -160,6 +211,7 @@ export class CdpCaptureEvents {
|
||||
language: boundedText(params.scriptLanguage, 100),
|
||||
sourceMapUrl: sourceMap.sanitized,
|
||||
sourceMapRawUrl: sourceMap.raw,
|
||||
executionContextKey: executionContextKey(params.executionContextId),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -624,6 +676,13 @@ const integerOrNull = (value: unknown): number | null => {
|
||||
return number === undefined ? null : Math.max(0, Math.trunc(number));
|
||||
};
|
||||
|
||||
const executionContextKey = (value: unknown): string | null => {
|
||||
const identifier = numberValue(value);
|
||||
return identifier !== undefined && Number.isSafeInteger(identifier)
|
||||
? String(identifier)
|
||||
: null;
|
||||
};
|
||||
|
||||
const isJsonContentType = (headers: UnknownRecord | undefined): boolean => {
|
||||
if (headers === undefined) return false;
|
||||
for (const [name, value] of Object.entries(headers))
|
||||
|
||||
@@ -8,12 +8,10 @@ import type {
|
||||
InspectElectronPageInput,
|
||||
} from "../domain/electronObservation.js";
|
||||
import { BrowserObservationError } from "../domain/errors.js";
|
||||
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
|
||||
import type { CdpConnection, CdpEvent } from "./CdpConnection.js";
|
||||
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import {
|
||||
boundedText,
|
||||
delayWithCancellation,
|
||||
numberValue,
|
||||
recordValue,
|
||||
@@ -22,6 +20,12 @@ import {
|
||||
stringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import {
|
||||
ingestElectronScriptEvent,
|
||||
type ElectronScriptDraft,
|
||||
} from "./CdpElectronScriptEvents.js";
|
||||
import { captureElectronScripts } from "./CdpElectronScripts.js";
|
||||
import { captureElectronWorkers } from "./CdpElectronWorkers.js";
|
||||
import {
|
||||
authorizedElectronFile,
|
||||
canonicalElectronRoots,
|
||||
@@ -37,124 +41,199 @@ interface ElectronContext {
|
||||
readonly progress?: ProgressReporter;
|
||||
}
|
||||
|
||||
interface ScriptDraft {
|
||||
readonly scriptId: string;
|
||||
readonly rawUrl: string;
|
||||
readonly hash: string;
|
||||
readonly length: number;
|
||||
readonly isModule: boolean;
|
||||
readonly language: string | null;
|
||||
interface ElectronInspectionState {
|
||||
readonly roots: readonly string[];
|
||||
readonly completeness: CdpCaptureCompleteness;
|
||||
readonly scripts: ElectronScriptDraft[];
|
||||
readonly executionContextFrames: Map<string, string>;
|
||||
readonly limitations: string[];
|
||||
mainFrameId: string | undefined;
|
||||
navigationDuringCapture: boolean;
|
||||
}
|
||||
|
||||
/** Passively inspect one root-confined Electron file page. */
|
||||
export const inspectCdpElectronPage = async (
|
||||
context: ElectronContext,
|
||||
): Promise<ElectronPageInspection> => {
|
||||
const roots = await canonicalElectronRoots(context.input.allowed_file_roots);
|
||||
const completeness = new CdpCaptureCompleteness();
|
||||
const scripts: ScriptDraft[] = [];
|
||||
let mainFrameId: string | undefined;
|
||||
let navigationDuringCapture = false;
|
||||
const state: ElectronInspectionState = {
|
||||
roots: await canonicalElectronRoots(context.input.allowed_file_roots),
|
||||
completeness: new CdpCaptureCompleteness(),
|
||||
scripts: [],
|
||||
executionContextFrames: new Map(),
|
||||
limitations: [
|
||||
"Only canonical file paths contained by an approved root are retained.",
|
||||
"REA does not evaluate renderer JavaScript, invoke Electron APIs, navigate, click, or close the page.",
|
||||
"Script contents require separate source-capture approval and remain byte bounded.",
|
||||
],
|
||||
mainFrameId: undefined,
|
||||
navigationDuringCapture: false,
|
||||
};
|
||||
const removeListener = context.connection.onEvent((event) => {
|
||||
if (event.sessionId !== context.sessionId) return;
|
||||
ingestScript(event, scripts, completeness);
|
||||
if (mainFrameId !== undefined && navigatedFrameId(event) === mainFrameId)
|
||||
navigationDuringCapture = true;
|
||||
ingestElectronScriptEvent({
|
||||
event,
|
||||
scripts: state.scripts,
|
||||
executionContextFrames: state.executionContextFrames,
|
||||
completeness: state.completeness,
|
||||
});
|
||||
if (
|
||||
state.mainFrameId !== undefined &&
|
||||
navigatedFrameId(event) === state.mainFrameId
|
||||
)
|
||||
state.navigationDuringCapture = true;
|
||||
});
|
||||
const startedAt = new Date().toISOString();
|
||||
try {
|
||||
await report(context.progress, 1, "Authorizing Electron file frames");
|
||||
await context.connection.send(
|
||||
"Page.enable",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const before = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const frames = await captureFrames(
|
||||
before,
|
||||
roots,
|
||||
context.input.limits.max_frames,
|
||||
completeness,
|
||||
);
|
||||
const main = frames[0];
|
||||
if (main === undefined)
|
||||
throw new BrowserObservationError(
|
||||
"inspect_web_page",
|
||||
"target_not_allowed",
|
||||
);
|
||||
mainFrameId = main.frame_id;
|
||||
await context.connection.send(
|
||||
"Debugger.enable",
|
||||
{ maxScriptsCacheSize: 4 * 1_024 * 1_024 },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
await delayWithCancellation(
|
||||
context.input.observation_ms,
|
||||
"inspect_electron_page",
|
||||
context.signal,
|
||||
);
|
||||
await report(context.progress, 2, "Capturing Electron structure");
|
||||
const resources = await captureResources(context, roots, completeness);
|
||||
const dom = await captureDom(context, roots, completeness);
|
||||
const normalizedScripts = await captureScripts(
|
||||
return await runElectronInspection(
|
||||
context,
|
||||
roots,
|
||||
scripts,
|
||||
completeness,
|
||||
state,
|
||||
new Date().toISOString(),
|
||||
);
|
||||
const after = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const afterMain = await mainFilePath(after, roots);
|
||||
if (afterMain === undefined)
|
||||
throw new BrowserObservationError(
|
||||
"inspect_web_page",
|
||||
"target_not_allowed",
|
||||
);
|
||||
if (navigationDuringCapture || afterMain !== main.file_path)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_changed");
|
||||
await report(context.progress, 3, "Electron inspection complete");
|
||||
return {
|
||||
schema_version: 1,
|
||||
browser: context.discovery.version,
|
||||
target: {
|
||||
target_id: context.target.id,
|
||||
type: context.target.type,
|
||||
title: context.target.title.slice(0, 16_384),
|
||||
file_path: main.file_path,
|
||||
attached: context.target.attached,
|
||||
},
|
||||
capture_window: {
|
||||
started_at: startedAt,
|
||||
ended_at: new Date().toISOString(),
|
||||
observation_ms: context.input.observation_ms,
|
||||
},
|
||||
completeness: completeness.snapshot(),
|
||||
frames,
|
||||
dom,
|
||||
scripts: normalizedScripts,
|
||||
resources,
|
||||
limitations: [
|
||||
"Only canonical file paths contained by an approved root are retained.",
|
||||
"REA does not evaluate renderer JavaScript, invoke Electron APIs, navigate, click, or close the page.",
|
||||
"Script contents require separate source-capture approval and remain byte bounded.",
|
||||
],
|
||||
};
|
||||
} finally {
|
||||
removeListener();
|
||||
}
|
||||
};
|
||||
|
||||
const runElectronInspection = async (
|
||||
context: ElectronContext,
|
||||
state: ElectronInspectionState,
|
||||
startedAt: string,
|
||||
): Promise<ElectronPageInspection> => {
|
||||
const frames = await authorizeInitialFrames(context, state);
|
||||
const main = frames[0]!;
|
||||
state.mainFrameId = main.frame_id;
|
||||
await enableElectronCapture(context);
|
||||
await delayWithCancellation(
|
||||
context.input.observation_ms,
|
||||
"inspect_electron_page",
|
||||
context.signal,
|
||||
);
|
||||
const captured = await captureElectronContent(context, state, frames);
|
||||
await assertStableMainFrame(context, state, main.file_path);
|
||||
await report(context.progress, 3, "Electron inspection complete");
|
||||
return {
|
||||
schema_version: 1,
|
||||
browser: context.discovery.version,
|
||||
target: {
|
||||
target_id: context.target.id,
|
||||
type: context.target.type,
|
||||
title: context.target.title.slice(0, 16_384),
|
||||
file_path: main.file_path,
|
||||
attached: context.target.attached,
|
||||
},
|
||||
capture_window: {
|
||||
started_at: startedAt,
|
||||
ended_at: new Date().toISOString(),
|
||||
observation_ms: context.input.observation_ms,
|
||||
},
|
||||
completeness: state.completeness.snapshot(),
|
||||
frames,
|
||||
...captured,
|
||||
limitations: state.limitations,
|
||||
};
|
||||
};
|
||||
|
||||
const authorizeInitialFrames = async (
|
||||
context: ElectronContext,
|
||||
state: ElectronInspectionState,
|
||||
): Promise<ElectronPageInspection["frames"]> => {
|
||||
await report(context.progress, 1, "Authorizing Electron file frames");
|
||||
await context.connection.send(
|
||||
"Page.enable",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const result = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const frames = await captureFrames(
|
||||
result,
|
||||
state.roots,
|
||||
context.input.limits.max_frames,
|
||||
state.completeness,
|
||||
);
|
||||
if (frames[0] === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
return frames;
|
||||
};
|
||||
|
||||
const enableElectronCapture = async (
|
||||
context: ElectronContext,
|
||||
): Promise<void> => {
|
||||
await context.connection.send(
|
||||
"Runtime.enable",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
await context.connection.send(
|
||||
"Debugger.enable",
|
||||
{ maxScriptsCacheSize: 4 * 1_024 * 1_024 },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
};
|
||||
|
||||
const captureElectronContent = async (
|
||||
context: ElectronContext,
|
||||
state: ElectronInspectionState,
|
||||
frames: ElectronPageInspection["frames"],
|
||||
): Promise<
|
||||
Pick<ElectronPageInspection, "dom" | "scripts" | "resources" | "workers">
|
||||
> => {
|
||||
await report(context.progress, 2, "Capturing Electron structure");
|
||||
const frameIds = new Set(frames.map((frame) => frame.frame_id));
|
||||
const resources = await captureResources(
|
||||
context,
|
||||
state.roots,
|
||||
state.completeness,
|
||||
);
|
||||
const dom = await captureDom(context, state.roots, state.completeness);
|
||||
const scripts = await captureElectronScripts({
|
||||
connection: context.connection,
|
||||
sessionId: context.sessionId,
|
||||
...(context.signal === undefined ? {} : { signal: context.signal }),
|
||||
request: context.input,
|
||||
roots: state.roots,
|
||||
scripts: state.scripts,
|
||||
executionContextFrames: state.executionContextFrames,
|
||||
frameIds,
|
||||
completeness: state.completeness,
|
||||
});
|
||||
const workers = await captureElectronWorkers({
|
||||
connection: context.connection,
|
||||
...(context.signal === undefined ? {} : { signal: context.signal }),
|
||||
target: context.target,
|
||||
request: context.input,
|
||||
roots: state.roots,
|
||||
frameIds,
|
||||
completeness: state.completeness,
|
||||
limitations: state.limitations,
|
||||
});
|
||||
return { dom, scripts, resources, workers };
|
||||
};
|
||||
|
||||
const assertStableMainFrame = async (
|
||||
context: ElectronContext,
|
||||
state: ElectronInspectionState,
|
||||
expectedPath: string,
|
||||
): Promise<void> => {
|
||||
const result = await context.connection.send(
|
||||
"Page.getFrameTree",
|
||||
{},
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
);
|
||||
const afterPath = await mainFilePath(result, state.roots);
|
||||
if (afterPath === undefined)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_not_allowed");
|
||||
if (state.navigationDuringCapture || afterPath !== expectedPath)
|
||||
throw new BrowserObservationError("inspect_web_page", "target_changed");
|
||||
};
|
||||
|
||||
const navigatedFrameId = (event: CdpEvent): string | undefined => {
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return undefined;
|
||||
@@ -165,37 +244,6 @@ const navigatedFrameId = (event: CdpEvent): string | undefined => {
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const ingestScript = (
|
||||
event: CdpEvent,
|
||||
scripts: ScriptDraft[],
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): void => {
|
||||
if (event.method !== "Debugger.scriptParsed") return;
|
||||
const value = recordValue(event.params);
|
||||
const scriptId = stringValue(value?.scriptId);
|
||||
const rawUrl = stringValue(value?.url);
|
||||
if (scriptId === undefined || scriptId.length > 256) {
|
||||
completeness.exclude("scripts", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (rawUrl === undefined || rawUrl === "") {
|
||||
completeness.exclude("scripts", "unattributed_origin");
|
||||
return;
|
||||
}
|
||||
if (scripts.length >= 2_000) {
|
||||
completeness.drop("scripts");
|
||||
return;
|
||||
}
|
||||
scripts.push({
|
||||
scriptId,
|
||||
rawUrl,
|
||||
hash: (stringValue(value?.hash) ?? "").slice(0, 512),
|
||||
length: nonnegativeInteger(value?.length),
|
||||
isModule: value?.isModule === true,
|
||||
language: boundedText(value?.scriptLanguage, 100),
|
||||
});
|
||||
};
|
||||
|
||||
const captureFrames = async (
|
||||
result: unknown,
|
||||
roots: readonly string[],
|
||||
@@ -350,98 +398,6 @@ const captureDom = async (
|
||||
return { total_nodes: total, nodes };
|
||||
};
|
||||
|
||||
const captureScripts = async (
|
||||
context: ElectronContext,
|
||||
roots: readonly string[],
|
||||
scripts: readonly ScriptDraft[],
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): Promise<ElectronPageInspection["scripts"]> => {
|
||||
let total = 0;
|
||||
let sourceBytes = 0;
|
||||
const items: ElectronPageInspection["scripts"]["items"] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const script of scripts) {
|
||||
const path = await authorizedElectronFile(script.rawUrl, roots);
|
||||
if (path === undefined) {
|
||||
completeness.exclude("scripts", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
const identity = {
|
||||
file_path: path,
|
||||
cdp_hash: script.hash,
|
||||
length: script.length,
|
||||
is_module: script.isModule,
|
||||
language: script.language,
|
||||
};
|
||||
const scriptKey = `electron_script_${digest(identity)}`;
|
||||
if (seen.has(scriptKey)) continue;
|
||||
seen.add(scriptKey);
|
||||
total += 1;
|
||||
if (items.length >= context.input.limits.max_scripts) {
|
||||
completeness.drop("scripts");
|
||||
continue;
|
||||
}
|
||||
let source: ElectronPageInspection["scripts"]["items"][number]["source"] = {
|
||||
included: false,
|
||||
reason: "source capture was not approved",
|
||||
};
|
||||
if (context.input.include_script_sources) {
|
||||
if (
|
||||
script.length > context.input.limits.max_script_source_bytes ||
|
||||
sourceBytes + script.length >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
source = {
|
||||
included: false,
|
||||
reason: "script source byte limit reached",
|
||||
};
|
||||
completeness.truncate("script_sources");
|
||||
} else {
|
||||
const result = requiredRecord(
|
||||
await context.connection.send(
|
||||
"Debugger.getScriptSource",
|
||||
{ scriptId: script.scriptId },
|
||||
context.sessionId,
|
||||
context.signal,
|
||||
),
|
||||
);
|
||||
const text = stringValue(result.scriptSource) ?? "";
|
||||
const bytes = Buffer.byteLength(text);
|
||||
if (
|
||||
bytes > context.input.limits.max_script_source_bytes ||
|
||||
sourceBytes + bytes >
|
||||
context.input.limits.max_total_script_source_bytes
|
||||
) {
|
||||
source = {
|
||||
included: false,
|
||||
reason: "script source byte limit reached",
|
||||
};
|
||||
completeness.truncate("script_sources");
|
||||
} else {
|
||||
source = {
|
||||
included: true,
|
||||
artifact: createWebTextArtifact(text, "text/javascript"),
|
||||
};
|
||||
sourceBytes += bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
items.push({
|
||||
script_key: scriptKey,
|
||||
...identity,
|
||||
source,
|
||||
});
|
||||
}
|
||||
if (!context.input.include_script_sources)
|
||||
completeness.exclude("script_sources", "not_approved", total);
|
||||
return {
|
||||
total,
|
||||
items: items.sort((left, right) =>
|
||||
left.script_key.localeCompare(right.script_key),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const mainFilePath = async (
|
||||
result: unknown,
|
||||
roots: readonly string[],
|
||||
@@ -462,9 +418,6 @@ const integer = (value: unknown, fallback: number): number => {
|
||||
return number === undefined ? fallback : Math.trunc(number);
|
||||
};
|
||||
|
||||
const nonnegativeInteger = (value: unknown): number =>
|
||||
Math.max(0, integer(value, 0));
|
||||
|
||||
const digest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined) throw new TypeError("Expected canonical JSON");
|
||||
|
||||
@@ -166,7 +166,11 @@ export class CdpElectronProvider implements ElectronObservationPort {
|
||||
return err(providerError(cause, "inspect_electron_page"));
|
||||
} finally {
|
||||
if (targetSession !== undefined)
|
||||
await closeCdpTargetSession(targetSession, ["Debugger", "Page"]);
|
||||
await closeCdpTargetSession(targetSession, [
|
||||
"Debugger",
|
||||
"Runtime",
|
||||
"Page",
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { CdpEvent } from "./CdpConnection.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import {
|
||||
boundedText,
|
||||
numberValue,
|
||||
recordValue,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
|
||||
export interface ElectronScriptDraft {
|
||||
readonly scriptId: string;
|
||||
readonly rawUrl: string;
|
||||
readonly hash: string;
|
||||
readonly length: number;
|
||||
readonly isModule: boolean;
|
||||
readonly language: string | null;
|
||||
readonly executionContextKey: string | null;
|
||||
}
|
||||
|
||||
/** Retain only bounded script/frame metadata from passive Electron events. */
|
||||
export const ingestElectronScriptEvent = (input: {
|
||||
readonly event: CdpEvent;
|
||||
readonly scripts: ElectronScriptDraft[];
|
||||
readonly executionContextFrames: Map<string, string>;
|
||||
readonly completeness: CdpCaptureCompleteness;
|
||||
}): void => {
|
||||
if (input.event.method === "Runtime.executionContextsCleared") {
|
||||
input.executionContextFrames.clear();
|
||||
return;
|
||||
}
|
||||
if (input.event.method === "Runtime.executionContextDestroyed") {
|
||||
const parameters = recordValue(input.event.params);
|
||||
const key = executionContextKey(parameters?.executionContextId);
|
||||
if (key !== null) input.executionContextFrames.delete(key);
|
||||
return;
|
||||
}
|
||||
if (input.event.method === "Runtime.executionContextCreated") {
|
||||
retainExecutionContext(
|
||||
input.event,
|
||||
input.executionContextFrames,
|
||||
input.completeness,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (input.event.method !== "Debugger.scriptParsed") return;
|
||||
const value = recordValue(input.event.params);
|
||||
const scriptId = stringValue(value?.scriptId);
|
||||
const rawUrl = stringValue(value?.url);
|
||||
if (scriptId === undefined || scriptId.length > 256) {
|
||||
input.completeness.exclude("scripts", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (rawUrl === undefined || rawUrl === "") {
|
||||
input.completeness.exclude("scripts", "unattributed_origin");
|
||||
return;
|
||||
}
|
||||
if (input.scripts.length >= 2_000) {
|
||||
input.completeness.drop("scripts");
|
||||
return;
|
||||
}
|
||||
input.scripts.push({
|
||||
scriptId,
|
||||
rawUrl,
|
||||
hash: (stringValue(value?.hash) ?? "").slice(0, 512),
|
||||
length: nonnegativeInteger(value?.length),
|
||||
isModule: value?.isModule === true,
|
||||
language: boundedText(value?.scriptLanguage, 100),
|
||||
executionContextKey: executionContextKey(value?.executionContextId),
|
||||
});
|
||||
};
|
||||
|
||||
const retainExecutionContext = (
|
||||
event: CdpEvent,
|
||||
frames: Map<string, string>,
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): void => {
|
||||
const parameters = recordValue(event.params);
|
||||
const runtimeContext = recordValue(parameters?.context);
|
||||
const contextKey = executionContextKey(runtimeContext?.id);
|
||||
const frameId = stringValue(recordValue(runtimeContext?.auxData)?.frameId);
|
||||
if (contextKey === null || frameId === undefined || frameId.length > 256)
|
||||
return;
|
||||
if (frames.size >= 2_000 && !frames.has(contextKey)) {
|
||||
completeness.truncate("scripts");
|
||||
return;
|
||||
}
|
||||
frames.set(contextKey, frameId);
|
||||
};
|
||||
|
||||
const nonnegativeInteger = (value: unknown): number => {
|
||||
const number = numberValue(value);
|
||||
return number === undefined ? 0 : Math.max(0, Math.trunc(number));
|
||||
};
|
||||
|
||||
const executionContextKey = (value: unknown): string | null => {
|
||||
const identifier = numberValue(value);
|
||||
return identifier !== undefined && Number.isSafeInteger(identifier)
|
||||
? String(identifier)
|
||||
: null;
|
||||
};
|
||||
@@ -0,0 +1,151 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import type {
|
||||
ElectronPageInspection,
|
||||
InspectElectronPageInput,
|
||||
} from "../domain/electronObservation.js";
|
||||
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
|
||||
import type { CdpConnection } from "./CdpConnection.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import { requiredRecord, stringValue } from "./CdpCaptureValues.js";
|
||||
import type { ElectronScriptDraft } from "./CdpElectronScriptEvents.js";
|
||||
import { authorizedElectronFile } from "./ElectronFileScope.js";
|
||||
|
||||
interface ElectronScriptCaptureInput {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string | undefined;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly request: InspectElectronPageInput;
|
||||
readonly roots: readonly string[];
|
||||
readonly scripts: readonly ElectronScriptDraft[];
|
||||
readonly executionContextFrames: ReadonlyMap<string, string>;
|
||||
readonly frameIds: ReadonlySet<string>;
|
||||
readonly completeness: CdpCaptureCompleteness;
|
||||
}
|
||||
|
||||
/** Normalize root-confined script metadata and optionally approved source. */
|
||||
export const captureElectronScripts = async (
|
||||
input: ElectronScriptCaptureInput,
|
||||
): Promise<ElectronPageInspection["scripts"]> => {
|
||||
let total = 0;
|
||||
let sourceBytes = 0;
|
||||
const items: ElectronPageInspection["scripts"]["items"] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const script of input.scripts) {
|
||||
const path = await authorizedElectronFile(script.rawUrl, input.roots);
|
||||
if (path === undefined) {
|
||||
input.completeness.exclude("scripts", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
const mappedFrame =
|
||||
script.executionContextKey === null
|
||||
? undefined
|
||||
: input.executionContextFrames.get(script.executionContextKey);
|
||||
const identity = {
|
||||
frame_id:
|
||||
mappedFrame !== undefined && input.frameIds.has(mappedFrame)
|
||||
? mappedFrame
|
||||
: null,
|
||||
file_path: path,
|
||||
cdp_hash: script.hash,
|
||||
length: script.length,
|
||||
is_module: script.isModule,
|
||||
language: script.language,
|
||||
};
|
||||
const scriptKey = `electron_script_${digest(identity)}`;
|
||||
if (seen.has(scriptKey)) continue;
|
||||
seen.add(scriptKey);
|
||||
total += 1;
|
||||
if (items.length >= input.request.limits.max_scripts) {
|
||||
input.completeness.drop("scripts");
|
||||
continue;
|
||||
}
|
||||
const capturedSource = await captureScriptSource(
|
||||
input,
|
||||
script,
|
||||
sourceBytes,
|
||||
);
|
||||
sourceBytes += capturedSource.bytes;
|
||||
items.push({
|
||||
script_key: scriptKey,
|
||||
...identity,
|
||||
source: capturedSource.source,
|
||||
});
|
||||
}
|
||||
if (!input.request.include_script_sources)
|
||||
input.completeness.exclude("script_sources", "not_approved", total);
|
||||
return {
|
||||
total,
|
||||
items: items.sort((left, right) =>
|
||||
left.script_key.localeCompare(right.script_key),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
type ElectronScriptSource =
|
||||
ElectronPageInspection["scripts"]["items"][number]["source"];
|
||||
|
||||
const captureScriptSource = async (
|
||||
input: ElectronScriptCaptureInput,
|
||||
script: ElectronScriptDraft,
|
||||
sourceBytes: number,
|
||||
): Promise<{
|
||||
readonly source: ElectronScriptSource;
|
||||
readonly bytes: number;
|
||||
}> => {
|
||||
if (!input.request.include_script_sources)
|
||||
return {
|
||||
source: {
|
||||
included: false,
|
||||
reason: "source capture was not approved",
|
||||
},
|
||||
bytes: 0,
|
||||
};
|
||||
if (sourceLimitReached(input.request.limits, script.length, sourceBytes))
|
||||
return sourceLimitResult(input.completeness);
|
||||
const result = requiredRecord(
|
||||
await input.connection.send(
|
||||
"Debugger.getScriptSource",
|
||||
{ scriptId: script.scriptId },
|
||||
input.sessionId,
|
||||
input.signal,
|
||||
),
|
||||
);
|
||||
const text = stringValue(result.scriptSource) ?? "";
|
||||
const bytes = Buffer.byteLength(text);
|
||||
if (sourceLimitReached(input.request.limits, bytes, sourceBytes))
|
||||
return sourceLimitResult(input.completeness);
|
||||
return {
|
||||
source: {
|
||||
included: true,
|
||||
artifact: createWebTextArtifact(text, "text/javascript"),
|
||||
},
|
||||
bytes,
|
||||
};
|
||||
};
|
||||
|
||||
const sourceLimitReached = (
|
||||
limits: InspectElectronPageInput["limits"],
|
||||
bytes: number,
|
||||
previousBytes: number,
|
||||
): boolean =>
|
||||
bytes > limits.max_script_source_bytes ||
|
||||
previousBytes + bytes > limits.max_total_script_source_bytes;
|
||||
|
||||
const sourceLimitResult = (
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): { readonly source: ElectronScriptSource; readonly bytes: 0 } => {
|
||||
completeness.truncate("script_sources");
|
||||
return {
|
||||
source: { included: false, reason: "script source byte limit reached" },
|
||||
bytes: 0,
|
||||
};
|
||||
};
|
||||
|
||||
const digest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined) throw new TypeError("Expected canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
import type {
|
||||
ElectronPageInspection,
|
||||
InspectElectronPageInput,
|
||||
} from "../domain/electronObservation.js";
|
||||
import type { CdpConnection } from "./CdpConnection.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import {
|
||||
boundedText,
|
||||
recordValue,
|
||||
recordsValue,
|
||||
stringValue,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import type { CdpEndpointTarget } from "./CdpEndpoint.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
import { authorizedElectronFile } from "./ElectronFileScope.js";
|
||||
|
||||
/** Inventory root-confined worker targets without attaching to them. */
|
||||
export const captureElectronWorkers = async (input: {
|
||||
readonly connection: CdpConnection;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly target: CdpEndpointTarget;
|
||||
readonly request: InspectElectronPageInput;
|
||||
readonly roots: readonly string[];
|
||||
readonly frameIds: ReadonlySet<string>;
|
||||
readonly completeness: CdpCaptureCompleteness;
|
||||
readonly limitations: string[];
|
||||
}): Promise<ElectronPageInspection["workers"]> => {
|
||||
const result = await optionalCdpCommand(
|
||||
{
|
||||
connection: input.connection,
|
||||
sessionId: undefined,
|
||||
...(input.signal === undefined ? {} : { signal: input.signal }),
|
||||
},
|
||||
"Target.getTargets",
|
||||
{},
|
||||
input.limitations,
|
||||
);
|
||||
if (result === undefined) {
|
||||
input.completeness.unavailable("workers");
|
||||
return [];
|
||||
}
|
||||
const workers: ElectronPageInspection["workers"] = [];
|
||||
for (const target of recordsValue(recordValue(result)?.targetInfos)) {
|
||||
const type = stringValue(target.type) ?? "";
|
||||
if (!type.includes("worker")) continue;
|
||||
const openerTargetId = boundedTargetField(target.openerId);
|
||||
const parentFrameId = boundedTargetField(target.parentFrameId);
|
||||
if (
|
||||
openerTargetId !== input.target.id &&
|
||||
(parentFrameId === null || !input.frameIds.has(parentFrameId))
|
||||
) {
|
||||
input.completeness.exclude("workers", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
const path = await authorizedElectronFile(
|
||||
stringValue(target.url) ?? "",
|
||||
input.roots,
|
||||
);
|
||||
if (path === undefined) {
|
||||
input.completeness.exclude("workers", "out_of_target_scope");
|
||||
continue;
|
||||
}
|
||||
if (workers.length >= input.request.limits.max_workers) {
|
||||
input.completeness.truncate("workers");
|
||||
continue;
|
||||
}
|
||||
const targetId = boundedTargetField(target.targetId);
|
||||
if (targetId === null) {
|
||||
input.completeness.exclude("workers", "invalid_protocol_value");
|
||||
continue;
|
||||
}
|
||||
workers.push({
|
||||
target_id: targetId,
|
||||
type: type.slice(0, 100),
|
||||
file_path: path,
|
||||
attached: target.attached === true,
|
||||
opener_target_id: openerTargetId,
|
||||
parent_frame_id: parentFrameId,
|
||||
});
|
||||
}
|
||||
return workers.sort((left, right) =>
|
||||
left.target_id.localeCompare(right.target_id),
|
||||
);
|
||||
};
|
||||
|
||||
const boundedTargetField = (value: unknown): string | null => {
|
||||
const field = boundedText(value, 256);
|
||||
return field === null || field === "" ? null : field;
|
||||
};
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
} from "./CdpCaptureDocuments.js";
|
||||
import {
|
||||
allowedSanitizedUrl,
|
||||
boundedText,
|
||||
delayWithCancellation,
|
||||
isHttpUrl,
|
||||
recordValue,
|
||||
@@ -153,6 +154,7 @@ const captureAuthorizedPage = async (
|
||||
state.events,
|
||||
resourceCapture.items,
|
||||
resources,
|
||||
new Set(frames.map((frame) => frame.frame_id)),
|
||||
);
|
||||
const workerCapture = await captureWorkers(
|
||||
state,
|
||||
@@ -406,6 +408,7 @@ const captureScripts = async (
|
||||
events: CdpCaptureEvents,
|
||||
rawResources: readonly CapturedResource[],
|
||||
resources: WebPageInspection["resources"],
|
||||
frameIds: ReadonlySet<string>,
|
||||
): Promise<CapturedScripts> => {
|
||||
let totalSourceBytes = 0;
|
||||
const drafts: {
|
||||
@@ -457,6 +460,7 @@ const captureScripts = async (
|
||||
}
|
||||
}
|
||||
const inventoryScript = {
|
||||
frame_id: events.frameForScript(script, frameIds),
|
||||
url: script.url,
|
||||
cdp_hash: script.hash,
|
||||
length: script.length,
|
||||
@@ -493,7 +497,8 @@ const captureScripts = async (
|
||||
left.base.localeCompare(right.base) ||
|
||||
sourceDigest(left.item.source).localeCompare(
|
||||
sourceDigest(right.item.source),
|
||||
),
|
||||
) ||
|
||||
(left.item.frame_id ?? "").localeCompare(right.item.frame_id ?? ""),
|
||||
);
|
||||
const totals = new Map<string, number>();
|
||||
for (const { base } of keyed) totals.set(base, (totals.get(base) ?? 0) + 1);
|
||||
@@ -587,6 +592,8 @@ const captureWorkers = async (
|
||||
url: url.url,
|
||||
origin: url.origin,
|
||||
attached: target.attached === true,
|
||||
opener_target_id: boundedText(target.openerId, 256) ?? null,
|
||||
parent_frame_id: boundedText(target.parentFrameId, 256) ?? null,
|
||||
});
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -39,6 +39,7 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
listElectronTargets: "list-electron-targets",
|
||||
inspectElectronPage: "inspect-electron-page",
|
||||
analyzeJavaScriptApplication: "analyze-javascript-application",
|
||||
reconcileJavaScriptRuntime: "reconcile-javascript-runtime",
|
||||
});
|
||||
|
||||
/** Ordered primary CLI inventory; aliases are intentionally excluded. */
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
|
||||
import { Cli, z } from "incur";
|
||||
|
||||
import {
|
||||
@@ -5,6 +7,7 @@ import {
|
||||
listElectronTargets,
|
||||
} from "./application/ElectronObservationService.js";
|
||||
import { analyzeJavaScriptApplication } from "./application/JavaScriptApplicationService.js";
|
||||
import { reconcileJavaScriptRuntimeEvidence } from "./application/JavaScriptRuntimeReconciliationService.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import { CdpElectronProvider } from "./browser/CdpElectronProvider.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
@@ -19,6 +22,8 @@ import type { JsonValue } from "./domain/jsonValue.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
|
||||
const MAX_RECONCILIATION_INPUT_BYTES = 64 * 1_024 * 1_024;
|
||||
|
||||
const scopeOptions = {
|
||||
allowedFileRoots: z
|
||||
.array(z.string().min(1))
|
||||
@@ -34,6 +39,35 @@ export const registerElectronCommands = (
|
||||
): void => {
|
||||
registerElectronObservationCommands(cli, logger);
|
||||
registerJavaScriptApplicationCommand(cli, logger);
|
||||
registerJavaScriptRuntimeReconciliationCommand(cli, logger);
|
||||
};
|
||||
|
||||
const registerJavaScriptRuntimeReconciliationCommand = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.reconcileJavaScriptRuntime, {
|
||||
description:
|
||||
"Reconcile static application and passive runtime Evidence JSON",
|
||||
args: z.object({
|
||||
inputJson: z
|
||||
.string()
|
||||
.describe(
|
||||
"Inline JSON or a JSON file path matching reconcile_javascript_runtime",
|
||||
),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(
|
||||
logger,
|
||||
CLI_COMMANDS.reconcileJavaScriptRuntime,
|
||||
async () => {
|
||||
const input = await parseJsonInput(args.inputJson);
|
||||
if (!input.ok) return input.error;
|
||||
const result = reconcileJavaScriptRuntimeEvidence(input.value);
|
||||
return result.ok ? result.value : cliError(result.error);
|
||||
},
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const registerElectronObservationCommands = (
|
||||
@@ -81,6 +115,7 @@ const registerElectronObservationCommands = (
|
||||
maxDomNodes: z.number().int().min(1).max(10_000).default(2_000),
|
||||
maxScripts: z.number().int().min(1).max(2_000).default(500),
|
||||
maxResources: z.number().int().min(1).max(10_000).default(2_000),
|
||||
maxWorkers: z.number().int().min(1).max(5_000).default(500),
|
||||
maxScriptSourceBytes: z
|
||||
.number()
|
||||
.int()
|
||||
@@ -112,6 +147,7 @@ const registerElectronObservationCommands = (
|
||||
max_dom_nodes: options.maxDomNodes,
|
||||
max_scripts: options.maxScripts,
|
||||
max_resources: options.maxResources,
|
||||
max_workers: options.maxWorkers,
|
||||
max_script_source_bytes: options.maxScriptSourceBytes,
|
||||
max_total_script_source_bytes: options.maxTotalScriptSourceBytes,
|
||||
},
|
||||
@@ -230,6 +266,60 @@ const electronContext = async () => {
|
||||
const inputError = (operation: string): JsonValue =>
|
||||
cliError(new AnalysisInputError(operation));
|
||||
|
||||
const parseJson = (value: string): unknown => {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const parseJsonInput = async (
|
||||
value: string,
|
||||
): Promise<
|
||||
| { readonly ok: true; readonly value: unknown }
|
||||
| { readonly ok: false; readonly error: JsonValue }
|
||||
> => {
|
||||
const inline = parseJson(value);
|
||||
if (inline !== undefined) return { ok: true, value: inline };
|
||||
if (["{", "["].includes(value.trimStart()[0] ?? ""))
|
||||
return {
|
||||
ok: false,
|
||||
error: inputError("reconcile_javascript_runtime"),
|
||||
};
|
||||
try {
|
||||
const metadata = await stat(value);
|
||||
if (!metadata.isFile()) return jsonFileError(value, "not-file");
|
||||
if (metadata.size > MAX_RECONCILIATION_INPUT_BYTES)
|
||||
return jsonFileError(value, "too-large");
|
||||
const bytes = await readFile(value);
|
||||
if (bytes.byteLength > MAX_RECONCILIATION_INPUT_BYTES)
|
||||
return jsonFileError(value, "too-large");
|
||||
const parsed = parseJson(bytes.toString("utf8"));
|
||||
return parsed === undefined
|
||||
? jsonFileError(value, "invalid-json")
|
||||
: { ok: true, value: parsed };
|
||||
} catch {
|
||||
return jsonFileError(value, "read-failed");
|
||||
}
|
||||
};
|
||||
|
||||
const jsonFileError = (
|
||||
path: string,
|
||||
reason: "not-file" | "too-large" | "invalid-json" | "read-failed",
|
||||
) => ({
|
||||
ok: false as const,
|
||||
error: {
|
||||
error: "Electron analysis failed",
|
||||
...projectAnalysisError(
|
||||
new AnalysisInputError("reconcile_javascript_runtime"),
|
||||
),
|
||||
input_path: path,
|
||||
input_reason: reason,
|
||||
maximum_input_bytes: MAX_RECONCILIATION_INPUT_BYTES,
|
||||
},
|
||||
});
|
||||
|
||||
const cliError = (
|
||||
error: Parameters<typeof projectAnalysisError>[0],
|
||||
): JsonValue => ({
|
||||
|
||||
@@ -10,6 +10,11 @@ import {
|
||||
analyzeJavaScriptApplicationInputSchema,
|
||||
javascriptApplicationAnalysisResultSchema,
|
||||
} from "../domain/javascriptApplicationAnalysis.js";
|
||||
import {
|
||||
javascriptRuntimeReconciliationResultSchema,
|
||||
reconcileJavaScriptRuntimeInputSchema,
|
||||
} from "../domain/javascriptRuntimeReconciliationSchemas.js";
|
||||
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "./javascriptRuntimeReconciliationExample.js";
|
||||
|
||||
const listOutputSchema = evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
@@ -20,6 +25,9 @@ const inspectionOutputSchema = evidenceEnvelopeSchema
|
||||
const applicationOutputSchema = evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: javascriptApplicationAnalysisResultSchema });
|
||||
const reconciliationOutputSchema = evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: javascriptRuntimeReconciliationResultSchema });
|
||||
|
||||
const endpoint = "http://127.0.0.1:9223";
|
||||
const root = "/Applications/Example.app/Contents/Resources";
|
||||
@@ -81,6 +89,7 @@ export const ELECTRON_TOOL_CONTRACTS = [
|
||||
max_dom_nodes: 2_000,
|
||||
max_scripts: 500,
|
||||
max_resources: 2_000,
|
||||
max_workers: 500,
|
||||
max_script_source_bytes: 1_048_576,
|
||||
max_total_script_source_bytes: 4_194_304,
|
||||
},
|
||||
@@ -113,4 +122,24 @@ export const ELECTRON_TOOL_CONTRACTS = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "reconcile_javascript_runtime",
|
||||
description:
|
||||
"Reconcile verified static JavaScript application graphs with existing passive web or Electron CDP Evidence. Exact captured-source digests take priority over caller-declared file/URL mappings; target, frame, script, and worker ambiguity remains explicit, and source-map authority stays separate.",
|
||||
kind: "electron-provider",
|
||||
inputSchema: reconcileJavaScriptRuntimeInputSchema,
|
||||
outputSchema: reconciliationOutputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: true,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
},
|
||||
examples: [
|
||||
{
|
||||
title: "Reconcile one passive Electron capture",
|
||||
input: JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE,
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import {
|
||||
createJavaScriptApplicationGraph,
|
||||
createJavaScriptApplicationNode,
|
||||
} from "../domain/javascriptApplicationGraph.js";
|
||||
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
|
||||
|
||||
const applicationSha256 = "1".repeat(64);
|
||||
const script = createWebTextArtifact(
|
||||
"export const example = true;\n",
|
||||
"text/javascript",
|
||||
);
|
||||
const inputPath = "/Applications/Example.app/Contents/Resources/app";
|
||||
const scriptPath = `${inputPath}/renderer.js`;
|
||||
|
||||
const completeCoverage = {
|
||||
status: "complete" as const,
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
};
|
||||
const graphEvidence = {
|
||||
authority: "artifact-bytes" as const,
|
||||
state: "observed" as const,
|
||||
confidence: "exact" as const,
|
||||
artifact: {
|
||||
available: true as const,
|
||||
artifact_id: `art_${script.sha256}`,
|
||||
sha256: script.sha256,
|
||||
},
|
||||
location: {
|
||||
available: true as const,
|
||||
value: { kind: "artifact-path" as const, path: "renderer.js" },
|
||||
},
|
||||
extractor: {
|
||||
name: "rea-javascript-application",
|
||||
version: "1",
|
||||
operation: "inventory-relevant-file",
|
||||
executable_sha256: null,
|
||||
},
|
||||
coverage: completeCoverage,
|
||||
limitations: [],
|
||||
evidence_ids: [],
|
||||
};
|
||||
const asset = createJavaScriptApplicationNode({
|
||||
kind: "javascript-asset",
|
||||
identity: {
|
||||
strategy: "content-digest",
|
||||
stability: "global-exact",
|
||||
sha256: script.sha256,
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: "renderer.js",
|
||||
properties: { path: "renderer.js", bytes: script.bytes },
|
||||
evidence: graphEvidence,
|
||||
},
|
||||
],
|
||||
});
|
||||
const graph = createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: [asset.node_id],
|
||||
nodes: [asset],
|
||||
edges: [],
|
||||
coverage: completeCoverage,
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const staticEvidence = createEvidence(
|
||||
{ path: inputPath, sha256: applicationSha256, format: "directory" },
|
||||
{
|
||||
id: "rea-javascript-application",
|
||||
name: "REA JavaScript application analyzer",
|
||||
version: "1",
|
||||
},
|
||||
{
|
||||
predicateType: "rea.javascript-application-analysis/v1",
|
||||
operation: "analyze_javascript_application",
|
||||
parameters: { approved: true, source_map_read_approved: false },
|
||||
result: {
|
||||
schema_version: 1,
|
||||
input_path: inputPath,
|
||||
format: "directory",
|
||||
root_artifact_sha256: applicationSha256,
|
||||
inventory_manifest_id: `agm_${"2".repeat(64)}`,
|
||||
inventory_graph_sha256: "3".repeat(64),
|
||||
graph,
|
||||
summary: {
|
||||
browser_windows: 0,
|
||||
explicit_web_preferences: 0,
|
||||
preload_entrypoints: 0,
|
||||
context_bridge_apis: 0,
|
||||
exposed_api_members: 0,
|
||||
ipc: {
|
||||
operations: 0,
|
||||
literal_channels: 0,
|
||||
dynamic_channel_operations: 0,
|
||||
renderer_transmissions: 0,
|
||||
renderer_listeners: 0,
|
||||
main_handlers: 0,
|
||||
paired_renderer_transmissions: 0,
|
||||
ambiguous_renderer_transmissions: 0,
|
||||
unpaired_literal_renderer_transmissions: 0,
|
||||
},
|
||||
sender_validation_observations: 0,
|
||||
utility_processes: 0,
|
||||
resolved_utility_entrypoints: 0,
|
||||
native_addon_bindings: 0,
|
||||
resolved_native_addon_bindings: 0,
|
||||
},
|
||||
statistics: {
|
||||
relevant_files: 1,
|
||||
nested_asar_containers: 0,
|
||||
text_files_selected: 1,
|
||||
text_bytes_read: script.bytes,
|
||||
omitted_text_files: 0,
|
||||
limit_omitted_text_files: 0,
|
||||
policy_filtered_text_files: 0,
|
||||
invalid_utf8_files: 0,
|
||||
parsed_javascript_files: 1,
|
||||
visited_ast_nodes: 1,
|
||||
findings: 0,
|
||||
modules: 0,
|
||||
parse_failures: 0,
|
||||
truncated_scopes: 0,
|
||||
},
|
||||
limitations: [],
|
||||
},
|
||||
confidence: "derived",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
);
|
||||
|
||||
const runtimeEvidence = createEvidence(
|
||||
undefined,
|
||||
{
|
||||
id: "rea-cdp-electron",
|
||||
name: "REA Electron file-page CDP observation provider",
|
||||
version: "1",
|
||||
},
|
||||
{
|
||||
predicateType: "rea.electron-page-inspection/v1",
|
||||
operation: "inspect_electron_page",
|
||||
parameters: {
|
||||
cdp_endpoint: "http://127.0.0.1:9223",
|
||||
allowed_file_roots: [inputPath],
|
||||
target_id: "example-target",
|
||||
include_script_sources: true,
|
||||
source_capture_approved: true,
|
||||
},
|
||||
result: {
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
product: "Electron/example",
|
||||
protocol_version: "1.3",
|
||||
revision: "example",
|
||||
user_agent: "Electron example",
|
||||
js_version: "1",
|
||||
},
|
||||
target: {
|
||||
target_id: "example-target",
|
||||
type: "page",
|
||||
title: "Example",
|
||||
file_path: `${inputPath}/index.html`,
|
||||
attached: false,
|
||||
},
|
||||
capture_window: {
|
||||
started_at: "2026-07-15T00:00:00.000Z",
|
||||
ended_at: "2026-07-15T00:00:00.100Z",
|
||||
observation_ms: 100,
|
||||
},
|
||||
completeness: browserCompleteness(),
|
||||
frames: [],
|
||||
dom: { total_nodes: 0, nodes: [] },
|
||||
scripts: {
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
script_key: `electron_script_${"4".repeat(64)}`,
|
||||
frame_id: null,
|
||||
file_path: scriptPath,
|
||||
cdp_hash: "example",
|
||||
length: script.bytes,
|
||||
is_module: true,
|
||||
language: "JavaScript",
|
||||
source: { included: true, artifact: script },
|
||||
},
|
||||
],
|
||||
},
|
||||
resources: [],
|
||||
workers: [],
|
||||
limitations: ["Example passive capture."],
|
||||
},
|
||||
confidence: "observed",
|
||||
authority: "external-service",
|
||||
},
|
||||
);
|
||||
|
||||
/** Compact valid Evidence pair used by the public reconciliation contract. */
|
||||
export const JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE = {
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: [runtimeEvidence],
|
||||
};
|
||||
|
||||
function browserCompleteness() {
|
||||
return {
|
||||
status: "complete_within_window" as const,
|
||||
conditions: ["complete_within_window" as const],
|
||||
policy_filtered_sections: [],
|
||||
attach_limited_sections: [],
|
||||
truncated_sections: [],
|
||||
unavailable_sections: [],
|
||||
excluded: [],
|
||||
dropped_events: {
|
||||
scripts: 0,
|
||||
network_requests: 0,
|
||||
console_events: 0,
|
||||
websocket_connections: 0,
|
||||
websocket_frames: 0,
|
||||
webmcp_tools: 0,
|
||||
timeline_events: 0,
|
||||
total: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -428,6 +428,7 @@ const browserResourceReconciliationSchema = z.discriminatedUnion("status", [
|
||||
]);
|
||||
const browserScriptSchema = z.object({
|
||||
script_key: z.string().regex(/^scr_[a-f0-9]{64}(?:_[0-9]+)?$/u),
|
||||
frame_id: z.string().nullable().default(null),
|
||||
url: z.string(),
|
||||
origin: z.string().nullable(),
|
||||
cdp_hash: z.string(),
|
||||
@@ -512,6 +513,8 @@ const browserWorkerSchema = z.object({
|
||||
url: z.string(),
|
||||
origin: z.string().nullable(),
|
||||
attached: z.boolean(),
|
||||
opener_target_id: z.string().nullable().default(null),
|
||||
parent_frame_id: z.string().nullable().default(null),
|
||||
});
|
||||
const browserCspSourceSchema = z.object({
|
||||
kind: z.enum([
|
||||
|
||||
@@ -49,6 +49,7 @@ export const inspectElectronPageInputSchema = z
|
||||
max_dom_nodes: z.number().int().min(1).max(10_000).default(2_000),
|
||||
max_scripts: z.number().int().min(1).max(2_000).default(500),
|
||||
max_resources: z.number().int().min(1).max(10_000).default(2_000),
|
||||
max_workers: z.number().int().min(1).max(5_000).default(500),
|
||||
max_script_source_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
@@ -67,6 +68,7 @@ export const inspectElectronPageInputSchema = z
|
||||
max_dom_nodes: 2_000,
|
||||
max_scripts: 500,
|
||||
max_resources: 2_000,
|
||||
max_workers: 500,
|
||||
max_script_source_bytes: 1_024 * 1_024,
|
||||
max_total_script_source_bytes: 4 * 1_024 * 1_024,
|
||||
}),
|
||||
@@ -169,6 +171,7 @@ export const electronPageInspectionSchema = z.object({
|
||||
items: z.array(
|
||||
z.object({
|
||||
script_key: z.string().regex(/^electron_script_[a-f0-9]{64}$/u),
|
||||
frame_id: z.string().nullable().default(null),
|
||||
file_path: z.string(),
|
||||
cdp_hash: z.string(),
|
||||
length: z.number().int().min(0),
|
||||
@@ -187,6 +190,18 @@ export const electronPageInspectionSchema = z.object({
|
||||
content_size: z.number().min(0).nullable(),
|
||||
}),
|
||||
),
|
||||
workers: z
|
||||
.array(
|
||||
z.object({
|
||||
target_id: z.string().min(1).max(256),
|
||||
type: z.string().min(1).max(100),
|
||||
file_path: z.string(),
|
||||
attached: z.boolean(),
|
||||
opener_target_id: z.string().min(1).max(256).nullable(),
|
||||
parent_frame_id: z.string().min(1).max(256).nullable(),
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export type ElectronPageInspection = z.infer<
|
||||
|
||||
@@ -23,6 +23,7 @@ const applicationEvidenceAuthoritySchema = z.enum([
|
||||
"ast-static-analysis",
|
||||
"static-relationship-inference",
|
||||
"passive-cdp-runtime",
|
||||
"cross-layer-reconciliation",
|
||||
"controlled-replay",
|
||||
"native-analysis-provider",
|
||||
"historical-reference",
|
||||
@@ -259,6 +260,15 @@ const checkAuthorityState = (
|
||||
path: ["state"],
|
||||
message: "Static relationship authority must remain inferred",
|
||||
});
|
||||
if (
|
||||
evidence.authority === "cross-layer-reconciliation" &&
|
||||
evidence.state !== "inferred"
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["state"],
|
||||
message: "Cross-layer reconciliation authority must remain inferred",
|
||||
});
|
||||
if (
|
||||
evidence.authority === "unknown" &&
|
||||
!["unknown", "unavailable"].includes(evidence.state)
|
||||
|
||||
@@ -20,7 +20,8 @@ import {
|
||||
type JavaScriptApplicationGraphInput,
|
||||
} from "./javascriptApplicationGraphSchemas.js";
|
||||
|
||||
const compareCodePoints = (left: string, right: string): number =>
|
||||
/** Compare strings by Unicode code point for canonical graph ordering. */
|
||||
export const compareCodePoints = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
|
||||
const canonicalJson = (value: unknown): string => {
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import {
|
||||
compareCodePoints,
|
||||
type ApplicationNode,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import type { ParsedStaticLayer } from "./javascriptRuntimeReconciliationParsing.js";
|
||||
import type {
|
||||
JavaScriptRuntimeReconciliationItem,
|
||||
JavaScriptStaticLoadState,
|
||||
} from "./javascriptRuntimeReconciliationSchemas.js";
|
||||
import type { RuntimeReconciliationEntity } from "./javascriptRuntimeReconciliationRuntime.js";
|
||||
import {
|
||||
createStaticRuntimeScope,
|
||||
mappedRuntimePaths,
|
||||
staticNodeWithinRuntimeScope,
|
||||
} from "./javascriptRuntimeStaticCandidates.js";
|
||||
|
||||
export interface StaticLoadStateProjection {
|
||||
readonly states: readonly JavaScriptStaticLoadState[];
|
||||
readonly omittedStates: number;
|
||||
}
|
||||
|
||||
/** Classify static code presence without claiming bundled module execution. */
|
||||
export const classifyStaticLoadStates = (
|
||||
layers: readonly ParsedStaticLayer[],
|
||||
runtimeEntities: readonly RuntimeReconciliationEntity[],
|
||||
matches: readonly JavaScriptRuntimeReconciliationItem[],
|
||||
options: {
|
||||
readonly maximumStates: number;
|
||||
readonly reconciliationComplete: boolean;
|
||||
},
|
||||
): StaticLoadStateProjection => {
|
||||
const states: JavaScriptStaticLoadState[] = [];
|
||||
let totalStates = 0;
|
||||
for (const layer of layers) {
|
||||
const projection = classifyLayer(layer, runtimeEntities, matches, {
|
||||
reconciliationComplete: options.reconciliationComplete,
|
||||
maximumStates: Math.max(0, options.maximumStates - states.length),
|
||||
});
|
||||
totalStates += projection.total;
|
||||
states.push(...projection.states);
|
||||
}
|
||||
return { states, omittedStates: totalStates - states.length };
|
||||
};
|
||||
|
||||
const classifyLayer = (
|
||||
layer: ParsedStaticLayer,
|
||||
runtimeEntities: readonly RuntimeReconciliationEntity[],
|
||||
matches: readonly JavaScriptRuntimeReconciliationItem[],
|
||||
options: {
|
||||
readonly reconciliationComplete: boolean;
|
||||
readonly maximumStates: number;
|
||||
},
|
||||
): { readonly states: JavaScriptStaticLoadState[]; readonly total: number } => {
|
||||
const nodes = layer.graph.nodes.filter(isLoadStateNode);
|
||||
if (options.maximumStates === 0) return { states: [], total: nodes.length };
|
||||
const direct = new Map<string, string[]>();
|
||||
for (const match of matches)
|
||||
if (
|
||||
match.status === "matched" &&
|
||||
match.static_layer_id === layer.layerId &&
|
||||
match.static_node_id !== null
|
||||
)
|
||||
append(direct, match.static_node_id, match.runtime_node_id);
|
||||
const resident = residentNodes(layer, new Set(direct.keys()));
|
||||
const runtimeScope = createStaticRuntimeScope(layer, runtimeEntities);
|
||||
const scopedEntities = runtimeEntities.filter(
|
||||
(entity) => mappedRuntimePaths(layer, entity).length > 0,
|
||||
);
|
||||
const layerComplete =
|
||||
options.reconciliationComplete &&
|
||||
layer.graph.coverage.status === "complete" &&
|
||||
scopedEntities.length > 0 &&
|
||||
scopedEntities.every(({ capture }) =>
|
||||
captureScriptsComplete(capture.evidence.evidence_id, runtimeEntities),
|
||||
);
|
||||
const states = nodes.slice(0, options.maximumStates).map((node) => {
|
||||
const runtimeNodeIds = uniqueSorted(direct.get(node.node_id) ?? []);
|
||||
if (runtimeNodeIds.length > 0)
|
||||
return state(layer, node, {
|
||||
status: "loaded",
|
||||
runtimeNodeIds,
|
||||
reason: "runtime-script-correspondence",
|
||||
});
|
||||
if (resident.has(node.node_id))
|
||||
return state(layer, node, {
|
||||
status: "resident-in-loaded-asset",
|
||||
runtimeNodeIds: [],
|
||||
reason: "containing-asset-was-loaded",
|
||||
});
|
||||
const nodeWithinScope = staticNodeWithinRuntimeScope(node, runtimeScope);
|
||||
if (layerComplete && nodeWithinScope)
|
||||
return state(layer, node, {
|
||||
status: "not-observed-in-capture",
|
||||
runtimeNodeIds: [],
|
||||
reason: "not-observed-in-bounded-capture",
|
||||
});
|
||||
return state(layer, node, {
|
||||
status: "unknown",
|
||||
runtimeNodeIds: [],
|
||||
reason: !nodeWithinScope
|
||||
? "layer-outside-runtime-scope"
|
||||
: "static-or-runtime-coverage-incomplete",
|
||||
});
|
||||
});
|
||||
return { states, total: nodes.length };
|
||||
};
|
||||
|
||||
const residentNodes = (
|
||||
layer: ParsedStaticLayer,
|
||||
directlyLoaded: ReadonlySet<string>,
|
||||
): ReadonlySet<string> => {
|
||||
const nodeKinds = new Map(
|
||||
layer.graph.nodes.map(({ node_id: id, kind }) => [id, kind]),
|
||||
);
|
||||
const children = new Map<string, string[]>();
|
||||
for (const edge of layer.graph.edges)
|
||||
if (edge.relation === "contains")
|
||||
append(children, edge.source_node_id, edge.target_node_id);
|
||||
const pending = [...directlyLoaded].filter(
|
||||
(nodeId) => nodeKinds.get(nodeId) === "javascript-asset",
|
||||
);
|
||||
const resident = new Set<string>();
|
||||
for (let index = 0; index < pending.length; index += 1) {
|
||||
const current = pending[index];
|
||||
if (current === undefined) break;
|
||||
for (const child of children.get(current) ?? []) {
|
||||
if (resident.has(child)) continue;
|
||||
resident.add(child);
|
||||
pending.push(child);
|
||||
}
|
||||
}
|
||||
return resident;
|
||||
};
|
||||
|
||||
const append = (
|
||||
values: Map<string, string[]>,
|
||||
key: string,
|
||||
value: string,
|
||||
): void => {
|
||||
const current = values.get(key);
|
||||
if (current === undefined) values.set(key, [value]);
|
||||
else current.push(value);
|
||||
};
|
||||
|
||||
const captureScriptsComplete = (
|
||||
evidenceId: string,
|
||||
entities: readonly RuntimeReconciliationEntity[],
|
||||
): boolean =>
|
||||
entities.find(({ capture }) => capture.evidence.evidence_id === evidenceId)
|
||||
?.capture.scriptsCompleteWithinScope === true;
|
||||
|
||||
const isLoadStateNode = (
|
||||
node: ApplicationNode,
|
||||
): node is ApplicationNode & {
|
||||
readonly kind: "javascript-asset" | "javascript-chunk" | "javascript-module";
|
||||
} =>
|
||||
node.kind === "javascript-asset" ||
|
||||
node.kind === "javascript-chunk" ||
|
||||
node.kind === "javascript-module";
|
||||
|
||||
const state = (
|
||||
layer: ParsedStaticLayer,
|
||||
node: ApplicationNode & {
|
||||
readonly kind:
|
||||
| "javascript-asset"
|
||||
| "javascript-chunk"
|
||||
| "javascript-module";
|
||||
},
|
||||
input: {
|
||||
readonly status: JavaScriptStaticLoadState["status"];
|
||||
readonly runtimeNodeIds: readonly string[];
|
||||
readonly reason: JavaScriptStaticLoadState["reason"];
|
||||
},
|
||||
): JavaScriptStaticLoadState => ({
|
||||
static_layer_id: layer.layerId,
|
||||
static_node_id: node.node_id,
|
||||
kind: node.kind,
|
||||
status: input.status,
|
||||
runtime_node_ids: [...input.runtimeNodeIds],
|
||||
reason: input.reason,
|
||||
});
|
||||
|
||||
const uniqueSorted = (values: readonly string[]): string[] =>
|
||||
[...new Set(values)].sort(compareCodePoints);
|
||||
@@ -0,0 +1,58 @@
|
||||
import { classifyStaticLoadStates } from "./javascriptRuntimeLoadState.js";
|
||||
import { buildReconciledApplicationGraph } from "./javascriptRuntimeReconciliationGraph.js";
|
||||
import { reconcileRuntimeEntities } from "./javascriptRuntimeReconciliationMatching.js";
|
||||
import {
|
||||
parseRuntimeCaptures,
|
||||
parseStaticLayers,
|
||||
} from "./javascriptRuntimeReconciliationParsing.js";
|
||||
import { createJavaScriptRuntimeReconciliationResult } from "./javascriptRuntimeReconciliationResult.js";
|
||||
import type { JavaScriptRuntimeReconciliationResult } from "./javascriptRuntimeReconciliationSchemas.js";
|
||||
import { reconcileJavaScriptRuntimeInputSchema } from "./javascriptRuntimeReconciliationSchemas.js";
|
||||
import { projectRuntimeCaptures } from "./javascriptRuntimeReconciliationRuntime.js";
|
||||
import { collectStaticRuntimeCandidates } from "./javascriptRuntimeStaticCandidates.js";
|
||||
|
||||
/** Reconcile static JAG layers with authorized passive CDP Evidence. */
|
||||
export const reconcileJavaScriptRuntime = (
|
||||
input: unknown,
|
||||
): JavaScriptRuntimeReconciliationResult => {
|
||||
const parsed = reconcileJavaScriptRuntimeInputSchema.parse(input);
|
||||
const layers = parseStaticLayers(parsed.static_layers);
|
||||
const captures = parseRuntimeCaptures(parsed.runtime_observations);
|
||||
const runtime = projectRuntimeCaptures(
|
||||
captures,
|
||||
parsed.limits.max_runtime_entities,
|
||||
);
|
||||
const candidates = collectStaticRuntimeCandidates(layers);
|
||||
const matching = reconcileRuntimeEntities({
|
||||
entities: runtime.entities,
|
||||
candidates,
|
||||
layers,
|
||||
maximumItems: parsed.limits.max_reconciliation_items,
|
||||
});
|
||||
const loadStates = classifyStaticLoadStates(
|
||||
layers,
|
||||
runtime.entities,
|
||||
matching.items,
|
||||
{
|
||||
maximumStates: parsed.limits.max_static_load_states,
|
||||
reconciliationComplete:
|
||||
runtime.omittedEntities === 0 && matching.omittedItems === 0,
|
||||
},
|
||||
);
|
||||
const graph = buildReconciledApplicationGraph({
|
||||
layers,
|
||||
captures,
|
||||
runtime,
|
||||
reconciliationEdges: matching.edges,
|
||||
omittedReconciliationItems: matching.omittedItems,
|
||||
});
|
||||
return createJavaScriptRuntimeReconciliationResult({
|
||||
layers,
|
||||
captures,
|
||||
runtime,
|
||||
matching,
|
||||
loadStates,
|
||||
graph: graph.graph,
|
||||
omittedGraphItems: graph.omittedGraphItems,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,274 @@
|
||||
import {
|
||||
compareCodePoints,
|
||||
createJavaScriptApplicationGraph,
|
||||
createJavaScriptApplicationNode,
|
||||
type ApplicationEdge,
|
||||
type ApplicationNode,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import type {
|
||||
ParsedRuntimeCapture,
|
||||
ParsedStaticLayer,
|
||||
} from "./javascriptRuntimeReconciliationParsing.js";
|
||||
import type { RuntimeProjection } from "./javascriptRuntimeReconciliationRuntime.js";
|
||||
|
||||
interface ReconciledGraphInput {
|
||||
readonly layers: readonly ParsedStaticLayer[];
|
||||
readonly captures: readonly ParsedRuntimeCapture[];
|
||||
readonly runtime: RuntimeProjection;
|
||||
readonly reconciliationEdges: readonly ApplicationEdge[];
|
||||
readonly omittedReconciliationItems: number;
|
||||
}
|
||||
|
||||
interface GraphCoverageFacts {
|
||||
readonly projectionOmissions: number;
|
||||
readonly knownOmissions: number;
|
||||
readonly omissionsKnown: boolean;
|
||||
readonly inputTruncated: boolean;
|
||||
readonly outputTruncated: boolean;
|
||||
readonly truncated: boolean;
|
||||
readonly complete: boolean;
|
||||
}
|
||||
|
||||
/** Combined graph plus omissions introduced while merging its observations. */
|
||||
export interface ReconciledApplicationGraphProjection {
|
||||
readonly graph: JavaScriptApplicationGraph;
|
||||
readonly omittedGraphItems: number;
|
||||
}
|
||||
|
||||
/** Merge source graphs, runtime nodes, and inferred mappings into one valid JAG. */
|
||||
export const buildReconciledApplicationGraph = (
|
||||
input: ReconciledGraphInput,
|
||||
): ReconciledApplicationGraphProjection => {
|
||||
const merged = mergeNodes([
|
||||
...input.layers.flatMap(({ graph }) => graph.nodes),
|
||||
...input.runtime.nodes,
|
||||
]);
|
||||
const allEdges = uniqueEdges([
|
||||
...input.layers.flatMap(({ graph }) => graph.edges),
|
||||
...input.runtime.edges,
|
||||
...input.reconciliationEdges,
|
||||
]);
|
||||
const bounded = boundGraphContent(input, merged.nodes, allEdges);
|
||||
const facts = graphCoverageFacts(
|
||||
input,
|
||||
merged.omittedObservations + bounded.omittedItems,
|
||||
);
|
||||
const graph = createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: bounded.rootNodeIds,
|
||||
nodes: bounded.nodes,
|
||||
edges: bounded.edges,
|
||||
coverage: graphCoverage(input, facts, bounded.nodes.length),
|
||||
limitations: uniqueSorted([
|
||||
...input.layers.flatMap(({ graph }) => graph.limitations),
|
||||
"Runtime presence is bounded to passive capture windows and does not prove feature execution.",
|
||||
"Cross-layer observed_as edges are inferences; digest equality proves byte identity only.",
|
||||
"Source-map relationships retain their original static authority and are not promoted into runtime matches.",
|
||||
...(facts.inputTruncated
|
||||
? [
|
||||
"One or more source graphs or passive captures were incomplete or truncated.",
|
||||
]
|
||||
: []),
|
||||
...(facts.outputTruncated
|
||||
? [
|
||||
"The reconciled graph omitted entities or classifications at caller limits.",
|
||||
]
|
||||
: []),
|
||||
]),
|
||||
});
|
||||
return {
|
||||
graph,
|
||||
omittedGraphItems: merged.omittedObservations + bounded.omittedItems,
|
||||
};
|
||||
};
|
||||
|
||||
const boundGraphContent = (
|
||||
input: ReconciledGraphInput,
|
||||
nodes: readonly ApplicationNode[],
|
||||
edges: readonly ApplicationEdge[],
|
||||
): {
|
||||
readonly rootNodeIds: string[];
|
||||
readonly nodes: ApplicationNode[];
|
||||
readonly edges: ApplicationEdge[];
|
||||
readonly omittedItems: number;
|
||||
} => {
|
||||
const allRoots = preferredRootIds(input);
|
||||
const rootNodeIds = allRoots.slice(0, 1_000);
|
||||
const roots = new Set(rootNodeIds);
|
||||
const sortedNodes = [...nodes].sort((left, right) =>
|
||||
compareCodePoints(left.node_id, right.node_id),
|
||||
);
|
||||
const retainedNodes = [
|
||||
...sortedNodes.filter(({ node_id: id }) => roots.has(id)),
|
||||
...sortedNodes.filter(({ node_id: id }) => !roots.has(id)),
|
||||
].slice(0, 100_000);
|
||||
const retainedIds = new Set(retainedNodes.map(({ node_id: id }) => id));
|
||||
const retainedEdges = [...edges]
|
||||
.sort((left, right) => compareCodePoints(left.edge_id, right.edge_id))
|
||||
.filter(
|
||||
({ source_node_id: source, target_node_id: target }) =>
|
||||
retainedIds.has(source) && retainedIds.has(target),
|
||||
)
|
||||
.slice(0, 200_000);
|
||||
return {
|
||||
rootNodeIds,
|
||||
nodes: retainedNodes,
|
||||
edges: retainedEdges,
|
||||
omittedItems:
|
||||
allRoots.length -
|
||||
rootNodeIds.length +
|
||||
(nodes.length - retainedNodes.length) +
|
||||
(edges.length - retainedEdges.length),
|
||||
};
|
||||
};
|
||||
|
||||
const preferredRootIds = (input: ReconciledGraphInput): string[] => {
|
||||
const runtime = [...input.runtime.targetNodeByEvidenceId.values()].map(
|
||||
({ node_id: id }) => id,
|
||||
);
|
||||
const application = input.layers
|
||||
.filter(({ role }) => role === "application")
|
||||
.flatMap(({ graph }) => graph.root_node_ids);
|
||||
const supplemental = input.layers
|
||||
.filter(({ role }) => role !== "application")
|
||||
.flatMap(({ graph }) => graph.root_node_ids);
|
||||
return [...new Set([...runtime, ...application, ...supplemental])];
|
||||
};
|
||||
|
||||
const graphCoverageFacts = (
|
||||
input: ReconciledGraphInput,
|
||||
omittedNodeObservations: number,
|
||||
): GraphCoverageFacts => {
|
||||
const projectionOmissions =
|
||||
input.runtime.omittedEntities +
|
||||
input.omittedReconciliationItems +
|
||||
omittedNodeObservations;
|
||||
const captureTruncated = input.captures.some(({ inspection }) =>
|
||||
inspection.completeness.conditions.includes("truncated"),
|
||||
);
|
||||
const captureHasUnknownOmissions = input.captures.some(
|
||||
({ inspection }) => inspection.completeness.unavailable_sections.length > 0,
|
||||
);
|
||||
const inputTruncated =
|
||||
input.layers.some(({ graph }) => graph.coverage.truncated) ||
|
||||
captureTruncated;
|
||||
const outputTruncated = projectionOmissions > 0;
|
||||
const sourceOmissions = input.layers.reduce(
|
||||
(total, { graph }) => total + (graph.coverage.omitted_count ?? 0),
|
||||
0,
|
||||
);
|
||||
const omissionsKnown =
|
||||
!captureTruncated &&
|
||||
!captureHasUnknownOmissions &&
|
||||
input.layers.every(({ graph }) => graph.coverage.omitted_count !== null);
|
||||
return {
|
||||
projectionOmissions,
|
||||
knownOmissions: projectionOmissions + sourceOmissions,
|
||||
omissionsKnown,
|
||||
inputTruncated,
|
||||
outputTruncated,
|
||||
truncated: inputTruncated || outputTruncated,
|
||||
complete:
|
||||
!inputTruncated &&
|
||||
!outputTruncated &&
|
||||
input.layers.every(({ graph }) => graph.coverage.status === "complete") &&
|
||||
input.captures.every(
|
||||
({ inspection }) =>
|
||||
inspection.completeness.status === "complete_within_window",
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const graphCoverage = (
|
||||
input: ReconciledGraphInput,
|
||||
facts: GraphCoverageFacts,
|
||||
nodeCount: number,
|
||||
): JavaScriptApplicationGraph["coverage"] =>
|
||||
facts.complete
|
||||
? { status: "complete", truncated: false, omitted_count: 0, limits: [] }
|
||||
: facts.truncated
|
||||
? {
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: facts.omissionsKnown ? facts.knownOmissions : null,
|
||||
limits: [
|
||||
...(facts.inputTruncated
|
||||
? [
|
||||
{
|
||||
name: "runtime-reconciliation-input-coverage",
|
||||
value: input.layers.length + input.captures.length,
|
||||
unit: "items" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(facts.outputTruncated
|
||||
? [
|
||||
{
|
||||
name: "runtime-reconciliation-output-limits",
|
||||
value: nodeCount,
|
||||
unit: "items" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
}
|
||||
: {
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: facts.omissionsKnown ? facts.knownOmissions : null,
|
||||
limits: [],
|
||||
};
|
||||
|
||||
const mergeNodes = (
|
||||
nodes: readonly ApplicationNode[],
|
||||
): {
|
||||
readonly nodes: ApplicationNode[];
|
||||
readonly omittedObservations: number;
|
||||
} => {
|
||||
const grouped = new Map<string, ApplicationNode[]>();
|
||||
for (const node of nodes)
|
||||
grouped.set(node.node_id, [...(grouped.get(node.node_id) ?? []), node]);
|
||||
let omittedObservations = 0;
|
||||
const merged = [...grouped.values()].map((group) => {
|
||||
const first = group[0];
|
||||
if (first === undefined) throw new TypeError("Empty JAG node group");
|
||||
if (
|
||||
group.some(
|
||||
({ kind, identity }) =>
|
||||
kind !== first.kind ||
|
||||
JSON.stringify(identity) !== JSON.stringify(first.identity),
|
||||
)
|
||||
)
|
||||
throw new TypeError("Colliding JAG node identifiers disagree");
|
||||
const observations = [
|
||||
...new Map(
|
||||
group
|
||||
.flatMap(({ observations: values }) => values)
|
||||
.map((observation) => [observation.observation_id, observation]),
|
||||
).values(),
|
||||
].sort((left, right) =>
|
||||
compareCodePoints(left.observation_id, right.observation_id),
|
||||
);
|
||||
omittedObservations += Math.max(0, observations.length - 64);
|
||||
return createJavaScriptApplicationNode({
|
||||
kind: first.kind,
|
||||
identity: first.identity,
|
||||
observations: observations
|
||||
.slice(0, 64)
|
||||
.map(
|
||||
({ observation_id: _id, identifier_strategy: _strategy, ...value }) =>
|
||||
value,
|
||||
),
|
||||
});
|
||||
});
|
||||
return { nodes: merged, omittedObservations };
|
||||
};
|
||||
|
||||
const uniqueEdges = (edges: readonly ApplicationEdge[]): ApplicationEdge[] => [
|
||||
...new Map(edges.map((edge) => [edge.edge_id, edge])).values(),
|
||||
];
|
||||
|
||||
const uniqueSorted = (values: readonly string[]): string[] =>
|
||||
[...new Set(values)].sort(compareCodePoints);
|
||||
@@ -0,0 +1,398 @@
|
||||
import {
|
||||
compareCodePoints,
|
||||
createJavaScriptApplicationEdge,
|
||||
type ApplicationEdge,
|
||||
type ApplicationGraphEvidence,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import {
|
||||
digestCanonical,
|
||||
type ParsedStaticLayer,
|
||||
} from "./javascriptRuntimeReconciliationParsing.js";
|
||||
import type { JavaScriptRuntimeReconciliationItem } from "./javascriptRuntimeReconciliationSchemas.js";
|
||||
import type { RuntimeReconciliationEntity } from "./javascriptRuntimeReconciliationRuntime.js";
|
||||
import {
|
||||
mappedRuntimePaths,
|
||||
type MappedRuntimePath,
|
||||
type StaticRuntimeCandidate,
|
||||
} from "./javascriptRuntimeStaticCandidates.js";
|
||||
|
||||
export interface RuntimeMatchingProjection {
|
||||
readonly items: readonly JavaScriptRuntimeReconciliationItem[];
|
||||
readonly edges: readonly ApplicationEdge[];
|
||||
readonly omittedItems: number;
|
||||
}
|
||||
|
||||
/** Match runtime entities conservatively and emit only inferred observed_as edges. */
|
||||
export const reconcileRuntimeEntities = (input: {
|
||||
readonly entities: readonly RuntimeReconciliationEntity[];
|
||||
readonly candidates: readonly StaticRuntimeCandidate[];
|
||||
readonly layers: readonly ParsedStaticLayer[];
|
||||
readonly maximumItems: number;
|
||||
}): RuntimeMatchingProjection => {
|
||||
const index = indexCandidates(input.candidates);
|
||||
const evaluated = input.entities.map((entity) =>
|
||||
reconcileEntity(entity, index, input.layers),
|
||||
);
|
||||
const retained = evaluated
|
||||
.sort((left, right) =>
|
||||
compareCodePoints(
|
||||
left.item.reconciliation_id,
|
||||
right.item.reconciliation_id,
|
||||
),
|
||||
)
|
||||
.slice(0, input.maximumItems);
|
||||
return {
|
||||
items: retained.map(({ item }) => item),
|
||||
edges: retained.flatMap(({ edge }) => (edge === null ? [] : [edge])),
|
||||
omittedItems: evaluated.length - retained.length,
|
||||
};
|
||||
};
|
||||
|
||||
interface EvaluatedMatch {
|
||||
readonly item: JavaScriptRuntimeReconciliationItem;
|
||||
readonly edge: ApplicationEdge | null;
|
||||
}
|
||||
|
||||
interface CandidateIndex {
|
||||
readonly byCategoryDigest: ReadonlyMap<
|
||||
string,
|
||||
readonly StaticRuntimeCandidate[]
|
||||
>;
|
||||
readonly byLayerCategoryPath: ReadonlyMap<
|
||||
string,
|
||||
readonly StaticRuntimeCandidate[]
|
||||
>;
|
||||
}
|
||||
|
||||
const reconcileEntity = (
|
||||
entity: RuntimeReconciliationEntity,
|
||||
index: CandidateIndex,
|
||||
layers: readonly ParsedStaticLayer[],
|
||||
): EvaluatedMatch => {
|
||||
const locations = candidatesWithLocation(entity, index, layers);
|
||||
if (entity.sourceSha256 !== null) {
|
||||
const content =
|
||||
index.byCategoryDigest.get(
|
||||
categoryDigestKey(entity.staticKind, entity.sourceSha256),
|
||||
) ?? [];
|
||||
const locatedKeys = new Set(
|
||||
locations.map(({ candidate }) => candidateKey(candidate)),
|
||||
);
|
||||
const combined = content.filter((candidate) =>
|
||||
locatedKeys.has(candidateKey(candidate)),
|
||||
);
|
||||
if (combined.length === 1)
|
||||
return matched(entity, combined[0]!, {
|
||||
basis: "content-and-location",
|
||||
confidence: "high",
|
||||
reason: "content-and-location-match",
|
||||
});
|
||||
if (content.length === 1) {
|
||||
const candidate = content[0]!;
|
||||
const digestBasis = candidate.digests.find(
|
||||
({ sha256 }) => sha256 === entity.sourceSha256,
|
||||
)?.basis;
|
||||
return matched(entity, candidate, {
|
||||
basis: digestBasis ?? "content-sha256",
|
||||
confidence: "high",
|
||||
reason: "unique-content-match",
|
||||
});
|
||||
}
|
||||
if (content.length > 1)
|
||||
return unresolved(entity, {
|
||||
status: "ambiguous",
|
||||
basis: "none",
|
||||
confidence: "unknown",
|
||||
reason: "ambiguous-static-candidates",
|
||||
candidates: content,
|
||||
});
|
||||
if (locations.length > 0)
|
||||
return unresolved(entity, {
|
||||
status: "unmatched",
|
||||
basis: strongestLocationBasis(locations),
|
||||
confidence: "high",
|
||||
reason: "captured-content-disagrees-with-static-location",
|
||||
candidates: locations.map(({ candidate }) => candidate),
|
||||
});
|
||||
return unresolved(entity, {
|
||||
status: "unmatched",
|
||||
basis: "none",
|
||||
confidence: "high",
|
||||
reason: "no-static-content-match",
|
||||
candidates: [],
|
||||
});
|
||||
}
|
||||
|
||||
if (locations.length === 1) {
|
||||
const located = locations[0]!;
|
||||
return matched(entity, located.candidate, {
|
||||
basis: located.mapping.basis,
|
||||
confidence: "medium",
|
||||
reason: "unique-location-match",
|
||||
});
|
||||
}
|
||||
if (locations.length > 1)
|
||||
return unresolved(entity, {
|
||||
status: "ambiguous",
|
||||
basis: strongestLocationBasis(locations),
|
||||
confidence: "unknown",
|
||||
reason: "ambiguous-static-candidates",
|
||||
candidates: locations.map(({ candidate }) => candidate),
|
||||
});
|
||||
const mapped = layers.some(
|
||||
(layer) => mappedRuntimePaths(layer, entity).length > 0,
|
||||
);
|
||||
return unresolved(entity, {
|
||||
status: mapped ? "unmatched" : "unknown",
|
||||
basis: "none",
|
||||
confidence: "unknown",
|
||||
reason: mapped
|
||||
? "no-static-content-match"
|
||||
: "no-authorized-location-mapping",
|
||||
candidates: [],
|
||||
});
|
||||
};
|
||||
|
||||
interface LocatedCandidate {
|
||||
readonly candidate: StaticRuntimeCandidate;
|
||||
readonly mapping: MappedRuntimePath;
|
||||
}
|
||||
|
||||
const candidatesWithLocation = (
|
||||
entity: RuntimeReconciliationEntity,
|
||||
index: CandidateIndex,
|
||||
layers: readonly ParsedStaticLayer[],
|
||||
): LocatedCandidate[] => {
|
||||
const located = new Map<string, LocatedCandidate>();
|
||||
for (const layer of layers)
|
||||
for (const mapping of mappedRuntimePaths(layer, entity))
|
||||
for (const candidate of index.byLayerCategoryPath.get(
|
||||
layerCategoryPathKey(layer.layerId, entity.staticKind, mapping.path),
|
||||
) ?? []) {
|
||||
const key = candidateKey(candidate);
|
||||
if (!located.has(key)) located.set(key, { candidate, mapping });
|
||||
}
|
||||
return [...located.values()].sort((left, right) =>
|
||||
compareCodePoints(
|
||||
candidateKey(left.candidate),
|
||||
candidateKey(right.candidate),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const indexCandidates = (
|
||||
candidates: readonly StaticRuntimeCandidate[],
|
||||
): CandidateIndex => {
|
||||
const byCategoryDigest = new Map<string, StaticRuntimeCandidate[]>();
|
||||
const byLayerCategoryPath = new Map<string, StaticRuntimeCandidate[]>();
|
||||
for (const candidate of candidates) {
|
||||
for (const { sha256 } of candidate.digests)
|
||||
appendIndex(
|
||||
byCategoryDigest,
|
||||
categoryDigestKey(candidate.category, sha256),
|
||||
candidate,
|
||||
);
|
||||
for (const path of candidate.paths)
|
||||
appendIndex(
|
||||
byLayerCategoryPath,
|
||||
layerCategoryPathKey(candidate.layer.layerId, candidate.category, path),
|
||||
candidate,
|
||||
);
|
||||
}
|
||||
return { byCategoryDigest, byLayerCategoryPath };
|
||||
};
|
||||
|
||||
const appendIndex = (
|
||||
index: Map<string, StaticRuntimeCandidate[]>,
|
||||
key: string,
|
||||
candidate: StaticRuntimeCandidate,
|
||||
): void => {
|
||||
const values = index.get(key);
|
||||
if (values === undefined) index.set(key, [candidate]);
|
||||
else values.push(candidate);
|
||||
};
|
||||
|
||||
const categoryDigestKey = (category: string, digest: string): string =>
|
||||
`${category}\0${digest}`;
|
||||
|
||||
const layerCategoryPathKey = (
|
||||
layerId: string,
|
||||
category: string,
|
||||
path: string,
|
||||
): string => `${layerId}\0${category}\0${path}`;
|
||||
|
||||
const matched = (
|
||||
entity: RuntimeReconciliationEntity,
|
||||
candidate: StaticRuntimeCandidate,
|
||||
input: Pick<ItemInput, "basis" | "confidence" | "reason">,
|
||||
): EvaluatedMatch => {
|
||||
const item = createItem(entity, {
|
||||
layer: candidate.layer,
|
||||
staticNodeId: candidate.node.node_id,
|
||||
status: "matched",
|
||||
basis: input.basis,
|
||||
confidence: input.confidence,
|
||||
reason: input.reason,
|
||||
candidates: [candidate],
|
||||
});
|
||||
return {
|
||||
item,
|
||||
edge: createJavaScriptApplicationEdge({
|
||||
source_node_id: candidate.node.node_id,
|
||||
target_node_id: entity.node.node_id,
|
||||
relation: "observed_as",
|
||||
properties: {
|
||||
reconciliation_id: item.reconciliation_id,
|
||||
basis: input.basis,
|
||||
static_layer_id: candidate.layer.layerId,
|
||||
},
|
||||
evidence: reconciliationEvidence(
|
||||
entity,
|
||||
candidate.layer,
|
||||
input.basis,
|
||||
input.confidence,
|
||||
),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const unresolved = (
|
||||
entity: RuntimeReconciliationEntity,
|
||||
input: Pick<
|
||||
ItemInput,
|
||||
"status" | "basis" | "confidence" | "reason" | "candidates"
|
||||
>,
|
||||
): EvaluatedMatch => ({
|
||||
item: createItem(entity, {
|
||||
layer: null,
|
||||
staticNodeId: null,
|
||||
status: input.status,
|
||||
basis: input.basis,
|
||||
confidence: input.confidence,
|
||||
reason: input.reason,
|
||||
candidates: input.candidates,
|
||||
}),
|
||||
edge: null,
|
||||
});
|
||||
|
||||
interface ItemInput {
|
||||
readonly layer: ParsedStaticLayer | null;
|
||||
readonly staticNodeId: string | null;
|
||||
readonly status: JavaScriptRuntimeReconciliationItem["status"];
|
||||
readonly basis: JavaScriptRuntimeReconciliationItem["basis"];
|
||||
readonly confidence: JavaScriptRuntimeReconciliationItem["confidence"];
|
||||
readonly reason: JavaScriptRuntimeReconciliationItem["reason"];
|
||||
readonly candidates: readonly StaticRuntimeCandidate[];
|
||||
}
|
||||
|
||||
const createItem = (
|
||||
entity: RuntimeReconciliationEntity,
|
||||
input: ItemInput,
|
||||
): JavaScriptRuntimeReconciliationItem => {
|
||||
const candidateReferences = uniqueCandidateReferences(input.candidates);
|
||||
const semantic = {
|
||||
entity_kind: entity.kind,
|
||||
runtime_evidence_id: entity.capture.evidence.evidence_id,
|
||||
runtime_node_id: entity.node.node_id,
|
||||
static_layer_id: input.layer?.layerId ?? null,
|
||||
static_node_id: input.staticNodeId,
|
||||
status: input.status,
|
||||
basis: input.basis,
|
||||
confidence: input.confidence,
|
||||
reason: input.reason,
|
||||
candidate_static_count: candidateReferences.count,
|
||||
candidate_static_nodes: candidateReferences.items,
|
||||
} satisfies Omit<JavaScriptRuntimeReconciliationItem, "reconciliation_id">;
|
||||
return {
|
||||
reconciliation_id: `jrr_item_${digestCanonical(semantic)}`,
|
||||
...semantic,
|
||||
};
|
||||
};
|
||||
|
||||
const reconciliationEvidence = (
|
||||
entity: RuntimeReconciliationEntity,
|
||||
layer: ParsedStaticLayer,
|
||||
basis: JavaScriptRuntimeReconciliationItem["basis"],
|
||||
confidence: JavaScriptRuntimeReconciliationItem["confidence"],
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority: "cross-layer-reconciliation",
|
||||
state: "inferred",
|
||||
confidence: confidence === "medium" ? "medium" : "high",
|
||||
artifact:
|
||||
entity.sourceSha256 === null
|
||||
? {
|
||||
available: false,
|
||||
reason: "not-observed",
|
||||
detail: "Runtime source bytes were not captured for this mapping.",
|
||||
}
|
||||
: {
|
||||
available: true,
|
||||
artifact_id: `art_${entity.sourceSha256}`,
|
||||
sha256: entity.sourceSha256,
|
||||
},
|
||||
location: entity.node.observations[0]!.evidence.location,
|
||||
extractor: {
|
||||
name: "rea-javascript-runtime-reconciliation",
|
||||
version: "1",
|
||||
operation: "reconcile_javascript_runtime",
|
||||
executable_sha256: null,
|
||||
},
|
||||
coverage:
|
||||
layer.graph.coverage.status === "complete" &&
|
||||
entity.capture.scriptsCompleteWithinScope
|
||||
? { status: "complete", truncated: false, omitted_count: 0, limits: [] }
|
||||
: {
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
},
|
||||
limitations: [
|
||||
basis === "content-sha256" ||
|
||||
basis === "module-source-sha256" ||
|
||||
basis === "content-and-location"
|
||||
? "Equal content digests establish byte identity, not execution causality."
|
||||
: "Location correspondence is inferred from an artifact root or caller-declared mapping.",
|
||||
"Passive script parsing or target presence does not prove feature execution.",
|
||||
],
|
||||
evidence_ids: [
|
||||
layer.evidence.evidence_id,
|
||||
entity.capture.evidence.evidence_id,
|
||||
].sort(),
|
||||
});
|
||||
|
||||
const strongestLocationBasis = (
|
||||
values: readonly LocatedCandidate[],
|
||||
): JavaScriptRuntimeReconciliationItem["basis"] => {
|
||||
const bases = new Set(values.map(({ mapping }) => mapping.basis));
|
||||
if (bases.has("artifact-path")) return "artifact-path";
|
||||
if (bases.has("operator-file-mapping")) return "operator-file-mapping";
|
||||
return "operator-url-mapping";
|
||||
};
|
||||
|
||||
const candidateKey = (candidate: StaticRuntimeCandidate): string =>
|
||||
`${candidate.layer.layerId}:${candidate.node.node_id}`;
|
||||
|
||||
const uniqueCandidateReferences = (
|
||||
candidates: readonly StaticRuntimeCandidate[],
|
||||
): {
|
||||
readonly count: number;
|
||||
readonly items: JavaScriptRuntimeReconciliationItem["candidate_static_nodes"];
|
||||
} => {
|
||||
const seen = new Set<string>();
|
||||
let count = 0;
|
||||
const items: JavaScriptRuntimeReconciliationItem["candidate_static_nodes"] =
|
||||
[];
|
||||
for (const { layer, node } of candidates) {
|
||||
const key = `${layer.layerId}:${node.node_id}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
count += 1;
|
||||
if (items.length < 1_000)
|
||||
items.push({
|
||||
static_layer_id: layer.layerId,
|
||||
static_node_id: node.node_id,
|
||||
});
|
||||
}
|
||||
return { count, items };
|
||||
};
|
||||
@@ -0,0 +1,286 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
browserAllowedOriginsSchema,
|
||||
browserEndpointSchema,
|
||||
webPageInspectionSchema,
|
||||
type WebPageInspection,
|
||||
} from "./browserObservation.js";
|
||||
import {
|
||||
electronFileRootsSchema,
|
||||
electronPageInspectionSchema,
|
||||
type ElectronPageInspection,
|
||||
} from "./electronObservation.js";
|
||||
import { parseEvidence, type Evidence } from "./evidence.js";
|
||||
import {
|
||||
javascriptApplicationAnalysisResultSchema,
|
||||
type JavaScriptApplicationAnalysisResult,
|
||||
} from "./javascriptApplicationAnalysis.js";
|
||||
import {
|
||||
compareCodePoints,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import type { ReconcileJavaScriptRuntimeInput } from "./javascriptRuntimeReconciliationSchemas.js";
|
||||
|
||||
type StaticLayerInput =
|
||||
ReconcileJavaScriptRuntimeInput["static_layers"][number];
|
||||
type RuntimeMapping = StaticLayerInput["runtime_mappings"][number];
|
||||
|
||||
export interface ParsedStaticLayer {
|
||||
readonly layerId: string;
|
||||
readonly role: StaticLayerInput["role"];
|
||||
readonly evidence: Evidence;
|
||||
readonly result: JavaScriptApplicationAnalysisResult;
|
||||
readonly graph: JavaScriptApplicationGraph;
|
||||
readonly runtimeMappings: readonly RuntimeMapping[];
|
||||
readonly sourceMapReadApproved: boolean;
|
||||
}
|
||||
|
||||
interface RuntimeCaptureBase {
|
||||
readonly evidence: Evidence;
|
||||
readonly captureSha256: string;
|
||||
readonly scriptsCompleteWithinScope: boolean;
|
||||
}
|
||||
|
||||
export type ParsedRuntimeCapture =
|
||||
| (RuntimeCaptureBase & {
|
||||
readonly kind: "browser";
|
||||
readonly inspection: WebPageInspection;
|
||||
})
|
||||
| (RuntimeCaptureBase & {
|
||||
readonly kind: "electron";
|
||||
readonly inspection: ElectronPageInspection;
|
||||
});
|
||||
|
||||
/** Parse and semantically bind every static analysis Evidence layer. */
|
||||
export const parseStaticLayers = (
|
||||
layers: readonly StaticLayerInput[],
|
||||
): ParsedStaticLayer[] =>
|
||||
layers
|
||||
.map((layer) => parseStaticLayer(layer))
|
||||
.sort((left, right) => compareCodePoints(left.layerId, right.layerId));
|
||||
|
||||
/** Parse only supported passive web/Electron inspection Evidence. */
|
||||
export const parseRuntimeCaptures = (
|
||||
observations: readonly Evidence[],
|
||||
): ParsedRuntimeCapture[] =>
|
||||
observations
|
||||
.map((observation) => parseRuntimeCapture(observation))
|
||||
.sort((left, right) =>
|
||||
compareCodePoints(left.evidence.evidence_id, right.evidence.evidence_id),
|
||||
);
|
||||
|
||||
export const digestCanonical = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Runtime reconciliation could not canonicalize input");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
|
||||
const parseStaticLayer = (layer: StaticLayerInput): ParsedStaticLayer => {
|
||||
const evidence = parseEvidence(layer.analysis);
|
||||
assertEvidenceIdentity(evidence, {
|
||||
operation: "analyze_javascript_application",
|
||||
predicate: "rea.javascript-application-analysis/v1",
|
||||
providerId: "rea-javascript-application",
|
||||
providerName: "REA JavaScript application analyzer",
|
||||
providerVersion: "1",
|
||||
authority: "shipped-artifact",
|
||||
confidence: "derived",
|
||||
});
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
if (
|
||||
evidence.subject === null ||
|
||||
evidence.subject.digest.sha256 !== result.root_artifact_sha256 ||
|
||||
evidence.subject.format !== result.format ||
|
||||
evidence.subject.local_path !== result.input_path
|
||||
)
|
||||
throw new TypeError(
|
||||
"JavaScript application Evidence subject disagrees with its result",
|
||||
);
|
||||
const parameters = z
|
||||
.object({
|
||||
approved: z.literal(true),
|
||||
source_map_read_approved: z.boolean(),
|
||||
})
|
||||
.passthrough()
|
||||
.parse(evidence.parameters);
|
||||
return {
|
||||
layerId: `jrl_${digestCanonical({
|
||||
role: layer.role,
|
||||
evidence_id: evidence.evidence_id,
|
||||
runtime_mappings: layer.runtime_mappings,
|
||||
})}`,
|
||||
role: layer.role,
|
||||
evidence,
|
||||
result,
|
||||
graph: result.graph,
|
||||
runtimeMappings: layer.runtime_mappings,
|
||||
sourceMapReadApproved: parameters.source_map_read_approved,
|
||||
};
|
||||
};
|
||||
|
||||
const parseRuntimeCapture = (input: Evidence): ParsedRuntimeCapture => {
|
||||
const evidence = parseEvidence(input);
|
||||
if (evidence.operation === "inspect_web_page") {
|
||||
assertEvidenceIdentity(evidence, {
|
||||
operation: "inspect_web_page",
|
||||
predicate: "rea.web-page-inspection/v2",
|
||||
providerId: "rea-cdp-browser",
|
||||
providerName: "REA Chrome DevTools Protocol observation provider",
|
||||
providerVersion: "2",
|
||||
authority: "external-service",
|
||||
confidence: "observed",
|
||||
});
|
||||
const inspection = webPageInspectionSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
assertRuntimeParameters(evidence, {
|
||||
kind: "browser",
|
||||
targetId: inspection.target.target_id,
|
||||
targetOrigin: inspection.target.origin,
|
||||
sourceIncluded: inspection.scripts.items.some(
|
||||
({ source }) => source.included,
|
||||
),
|
||||
});
|
||||
return {
|
||||
kind: "browser",
|
||||
evidence,
|
||||
inspection,
|
||||
captureSha256: digestCanonical(inspection),
|
||||
scriptsCompleteWithinScope: scriptsComplete(inspection.completeness),
|
||||
};
|
||||
}
|
||||
if (evidence.operation === "inspect_electron_page") {
|
||||
assertEvidenceIdentity(evidence, {
|
||||
operation: "inspect_electron_page",
|
||||
predicate: "rea.electron-page-inspection/v1",
|
||||
providerId: "rea-cdp-electron",
|
||||
providerName: "REA Electron file-page CDP observation provider",
|
||||
providerVersion: "1",
|
||||
authority: "external-service",
|
||||
confidence: "observed",
|
||||
});
|
||||
const inspection = electronPageInspectionSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
assertRuntimeParameters(evidence, {
|
||||
kind: "electron",
|
||||
targetId: inspection.target.target_id,
|
||||
sourceIncluded: inspection.scripts.items.some(
|
||||
({ source }) => source.included,
|
||||
),
|
||||
});
|
||||
return {
|
||||
kind: "electron",
|
||||
evidence,
|
||||
inspection,
|
||||
captureSha256: digestCanonical(inspection),
|
||||
scriptsCompleteWithinScope: scriptsComplete(inspection.completeness),
|
||||
};
|
||||
}
|
||||
throw new TypeError(
|
||||
"Runtime reconciliation requires inspect_web_page or inspect_electron_page Evidence",
|
||||
);
|
||||
};
|
||||
|
||||
const assertRuntimeParameters = (
|
||||
evidence: Evidence,
|
||||
expected:
|
||||
| {
|
||||
readonly kind: "browser";
|
||||
readonly targetId: string;
|
||||
readonly targetOrigin: string;
|
||||
readonly sourceIncluded: boolean;
|
||||
}
|
||||
| {
|
||||
readonly kind: "electron";
|
||||
readonly targetId: string;
|
||||
readonly sourceIncluded: boolean;
|
||||
},
|
||||
): void => {
|
||||
const common = {
|
||||
target_id: z.string().trim().min(1).max(256),
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
include_script_sources: z.boolean(),
|
||||
};
|
||||
if (expected.kind === "browser") {
|
||||
const parameters = z
|
||||
.object({ ...common, allowed_origins: browserAllowedOriginsSchema })
|
||||
.passthrough()
|
||||
.parse(evidence.parameters);
|
||||
if (parameters.target_id !== expected.targetId)
|
||||
throw new TypeError(
|
||||
"Runtime Evidence target disagrees with its captured result",
|
||||
);
|
||||
if (!parameters.allowed_origins.includes(expected.targetOrigin))
|
||||
throw new TypeError(
|
||||
"Browser Evidence target is outside its recorded origin scope",
|
||||
);
|
||||
if (expected.sourceIncluded && !parameters.include_script_sources)
|
||||
throw new TypeError(
|
||||
"Runtime Evidence contains source without source-capture approval",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const parameters = z
|
||||
.object({
|
||||
...common,
|
||||
allowed_file_roots: electronFileRootsSchema,
|
||||
source_capture_approved: z.boolean(),
|
||||
})
|
||||
.passthrough()
|
||||
.parse(evidence.parameters);
|
||||
if (parameters.target_id !== expected.targetId)
|
||||
throw new TypeError(
|
||||
"Runtime Evidence target disagrees with its captured result",
|
||||
);
|
||||
if (
|
||||
expected.sourceIncluded &&
|
||||
(!parameters.include_script_sources ||
|
||||
parameters.source_capture_approved !== true)
|
||||
)
|
||||
throw new TypeError(
|
||||
"Runtime Evidence contains source without source-capture approval",
|
||||
);
|
||||
};
|
||||
|
||||
const scriptsComplete = (completeness: {
|
||||
readonly truncated_sections: readonly string[];
|
||||
readonly unavailable_sections: readonly string[];
|
||||
readonly dropped_events: { readonly scripts: number };
|
||||
}): boolean =>
|
||||
!completeness.truncated_sections.includes("scripts") &&
|
||||
!completeness.unavailable_sections.includes("scripts") &&
|
||||
completeness.dropped_events.scripts === 0;
|
||||
|
||||
const assertEvidenceIdentity = (
|
||||
evidence: Evidence,
|
||||
expected: {
|
||||
readonly operation: string;
|
||||
readonly predicate: string;
|
||||
readonly providerId: string;
|
||||
readonly providerName: string;
|
||||
readonly providerVersion: string;
|
||||
readonly authority: Evidence["authority"];
|
||||
readonly confidence: Evidence["confidence"];
|
||||
},
|
||||
): void => {
|
||||
if (
|
||||
evidence.operation !== expected.operation ||
|
||||
evidence.predicate_type !== expected.predicate ||
|
||||
evidence.provider.id !== expected.providerId ||
|
||||
evidence.provider.name !== expected.providerName ||
|
||||
evidence.provider.version !== expected.providerVersion ||
|
||||
evidence.authority !== expected.authority ||
|
||||
evidence.confidence !== expected.confidence
|
||||
)
|
||||
throw new TypeError(
|
||||
`Evidence does not match the supported ${expected.operation} contract`,
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,209 @@
|
||||
import {
|
||||
compareCodePoints,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import type { StaticLoadStateProjection } from "./javascriptRuntimeLoadState.js";
|
||||
import type { RuntimeMatchingProjection } from "./javascriptRuntimeReconciliationMatching.js";
|
||||
import {
|
||||
digestCanonical,
|
||||
type ParsedRuntimeCapture,
|
||||
type ParsedStaticLayer,
|
||||
} from "./javascriptRuntimeReconciliationParsing.js";
|
||||
import {
|
||||
javascriptRuntimeReconciliationResultSchema,
|
||||
type JavaScriptRuntimeReconciliationResult,
|
||||
} from "./javascriptRuntimeReconciliationSchemas.js";
|
||||
import type { RuntimeProjection } from "./javascriptRuntimeReconciliationRuntime.js";
|
||||
|
||||
interface ReconciliationProjection {
|
||||
readonly layers: readonly ParsedStaticLayer[];
|
||||
readonly captures: readonly ParsedRuntimeCapture[];
|
||||
readonly runtime: RuntimeProjection;
|
||||
readonly matching: RuntimeMatchingProjection;
|
||||
readonly loadStates: StaticLoadStateProjection;
|
||||
readonly graph: JavaScriptApplicationGraph;
|
||||
readonly omittedGraphItems: number;
|
||||
}
|
||||
|
||||
interface CompletionFlags {
|
||||
readonly outputTruncated: boolean;
|
||||
readonly inputTruncated: boolean;
|
||||
readonly inputPartial: boolean;
|
||||
}
|
||||
|
||||
/** Build and verify the deterministic caller-visible reconciliation result. */
|
||||
export const createJavaScriptRuntimeReconciliationResult = (
|
||||
input: ReconciliationProjection,
|
||||
): JavaScriptRuntimeReconciliationResult => {
|
||||
const completion = completionFlags(input);
|
||||
const semantic = {
|
||||
schema_version: 1 as const,
|
||||
static_layers: staticLayerSummaries(input.layers),
|
||||
runtime_captures: captureSummaries(input.captures, input.runtime),
|
||||
graph: input.graph,
|
||||
summary: reconciliationSummary(input),
|
||||
reconciliations: input.matching.items,
|
||||
static_load_states: input.loadStates.states,
|
||||
source_map_authority: sourceMapAuthority(input),
|
||||
coverage: reconciliationCoverage(input, completion),
|
||||
evidence_links: uniqueSorted([
|
||||
...input.layers.map(({ evidence }) => evidence.evidence_id),
|
||||
...input.captures.map(({ evidence }) => evidence.evidence_id),
|
||||
]),
|
||||
limitations: reconciliationLimitations(completion),
|
||||
};
|
||||
return javascriptRuntimeReconciliationResultSchema.parse({
|
||||
reconciliation_id: `jrr_${digestCanonical(semantic)}`,
|
||||
...semantic,
|
||||
});
|
||||
};
|
||||
|
||||
const staticLayerSummaries = (
|
||||
layers: readonly ParsedStaticLayer[],
|
||||
): JavaScriptRuntimeReconciliationResult["static_layers"] =>
|
||||
layers.map((layer) => ({
|
||||
layer_id: layer.layerId,
|
||||
role: layer.role,
|
||||
evidence_id: layer.evidence.evidence_id,
|
||||
graph_id: layer.graph.graph_id,
|
||||
root_artifact_sha256: layer.result.root_artifact_sha256,
|
||||
input_path: layer.result.input_path,
|
||||
format: layer.result.format,
|
||||
runtime_mappings: [...layer.runtimeMappings],
|
||||
}));
|
||||
|
||||
const captureSummaries = (
|
||||
captures: readonly ParsedRuntimeCapture[],
|
||||
runtime: RuntimeProjection,
|
||||
): JavaScriptRuntimeReconciliationResult["runtime_captures"] =>
|
||||
captures.map((capture) => {
|
||||
const targetNode = runtime.targetNodeByEvidenceId.get(
|
||||
capture.evidence.evidence_id,
|
||||
);
|
||||
if (targetNode === undefined)
|
||||
throw new TypeError("Runtime projection omitted a required target node");
|
||||
return {
|
||||
evidence_id: capture.evidence.evidence_id,
|
||||
capture_sha256: capture.captureSha256,
|
||||
kind: capture.kind,
|
||||
target_node_id: targetNode.node_id,
|
||||
target_key: capture.inspection.target.target_id,
|
||||
target_location:
|
||||
capture.kind === "browser"
|
||||
? capture.inspection.target.url.slice(0, 4_096)
|
||||
: capture.inspection.target.file_path.slice(0, 4_096),
|
||||
frames: capture.inspection.frames.length,
|
||||
scripts: capture.inspection.scripts.items.length,
|
||||
workers: capture.inspection.workers.length,
|
||||
scripts_complete_within_scope: capture.scriptsCompleteWithinScope,
|
||||
};
|
||||
});
|
||||
|
||||
const reconciliationSummary = (
|
||||
input: ReconciliationProjection,
|
||||
): JavaScriptRuntimeReconciliationResult["summary"] => ({
|
||||
runtime_targets: countBy(input.runtime.entities, "kind", "target"),
|
||||
runtime_frames: countBy(input.runtime.entities, "kind", "frame"),
|
||||
runtime_scripts: countBy(input.runtime.entities, "kind", "script"),
|
||||
runtime_workers: countBy(input.runtime.entities, "kind", "worker"),
|
||||
matched: countBy(input.matching.items, "status", "matched"),
|
||||
ambiguous: countBy(input.matching.items, "status", "ambiguous"),
|
||||
unmatched: countBy(input.matching.items, "status", "unmatched"),
|
||||
unknown: countBy(input.matching.items, "status", "unknown"),
|
||||
static_loaded: countBy(input.loadStates.states, "status", "loaded"),
|
||||
static_resident: countBy(
|
||||
input.loadStates.states,
|
||||
"status",
|
||||
"resident-in-loaded-asset",
|
||||
),
|
||||
static_not_observed: countBy(
|
||||
input.loadStates.states,
|
||||
"status",
|
||||
"not-observed-in-capture",
|
||||
),
|
||||
static_unknown: countBy(input.loadStates.states, "status", "unknown"),
|
||||
});
|
||||
|
||||
const sourceMapAuthority = (
|
||||
input: ReconciliationProjection,
|
||||
): JavaScriptRuntimeReconciliationResult["source_map_authority"] => ({
|
||||
used_for_primary_matching: false,
|
||||
static_layers_with_read_approval: input.layers.filter(
|
||||
({ sourceMapReadApproved }) => sourceMapReadApproved,
|
||||
).length,
|
||||
runtime_script_declarations: input.captures.reduce(
|
||||
(total, capture) =>
|
||||
total +
|
||||
(capture.kind === "browser"
|
||||
? capture.inspection.scripts.items.filter(
|
||||
({ source_map_url: url }) => url !== null,
|
||||
).length
|
||||
: 0),
|
||||
0,
|
||||
),
|
||||
limitation:
|
||||
"Source-map declarations and approved original-source reads retain separate static authority and are not used as primary runtime byte matches.",
|
||||
});
|
||||
|
||||
const reconciliationCoverage = (
|
||||
input: ReconciliationProjection,
|
||||
completion: CompletionFlags,
|
||||
): JavaScriptRuntimeReconciliationResult["coverage"] => ({
|
||||
status:
|
||||
completion.outputTruncated || completion.inputTruncated
|
||||
? "truncated"
|
||||
: completion.inputPartial
|
||||
? "partial"
|
||||
: "complete-within-inputs",
|
||||
truncated: completion.outputTruncated || completion.inputTruncated,
|
||||
omitted_runtime_entities: input.runtime.omittedEntities,
|
||||
omitted_reconciliation_items: input.matching.omittedItems,
|
||||
omitted_static_load_states: input.loadStates.omittedStates,
|
||||
omitted_graph_items: input.omittedGraphItems,
|
||||
});
|
||||
|
||||
const completionFlags = (input: ReconciliationProjection): CompletionFlags => ({
|
||||
outputTruncated:
|
||||
input.runtime.omittedEntities > 0 ||
|
||||
input.matching.omittedItems > 0 ||
|
||||
input.loadStates.omittedStates > 0 ||
|
||||
input.omittedGraphItems > 0,
|
||||
inputTruncated:
|
||||
input.layers.some(({ graph }) => graph.coverage.truncated) ||
|
||||
input.captures.some(({ inspection }) =>
|
||||
inspection.completeness.conditions.includes("truncated"),
|
||||
),
|
||||
inputPartial:
|
||||
input.layers.some(({ graph }) => graph.coverage.status !== "complete") ||
|
||||
input.captures.some(
|
||||
({ inspection }) =>
|
||||
inspection.completeness.status !== "complete_within_window",
|
||||
),
|
||||
});
|
||||
|
||||
const reconciliationLimitations = (completion: CompletionFlags): string[] =>
|
||||
uniqueSorted([
|
||||
"Only caller-supplied, semantically verified Evidence records were reconciled.",
|
||||
"Digest equality establishes byte identity but not code reachability, module initialization, or feature execution.",
|
||||
"A static module resident in an observed bundle is not reported as executed.",
|
||||
"Not-observed means absent from the bounded captures in scope, never globally unloaded.",
|
||||
"Caller-declared file and URL mappings are inference inputs and do not expand CDP origin or filesystem-root authority.",
|
||||
"Source-map authority remains separate from passive runtime authority.",
|
||||
...(completion.inputPartial
|
||||
? ["One or more static graphs or passive captures were incomplete."]
|
||||
: []),
|
||||
...(completion.outputTruncated
|
||||
? [
|
||||
"Caller limits omitted runtime entities or reconciliation classifications.",
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
|
||||
const countBy = <Item extends Record<Key, string>, Key extends keyof Item>(
|
||||
items: readonly Item[],
|
||||
key: Key,
|
||||
value: Item[Key],
|
||||
): number => items.filter((item) => item[key] === value).length;
|
||||
|
||||
const uniqueSorted = (values: readonly string[]): string[] =>
|
||||
[...new Set(values)].sort(compareCodePoints);
|
||||
@@ -0,0 +1,433 @@
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import {
|
||||
createJavaScriptApplicationEdge,
|
||||
createJavaScriptApplicationNode,
|
||||
type ApplicationEdge,
|
||||
type ApplicationGraphEvidence,
|
||||
type ApplicationNode,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import type { ParsedRuntimeCapture } from "./javascriptRuntimeReconciliationParsing.js";
|
||||
|
||||
export interface RuntimeReconciliationEntity {
|
||||
readonly kind: "target" | "frame" | "script" | "worker";
|
||||
readonly section: "target" | "frames" | "scripts" | "workers";
|
||||
readonly node: ApplicationNode;
|
||||
readonly capture: ParsedRuntimeCapture;
|
||||
readonly runtimeKey: string;
|
||||
readonly location: { readonly kind: "file" | "url"; readonly value: string };
|
||||
readonly frameKey: string | null;
|
||||
readonly sourceSha256: string | null;
|
||||
readonly staticKind: "renderer" | "javascript" | "worker" | "service-worker";
|
||||
}
|
||||
|
||||
export interface RuntimeProjection {
|
||||
readonly entities: readonly RuntimeReconciliationEntity[];
|
||||
readonly nodes: readonly ApplicationNode[];
|
||||
readonly edges: readonly ApplicationEdge[];
|
||||
readonly targetNodeByEvidenceId: ReadonlyMap<string, ApplicationNode>;
|
||||
readonly omittedEntities: number;
|
||||
}
|
||||
|
||||
/** Project authorized passive capture metadata into capture-scoped JAG nodes. */
|
||||
export const projectRuntimeCaptures = (
|
||||
captures: readonly ParsedRuntimeCapture[],
|
||||
maximumEntities: number,
|
||||
): RuntimeProjection => {
|
||||
if (maximumEntities < captures.length)
|
||||
throw new TypeError(
|
||||
"Runtime entity limit must admit one target for every capture",
|
||||
);
|
||||
const all = captures.flatMap(projectCapture);
|
||||
const targets = all.filter(({ kind }) => kind === "target");
|
||||
const nonTargets = all.filter(({ kind }) => kind !== "target");
|
||||
const retained = [...targets, ...nonTargets].slice(0, maximumEntities);
|
||||
const retainedIds = new Set(retained.map(({ node }) => node.node_id));
|
||||
const nodes = retained.map(({ node }) => node);
|
||||
const edges = captures
|
||||
.flatMap((capture) => runtimeEdges(capture, all))
|
||||
.filter(
|
||||
({ source_node_id: source, target_node_id: target }) =>
|
||||
retainedIds.has(source) && retainedIds.has(target),
|
||||
);
|
||||
const targetNodeByEvidenceId = new Map(
|
||||
retained
|
||||
.filter(({ kind }) => kind === "target")
|
||||
.map(({ capture, node }) => [capture.evidence.evidence_id, node]),
|
||||
);
|
||||
return {
|
||||
entities: retained,
|
||||
nodes,
|
||||
edges,
|
||||
targetNodeByEvidenceId,
|
||||
omittedEntities: all.length - retained.length,
|
||||
};
|
||||
};
|
||||
|
||||
const projectCapture = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
): RuntimeReconciliationEntity[] => {
|
||||
const target = targetEntity(capture);
|
||||
return [
|
||||
target,
|
||||
...frameEntities(capture),
|
||||
...scriptEntities(capture),
|
||||
...workerEntities(capture),
|
||||
];
|
||||
};
|
||||
|
||||
const targetEntity = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
): RuntimeReconciliationEntity => {
|
||||
const target = capture.inspection.target;
|
||||
const location =
|
||||
"url" in target
|
||||
? ({ kind: "url", value: target.url } as const)
|
||||
: ({ kind: "file", value: target.file_path } as const);
|
||||
return runtimeEntity(capture, {
|
||||
kind: "target",
|
||||
nodeKind: "target",
|
||||
runtimeKey: target.target_id,
|
||||
targetKey: target.target_id,
|
||||
frameKey: null,
|
||||
scriptKey: null,
|
||||
location,
|
||||
staticKind: "renderer",
|
||||
sourceSha256: null,
|
||||
label: target.title,
|
||||
properties: {
|
||||
runtime_type: target.type,
|
||||
location: location.value.slice(0, 4_096),
|
||||
attached: target.attached,
|
||||
},
|
||||
section: "target",
|
||||
});
|
||||
};
|
||||
|
||||
const frameEntities = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
): RuntimeReconciliationEntity[] =>
|
||||
capture.inspection.frames.map((frame) => {
|
||||
const location =
|
||||
"url" in frame
|
||||
? ({ kind: "url", value: frame.url } as const)
|
||||
: ({ kind: "file", value: frame.file_path } as const);
|
||||
return runtimeEntity(capture, {
|
||||
kind: "frame",
|
||||
nodeKind: "frame",
|
||||
runtimeKey: frame.frame_id,
|
||||
targetKey: capture.inspection.target.target_id,
|
||||
frameKey: frame.frame_id,
|
||||
scriptKey: null,
|
||||
location,
|
||||
staticKind: "renderer",
|
||||
sourceSha256: null,
|
||||
label: location.value,
|
||||
properties: {
|
||||
parent_frame_id: frame.parent_frame_id,
|
||||
location: location.value.slice(0, 4_096),
|
||||
},
|
||||
section: "frames",
|
||||
});
|
||||
});
|
||||
|
||||
const scriptEntities = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
): RuntimeReconciliationEntity[] =>
|
||||
capture.inspection.scripts.items.map((script) => {
|
||||
const location =
|
||||
"url" in script
|
||||
? ({ kind: "url", value: script.url } as const)
|
||||
: ({ kind: "file", value: script.file_path } as const);
|
||||
return runtimeEntity(capture, {
|
||||
kind: "script",
|
||||
nodeKind: "runtime-script-instance",
|
||||
runtimeKey: script.script_key,
|
||||
targetKey: capture.inspection.target.target_id,
|
||||
frameKey: script.frame_id,
|
||||
scriptKey: script.script_key,
|
||||
location,
|
||||
staticKind: "javascript",
|
||||
sourceSha256: script.source.included
|
||||
? script.source.artifact.sha256
|
||||
: null,
|
||||
label: location.value,
|
||||
properties: {
|
||||
location: location.value.slice(0, 4_096),
|
||||
cdp_hash: script.cdp_hash,
|
||||
length: script.length,
|
||||
is_module: script.is_module,
|
||||
language: script.language,
|
||||
source_sha256: script.source.included
|
||||
? script.source.artifact.sha256
|
||||
: null,
|
||||
...("source_map_url" in script
|
||||
? { source_map_url: script.source_map_url }
|
||||
: {}),
|
||||
},
|
||||
section: "scripts",
|
||||
...(script.source.included
|
||||
? { artifactSha256: script.source.artifact.sha256 }
|
||||
: {}),
|
||||
});
|
||||
});
|
||||
|
||||
const workerEntities = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
): RuntimeReconciliationEntity[] =>
|
||||
capture.inspection.workers.map((worker) => {
|
||||
const location =
|
||||
"url" in worker
|
||||
? ({ kind: "url", value: worker.url } as const)
|
||||
: ({ kind: "file", value: worker.file_path } as const);
|
||||
const serviceWorker = worker.type.includes("service");
|
||||
return runtimeEntity(capture, {
|
||||
kind: "worker",
|
||||
nodeKind: serviceWorker ? "service-worker" : "worker",
|
||||
runtimeKey: worker.target_id,
|
||||
targetKey: worker.target_id,
|
||||
frameKey: worker.parent_frame_id,
|
||||
scriptKey: null,
|
||||
location,
|
||||
staticKind: serviceWorker ? "service-worker" : "worker",
|
||||
sourceSha256: null,
|
||||
label: location.value,
|
||||
properties: {
|
||||
runtime_type: worker.type,
|
||||
location: location.value.slice(0, 4_096),
|
||||
attached: worker.attached,
|
||||
opener_target_id: worker.opener_target_id,
|
||||
parent_frame_id: worker.parent_frame_id,
|
||||
},
|
||||
section: "workers",
|
||||
});
|
||||
});
|
||||
|
||||
interface RuntimeEntityInput {
|
||||
readonly kind: RuntimeReconciliationEntity["kind"];
|
||||
readonly nodeKind: ApplicationNode["kind"];
|
||||
readonly runtimeKey: string;
|
||||
readonly targetKey: string;
|
||||
readonly frameKey: string | null;
|
||||
readonly scriptKey: string | null;
|
||||
readonly location: RuntimeReconciliationEntity["location"];
|
||||
readonly staticKind: RuntimeReconciliationEntity["staticKind"];
|
||||
readonly sourceSha256: string | null;
|
||||
readonly label: string;
|
||||
readonly properties: Readonly<Record<string, JsonValue>>;
|
||||
readonly section: "target" | "frames" | "scripts" | "workers";
|
||||
readonly artifactSha256?: string;
|
||||
}
|
||||
|
||||
const runtimeEntity = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
input: RuntimeEntityInput,
|
||||
): RuntimeReconciliationEntity => ({
|
||||
kind: input.kind,
|
||||
section: input.section,
|
||||
capture,
|
||||
runtimeKey: input.runtimeKey,
|
||||
location: input.location,
|
||||
frameKey: input.frameKey,
|
||||
sourceSha256: input.sourceSha256,
|
||||
staticKind: input.staticKind,
|
||||
node: createJavaScriptApplicationNode({
|
||||
kind: input.nodeKind,
|
||||
identity: {
|
||||
strategy: "runtime-instance",
|
||||
stability: "capture-only",
|
||||
capture_sha256: capture.captureSha256,
|
||||
runtime_key: input.runtimeKey,
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: input.label.slice(0, 1_024) || null,
|
||||
properties: input.properties,
|
||||
evidence: runtimeEvidence(capture, input),
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
const runtimeEvidence = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
input: RuntimeEntityInput,
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority: "passive-cdp-runtime",
|
||||
state: "observed",
|
||||
confidence: "exact",
|
||||
artifact:
|
||||
input.artifactSha256 === undefined
|
||||
? {
|
||||
available: false,
|
||||
reason:
|
||||
input.section === "scripts" ? "not-observed" : "not-applicable",
|
||||
detail:
|
||||
input.section === "scripts"
|
||||
? "Script source bytes were not included in this passive capture."
|
||||
: "This runtime entity has no standalone artifact bytes.",
|
||||
}
|
||||
: {
|
||||
available: true,
|
||||
artifact_id: `art_${input.artifactSha256}`,
|
||||
sha256: input.artifactSha256,
|
||||
},
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
kind: "runtime",
|
||||
capture_sha256: capture.captureSha256,
|
||||
target_key: input.targetKey,
|
||||
frame_key: input.frameKey,
|
||||
script_key: input.scriptKey,
|
||||
},
|
||||
},
|
||||
extractor: {
|
||||
name: capture.evidence.provider.id,
|
||||
version:
|
||||
capture.evidence.provider.version ??
|
||||
(capture.kind === "browser" ? "2" : "1"),
|
||||
operation:
|
||||
capture.kind === "browser" ? "inspect_web_page" : "inspect_electron_page",
|
||||
executable_sha256: null,
|
||||
},
|
||||
coverage: runtimeSectionCoverage(capture, input.section),
|
||||
limitations: [
|
||||
"The entity was observed only within one bounded passive CDP capture.",
|
||||
...(runtimeSectionComplete(capture, input.section)
|
||||
? []
|
||||
: [
|
||||
`The runtime ${input.section} inventory was incomplete within this capture.`,
|
||||
]),
|
||||
],
|
||||
evidence_ids: [capture.evidence.evidence_id],
|
||||
});
|
||||
|
||||
const runtimeEdges = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
entities: readonly RuntimeReconciliationEntity[],
|
||||
): ApplicationEdge[] => {
|
||||
const local = entities.filter(
|
||||
({ capture: candidate }) =>
|
||||
candidate.evidence.evidence_id === capture.evidence.evidence_id,
|
||||
);
|
||||
const target = local.find(({ kind }) => kind === "target");
|
||||
if (target === undefined) return [];
|
||||
const frames = new Map(
|
||||
local
|
||||
.filter(({ kind }) => kind === "frame")
|
||||
.map((entity) => [entity.runtimeKey, entity]),
|
||||
);
|
||||
return local.flatMap((entity) => {
|
||||
if (entity === target) return [];
|
||||
const parent =
|
||||
(entity.kind === "script" || entity.kind === "worker") &&
|
||||
entity.frameKey !== null
|
||||
? (frames.get(entity.frameKey) ?? target)
|
||||
: target;
|
||||
return [
|
||||
createJavaScriptApplicationEdge({
|
||||
source_node_id: parent.node.node_id,
|
||||
target_node_id: entity.node.node_id,
|
||||
relation: entity.kind === "script" ? "loads" : "contains",
|
||||
properties: { basis: "passive-cdp-observation" },
|
||||
evidence: runtimeRelationshipEvidence(capture, entity),
|
||||
}),
|
||||
];
|
||||
});
|
||||
};
|
||||
|
||||
const runtimeRelationshipEvidence = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
entity: RuntimeReconciliationEntity,
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority: "passive-cdp-runtime",
|
||||
state: "observed",
|
||||
confidence: "exact",
|
||||
artifact: {
|
||||
available: false,
|
||||
reason: "not-applicable",
|
||||
detail: "The relationship is runtime metadata, not standalone bytes.",
|
||||
},
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
kind: "runtime",
|
||||
capture_sha256: capture.captureSha256,
|
||||
target_key: capture.inspection.target.target_id,
|
||||
frame_key: entity.frameKey,
|
||||
script_key: entity.kind === "script" ? entity.runtimeKey : null,
|
||||
},
|
||||
},
|
||||
extractor: {
|
||||
name: capture.evidence.provider.id,
|
||||
version:
|
||||
capture.evidence.provider.version ??
|
||||
(capture.kind === "browser" ? "2" : "1"),
|
||||
operation:
|
||||
capture.kind === "browser" ? "inspect_web_page" : "inspect_electron_page",
|
||||
executable_sha256: null,
|
||||
},
|
||||
coverage: runtimeSectionCoverage(capture, entity.section),
|
||||
limitations: [
|
||||
"The relationship was observed only within one bounded passive CDP capture.",
|
||||
],
|
||||
evidence_ids: [capture.evidence.evidence_id],
|
||||
});
|
||||
|
||||
const runtimeSectionComplete = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
section: RuntimeEntityInput["section"],
|
||||
): boolean => {
|
||||
if (section === "target") return true;
|
||||
if (section === "scripts") return capture.scriptsCompleteWithinScope;
|
||||
return (
|
||||
!capture.inspection.completeness.truncated_sections.includes(section) &&
|
||||
!capture.inspection.completeness.unavailable_sections.includes(section)
|
||||
);
|
||||
};
|
||||
|
||||
const runtimeSectionCoverage = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
section: RuntimeEntityInput["section"],
|
||||
): ApplicationGraphEvidence["coverage"] => {
|
||||
if (runtimeSectionComplete(capture, section))
|
||||
return {
|
||||
status: "complete",
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
};
|
||||
const truncated =
|
||||
section !== "target" &&
|
||||
capture.inspection.completeness.truncated_sections.includes(section);
|
||||
return {
|
||||
status: "partial",
|
||||
truncated,
|
||||
omitted_count: null,
|
||||
limits: truncated
|
||||
? [
|
||||
{
|
||||
name: `passive-cdp-${section}-limit`,
|
||||
value: runtimeSectionCount(capture, section),
|
||||
unit: "items",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
};
|
||||
};
|
||||
|
||||
const runtimeSectionCount = (
|
||||
capture: ParsedRuntimeCapture,
|
||||
section: RuntimeEntityInput["section"],
|
||||
): number => {
|
||||
switch (section) {
|
||||
case "target":
|
||||
return 1;
|
||||
case "frames":
|
||||
return capture.inspection.frames.length;
|
||||
case "scripts":
|
||||
return capture.inspection.scripts.items.length;
|
||||
case "workers":
|
||||
return capture.inspection.workers.length;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,299 @@
|
||||
import { isAbsolute, resolve } from "node:path";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { evidenceSchema } from "./evidence.js";
|
||||
import {
|
||||
compareCodePoints,
|
||||
javascriptApplicationGraphSchema,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
const nodeIdSchema = z.string().regex(/^jag_node_[a-f0-9]{64}$/u);
|
||||
const boundedTextSchema = z.string().min(1).max(4_096);
|
||||
const safePrefixSchema = z
|
||||
.string()
|
||||
.max(4_096)
|
||||
.refine(
|
||||
(value) =>
|
||||
value === "" ||
|
||||
(!value.startsWith("/") &&
|
||||
!value.includes("\\") &&
|
||||
value.split("/").every((part) => !["", ".", ".."].includes(part))),
|
||||
"Artifact prefix must be empty or a safe relative POSIX path",
|
||||
);
|
||||
|
||||
const runtimeFileMappingSchema = z.strictObject({
|
||||
kind: z.literal("file-root"),
|
||||
root: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(16_384)
|
||||
.refine(isAbsolute, "Runtime file mapping root must be absolute")
|
||||
.overwrite((value) => resolve(value)),
|
||||
artifact_prefix: safePrefixSchema.default(""),
|
||||
});
|
||||
|
||||
const runtimeUrlMappingSchema = z.strictObject({
|
||||
kind: z.literal("url-prefix"),
|
||||
prefix: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(16_384)
|
||||
.refine(
|
||||
(value) => normalizeRuntimeUrlPrefix(value) !== null,
|
||||
"Runtime URL prefix must be HTTP(S) without credentials, query, or fragment",
|
||||
)
|
||||
.overwrite((value) => normalizeRuntimeUrlPrefix(value) ?? value),
|
||||
artifact_prefix: safePrefixSchema.default(""),
|
||||
});
|
||||
|
||||
const normalizeRuntimeUrlPrefix = (value: string): string | null => {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
!["http:", "https:"].includes(url.protocol) ||
|
||||
url.username !== "" ||
|
||||
url.password !== "" ||
|
||||
url.search !== "" ||
|
||||
url.hash !== ""
|
||||
)
|
||||
return null;
|
||||
if (!url.pathname.endsWith("/")) url.pathname += "/";
|
||||
return url.href;
|
||||
};
|
||||
|
||||
/** Caller-declared translation from an authorized runtime location to a layer. */
|
||||
const runtimeLocationMappingSchema = z.discriminatedUnion("kind", [
|
||||
runtimeFileMappingSchema,
|
||||
runtimeUrlMappingSchema,
|
||||
]);
|
||||
type RuntimeLocationMapping = z.infer<typeof runtimeLocationMappingSchema>;
|
||||
|
||||
const staticLayerSchema = z.strictObject({
|
||||
role: z.enum(["application", "cache", "assets"]),
|
||||
analysis: evidenceSchema,
|
||||
runtime_mappings: z
|
||||
.array(runtimeLocationMappingSchema)
|
||||
.max(32)
|
||||
.overwrite(normalizeRuntimeMappings)
|
||||
.default([]),
|
||||
});
|
||||
|
||||
function normalizeRuntimeMappings(
|
||||
mappings: RuntimeLocationMapping[],
|
||||
): RuntimeLocationMapping[] {
|
||||
return [
|
||||
...new Map(
|
||||
mappings.map((mapping) => [runtimeMappingKey(mapping), mapping]),
|
||||
).values(),
|
||||
].sort((left, right) =>
|
||||
compareCodePoints(runtimeMappingKey(left), runtimeMappingKey(right)),
|
||||
);
|
||||
}
|
||||
|
||||
function runtimeMappingKey(mapping: RuntimeLocationMapping): string {
|
||||
return mapping.kind === "file-root"
|
||||
? `file-root\0${mapping.root}\0${mapping.artifact_prefix}`
|
||||
: `url-prefix\0${mapping.prefix}\0${mapping.artifact_prefix}`;
|
||||
}
|
||||
|
||||
const reconciliationLimitsSchema = z.strictObject({
|
||||
max_runtime_entities: z.number().int().min(1).max(50_000).default(10_000),
|
||||
max_reconciliation_items: z.number().int().min(1).max(50_000).default(20_000),
|
||||
max_static_load_states: z.number().int().min(1).max(50_000).default(20_000),
|
||||
});
|
||||
|
||||
/** Evidence-backed static layers and passive captures to reconcile. */
|
||||
export const reconcileJavaScriptRuntimeInputSchema = z
|
||||
.strictObject({
|
||||
static_layers: z.array(staticLayerSchema).min(1).max(8),
|
||||
runtime_observations: z.array(evidenceSchema).min(1).max(32),
|
||||
limits: reconciliationLimitsSchema.default({
|
||||
max_runtime_entities: 10_000,
|
||||
max_reconciliation_items: 20_000,
|
||||
max_static_load_states: 20_000,
|
||||
}),
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
if (
|
||||
input.static_layers.filter(({ role }) => role === "application")
|
||||
.length !== 1
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["static_layers"],
|
||||
message: "Exactly one application static layer is required",
|
||||
});
|
||||
const staticIds = input.static_layers.map(
|
||||
({ analysis }) => analysis.evidence_id,
|
||||
);
|
||||
if (new Set(staticIds).size !== staticIds.length)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["static_layers"],
|
||||
message: "Static layer Evidence must be unique",
|
||||
});
|
||||
const runtimeIds = input.runtime_observations.map(
|
||||
({ evidence_id: id }) => id,
|
||||
);
|
||||
if (new Set(runtimeIds).size !== runtimeIds.length)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["runtime_observations"],
|
||||
message: "Runtime observation Evidence must be unique",
|
||||
});
|
||||
if (input.limits.max_runtime_entities < input.runtime_observations.length)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["limits", "max_runtime_entities"],
|
||||
message: "Runtime entity limit must retain one target per observation",
|
||||
});
|
||||
});
|
||||
|
||||
const layerSummarySchema = z.strictObject({
|
||||
layer_id: z.string().regex(/^jrl_[a-f0-9]{64}$/u),
|
||||
role: z.enum(["application", "cache", "assets"]),
|
||||
evidence_id: evidenceIdSchema,
|
||||
graph_id: z.string().regex(/^jag_[a-f0-9]{64}$/u),
|
||||
root_artifact_sha256: digestSchema,
|
||||
input_path: z.string().min(1).max(16_384),
|
||||
format: z.enum(["asar", "directory"]),
|
||||
runtime_mappings: z.array(runtimeLocationMappingSchema).max(32),
|
||||
});
|
||||
|
||||
const captureSummarySchema = z.strictObject({
|
||||
evidence_id: evidenceIdSchema,
|
||||
capture_sha256: digestSchema,
|
||||
kind: z.enum(["browser", "electron"]),
|
||||
target_node_id: nodeIdSchema,
|
||||
target_key: boundedTextSchema,
|
||||
target_location: boundedTextSchema,
|
||||
frames: z.number().int().min(0),
|
||||
scripts: z.number().int().min(0),
|
||||
workers: z.number().int().min(0),
|
||||
scripts_complete_within_scope: z.boolean(),
|
||||
});
|
||||
|
||||
const reconciliationReasonSchema = z.enum([
|
||||
"content-and-location-match",
|
||||
"unique-content-match",
|
||||
"unique-location-match",
|
||||
"ambiguous-static-candidates",
|
||||
"captured-content-disagrees-with-static-location",
|
||||
"no-static-content-match",
|
||||
"no-authorized-location-mapping",
|
||||
"runtime-frame-unattributed",
|
||||
"static-or-runtime-coverage-incomplete",
|
||||
"reconciliation-limit-reached",
|
||||
]);
|
||||
|
||||
const reconciliationItemSchema = z.strictObject({
|
||||
reconciliation_id: z.string().regex(/^jrr_item_[a-f0-9]{64}$/u),
|
||||
entity_kind: z.enum(["target", "frame", "script", "worker"]),
|
||||
runtime_evidence_id: evidenceIdSchema,
|
||||
runtime_node_id: nodeIdSchema,
|
||||
static_layer_id: z
|
||||
.string()
|
||||
.regex(/^jrl_[a-f0-9]{64}$/u)
|
||||
.nullable(),
|
||||
static_node_id: nodeIdSchema.nullable(),
|
||||
status: z.enum(["matched", "ambiguous", "unmatched", "unknown"]),
|
||||
basis: z.enum([
|
||||
"content-and-location",
|
||||
"content-sha256",
|
||||
"module-source-sha256",
|
||||
"artifact-path",
|
||||
"operator-file-mapping",
|
||||
"operator-url-mapping",
|
||||
"none",
|
||||
]),
|
||||
confidence: z.enum(["exact", "high", "medium", "low", "unknown"]),
|
||||
reason: reconciliationReasonSchema,
|
||||
candidate_static_count: z.number().int().min(0).max(800_000),
|
||||
candidate_static_nodes: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
static_layer_id: z.string().regex(/^jrl_[a-f0-9]{64}$/u),
|
||||
static_node_id: nodeIdSchema,
|
||||
}),
|
||||
)
|
||||
.max(1_000),
|
||||
});
|
||||
|
||||
const staticLoadStateSchema = z.strictObject({
|
||||
static_layer_id: z.string().regex(/^jrl_[a-f0-9]{64}$/u),
|
||||
static_node_id: nodeIdSchema,
|
||||
kind: z.enum(["javascript-asset", "javascript-chunk", "javascript-module"]),
|
||||
status: z.enum([
|
||||
"loaded",
|
||||
"resident-in-loaded-asset",
|
||||
"not-observed-in-capture",
|
||||
"unknown",
|
||||
]),
|
||||
runtime_node_ids: z.array(nodeIdSchema).max(10_000),
|
||||
reason: z.enum([
|
||||
"runtime-script-correspondence",
|
||||
"containing-asset-was-loaded",
|
||||
"not-observed-in-bounded-capture",
|
||||
"layer-outside-runtime-scope",
|
||||
"static-or-runtime-coverage-incomplete",
|
||||
]),
|
||||
});
|
||||
|
||||
/** Deterministic static/passive-runtime reconciliation with a combined JAG. */
|
||||
export const javascriptRuntimeReconciliationResultSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
reconciliation_id: z.string().regex(/^jrr_[a-f0-9]{64}$/u),
|
||||
static_layers: z.array(layerSummarySchema).min(1).max(8),
|
||||
runtime_captures: z.array(captureSummarySchema).min(1).max(32),
|
||||
graph: javascriptApplicationGraphSchema,
|
||||
summary: z.strictObject({
|
||||
runtime_targets: z.number().int().min(0),
|
||||
runtime_frames: z.number().int().min(0),
|
||||
runtime_scripts: z.number().int().min(0),
|
||||
runtime_workers: z.number().int().min(0),
|
||||
matched: z.number().int().min(0),
|
||||
ambiguous: z.number().int().min(0),
|
||||
unmatched: z.number().int().min(0),
|
||||
unknown: z.number().int().min(0),
|
||||
static_loaded: z.number().int().min(0),
|
||||
static_resident: z.number().int().min(0),
|
||||
static_not_observed: z.number().int().min(0),
|
||||
static_unknown: z.number().int().min(0),
|
||||
}),
|
||||
reconciliations: z.array(reconciliationItemSchema).max(50_000),
|
||||
static_load_states: z.array(staticLoadStateSchema).max(50_000),
|
||||
source_map_authority: z.strictObject({
|
||||
used_for_primary_matching: z.literal(false),
|
||||
static_layers_with_read_approval: z.number().int().min(0),
|
||||
runtime_script_declarations: z.number().int().min(0),
|
||||
limitation: boundedTextSchema,
|
||||
}),
|
||||
coverage: z.strictObject({
|
||||
status: z.enum(["complete-within-inputs", "partial", "truncated"]),
|
||||
truncated: z.boolean(),
|
||||
omitted_runtime_entities: z.number().int().min(0),
|
||||
omitted_reconciliation_items: z.number().int().min(0),
|
||||
omitted_static_load_states: z.number().int().min(0),
|
||||
omitted_graph_items: z.number().int().min(0),
|
||||
}),
|
||||
evidence_links: z.array(evidenceIdSchema).min(2).max(40),
|
||||
limitations: z.array(boundedTextSchema).max(1_000),
|
||||
});
|
||||
|
||||
export type ReconcileJavaScriptRuntimeInput = z.infer<
|
||||
typeof reconcileJavaScriptRuntimeInputSchema
|
||||
>;
|
||||
export type JavaScriptRuntimeReconciliationResult = z.infer<
|
||||
typeof javascriptRuntimeReconciliationResultSchema
|
||||
>;
|
||||
export type JavaScriptRuntimeReconciliationItem = z.infer<
|
||||
typeof reconciliationItemSchema
|
||||
>;
|
||||
export type JavaScriptStaticLoadState = z.infer<typeof staticLoadStateSchema>;
|
||||
@@ -0,0 +1,297 @@
|
||||
import { isAbsolute, posix, relative } from "node:path";
|
||||
|
||||
import {
|
||||
compareCodePoints,
|
||||
type ApplicationNode,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import type { ParsedStaticLayer } from "./javascriptRuntimeReconciliationParsing.js";
|
||||
import type { RuntimeReconciliationEntity } from "./javascriptRuntimeReconciliationRuntime.js";
|
||||
|
||||
export interface StaticRuntimeCandidate {
|
||||
readonly layer: ParsedStaticLayer;
|
||||
readonly node: ApplicationNode;
|
||||
readonly category: "renderer" | "javascript" | "worker" | "service-worker";
|
||||
readonly paths: readonly string[];
|
||||
readonly digests: readonly {
|
||||
readonly sha256: string;
|
||||
readonly basis: "content-sha256" | "module-source-sha256";
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface MappedRuntimePath {
|
||||
readonly path: string;
|
||||
readonly basis:
|
||||
| "artifact-path"
|
||||
| "operator-file-mapping"
|
||||
| "operator-url-mapping";
|
||||
}
|
||||
|
||||
/** Precomputed mapping scope and graph paths for static load-state decisions. */
|
||||
export interface StaticRuntimeScope {
|
||||
readonly artifactPrefixes: readonly string[];
|
||||
readonly pathsByNodeId: ReadonlyMap<string, readonly string[]>;
|
||||
}
|
||||
|
||||
/** Index statically reconstructed entities that can receive runtime matches. */
|
||||
export const collectStaticRuntimeCandidates = (
|
||||
layers: readonly ParsedStaticLayer[],
|
||||
): StaticRuntimeCandidate[] =>
|
||||
layers
|
||||
.flatMap((layer) => candidatesForLayer(layer))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
compareCodePoints(left.layer.layerId, right.layer.layerId) ||
|
||||
compareCodePoints(left.node.node_id, right.node.node_id),
|
||||
);
|
||||
|
||||
/** Translate one already-authorized runtime location into artifact paths. */
|
||||
export const mappedRuntimePaths = (
|
||||
layer: ParsedStaticLayer,
|
||||
entity: RuntimeReconciliationEntity,
|
||||
): MappedRuntimePath[] => {
|
||||
const paths: MappedRuntimePath[] = [];
|
||||
if (entity.location.kind === "file" && layer.result.format === "directory") {
|
||||
const path = pathBelowRoot(layer.result.input_path, entity.location.value);
|
||||
if (path !== null) paths.push({ path, basis: "artifact-path" });
|
||||
}
|
||||
for (const mapping of layer.runtimeMappings) {
|
||||
const suffix =
|
||||
mapping.kind === "file-root" && entity.location.kind === "file"
|
||||
? pathBelowRoot(mapping.root, entity.location.value)
|
||||
: mapping.kind === "url-prefix" && entity.location.kind === "url"
|
||||
? pathBelowUrlPrefix(mapping.prefix, entity.location.value)
|
||||
: null;
|
||||
if (suffix === null) continue;
|
||||
const path = safeArtifactPath(mapping.artifact_prefix, suffix);
|
||||
if (path === null) continue;
|
||||
paths.push({
|
||||
path,
|
||||
basis:
|
||||
mapping.kind === "file-root"
|
||||
? "operator-file-mapping"
|
||||
: "operator-url-mapping",
|
||||
});
|
||||
}
|
||||
return uniqueMappedPaths(paths);
|
||||
};
|
||||
|
||||
/** Precompute the artifact prefixes exercised by a bounded runtime set. */
|
||||
export const createStaticRuntimeScope = (
|
||||
layer: ParsedStaticLayer,
|
||||
entities: readonly RuntimeReconciliationEntity[],
|
||||
): StaticRuntimeScope => ({
|
||||
artifactPrefixes: activeArtifactPrefixes(layer, entities),
|
||||
pathsByNodeId: indexStaticPaths(layer.graph),
|
||||
});
|
||||
|
||||
/** Whether one static node falls under a mapping exercised by this runtime set. */
|
||||
export const staticNodeWithinRuntimeScope = (
|
||||
node: ApplicationNode,
|
||||
scope: StaticRuntimeScope,
|
||||
): boolean =>
|
||||
(scope.pathsByNodeId.get(node.node_id) ?? []).some((path) =>
|
||||
scope.artifactPrefixes.some((prefix) => pathWithinPrefix(path, prefix)),
|
||||
);
|
||||
|
||||
const candidatesForLayer = (
|
||||
layer: ParsedStaticLayer,
|
||||
): StaticRuntimeCandidate[] => {
|
||||
const graph = layer.graph;
|
||||
const pathsByNodeId = indexStaticPaths(graph);
|
||||
return graph.nodes.flatMap((node) => {
|
||||
const category = candidateCategory(node);
|
||||
if (category === null) return [];
|
||||
return [
|
||||
{
|
||||
layer,
|
||||
node,
|
||||
category,
|
||||
paths: pathsByNodeId.get(node.node_id) ?? [],
|
||||
digests: candidateDigests(node),
|
||||
},
|
||||
];
|
||||
});
|
||||
};
|
||||
|
||||
const candidateCategory = (
|
||||
node: ApplicationNode,
|
||||
): StaticRuntimeCandidate["category"] | null => {
|
||||
if (node.kind === "electron-renderer") return "renderer";
|
||||
if (node.kind === "javascript-asset" || node.kind === "javascript-module")
|
||||
return "javascript";
|
||||
if (node.kind === "worker") return "worker";
|
||||
if (node.kind === "service-worker") return "service-worker";
|
||||
return null;
|
||||
};
|
||||
|
||||
const indexStaticPaths = (
|
||||
graph: JavaScriptApplicationGraph,
|
||||
): ReadonlyMap<string, readonly string[]> => {
|
||||
const nodes = new Map(
|
||||
graph.nodes.map((candidate) => [candidate.node_id, candidate]),
|
||||
);
|
||||
const relatedBySource = new Map<string, ApplicationNode[]>();
|
||||
for (const edge of graph.edges) {
|
||||
if (edge.relation !== "maps_to") continue;
|
||||
const target = nodes.get(edge.target_node_id);
|
||||
if (target === undefined) continue;
|
||||
const related = relatedBySource.get(edge.source_node_id);
|
||||
if (related === undefined)
|
||||
relatedBySource.set(edge.source_node_id, [target]);
|
||||
else related.push(target);
|
||||
}
|
||||
return new Map(
|
||||
graph.nodes.map((node) => [
|
||||
node.node_id,
|
||||
uniqueSorted([
|
||||
...nodePaths(node),
|
||||
...(relatedBySource.get(node.node_id) ?? []).flatMap(nodePaths),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
const nodePaths = (node: ApplicationNode): string[] => {
|
||||
const paths: string[] = [];
|
||||
if (node.identity.strategy === "canonical-path")
|
||||
paths.push(node.identity.path);
|
||||
for (const observation of node.observations) {
|
||||
for (const property of ["path", "resolved_path", "declared_path"])
|
||||
if (typeof observation.properties[property] === "string")
|
||||
paths.push(observation.properties[property]);
|
||||
if (
|
||||
observation.evidence.location.available &&
|
||||
observation.evidence.location.value.kind === "artifact-path"
|
||||
)
|
||||
paths.push(observation.evidence.location.value.path);
|
||||
}
|
||||
return paths
|
||||
.map(normalizeArtifactPath)
|
||||
.filter(
|
||||
(path): path is string => path !== null && path !== "artifact-root",
|
||||
);
|
||||
};
|
||||
|
||||
const candidateDigests = (
|
||||
node: ApplicationNode,
|
||||
): StaticRuntimeCandidate["digests"] => {
|
||||
const values: StaticRuntimeCandidate["digests"][number][] = [];
|
||||
if (
|
||||
node.kind === "javascript-asset" &&
|
||||
node.identity.strategy === "content-digest"
|
||||
)
|
||||
values.push({
|
||||
sha256: node.identity.sha256,
|
||||
basis: "content-sha256",
|
||||
});
|
||||
if (node.kind === "javascript-module")
|
||||
for (const observation of node.observations) {
|
||||
const digest = observation.properties.source_sha256;
|
||||
if (typeof digest === "string" && /^[a-f0-9]{64}$/u.test(digest))
|
||||
values.push({ sha256: digest, basis: "module-source-sha256" });
|
||||
}
|
||||
return [
|
||||
...new Map(
|
||||
values.map((value) => [`${value.basis}:${value.sha256}`, value]),
|
||||
).values(),
|
||||
];
|
||||
};
|
||||
|
||||
const pathBelowRoot = (root: string, value: string): string | null => {
|
||||
const remainder = relative(root, value);
|
||||
if (
|
||||
remainder === "" ||
|
||||
remainder.startsWith("..") ||
|
||||
isAbsolute(remainder) ||
|
||||
remainder.includes("\\")
|
||||
)
|
||||
return null;
|
||||
return normalizeArtifactPath(remainder);
|
||||
};
|
||||
|
||||
const pathBelowUrlPrefix = (prefix: string, value: string): string | null => {
|
||||
let base: URL;
|
||||
let candidate: URL;
|
||||
try {
|
||||
base = new URL(prefix);
|
||||
candidate = new URL(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
base.origin !== candidate.origin ||
|
||||
!candidate.pathname.startsWith(base.pathname)
|
||||
)
|
||||
return null;
|
||||
try {
|
||||
return normalizeArtifactPath(
|
||||
decodeURIComponent(candidate.pathname.slice(base.pathname.length)),
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const activeArtifactPrefixes = (
|
||||
layer: ParsedStaticLayer,
|
||||
entities: readonly RuntimeReconciliationEntity[],
|
||||
): string[] => {
|
||||
const prefixes = new Set<string>();
|
||||
if (
|
||||
layer.result.format === "directory" &&
|
||||
entities.some(
|
||||
({ location }) =>
|
||||
location.kind === "file" &&
|
||||
pathBelowRoot(layer.result.input_path, location.value) !== null,
|
||||
)
|
||||
)
|
||||
prefixes.add("");
|
||||
for (const mapping of layer.runtimeMappings)
|
||||
if (
|
||||
entities.some(({ location }) =>
|
||||
mapping.kind === "file-root" && location.kind === "file"
|
||||
? pathBelowRoot(mapping.root, location.value) !== null
|
||||
: mapping.kind === "url-prefix" && location.kind === "url"
|
||||
? pathBelowUrlPrefix(mapping.prefix, location.value) !== null
|
||||
: false,
|
||||
)
|
||||
)
|
||||
prefixes.add(mapping.artifact_prefix);
|
||||
return [...prefixes].sort(compareCodePoints);
|
||||
};
|
||||
|
||||
const pathWithinPrefix = (path: string, prefix: string): boolean =>
|
||||
prefix === "" || path === prefix || path.startsWith(`${prefix}/`);
|
||||
|
||||
const safeArtifactPath = (prefix: string, suffix: string): string | null =>
|
||||
normalizeArtifactPath(prefix === "" ? suffix : posix.join(prefix, suffix));
|
||||
|
||||
const normalizeArtifactPath = (value: string): string | null => {
|
||||
const normalized = posix
|
||||
.normalize(value.replaceAll("\\", "/"))
|
||||
.replace(/^\.\//u, "");
|
||||
return normalized !== "" &&
|
||||
normalized !== "." &&
|
||||
normalized !== ".." &&
|
||||
!normalized.startsWith("/") &&
|
||||
!normalized.startsWith("../")
|
||||
? normalized
|
||||
: null;
|
||||
};
|
||||
|
||||
const uniqueMappedPaths = (
|
||||
values: readonly MappedRuntimePath[],
|
||||
): MappedRuntimePath[] =>
|
||||
[
|
||||
...new Map(
|
||||
values.map((value) => [`${value.basis}:${value.path}`, value]),
|
||||
).values(),
|
||||
].sort(
|
||||
(left, right) =>
|
||||
compareCodePoints(left.path, right.path) ||
|
||||
compareCodePoints(left.basis, right.basis),
|
||||
);
|
||||
|
||||
const uniqueSorted = (values: readonly string[]): string[] =>
|
||||
[...new Set(values)].sort(compareCodePoints);
|
||||
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
|
||||
serverSdkVersion: "2.0.0-beta.4",
|
||||
clientSdkVersion: "2.0.0-beta.4",
|
||||
coreSdkVersion: "2.0.0-beta.4",
|
||||
skillVersion: "15",
|
||||
skillVersion: "16",
|
||||
} as const;
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { ElectronObservationPort } from "../application/ElectronObservationPort.js";
|
||||
import { analyzeJavaScriptApplication } from "../application/JavaScriptApplicationService.js";
|
||||
import { reconcileJavaScriptRuntimeEvidence } from "../application/JavaScriptRuntimeReconciliationService.js";
|
||||
import {
|
||||
inspectElectronPage,
|
||||
listElectronTargets,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
listElectronTargetsInputSchema,
|
||||
} from "../domain/electronObservation.js";
|
||||
import { analyzeJavaScriptApplicationInputSchema } from "../domain/javascriptApplicationAnalysis.js";
|
||||
import { reconcileJavaScriptRuntimeInputSchema } from "../domain/javascriptRuntimeReconciliationSchemas.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
@@ -32,7 +34,7 @@ export const registerElectronTools = (
|
||||
server: McpServer,
|
||||
options: ElectronToolRegistration,
|
||||
): void => {
|
||||
const [listContract, inspectContract, analyzeContract] =
|
||||
const [listContract, inspectContract, analyzeContract, reconcileContract] =
|
||||
ELECTRON_TOOL_CONTRACTS;
|
||||
server.registerTool(
|
||||
listContract.name,
|
||||
@@ -95,6 +97,28 @@ export const registerElectronTools = (
|
||||
return evidenceResult(options, analyzeContract, result.value);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
reconcileContract.name,
|
||||
toolRegistrationOptions(reconcileContract),
|
||||
async (input) => {
|
||||
const parsed = reconcileJavaScriptRuntimeInputSchema.parse(input);
|
||||
const result = await logToolExecution(
|
||||
options.logger,
|
||||
reconcileContract.name,
|
||||
() => Promise.resolve(reconcileJavaScriptRuntimeEvidence(parsed)),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, reconcileContract);
|
||||
for (const source of [
|
||||
...parsed.static_layers.map(({ analysis }) => analysis),
|
||||
...parsed.runtime_observations,
|
||||
]) {
|
||||
const recorded = options.recordEvidence?.(source);
|
||||
if (recorded !== undefined && !recorded.ok)
|
||||
return toCallToolResult(recorded, reconcileContract);
|
||||
}
|
||||
return evidenceResult(options, reconcileContract, result.value);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const evidenceResult = (
|
||||
|
||||
Reference in New Issue
Block a user