feat(electron): reconcile static artifacts with passive runtime
This commit is contained in:
@@ -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);
|
||||
Reference in New Issue
Block a user