feat(artifact): reconstruct JavaScript application structure
This commit is contained in:
@@ -0,0 +1,449 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { analyzeJavaScriptStaticSource } from "../domain/javascriptStaticAnalysis.js";
|
||||
import type {
|
||||
JavaScriptSourceRange,
|
||||
JavaScriptSourcePoint,
|
||||
JavaScriptStaticAnalysis,
|
||||
} from "../domain/javascriptStaticAnalysisTypes.js";
|
||||
import type {
|
||||
JavaScriptArtifactFile,
|
||||
JavaScriptArtifactFileSet,
|
||||
} from "./JavaScriptArtifactFiles.js";
|
||||
import type {
|
||||
AnalyzedJavaScriptArtifactFile,
|
||||
JavaScriptArtifactAnalysis,
|
||||
JavaScriptHtmlScriptObservation,
|
||||
JavaScriptPackageObservation,
|
||||
JavaScriptSourceMapObservation,
|
||||
JavaScriptSourceMapOriginal,
|
||||
} from "./JavaScriptArtifactAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactReconstructionInput } from "./JavaScriptArtifactReconstructionInput.js";
|
||||
|
||||
interface MutableArtifactAnalysis {
|
||||
readonly files: AnalyzedJavaScriptArtifactFile[];
|
||||
readonly packages: JavaScriptPackageObservation[];
|
||||
readonly htmlScripts: JavaScriptHtmlScriptObservation[];
|
||||
readonly sourceMaps: JavaScriptSourceMapObservation[];
|
||||
visitedNodes: number;
|
||||
findings: number;
|
||||
modules: number;
|
||||
parseFailures: number;
|
||||
truncatedScopes: number;
|
||||
sourceMapSources: number;
|
||||
}
|
||||
|
||||
interface ArtifactAnalysisContext {
|
||||
readonly state: MutableArtifactAnalysis;
|
||||
readonly input: JavaScriptArtifactReconstructionInput;
|
||||
readonly deadline: number;
|
||||
readonly now: () => number;
|
||||
}
|
||||
|
||||
/** Analyze selected text files under one shared AST, finding, module, and time budget. */
|
||||
export const analyzeJavaScriptArtifactFiles = (
|
||||
fileSet: JavaScriptArtifactFileSet,
|
||||
input: JavaScriptArtifactReconstructionInput,
|
||||
now: () => number,
|
||||
): JavaScriptArtifactAnalysis => {
|
||||
const state = emptyArtifactAnalysis();
|
||||
const context = {
|
||||
state,
|
||||
input,
|
||||
deadline: now() + input.limits.max_parse_milliseconds,
|
||||
now,
|
||||
};
|
||||
for (const file of fileSet.files) analyzeArtifactFile(file, context);
|
||||
return finalizeArtifactAnalysis(state, input);
|
||||
};
|
||||
|
||||
const finalizeArtifactAnalysis = (
|
||||
state: MutableArtifactAnalysis,
|
||||
input: JavaScriptArtifactReconstructionInput,
|
||||
): JavaScriptArtifactAnalysis => {
|
||||
const omittedHtmlFindings = Math.max(
|
||||
0,
|
||||
state.htmlScripts.length + state.findings - input.limits.max_findings,
|
||||
);
|
||||
const findings = Math.min(
|
||||
input.limits.max_findings,
|
||||
state.findings + state.htmlScripts.length,
|
||||
);
|
||||
const sourceMapTruncations = state.sourceMaps.filter(
|
||||
({ status }) => status === "truncated",
|
||||
).length;
|
||||
const truncatedScopes =
|
||||
state.truncatedScopes +
|
||||
sourceMapTruncations +
|
||||
(omittedHtmlFindings > 0 ? 1 : 0);
|
||||
return {
|
||||
files: state.files,
|
||||
packages: state.packages,
|
||||
html_scripts: state.htmlScripts.slice(0, input.limits.max_findings),
|
||||
source_maps: state.sourceMaps,
|
||||
visited_ast_nodes: state.visitedNodes,
|
||||
findings,
|
||||
modules: state.modules,
|
||||
parse_failures: state.parseFailures,
|
||||
truncated_scopes: truncatedScopes,
|
||||
limitations: [
|
||||
"JavaScript and HTML were parsed as inert text; bundle bootstrap code was never executed.",
|
||||
"Static paths and relationships may remain unresolved when expressions are dynamic or obfuscated.",
|
||||
...(input.source_map_read_approved
|
||||
? []
|
||||
: [
|
||||
"Source maps were inventoried but their contents were not read without separate approval.",
|
||||
]),
|
||||
...(truncatedScopes === 0
|
||||
? []
|
||||
: ["One or more static-analysis scopes reached an approved bound."]),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const analyzeArtifactFile = (
|
||||
file: JavaScriptArtifactFile,
|
||||
context: ArtifactAnalysisContext,
|
||||
): void => {
|
||||
const { state, input } = context;
|
||||
if (file.kind === "package-json") state.packages.push(parsePackage(file));
|
||||
if (file.kind === "html" && file.text.included)
|
||||
state.htmlScripts.push(
|
||||
...parseHtmlScripts(
|
||||
file.path,
|
||||
file.text.value,
|
||||
Math.max(0, input.limits.max_findings - state.findings),
|
||||
),
|
||||
);
|
||||
if (file.kind === "source-map") addSourceMap(file, context);
|
||||
if (file.kind !== "javascript" || !file.text.included) {
|
||||
state.files.push({ file, javascript: null });
|
||||
return;
|
||||
}
|
||||
const remainingNodes = input.limits.max_ast_nodes - state.visitedNodes;
|
||||
const remainingFindings = input.limits.max_findings - state.findings;
|
||||
const remainingModules = input.limits.max_modules - state.modules;
|
||||
if (
|
||||
remainingNodes <= 0 ||
|
||||
remainingFindings <= 0 ||
|
||||
remainingModules <= 0 ||
|
||||
context.now() > context.deadline
|
||||
) {
|
||||
state.files.push({ file, javascript: null });
|
||||
state.truncatedScopes += 1;
|
||||
return;
|
||||
}
|
||||
const analysis = analyzeJavaScriptStaticSource(file.text.value, {
|
||||
maxAstNodes: remainingNodes,
|
||||
maxFindings: remainingFindings,
|
||||
maxModules: remainingModules,
|
||||
deadline: context.deadline,
|
||||
now: context.now,
|
||||
});
|
||||
state.files.push({ file, javascript: analysis });
|
||||
state.visitedNodes += analysis.visited_ast_nodes;
|
||||
state.findings += findingCount(analysis);
|
||||
state.modules += analysis.bundler_registrations.reduce(
|
||||
(count, registration) => count + registration.modules.length,
|
||||
0,
|
||||
);
|
||||
if (analysis.parse_status === "failed") state.parseFailures += 1;
|
||||
if (analysis.parse_status === "truncated") state.truncatedScopes += 1;
|
||||
};
|
||||
|
||||
const addSourceMap = (
|
||||
file: JavaScriptArtifactFile,
|
||||
context: ArtifactAnalysisContext,
|
||||
): void => {
|
||||
const sourceMap = parseSourceMap(file, {
|
||||
deadline: context.deadline,
|
||||
now: context.now,
|
||||
maximumSources: Math.max(
|
||||
0,
|
||||
context.input.limits.max_source_map_sources -
|
||||
context.state.sourceMapSources,
|
||||
),
|
||||
});
|
||||
context.state.sourceMaps.push(sourceMap);
|
||||
context.state.sourceMapSources += sourceMap.sources.length;
|
||||
};
|
||||
|
||||
const emptyArtifactAnalysis = (): MutableArtifactAnalysis => ({
|
||||
files: [],
|
||||
packages: [],
|
||||
htmlScripts: [],
|
||||
sourceMaps: [],
|
||||
visitedNodes: 0,
|
||||
findings: 0,
|
||||
modules: 0,
|
||||
parseFailures: 0,
|
||||
truncatedScopes: 0,
|
||||
sourceMapSources: 0,
|
||||
});
|
||||
|
||||
const parsePackage = (
|
||||
file: JavaScriptArtifactFile,
|
||||
): JavaScriptPackageObservation => {
|
||||
if (!file.text.included)
|
||||
return unavailablePackage(file, "Package metadata text was unavailable.");
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(file.text.value);
|
||||
} catch {
|
||||
return invalidPackage(file, "package.json is not valid JSON.");
|
||||
}
|
||||
if (!isRecord(value))
|
||||
return invalidPackage(file, "package.json root is not an object.");
|
||||
return {
|
||||
path: file.path,
|
||||
sha256: file.sha256,
|
||||
status: "included",
|
||||
name: boundedString(value.name),
|
||||
version: boundedString(value.version),
|
||||
main: boundedString(value.main),
|
||||
renderer:
|
||||
boundedString(value.renderer) ??
|
||||
boundedString(value.browser) ??
|
||||
boundedString(value.module),
|
||||
limitation: null,
|
||||
};
|
||||
};
|
||||
|
||||
const invalidPackage = (
|
||||
file: JavaScriptArtifactFile,
|
||||
limitation: string,
|
||||
): JavaScriptPackageObservation => ({
|
||||
...unavailablePackage(file, limitation),
|
||||
status: "invalid",
|
||||
});
|
||||
|
||||
const unavailablePackage = (
|
||||
file: JavaScriptArtifactFile,
|
||||
limitation: string,
|
||||
): JavaScriptPackageObservation => ({
|
||||
path: file.path,
|
||||
sha256: file.sha256,
|
||||
status: "unavailable",
|
||||
name: null,
|
||||
version: null,
|
||||
main: null,
|
||||
renderer: null,
|
||||
limitation,
|
||||
});
|
||||
|
||||
const parseHtmlScripts = (
|
||||
path: string,
|
||||
text: string,
|
||||
maximum: number,
|
||||
): JavaScriptHtmlScriptObservation[] => {
|
||||
const scripts: JavaScriptHtmlScriptObservation[] = [];
|
||||
const pattern = /<script\b[^>]*\bsrc\s*=\s*(["'])([^"']+)\1[^>]*>/giu;
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
const script = match[2]?.slice(0, 4_096);
|
||||
if (script === undefined || scripts.length >= maximum) break;
|
||||
const start = match.index;
|
||||
scripts.push({
|
||||
html_path: path,
|
||||
script_path: script,
|
||||
location: rangeForOffsets(text, start, start + match[0].length),
|
||||
});
|
||||
}
|
||||
return scripts;
|
||||
};
|
||||
|
||||
const parseSourceMap = (
|
||||
file: JavaScriptArtifactFile,
|
||||
context: {
|
||||
readonly deadline: number;
|
||||
readonly now: () => number;
|
||||
readonly maximumSources: number;
|
||||
},
|
||||
): JavaScriptSourceMapObservation => {
|
||||
if (!file.text.included) return unavailableSourceMap(file);
|
||||
if (context.now() > context.deadline)
|
||||
return truncatedSourceMap(
|
||||
file,
|
||||
null,
|
||||
"Parse deadline reached before source-map decoding.",
|
||||
);
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(file.text.value);
|
||||
} catch {
|
||||
return invalidSourceMap(file, "Source map is not valid JSON.");
|
||||
}
|
||||
if (context.now() > context.deadline)
|
||||
return truncatedSourceMap(
|
||||
file,
|
||||
null,
|
||||
"Parse deadline elapsed during source-map decoding.",
|
||||
);
|
||||
const maps = flattenSourceMaps(value, 10_000);
|
||||
if (maps === undefined)
|
||||
return invalidSourceMap(file, "Source map is not a bounded version 3 map.");
|
||||
return collectSourceMapOriginals(file, maps, context);
|
||||
};
|
||||
|
||||
const collectSourceMapOriginals = (
|
||||
file: JavaScriptArtifactFile,
|
||||
maps: readonly Readonly<Record<string, unknown>>[],
|
||||
context: {
|
||||
readonly deadline: number;
|
||||
readonly now: () => number;
|
||||
readonly maximumSources: number;
|
||||
},
|
||||
): JavaScriptSourceMapObservation => {
|
||||
const sources: JavaScriptSourceMapOriginal[] = [];
|
||||
let total = 0;
|
||||
for (const map of maps) {
|
||||
const names = map.sources;
|
||||
if (!Array.isArray(names))
|
||||
return invalidSourceMap(file, "Source map has no sources array.");
|
||||
const contents = Array.isArray(map.sourcesContent)
|
||||
? map.sourcesContent
|
||||
: [];
|
||||
const root = typeof map.sourceRoot === "string" ? map.sourceRoot : "";
|
||||
for (const [index, raw] of names.entries()) {
|
||||
if (total % 1_024 === 0 && context.now() > context.deadline)
|
||||
return {
|
||||
path: file.path,
|
||||
sha256: file.sha256,
|
||||
status: "truncated",
|
||||
sources,
|
||||
omitted_sources: null,
|
||||
limitation: "Parse deadline elapsed during source-map traversal.",
|
||||
};
|
||||
if (typeof raw !== "string")
|
||||
return invalidSourceMap(
|
||||
file,
|
||||
"Source map contains a non-string source name.",
|
||||
);
|
||||
total += 1;
|
||||
if (sources.length >= context.maximumSources) continue;
|
||||
const content =
|
||||
typeof contents[index] === "string" ? contents[index] : null;
|
||||
sources.push({
|
||||
source: resolveSourceName(root, raw),
|
||||
content,
|
||||
content_sha256: content === null ? null : sha256(content),
|
||||
});
|
||||
}
|
||||
}
|
||||
const omitted = total - sources.length;
|
||||
return {
|
||||
path: file.path,
|
||||
sha256: file.sha256,
|
||||
status: omitted === 0 ? "included" : "truncated",
|
||||
sources,
|
||||
omitted_sources: omitted,
|
||||
limitation:
|
||||
omitted === 0
|
||||
? null
|
||||
: "Original-source inventory reached the approved source-map limit.",
|
||||
};
|
||||
};
|
||||
|
||||
const unavailableSourceMap = (
|
||||
file: JavaScriptArtifactFile,
|
||||
): JavaScriptSourceMapObservation => {
|
||||
if (file.text.included)
|
||||
throw new TypeError("Expected unavailable source-map text");
|
||||
const notApproved = file.text.reason === "not-approved";
|
||||
return {
|
||||
path: file.path,
|
||||
sha256: file.sha256,
|
||||
status: notApproved ? "not-approved" : "invalid",
|
||||
sources: [],
|
||||
omitted_sources: 0,
|
||||
limitation: notApproved
|
||||
? "Source-map content requires separate approval."
|
||||
: "Source-map text was unavailable within approved limits.",
|
||||
};
|
||||
};
|
||||
|
||||
const flattenSourceMaps = (
|
||||
root: unknown,
|
||||
maximum: number,
|
||||
): Readonly<Record<string, unknown>>[] | undefined => {
|
||||
if (!isRecord(root) || root.version !== 3) return undefined;
|
||||
const maps: Readonly<Record<string, unknown>>[] = [];
|
||||
const pending = [root];
|
||||
while (pending.length > 0) {
|
||||
const map = pending.pop();
|
||||
if (map === undefined || map.version !== 3) return undefined;
|
||||
if (Array.isArray(map.sections)) {
|
||||
if (pending.length + maps.length + map.sections.length > maximum)
|
||||
return undefined;
|
||||
for (const section of map.sections) {
|
||||
if (!isRecord(section) || !isRecord(section.map)) return undefined;
|
||||
pending.push(section.map);
|
||||
}
|
||||
} else maps.push(map);
|
||||
}
|
||||
return maps;
|
||||
};
|
||||
|
||||
const truncatedSourceMap = (
|
||||
file: JavaScriptArtifactFile,
|
||||
omitted: number | null,
|
||||
limitation: string,
|
||||
): JavaScriptSourceMapObservation => ({
|
||||
path: file.path,
|
||||
sha256: file.sha256,
|
||||
status: "truncated",
|
||||
sources: [],
|
||||
omitted_sources: omitted,
|
||||
limitation,
|
||||
});
|
||||
|
||||
const invalidSourceMap = (
|
||||
file: JavaScriptArtifactFile,
|
||||
limitation: string,
|
||||
): JavaScriptSourceMapObservation => ({
|
||||
path: file.path,
|
||||
sha256: file.sha256,
|
||||
status: "invalid",
|
||||
sources: [],
|
||||
omitted_sources: 0,
|
||||
limitation,
|
||||
});
|
||||
|
||||
const findingCount = (analysis: JavaScriptStaticAnalysis): number =>
|
||||
analysis.references.length +
|
||||
analysis.endpoints.length +
|
||||
analysis.storage.length +
|
||||
analysis.role_paths.length +
|
||||
analysis.source_map_urls.length +
|
||||
analysis.bundler_registrations.length;
|
||||
|
||||
const rangeForOffsets = (
|
||||
text: string,
|
||||
start: number,
|
||||
end: number,
|
||||
): JavaScriptSourceRange => ({
|
||||
start: pointForOffset(text, start),
|
||||
end: pointForOffset(text, end),
|
||||
});
|
||||
|
||||
const pointForOffset = (
|
||||
text: string,
|
||||
offset: number,
|
||||
): JavaScriptSourcePoint => {
|
||||
const lines = text.slice(0, offset).split("\n");
|
||||
return { line: lines.length, column: lines.at(-1)?.length ?? 0 };
|
||||
};
|
||||
|
||||
const resolveSourceName = (root: string, source: string): string =>
|
||||
`${root}${root !== "" && !root.endsWith("/") ? "/" : ""}${source}`.slice(
|
||||
0,
|
||||
4_096,
|
||||
);
|
||||
|
||||
const boundedString = (value: unknown): string | null =>
|
||||
typeof value === "string" && value.length > 0 ? value.slice(0, 4_096) : null;
|
||||
|
||||
const sha256 = (value: string): string =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
|
||||
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
@@ -0,0 +1,61 @@
|
||||
import type {
|
||||
JavaScriptSourceRange,
|
||||
JavaScriptStaticAnalysis,
|
||||
} from "../domain/javascriptStaticAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
|
||||
|
||||
/** Parsed package metadata used only for static entrypoint discovery. */
|
||||
export interface JavaScriptPackageObservation {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
readonly status: "included" | "invalid" | "unavailable";
|
||||
readonly name: string | null;
|
||||
readonly version: string | null;
|
||||
readonly main: string | null;
|
||||
readonly renderer: string | null;
|
||||
readonly limitation: string | null;
|
||||
}
|
||||
|
||||
/** One HTML script source observed without building or executing a DOM. */
|
||||
export interface JavaScriptHtmlScriptObservation {
|
||||
readonly html_path: string;
|
||||
readonly script_path: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One original source declared by an approved local source map. */
|
||||
export interface JavaScriptSourceMapOriginal {
|
||||
readonly source: string;
|
||||
readonly content: string | null;
|
||||
readonly content_sha256: string | null;
|
||||
}
|
||||
|
||||
/** Bounded local source-map parse result. */
|
||||
export interface JavaScriptSourceMapObservation {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
readonly status: "included" | "truncated" | "invalid" | "not-approved";
|
||||
readonly sources: readonly JavaScriptSourceMapOriginal[];
|
||||
readonly omitted_sources: number | null;
|
||||
readonly limitation: string | null;
|
||||
}
|
||||
|
||||
/** One relevant file plus optional AST-only JavaScript facts. */
|
||||
export interface AnalyzedJavaScriptArtifactFile {
|
||||
readonly file: JavaScriptArtifactFile;
|
||||
readonly javascript: JavaScriptStaticAnalysis | null;
|
||||
}
|
||||
|
||||
/** Complete bounded static-analysis projection before graph construction. */
|
||||
export interface JavaScriptArtifactAnalysis {
|
||||
readonly files: readonly AnalyzedJavaScriptArtifactFile[];
|
||||
readonly packages: readonly JavaScriptPackageObservation[];
|
||||
readonly html_scripts: readonly JavaScriptHtmlScriptObservation[];
|
||||
readonly source_maps: readonly JavaScriptSourceMapObservation[];
|
||||
readonly visited_ast_nodes: number;
|
||||
readonly findings: number;
|
||||
readonly modules: number;
|
||||
readonly parse_failures: number;
|
||||
readonly truncated_scopes: number;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { isAbsolute } from "node:path";
|
||||
import type { Readable } from "node:stream";
|
||||
|
||||
import { AsarArtifactReader } from "../artifacts/AsarArtifactReader.js";
|
||||
import {
|
||||
ArtifactPathRegistry,
|
||||
normalizeArtifactPath,
|
||||
} from "../artifacts/ArtifactPaths.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactEntry,
|
||||
type ArtifactReader,
|
||||
} from "../artifacts/ArtifactReader.js";
|
||||
import { streamChunkToBuffer } from "../artifacts/StreamBytes.js";
|
||||
import type { ArtifactInventorySnapshot } from "./ArtifactInventory.js";
|
||||
import type { JavaScriptArtifactReconstructionInput } from "./JavaScriptArtifactReconstructionInput.js";
|
||||
|
||||
/** Relevant file categories projected from the complete artifact inventory. */
|
||||
export type JavaScriptArtifactFileKind =
|
||||
| "package-json"
|
||||
| "javascript"
|
||||
| "html"
|
||||
| "source-map"
|
||||
| "native-addon";
|
||||
|
||||
/** One content-addressed local artifact file and its bounded text availability. */
|
||||
export interface JavaScriptArtifactFile {
|
||||
readonly path: string;
|
||||
readonly container_sha256: string;
|
||||
readonly sha256: string;
|
||||
readonly bytes: number;
|
||||
readonly inventory_artifact_id: string;
|
||||
readonly kind: JavaScriptArtifactFileKind;
|
||||
readonly unpacked: boolean;
|
||||
readonly text:
|
||||
| { readonly included: true; readonly value: string }
|
||||
| {
|
||||
readonly included: false;
|
||||
readonly reason:
|
||||
| "not-applicable"
|
||||
| "not-approved"
|
||||
| "file-limit"
|
||||
| "byte-limit"
|
||||
| "invalid-utf8";
|
||||
};
|
||||
}
|
||||
|
||||
/** One filesystem-backed ASAR nested beneath a directory input. */
|
||||
export interface JavaScriptArtifactContainer {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
readonly bytes: number;
|
||||
readonly inventory_artifact_id: string;
|
||||
}
|
||||
|
||||
/** Deterministic relevant-file projection plus explicit omissions. */
|
||||
export interface JavaScriptArtifactFileSet {
|
||||
readonly files: readonly JavaScriptArtifactFile[];
|
||||
readonly containers: readonly JavaScriptArtifactContainer[];
|
||||
readonly text_files_selected: number;
|
||||
readonly text_bytes_read: number;
|
||||
readonly omitted_text_files: number;
|
||||
readonly limit_omitted_text_files: number;
|
||||
readonly policy_filtered_text_files: number;
|
||||
readonly invalid_utf8_files: number;
|
||||
}
|
||||
|
||||
interface ExpectedFile {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
readonly bytes: number;
|
||||
readonly inventoryArtifactId: string;
|
||||
readonly kind: JavaScriptArtifactFileKind;
|
||||
}
|
||||
|
||||
interface Selection {
|
||||
readonly selected: boolean;
|
||||
readonly reason: "file-limit" | "byte-limit" | "not-approved" | null;
|
||||
}
|
||||
|
||||
interface ReadContext {
|
||||
readonly input: JavaScriptArtifactReconstructionInput;
|
||||
readonly expected: ReadonlyMap<string, ExpectedFile>;
|
||||
readonly expectedContainers: ReadonlyMap<string, JavaScriptArtifactContainer>;
|
||||
readonly selections: ReadonlyMap<string, Selection>;
|
||||
readonly registry: ArtifactPathRegistry;
|
||||
readonly files: JavaScriptArtifactFile[];
|
||||
readonly containers: JavaScriptArtifactContainer[];
|
||||
readonly signal: AbortSignal | undefined;
|
||||
textBytes: number;
|
||||
invalidUtf8: number;
|
||||
}
|
||||
|
||||
interface ReadTextInput {
|
||||
readonly reader: ArtifactReader;
|
||||
readonly entry: ArtifactEntry;
|
||||
readonly expected: ExpectedFile;
|
||||
readonly selection: Selection | undefined;
|
||||
}
|
||||
|
||||
/** Read only selected textual entries through an already-inventoried reader. */
|
||||
export const readJavaScriptArtifactFiles = async (
|
||||
reader: ArtifactReader,
|
||||
snapshot: ArtifactInventorySnapshot,
|
||||
input: JavaScriptArtifactReconstructionInput,
|
||||
signal?: AbortSignal,
|
||||
): Promise<JavaScriptArtifactFileSet> => {
|
||||
const inventory = expectedInventory(snapshot);
|
||||
const expected = inventory.files;
|
||||
const selections = selectTextFiles(expected, input);
|
||||
const context: ReadContext = {
|
||||
input,
|
||||
expected,
|
||||
expectedContainers: inventory.containers,
|
||||
selections,
|
||||
registry: new ArtifactPathRegistry(),
|
||||
files: [],
|
||||
containers: [],
|
||||
signal,
|
||||
textBytes: 0,
|
||||
invalidUtf8: 0,
|
||||
};
|
||||
await visitReader(reader, "", snapshot.manifest.root_sha256, context);
|
||||
const files = context.files.sort((left, right) =>
|
||||
compareCodePoints(left.path, right.path),
|
||||
);
|
||||
assertExpectedFilesWereVisited(expected, files);
|
||||
const selected = [...selections.values()].filter(
|
||||
({ selected: isSelected }) => isSelected,
|
||||
).length;
|
||||
return {
|
||||
files,
|
||||
containers: context.containers.sort((left, right) =>
|
||||
compareCodePoints(left.path, right.path),
|
||||
),
|
||||
text_files_selected: selected,
|
||||
text_bytes_read: context.textBytes,
|
||||
omitted_text_files: [...selections.values()].filter(
|
||||
({ selected: isSelected }) => !isSelected,
|
||||
).length,
|
||||
limit_omitted_text_files: [...selections.values()].filter(
|
||||
({ reason }) => reason === "file-limit" || reason === "byte-limit",
|
||||
).length,
|
||||
policy_filtered_text_files: [...selections.values()].filter(
|
||||
({ reason }) => reason === "not-approved",
|
||||
).length,
|
||||
invalid_utf8_files: context.invalidUtf8,
|
||||
};
|
||||
};
|
||||
|
||||
const visitReader = async (
|
||||
reader: ArtifactReader,
|
||||
prefix: string,
|
||||
containerSha256: string,
|
||||
context: ReadContext,
|
||||
): Promise<void> => {
|
||||
for await (const entry of reader.entries(context.signal)) {
|
||||
abortIfNeeded(context.signal);
|
||||
const path = normalizeArtifactPath(
|
||||
prefix === "" ? entry.path : `${prefix}/${entry.path}`,
|
||||
{
|
||||
maxDepth: context.input.limits.max_depth,
|
||||
maxPathBytes: context.input.limits.max_path_bytes,
|
||||
},
|
||||
);
|
||||
const nestedAsar = isFilesystemAsar(entry, path);
|
||||
context.registry.add(path, nestedAsar ? "directory" : entry.kind);
|
||||
if (nestedAsar) {
|
||||
await visitNestedAsar(entry, path, context);
|
||||
continue;
|
||||
}
|
||||
const expected = context.expected.get(path);
|
||||
if (expected === undefined) continue;
|
||||
const selection = context.selections.get(path);
|
||||
const text = await readTextIfSelected(context, {
|
||||
reader,
|
||||
entry,
|
||||
expected,
|
||||
selection,
|
||||
});
|
||||
context.files.push({
|
||||
path,
|
||||
container_sha256: containerSha256,
|
||||
sha256: expected.sha256,
|
||||
bytes: expected.bytes,
|
||||
inventory_artifact_id: expected.inventoryArtifactId,
|
||||
kind: expected.kind,
|
||||
unpacked: entry.unpacked,
|
||||
text,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const visitNestedAsar = async (
|
||||
entry: ArtifactEntry,
|
||||
path: string,
|
||||
context: ReadContext,
|
||||
): Promise<void> => {
|
||||
const inventory = expectedContainer(path, context);
|
||||
context.containers.push(inventory);
|
||||
const nested = new AsarArtifactReader(entry.adapterKey);
|
||||
try {
|
||||
await visitReader(nested, path, inventory.sha256, context);
|
||||
} finally {
|
||||
await nested.close();
|
||||
}
|
||||
};
|
||||
|
||||
const expectedContainer = (
|
||||
path: string,
|
||||
context: ReadContext,
|
||||
): JavaScriptArtifactContainer => {
|
||||
const container = context.expectedContainers.get(path);
|
||||
if (container === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Nested ASAR disappeared from inventory: ${path}`,
|
||||
);
|
||||
return container;
|
||||
};
|
||||
|
||||
const readTextIfSelected = async (
|
||||
context: ReadContext,
|
||||
input: ReadTextInput,
|
||||
): Promise<JavaScriptArtifactFile["text"]> => {
|
||||
if (input.expected.kind === "native-addon")
|
||||
return { included: false, reason: "not-applicable" };
|
||||
if (input.selection?.selected !== true)
|
||||
return {
|
||||
included: false,
|
||||
reason: input.selection?.reason ?? "file-limit",
|
||||
};
|
||||
const bytes = await readBounded(
|
||||
await input.reader.open(input.entry, context.signal),
|
||||
context.input.limits.max_text_file_bytes,
|
||||
context.signal,
|
||||
);
|
||||
const digest = createHash("sha256").update(bytes).digest("hex");
|
||||
if (digest !== input.expected.sha256 || bytes.length !== input.expected.bytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact entry changed after inventory: ${input.expected.path}`,
|
||||
);
|
||||
context.textBytes += bytes.length;
|
||||
try {
|
||||
return {
|
||||
included: true,
|
||||
value: new TextDecoder("utf-8", { fatal: true }).decode(bytes),
|
||||
};
|
||||
} catch {
|
||||
context.invalidUtf8 += 1;
|
||||
return { included: false, reason: "invalid-utf8" };
|
||||
}
|
||||
};
|
||||
|
||||
const expectedInventory = (
|
||||
snapshot: ArtifactInventorySnapshot,
|
||||
): {
|
||||
readonly files: ReadonlyMap<string, ExpectedFile>;
|
||||
readonly containers: ReadonlyMap<string, JavaScriptArtifactContainer>;
|
||||
} => {
|
||||
const nodes = new Map(snapshot.nodes.map((node) => [node.artifact_id, node]));
|
||||
const files = new Map<string, ExpectedFile>();
|
||||
const containers = new Map<string, JavaScriptArtifactContainer>();
|
||||
for (const occurrence of snapshot.occurrences) {
|
||||
if (occurrence.artifact_id === null || occurrence.logical_path === ".")
|
||||
continue;
|
||||
const node = nodes.get(occurrence.artifact_id);
|
||||
if (node === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact inventory node is missing: ${occurrence.logical_path}`,
|
||||
);
|
||||
if (occurrence.logical_path.toLowerCase().endsWith(".asar"))
|
||||
containers.set(occurrence.logical_path, {
|
||||
path: occurrence.logical_path,
|
||||
sha256: node.sha256,
|
||||
bytes: node.size,
|
||||
inventory_artifact_id: node.artifact_id,
|
||||
});
|
||||
const kind = relevantKind(occurrence.logical_path);
|
||||
if (kind === undefined) continue;
|
||||
files.set(occurrence.logical_path, {
|
||||
path: occurrence.logical_path,
|
||||
sha256: node.sha256,
|
||||
bytes: node.size,
|
||||
inventoryArtifactId: node.artifact_id,
|
||||
kind,
|
||||
});
|
||||
}
|
||||
return { files, containers };
|
||||
};
|
||||
|
||||
const selectTextFiles = (
|
||||
files: ReadonlyMap<string, ExpectedFile>,
|
||||
input: JavaScriptArtifactReconstructionInput,
|
||||
): ReadonlyMap<string, Selection> => {
|
||||
const selected = new Map<string, Selection>();
|
||||
let fileCount = 0;
|
||||
let bytes = 0;
|
||||
const ordered = [...files.values()].sort((left, right) => {
|
||||
const priority = filePriority(left.kind) - filePriority(right.kind);
|
||||
return priority === 0 ? compareCodePoints(left.path, right.path) : priority;
|
||||
});
|
||||
for (const file of ordered) {
|
||||
if (file.kind === "native-addon") continue;
|
||||
if (file.kind === "source-map" && !input.source_map_read_approved) {
|
||||
selected.set(file.path, { selected: false, reason: "not-approved" });
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
fileCount >= input.limits.max_text_files ||
|
||||
file.bytes > input.limits.max_text_file_bytes
|
||||
) {
|
||||
selected.set(file.path, { selected: false, reason: "file-limit" });
|
||||
continue;
|
||||
}
|
||||
if (bytes + file.bytes > input.limits.max_total_text_bytes) {
|
||||
selected.set(file.path, { selected: false, reason: "byte-limit" });
|
||||
continue;
|
||||
}
|
||||
selected.set(file.path, { selected: true, reason: null });
|
||||
fileCount += 1;
|
||||
bytes += file.bytes;
|
||||
}
|
||||
return selected;
|
||||
};
|
||||
|
||||
const readBounded = async (
|
||||
stream: Readable,
|
||||
maximum: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Buffer> => {
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
for await (const raw of stream) {
|
||||
abortIfNeeded(signal);
|
||||
const chunk = streamChunkToBuffer(raw);
|
||||
bytes += chunk.length;
|
||||
if (bytes > maximum) {
|
||||
stream.destroy();
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Selected JavaScript artifact text exceeded its byte limit",
|
||||
);
|
||||
}
|
||||
chunks.push(chunk);
|
||||
}
|
||||
return Buffer.concat(chunks, bytes);
|
||||
};
|
||||
|
||||
const assertExpectedFilesWereVisited = (
|
||||
expected: ReadonlyMap<string, ExpectedFile>,
|
||||
actual: readonly JavaScriptArtifactFile[],
|
||||
): void => {
|
||||
const observed = new Set(actual.map(({ path }) => path));
|
||||
for (const path of expected.keys())
|
||||
if (!observed.has(path))
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Relevant artifact entry disappeared after inventory: ${path}`,
|
||||
);
|
||||
};
|
||||
|
||||
const relevantKind = (path: string): JavaScriptArtifactFileKind | undefined => {
|
||||
const lower = path.toLowerCase();
|
||||
if (lower === "package.json" || lower.endsWith("/package.json"))
|
||||
return "package-json";
|
||||
if (/\.(?:cjs|mjs|js|jsx|ts|tsx)$/u.test(lower)) return "javascript";
|
||||
if (/\.html?$/u.test(lower)) return "html";
|
||||
if (lower.endsWith(".map")) return "source-map";
|
||||
if (lower.endsWith(".node")) return "native-addon";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const filePriority = (kind: JavaScriptArtifactFileKind): number => {
|
||||
switch (kind) {
|
||||
case "package-json":
|
||||
return 0;
|
||||
case "html":
|
||||
return 1;
|
||||
case "javascript":
|
||||
return 2;
|
||||
case "source-map":
|
||||
return 3;
|
||||
case "native-addon":
|
||||
return 4;
|
||||
}
|
||||
};
|
||||
|
||||
const isFilesystemAsar = (entry: ArtifactEntry, path: string): boolean =>
|
||||
entry.kind === "file" &&
|
||||
path.toLowerCase().endsWith(".asar") &&
|
||||
isAbsolute(entry.adapterKey);
|
||||
|
||||
const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"JavaScript artifact reconstruction cancelled",
|
||||
);
|
||||
};
|
||||
|
||||
const compareCodePoints = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
createJavaScriptApplicationEdge,
|
||||
createJavaScriptApplicationNode,
|
||||
type ApplicationEdge,
|
||||
type ApplicationNode,
|
||||
} from "../domain/javascriptApplicationGraph.js";
|
||||
|
||||
/** Deduplicate graph entities while retaining distinct evidence observations. */
|
||||
export class JavaScriptArtifactGraphAccumulator {
|
||||
readonly #nodes = new Map<string, ApplicationNode>();
|
||||
readonly #edges = new Map<string, ApplicationEdge>();
|
||||
#omittedObservations = 0;
|
||||
|
||||
/** Create or merge one canonical node. */
|
||||
addNode(input: unknown): ApplicationNode {
|
||||
const created = createJavaScriptApplicationNode(input);
|
||||
const existing = this.#nodes.get(created.node_id);
|
||||
if (existing === undefined) {
|
||||
this.#nodes.set(created.node_id, created);
|
||||
return created;
|
||||
}
|
||||
const bySemanticId = new Map(
|
||||
[...existing.observations, ...created.observations].map((observation) => [
|
||||
observation.observation_id,
|
||||
observationInput(observation),
|
||||
]),
|
||||
);
|
||||
const observations = [...bySemanticId.entries()]
|
||||
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
||||
.slice(0, 64)
|
||||
.map(([, observation]) => observation);
|
||||
this.#omittedObservations += Math.max(0, bySemanticId.size - 64);
|
||||
const merged = createJavaScriptApplicationNode({
|
||||
kind: existing.kind,
|
||||
identity: existing.identity,
|
||||
observations,
|
||||
});
|
||||
this.#nodes.set(merged.node_id, merged);
|
||||
return merged;
|
||||
}
|
||||
|
||||
/** Create or replace one canonical edge by semantic identifier. */
|
||||
addEdge(input: unknown): ApplicationEdge {
|
||||
const edge = createJavaScriptApplicationEdge(input);
|
||||
this.#edges.set(edge.edge_id, edge);
|
||||
return edge;
|
||||
}
|
||||
|
||||
/** Return all accumulated canonical nodes. */
|
||||
nodes(): readonly ApplicationNode[] {
|
||||
return [...this.#nodes.values()];
|
||||
}
|
||||
|
||||
/** Return all accumulated canonical edges. */
|
||||
edges(): readonly ApplicationEdge[] {
|
||||
return [...this.#edges.values()];
|
||||
}
|
||||
|
||||
/** Count distinct node observations omitted by the graph contract bound. */
|
||||
omittedObservations(): number {
|
||||
return this.#omittedObservations;
|
||||
}
|
||||
}
|
||||
|
||||
const observationInput = (
|
||||
observation: ApplicationNode["observations"][number],
|
||||
) => {
|
||||
const {
|
||||
observation_id: _observationId,
|
||||
identifier_strategy: _strategy,
|
||||
...input
|
||||
} = observation;
|
||||
return input;
|
||||
};
|
||||
@@ -0,0 +1,153 @@
|
||||
import type { ArtifactInventorySnapshot } from "./ArtifactInventory.js";
|
||||
import {
|
||||
createJavaScriptApplicationGraph,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "../domain/javascriptApplicationGraph.js";
|
||||
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactFileSet } from "./JavaScriptArtifactFiles.js";
|
||||
import { JavaScriptArtifactGraphAccumulator } from "./JavaScriptArtifactGraphAccumulator.js";
|
||||
import {
|
||||
javaScriptAnalysisLimits,
|
||||
type JavaScriptArtifactGraphContext,
|
||||
} from "./JavaScriptArtifactGraphContext.js";
|
||||
import {
|
||||
addJavaScriptHtmlRoles,
|
||||
addJavaScriptSourceMapOriginals,
|
||||
} from "./JavaScriptArtifactGraphDocuments.js";
|
||||
import { addJavaScriptStaticFindings } from "./JavaScriptArtifactGraphFindings.js";
|
||||
import {
|
||||
completeReconstructionCoverage,
|
||||
partialReconstructionCoverage,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
import {
|
||||
addJavaScriptArtifactContainers,
|
||||
addJavaScriptArtifactFiles,
|
||||
addJavaScriptBundlerNodes,
|
||||
addJavaScriptPackageNodes,
|
||||
createJavaScriptArtifactRootNode,
|
||||
} from "./JavaScriptArtifactGraphStructure.js";
|
||||
import type { JavaScriptArtifactReconstructionInput } from "./JavaScriptArtifactReconstructionInput.js";
|
||||
|
||||
/** Project bounded artifact and AST facts into JavaScript Application Graph v1. */
|
||||
export const buildJavaScriptArtifactGraph = (
|
||||
snapshot: ArtifactInventorySnapshot,
|
||||
fileSet: JavaScriptArtifactFileSet,
|
||||
analysis: JavaScriptArtifactAnalysis,
|
||||
input: JavaScriptArtifactReconstructionInput,
|
||||
): JavaScriptApplicationGraph => {
|
||||
const accumulator = new JavaScriptArtifactGraphAccumulator();
|
||||
const root = createJavaScriptArtifactRootNode(accumulator, snapshot);
|
||||
const context: JavaScriptArtifactGraphContext = {
|
||||
accumulator,
|
||||
snapshot,
|
||||
fileSet,
|
||||
analysis,
|
||||
input,
|
||||
root,
|
||||
filesByPath: new Map(fileSet.files.map((file) => [file.path, file])),
|
||||
fileNodes: new Map(),
|
||||
assetNodes: new Map(),
|
||||
moduleNodes: new Map(),
|
||||
containerNodes: new Map([[snapshot.manifest.root_sha256, root]]),
|
||||
};
|
||||
addJavaScriptArtifactContainers(context);
|
||||
addJavaScriptArtifactFiles(context);
|
||||
const packageRoots = addJavaScriptPackageNodes(context);
|
||||
addJavaScriptBundlerNodes(context);
|
||||
addJavaScriptStaticFindings(context);
|
||||
addJavaScriptHtmlRoles(context);
|
||||
addJavaScriptSourceMapOriginals(context);
|
||||
const coverage = graphCoverage(context);
|
||||
return createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids:
|
||||
packageRoots.length === 0
|
||||
? [root.node_id]
|
||||
: packageRoots.map(({ node_id: id }) => id),
|
||||
nodes: accumulator.nodes(),
|
||||
edges: accumulator.edges(),
|
||||
coverage,
|
||||
limitations: graphLimitations(context, coverage.status),
|
||||
});
|
||||
};
|
||||
|
||||
const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
|
||||
const exactLimitOmissions =
|
||||
context.fileSet.limit_omitted_text_files +
|
||||
context.accumulator.omittedObservations();
|
||||
const sourceMapPolicyGap = context.analysis.source_maps.some(
|
||||
({ status }) => status === "not-approved",
|
||||
);
|
||||
const malformedStructuredData =
|
||||
context.analysis.packages.some(({ status }) => status !== "included") ||
|
||||
context.analysis.source_maps.some(({ status }) => status === "invalid");
|
||||
const unknownGap =
|
||||
context.analysis.parse_failures > 0 ||
|
||||
context.fileSet.invalid_utf8_files > 0 ||
|
||||
sourceMapPolicyGap ||
|
||||
malformedStructuredData;
|
||||
if (context.analysis.truncated_scopes > 0)
|
||||
return partialReconstructionCoverage(
|
||||
reconstructionLimits(context.input),
|
||||
null,
|
||||
true,
|
||||
);
|
||||
if (exactLimitOmissions > 0)
|
||||
return partialReconstructionCoverage(
|
||||
reconstructionLimits(context.input),
|
||||
exactLimitOmissions,
|
||||
true,
|
||||
);
|
||||
if (unknownGap)
|
||||
return partialReconstructionCoverage(
|
||||
reconstructionLimits(context.input),
|
||||
null,
|
||||
false,
|
||||
);
|
||||
return completeReconstructionCoverage(reconstructionLimits(context.input));
|
||||
};
|
||||
|
||||
const graphLimitations = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
coverage: "complete" | "partial" | "unknown" | "unavailable",
|
||||
): string[] => [
|
||||
...context.analysis.limitations,
|
||||
"Webpack/Rspack factories were recovered from AST literals; REA did not invoke push handlers or bundle bootstrap code.",
|
||||
"Static imports, entrypoints, workers, endpoints, and storage relationships do not prove runtime execution.",
|
||||
...(context.accumulator.omittedObservations() === 0
|
||||
? []
|
||||
: [
|
||||
"Repeated content identities exceeded the per-node observation bound; containment edges still preserve inventoried paths.",
|
||||
]),
|
||||
...(coverage === "complete"
|
||||
? []
|
||||
: [
|
||||
"Graph coverage is incomplete; unavailable facts remain explicit and must not be read as absence.",
|
||||
]),
|
||||
];
|
||||
|
||||
const reconstructionLimits = (input: JavaScriptArtifactReconstructionInput) => [
|
||||
{
|
||||
name: "max-entries",
|
||||
value: input.limits.max_entries,
|
||||
unit: "items" as const,
|
||||
},
|
||||
{
|
||||
name: "max-total-artifact-bytes",
|
||||
value: input.limits.max_total_artifact_bytes,
|
||||
unit: "bytes" as const,
|
||||
},
|
||||
{
|
||||
name: "max-text-files",
|
||||
value: input.limits.max_text_files,
|
||||
unit: "items" as const,
|
||||
},
|
||||
{
|
||||
name: "max-total-text-bytes",
|
||||
value: input.limits.max_total_text_bytes,
|
||||
unit: "bytes" as const,
|
||||
},
|
||||
...javaScriptAnalysisLimits(input),
|
||||
{ name: "max-observations-per-node", value: 64, unit: "items" as const },
|
||||
];
|
||||
@@ -0,0 +1,359 @@
|
||||
import { posix } from "node:path";
|
||||
|
||||
import type { ArtifactInventorySnapshot } from "./ArtifactInventory.js";
|
||||
import type { ApplicationGraphEvidence } from "../domain/javascriptApplicationEvidenceSchemas.js";
|
||||
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
|
||||
import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
|
||||
import type {
|
||||
JavaScriptArtifactFile,
|
||||
JavaScriptArtifactFileSet,
|
||||
} from "./JavaScriptArtifactFiles.js";
|
||||
import { JavaScriptArtifactGraphAccumulator } from "./JavaScriptArtifactGraphAccumulator.js";
|
||||
import {
|
||||
artifactObservationEvidence,
|
||||
astObservationEvidence,
|
||||
completeReconstructionCoverage,
|
||||
partialReconstructionCoverage,
|
||||
staticInferenceEvidence,
|
||||
unavailableAstEvidence,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
import type { JavaScriptArtifactReconstructionInput } from "./JavaScriptArtifactReconstructionInput.js";
|
||||
|
||||
/** Mutable graph-construction state scoped to one reconstruction. */
|
||||
export interface JavaScriptArtifactGraphContext {
|
||||
readonly accumulator: JavaScriptArtifactGraphAccumulator;
|
||||
readonly snapshot: ArtifactInventorySnapshot;
|
||||
readonly fileSet: JavaScriptArtifactFileSet;
|
||||
readonly analysis: JavaScriptArtifactAnalysis;
|
||||
readonly input: JavaScriptArtifactReconstructionInput;
|
||||
readonly root: ApplicationNode;
|
||||
readonly filesByPath: ReadonlyMap<string, JavaScriptArtifactFile>;
|
||||
readonly fileNodes: Map<string, ApplicationNode>;
|
||||
readonly assetNodes: Map<string, ApplicationNode>;
|
||||
readonly moduleNodes: Map<string, ApplicationNode>;
|
||||
readonly containerNodes: Map<string, ApplicationNode>;
|
||||
}
|
||||
|
||||
/** Evidence coverage shape shared by reconstruction graph helpers. */
|
||||
export type JavaScriptArtifactGraphCoverage =
|
||||
ApplicationGraphEvidence["coverage"];
|
||||
|
||||
/** Direct artifact-containment edge values. */
|
||||
export interface ContainsEdgeInput {
|
||||
readonly source: ApplicationNode;
|
||||
readonly target: ApplicationNode;
|
||||
readonly file: JavaScriptArtifactFile;
|
||||
readonly operation: string;
|
||||
}
|
||||
|
||||
/** Exact AST containment edge values. */
|
||||
export interface AstEdgeInput {
|
||||
readonly source: ApplicationNode;
|
||||
readonly target: ApplicationNode;
|
||||
readonly file: JavaScriptArtifactFile;
|
||||
readonly range: JavaScriptSourceRange;
|
||||
readonly coverage: JavaScriptArtifactGraphCoverage;
|
||||
readonly properties: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
/** Inferred static relationship edge values. */
|
||||
export interface InferenceEdgeInput extends AstEdgeInput {
|
||||
readonly relation:
|
||||
| "imports"
|
||||
| "loads"
|
||||
| "maps_to"
|
||||
| "exposes"
|
||||
| "calls"
|
||||
| "persists_to";
|
||||
}
|
||||
|
||||
/** Electron role identity and static discovery evidence. */
|
||||
export interface RoleNodeInput {
|
||||
readonly kind: "electron-main" | "electron-preload" | "electron-renderer";
|
||||
readonly anchor: JavaScriptArtifactFile;
|
||||
readonly declaredPath: string;
|
||||
readonly resolvedPath: string | null;
|
||||
readonly mechanism: string;
|
||||
readonly range?: JavaScriptSourceRange;
|
||||
readonly coverage?: JavaScriptArtifactGraphCoverage;
|
||||
}
|
||||
|
||||
/** Resolution from an inferred Electron role to an artifact asset. */
|
||||
export interface RoleAssetLinkInput {
|
||||
readonly role: ApplicationNode;
|
||||
readonly anchor: JavaScriptArtifactFile;
|
||||
readonly path: string | null;
|
||||
readonly range?: JavaScriptSourceRange;
|
||||
readonly coverage?: JavaScriptArtifactGraphCoverage;
|
||||
}
|
||||
|
||||
/** Explicit package, JavaScript, or source-map parse gap. */
|
||||
export interface UnavailableParseInput {
|
||||
readonly file: JavaScriptArtifactFile;
|
||||
readonly asset: ApplicationNode;
|
||||
readonly operation: string;
|
||||
readonly limitation: string;
|
||||
}
|
||||
|
||||
/** Add a direct artifact-containment edge. */
|
||||
export const addArtifactContainsEdge = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: ContainsEdgeInput,
|
||||
): void => {
|
||||
context.accumulator.addEdge({
|
||||
source_node_id: input.source.node_id,
|
||||
target_node_id: input.target.node_id,
|
||||
relation: "contains",
|
||||
properties: { path: input.file.path },
|
||||
evidence: artifactObservationEvidence({
|
||||
sha256:
|
||||
input.operation === "inventory-entry"
|
||||
? input.file.container_sha256
|
||||
: input.file.sha256,
|
||||
path: input.file.path,
|
||||
operation: input.operation,
|
||||
coverage: completeReconstructionCoverage(),
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
/** Add an exact AST containment edge. */
|
||||
export const addAstContainsEdge = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: AstEdgeInput,
|
||||
): void => {
|
||||
context.accumulator.addEdge({
|
||||
source_node_id: input.source.node_id,
|
||||
target_node_id: input.target.node_id,
|
||||
relation: "contains",
|
||||
properties: input.properties,
|
||||
evidence: astObservationEvidence({
|
||||
sha256: input.file.sha256,
|
||||
path: input.file.path,
|
||||
range: input.range,
|
||||
operation: "map-bundler-structure",
|
||||
coverage: input.coverage,
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
/** Add an explicitly inferred static relationship edge. */
|
||||
export const addStaticInferenceEdge = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: InferenceEdgeInput,
|
||||
): void => {
|
||||
context.accumulator.addEdge({
|
||||
source_node_id: input.source.node_id,
|
||||
target_node_id: input.target.node_id,
|
||||
relation: input.relation,
|
||||
properties: input.properties,
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: input.file.sha256,
|
||||
path: input.file.path,
|
||||
range: input.range,
|
||||
operation: "map-static-relationship",
|
||||
coverage: input.coverage,
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
/** Preserve a static parse or approval gap as an explicit unknown scope. */
|
||||
export const addUnavailableStaticParseScope = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: UnavailableParseInput,
|
||||
): void => {
|
||||
const node = context.accumulator.addNode({
|
||||
kind: "unknown",
|
||||
identity: artifactLocalIdentity(
|
||||
input.file.sha256,
|
||||
"static-parse-scope",
|
||||
`${input.operation}:${input.file.path}`,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
label: `${input.file.path} parse scope`,
|
||||
properties: {
|
||||
path: input.file.path,
|
||||
operation: input.operation,
|
||||
limitation: input.limitation,
|
||||
},
|
||||
evidence: unavailableAstEvidence({
|
||||
sha256: input.file.sha256,
|
||||
path: input.file.path,
|
||||
operation: input.operation,
|
||||
coverage: partialReconstructionCoverage([], null, false),
|
||||
limitation: input.limitation,
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
context.accumulator.addEdge({
|
||||
source_node_id: input.asset.node_id,
|
||||
target_node_id: node.node_id,
|
||||
relation: "contains",
|
||||
properties: { scope: "unavailable-static-analysis" },
|
||||
evidence: artifactObservationEvidence({
|
||||
sha256: input.file.sha256,
|
||||
path: input.file.path,
|
||||
operation: "associate-unavailable-parse-scope",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
/** Coverage for one bounded JavaScript AST analysis. */
|
||||
export const javascriptAnalysisCoverage = (
|
||||
analysis: NonNullable<
|
||||
JavaScriptArtifactAnalysis["files"][number]["javascript"]
|
||||
>,
|
||||
input: JavaScriptArtifactReconstructionInput,
|
||||
): JavaScriptArtifactGraphCoverage =>
|
||||
analysis.parse_status === "complete"
|
||||
? completeReconstructionCoverage(javaScriptAnalysisLimits(input))
|
||||
: {
|
||||
status: "partial",
|
||||
truncated: analysis.parse_status === "truncated",
|
||||
omitted_count: null,
|
||||
limits: javaScriptAnalysisLimits(input),
|
||||
};
|
||||
|
||||
/** Stable identity for a fact scoped to one exact artifact. */
|
||||
export const artifactLocalIdentity = (
|
||||
sha256: string,
|
||||
namespace: string,
|
||||
key: string,
|
||||
) => ({
|
||||
strategy: "artifact-local-key" as const,
|
||||
stability: "artifact-version" as const,
|
||||
artifact_sha256: sha256,
|
||||
namespace: namespace.slice(0, 512),
|
||||
key: key.slice(0, 4_096),
|
||||
});
|
||||
|
||||
/** Create or merge an Electron role inferred from static syntax or metadata. */
|
||||
export const createElectronRoleNode = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: RoleNodeInput,
|
||||
): ApplicationNode =>
|
||||
context.accumulator.addNode({
|
||||
kind: input.kind,
|
||||
identity: artifactLocalIdentity(
|
||||
input.anchor.sha256,
|
||||
"electron-role",
|
||||
`${input.kind}:${input.resolvedPath ?? input.declaredPath}`,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
label: input.resolvedPath ?? input.declaredPath,
|
||||
properties: {
|
||||
declared_path: input.declaredPath,
|
||||
resolved_path: input.resolvedPath,
|
||||
mechanism: input.mechanism,
|
||||
},
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: input.anchor.sha256,
|
||||
path: input.anchor.path,
|
||||
operation: "discover-electron-entrypoint",
|
||||
coverage: input.coverage ?? completeReconstructionCoverage(),
|
||||
...(input.range === undefined ? {} : { range: input.range }),
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
/** Resolve an Electron role to an inventoried asset when available. */
|
||||
export const linkElectronRoleToAsset = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: RoleAssetLinkInput,
|
||||
): void => {
|
||||
if (input.path === null) return;
|
||||
const asset =
|
||||
context.assetNodes.get(input.path) ?? context.fileNodes.get(input.path);
|
||||
if (asset === undefined) return;
|
||||
context.accumulator.addEdge({
|
||||
source_node_id: input.role.node_id,
|
||||
target_node_id: asset.node_id,
|
||||
relation: "maps_to",
|
||||
properties: { resolved_path: input.path },
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: input.anchor.sha256,
|
||||
path: input.anchor.path,
|
||||
operation: "resolve-electron-entrypoint",
|
||||
coverage: input.coverage ?? completeReconstructionCoverage(),
|
||||
...(input.range === undefined ? {} : { range: input.range }),
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
/** Deterministic key for one recovered module inside a bundle asset. */
|
||||
export const moduleLookupKey = (path: string, moduleKey: string): string =>
|
||||
`${path}\0${moduleKey}`;
|
||||
|
||||
/** Resolve a relative static specifier without escaping the artifact root. */
|
||||
export const resolveArtifactPath = (
|
||||
specifier: string,
|
||||
sourcePath: string,
|
||||
files: ReadonlyMap<string, JavaScriptArtifactFile>,
|
||||
): string | null => {
|
||||
const clean = specifier.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
if (clean === "" || /^[A-Za-z][A-Za-z+.-]*:/u.test(clean)) return null;
|
||||
if (!clean.startsWith(".") && !clean.startsWith("/")) return null;
|
||||
const candidate = posix.normalize(
|
||||
clean.startsWith("/")
|
||||
? clean.slice(1)
|
||||
: posix.join(posix.dirname(sourcePath), clean),
|
||||
);
|
||||
if (candidate === ".." || candidate.startsWith("../")) return null;
|
||||
for (const path of pathCandidates(candidate))
|
||||
if (files.has(path)) return path;
|
||||
return null;
|
||||
};
|
||||
|
||||
/** Locate the recovered module that owns a static finding. */
|
||||
export const sourceNodeFor = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
path: string,
|
||||
moduleKey: string | null,
|
||||
): ApplicationNode | undefined =>
|
||||
moduleKey === null
|
||||
? undefined
|
||||
: context.moduleNodes.get(moduleLookupKey(path, moduleKey));
|
||||
|
||||
const pathCandidates = (path: string): readonly string[] => [
|
||||
path,
|
||||
`${path}.js`,
|
||||
`${path}.mjs`,
|
||||
`${path}.cjs`,
|
||||
`${path}.ts`,
|
||||
`${path}.tsx`,
|
||||
`${path}.node`,
|
||||
posix.join(path, "index.js"),
|
||||
posix.join(path, "index.ts"),
|
||||
];
|
||||
|
||||
/** Named AST budgets committed to graph evidence coverage. */
|
||||
export const javaScriptAnalysisLimits = (
|
||||
input: JavaScriptArtifactReconstructionInput,
|
||||
) => [
|
||||
{
|
||||
name: "max-ast-nodes",
|
||||
value: input.limits.max_ast_nodes,
|
||||
unit: "items" as const,
|
||||
},
|
||||
{
|
||||
name: "max-findings",
|
||||
value: input.limits.max_findings,
|
||||
unit: "items" as const,
|
||||
},
|
||||
{
|
||||
name: "max-modules",
|
||||
value: input.limits.max_modules,
|
||||
unit: "items" as const,
|
||||
},
|
||||
{
|
||||
name: "max-parse-milliseconds",
|
||||
value: input.limits.max_parse_milliseconds,
|
||||
unit: "milliseconds" as const,
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,134 @@
|
||||
import {
|
||||
addArtifactContainsEdge,
|
||||
addStaticInferenceEdge,
|
||||
createElectronRoleNode,
|
||||
resolveArtifactPath,
|
||||
type JavaScriptArtifactGraphContext,
|
||||
} from "./JavaScriptArtifactGraphContext.js";
|
||||
import {
|
||||
artifactObservationEvidence,
|
||||
completeReconstructionCoverage,
|
||||
partialReconstructionCoverage,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
|
||||
/** Project HTML renderer entrypoints and their local script assets. */
|
||||
export const addJavaScriptHtmlRoles = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
): void => {
|
||||
const byHtml = new Map<string, typeof context.analysis.html_scripts>();
|
||||
for (const script of context.analysis.html_scripts) {
|
||||
const existing = byHtml.get(script.html_path);
|
||||
byHtml.set(
|
||||
script.html_path,
|
||||
existing === undefined ? [script] : [...existing, script],
|
||||
);
|
||||
}
|
||||
for (const [htmlPath, scripts] of byHtml) {
|
||||
const html = context.filesByPath.get(htmlPath);
|
||||
if (html === undefined) continue;
|
||||
const role = createElectronRoleNode(context, {
|
||||
kind: "electron-renderer",
|
||||
anchor: html,
|
||||
declaredPath: html.path,
|
||||
resolvedPath: html.path,
|
||||
mechanism: "html-script-entrypoint",
|
||||
});
|
||||
addArtifactContainsEdge(context, {
|
||||
source: context.root,
|
||||
target: role,
|
||||
file: html,
|
||||
operation: "discover-html-renderer",
|
||||
});
|
||||
for (const script of scripts) {
|
||||
const resolvedPath = resolveArtifactPath(
|
||||
script.script_path,
|
||||
html.path,
|
||||
context.filesByPath,
|
||||
);
|
||||
if (resolvedPath === null) continue;
|
||||
const resolved = context.fileNodes.get(resolvedPath);
|
||||
if (resolved === undefined) continue;
|
||||
addStaticInferenceEdge(context, {
|
||||
source: role,
|
||||
target: resolved,
|
||||
file: html,
|
||||
range: script.location,
|
||||
coverage: completeReconstructionCoverage(),
|
||||
relation: "loads",
|
||||
properties: {
|
||||
script_path: script.script_path,
|
||||
resolved_path: resolvedPath,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** Project original source names and optional content digests from approved maps. */
|
||||
export const addJavaScriptSourceMapOriginals = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
): void => {
|
||||
for (const sourceMap of context.analysis.source_maps) {
|
||||
const mapFile = context.filesByPath.get(sourceMap.path);
|
||||
const mapNode = context.fileNodes.get(sourceMap.path);
|
||||
if (mapFile === undefined || mapNode === undefined) continue;
|
||||
const coverage =
|
||||
sourceMap.status === "truncated"
|
||||
? partialReconstructionCoverage(
|
||||
[
|
||||
{
|
||||
name: "max-source-map-sources",
|
||||
value: context.input.limits.max_source_map_sources,
|
||||
unit: "items",
|
||||
},
|
||||
],
|
||||
sourceMap.omitted_sources,
|
||||
true,
|
||||
)
|
||||
: completeReconstructionCoverage();
|
||||
for (const original of sourceMap.sources) {
|
||||
const node = context.accumulator.addNode({
|
||||
kind: "source-module",
|
||||
identity: {
|
||||
strategy: "source-map-original",
|
||||
stability: "source-map-exact",
|
||||
source_map_sha256: mapFile.sha256,
|
||||
original_source: original.source,
|
||||
source_sha256: original.content_sha256,
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: original.source,
|
||||
properties: {
|
||||
source: original.source,
|
||||
content_available: original.content !== null,
|
||||
source_sha256: original.content_sha256,
|
||||
},
|
||||
evidence: artifactObservationEvidence({
|
||||
sha256: mapFile.sha256,
|
||||
path: mapFile.path,
|
||||
operation: "parse-local-source-map",
|
||||
coverage,
|
||||
limitations:
|
||||
sourceMap.limitation === null ? [] : [sourceMap.limitation],
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
context.accumulator.addEdge({
|
||||
source_node_id: mapNode.node_id,
|
||||
target_node_id: node.node_id,
|
||||
relation: "contains",
|
||||
properties: { original_source: original.source },
|
||||
evidence: artifactObservationEvidence({
|
||||
sha256: mapFile.sha256,
|
||||
path: mapFile.path,
|
||||
operation: "parse-local-source-map",
|
||||
coverage,
|
||||
limitations:
|
||||
sourceMap.limitation === null ? [] : [sourceMap.limitation],
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,130 @@
|
||||
import type { ApplicationGraphEvidence } from "../domain/javascriptApplicationEvidenceSchemas.js";
|
||||
import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js";
|
||||
|
||||
const EXTRACTOR = {
|
||||
name: "rea-javascript-artifact-reconstruction",
|
||||
version: "1",
|
||||
executable_sha256: null,
|
||||
} as const;
|
||||
|
||||
/** Coverage shape accepted by reconstruction evidence helpers. */
|
||||
export type ReconstructionEvidenceCoverage =
|
||||
ApplicationGraphEvidence["coverage"];
|
||||
|
||||
/** Shared exact artifact location and bounded coverage for static evidence. */
|
||||
export interface EvidenceInput {
|
||||
readonly sha256: string;
|
||||
readonly path: string;
|
||||
readonly operation: string;
|
||||
readonly coverage: ReconstructionEvidenceCoverage;
|
||||
readonly limitations?: readonly string[];
|
||||
readonly range?: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** Exact artifact-byte evidence for one safely inventoried local file. */
|
||||
export const artifactObservationEvidence = (
|
||||
input: EvidenceInput,
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority: "artifact-bytes",
|
||||
state: "observed",
|
||||
confidence: "exact",
|
||||
artifact: artifactReference(input.sha256),
|
||||
location: {
|
||||
available: true,
|
||||
value: { kind: "artifact-path", path: input.path },
|
||||
},
|
||||
extractor: { ...EXTRACTOR, operation: input.operation },
|
||||
coverage: input.coverage,
|
||||
limitations: [...(input.limitations ?? [])],
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
/** Exact AST syntax evidence with an actionable source range. */
|
||||
export const astObservationEvidence = (
|
||||
input: EvidenceInput & { readonly range: JavaScriptSourceRange },
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority: "ast-static-analysis",
|
||||
state: "observed",
|
||||
confidence: "exact",
|
||||
artifact: artifactReference(input.sha256),
|
||||
location: {
|
||||
available: true,
|
||||
value: { kind: "source-range", source: input.path, ...input.range },
|
||||
},
|
||||
extractor: { ...EXTRACTOR, operation: input.operation },
|
||||
coverage: input.coverage,
|
||||
limitations: [...(input.limitations ?? [])],
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
/** Explicit static relationship inference; never promoted to observation. */
|
||||
export const staticInferenceEvidence = (
|
||||
input: EvidenceInput & {
|
||||
readonly confidence?: "high" | "medium" | "low";
|
||||
},
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority: "static-relationship-inference",
|
||||
state: "inferred",
|
||||
confidence: input.confidence ?? "high",
|
||||
artifact: artifactReference(input.sha256),
|
||||
location:
|
||||
input.range === undefined
|
||||
? { available: true, value: { kind: "artifact-path", path: input.path } }
|
||||
: {
|
||||
available: true,
|
||||
value: { kind: "source-range", source: input.path, ...input.range },
|
||||
},
|
||||
extractor: { ...EXTRACTOR, operation: input.operation },
|
||||
coverage: input.coverage,
|
||||
limitations: [
|
||||
"Static syntax does not prove that this relationship executes at runtime.",
|
||||
...(input.limitations ?? []),
|
||||
],
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
/** Unavailable AST fact that preserves a parse, approval, or limit gap. */
|
||||
export const unavailableAstEvidence = (
|
||||
input: EvidenceInput & { readonly limitation: string },
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority: "ast-static-analysis",
|
||||
state: "unavailable",
|
||||
confidence: "unknown",
|
||||
artifact: artifactReference(input.sha256),
|
||||
location: {
|
||||
available: true,
|
||||
value: { kind: "artifact-path", path: input.path },
|
||||
},
|
||||
extractor: { ...EXTRACTOR, operation: input.operation },
|
||||
coverage: input.coverage,
|
||||
limitations: [input.limitation, ...(input.limitations ?? [])],
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
/** Complete local projection coverage under named hard limits. */
|
||||
export const completeReconstructionCoverage = (
|
||||
limits: ReconstructionEvidenceCoverage["limits"] = [],
|
||||
): ReconstructionEvidenceCoverage => ({
|
||||
status: "complete",
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [...limits],
|
||||
});
|
||||
|
||||
/** Partial reconstruction coverage with either exact truncation or a policy gap. */
|
||||
export const partialReconstructionCoverage = (
|
||||
limits: ReconstructionEvidenceCoverage["limits"],
|
||||
omitted: number | null,
|
||||
truncated: boolean,
|
||||
): ReconstructionEvidenceCoverage => ({
|
||||
status: "partial",
|
||||
truncated,
|
||||
omitted_count: omitted,
|
||||
limits: [...limits],
|
||||
});
|
||||
|
||||
const artifactReference = (sha256: string) => ({
|
||||
available: true as const,
|
||||
artifact_id: `art_${sha256}`,
|
||||
sha256,
|
||||
});
|
||||
@@ -0,0 +1,380 @@
|
||||
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
|
||||
import type { JavaScriptStaticAnalysis } from "../domain/javascriptStaticAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
|
||||
import {
|
||||
addStaticInferenceEdge,
|
||||
artifactLocalIdentity,
|
||||
createElectronRoleNode,
|
||||
javascriptAnalysisCoverage,
|
||||
linkElectronRoleToAsset,
|
||||
moduleLookupKey,
|
||||
resolveArtifactPath,
|
||||
sourceNodeFor,
|
||||
type JavaScriptArtifactGraphContext,
|
||||
type JavaScriptArtifactGraphCoverage,
|
||||
} from "./JavaScriptArtifactGraphContext.js";
|
||||
import {
|
||||
astObservationEvidence,
|
||||
staticInferenceEvidence,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
|
||||
type StaticReference = JavaScriptStaticAnalysis["references"][number];
|
||||
type StaticEndpoint = JavaScriptStaticAnalysis["endpoints"][number];
|
||||
type StaticStorage = JavaScriptStaticAnalysis["storage"][number];
|
||||
type StaticRolePath = JavaScriptStaticAnalysis["role_paths"][number];
|
||||
type StaticSourceMap = JavaScriptStaticAnalysis["source_map_urls"][number];
|
||||
|
||||
interface FindingInput<Value> {
|
||||
readonly file: JavaScriptArtifactFile;
|
||||
readonly asset: ApplicationNode;
|
||||
readonly value: Value;
|
||||
readonly coverage: JavaScriptArtifactGraphCoverage;
|
||||
}
|
||||
|
||||
interface ResolvedReference {
|
||||
readonly path: string;
|
||||
readonly file: JavaScriptArtifactFile;
|
||||
readonly node: ApplicationNode;
|
||||
}
|
||||
|
||||
/** Project imports, workers, roles, endpoints, storage, and source-map links. */
|
||||
export const addJavaScriptStaticFindings = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
): void => {
|
||||
for (const analyzed of context.analysis.files) {
|
||||
const { file, javascript } = analyzed;
|
||||
const asset = context.assetNodes.get(file.path);
|
||||
if (javascript === null || asset === undefined) continue;
|
||||
const coverage = javascriptAnalysisCoverage(javascript, context.input);
|
||||
for (const value of javascript.references)
|
||||
addReference(context, { file, asset, value, coverage });
|
||||
for (const value of javascript.endpoints)
|
||||
addEndpoint(context, { file, asset, value, coverage });
|
||||
for (const value of javascript.storage)
|
||||
addStorage(context, { file, asset, value, coverage });
|
||||
for (const value of javascript.role_paths)
|
||||
addDiscoveredRole(context, { file, asset, value, coverage });
|
||||
for (const value of javascript.source_map_urls)
|
||||
addSourceMapEdge(context, { file, asset, value, coverage });
|
||||
}
|
||||
};
|
||||
|
||||
const addReference = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: FindingInput<StaticReference>,
|
||||
): void => {
|
||||
const source =
|
||||
sourceNodeFor(context, input.file.path, input.value.module_key) ??
|
||||
input.asset;
|
||||
const resolved =
|
||||
input.value.specifier === null
|
||||
? null
|
||||
: resolveReference(context, input.file.path, input.value.specifier);
|
||||
if (input.value.kind === "worker" || input.value.kind === "service-worker") {
|
||||
const worker = context.accumulator.addNode({
|
||||
kind: input.value.kind === "worker" ? "worker" : "service-worker",
|
||||
identity: artifactLocalIdentity(
|
||||
input.file.sha256,
|
||||
input.value.kind,
|
||||
input.value.specifier ?? input.value.expression ?? "[dynamic]",
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
label: input.value.specifier,
|
||||
properties: {
|
||||
declared_specifier: input.value.specifier,
|
||||
expression: input.value.expression,
|
||||
resolved_path: resolved?.path ?? null,
|
||||
},
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: input.file.sha256,
|
||||
path: input.file.path,
|
||||
range: input.value.location,
|
||||
operation: "discover-worker",
|
||||
coverage: input.coverage,
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
addStaticInferenceEdge(context, {
|
||||
source,
|
||||
target: worker,
|
||||
file: input.file,
|
||||
range: input.value.location,
|
||||
coverage: input.coverage,
|
||||
relation: "loads",
|
||||
properties: { kind: input.value.kind },
|
||||
});
|
||||
if (resolved !== null)
|
||||
addStaticInferenceEdge(context, {
|
||||
source: worker,
|
||||
target: resolved.node,
|
||||
file: input.file,
|
||||
range: input.value.location,
|
||||
coverage: input.coverage,
|
||||
relation: "maps_to",
|
||||
properties: { resolved_path: resolved.path },
|
||||
});
|
||||
return;
|
||||
}
|
||||
const target =
|
||||
resolved?.node ??
|
||||
unresolvedReferenceNode(context, input.file, input.value, input.coverage);
|
||||
addStaticInferenceEdge(context, {
|
||||
source,
|
||||
target,
|
||||
file: input.file,
|
||||
range: input.value.location,
|
||||
coverage: input.coverage,
|
||||
relation: resolved?.file.kind === "native-addon" ? "loads" : "imports",
|
||||
properties: {
|
||||
kind: input.value.kind,
|
||||
specifier: input.value.specifier,
|
||||
expression: input.value.expression,
|
||||
resolved_path: resolved?.path ?? null,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const addEndpoint = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: FindingInput<StaticEndpoint>,
|
||||
): void => {
|
||||
const source =
|
||||
sourceNodeFor(context, input.file.path, input.value.module_key) ??
|
||||
input.asset;
|
||||
const node = context.accumulator.addNode({
|
||||
kind: "endpoint",
|
||||
identity: artifactLocalIdentity(
|
||||
input.file.sha256,
|
||||
input.value.kind,
|
||||
input.value.value,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
label: input.value.value,
|
||||
properties: {
|
||||
endpoint_kind: input.value.kind,
|
||||
value: input.value.value,
|
||||
mechanism: input.value.mechanism,
|
||||
},
|
||||
evidence: astObservationEvidence({
|
||||
sha256: input.file.sha256,
|
||||
path: input.file.path,
|
||||
range: input.value.location,
|
||||
operation: "discover-static-endpoint",
|
||||
coverage: input.coverage,
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
addStaticInferenceEdge(context, {
|
||||
source,
|
||||
target: node,
|
||||
file: input.file,
|
||||
range: input.value.location,
|
||||
coverage: input.coverage,
|
||||
relation: input.value.kind === "route" ? "exposes" : "calls",
|
||||
properties: { mechanism: input.value.mechanism },
|
||||
});
|
||||
};
|
||||
|
||||
const addStorage = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: FindingInput<StaticStorage>,
|
||||
): void => {
|
||||
const source =
|
||||
sourceNodeFor(context, input.file.path, input.value.module_key) ??
|
||||
input.asset;
|
||||
const node = context.accumulator.addNode({
|
||||
kind: "storage",
|
||||
identity: artifactLocalIdentity(
|
||||
input.file.sha256,
|
||||
input.value.kind,
|
||||
input.value.name ?? input.value.mechanism,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
label: input.value.name ?? input.value.kind,
|
||||
properties: {
|
||||
storage_kind: input.value.kind,
|
||||
name: input.value.name,
|
||||
mechanism: input.value.mechanism,
|
||||
},
|
||||
evidence: astObservationEvidence({
|
||||
sha256: input.file.sha256,
|
||||
path: input.file.path,
|
||||
range: input.value.location,
|
||||
operation: "discover-static-storage",
|
||||
coverage: input.coverage,
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
addStaticInferenceEdge(context, {
|
||||
source,
|
||||
target: node,
|
||||
file: input.file,
|
||||
range: input.value.location,
|
||||
coverage: input.coverage,
|
||||
relation: "persists_to",
|
||||
properties: { mechanism: input.value.mechanism },
|
||||
});
|
||||
};
|
||||
|
||||
const addDiscoveredRole = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: FindingInput<StaticRolePath>,
|
||||
): void => {
|
||||
const resolvedPath = resolveArtifactPath(
|
||||
input.value.path,
|
||||
input.file.path,
|
||||
context.filesByPath,
|
||||
);
|
||||
const role = createElectronRoleNode(context, {
|
||||
kind:
|
||||
input.value.role === "preload" ? "electron-preload" : "electron-renderer",
|
||||
anchor: input.file,
|
||||
declaredPath: input.value.path,
|
||||
resolvedPath,
|
||||
mechanism: input.value.mechanism,
|
||||
range: input.value.location,
|
||||
coverage: input.coverage,
|
||||
});
|
||||
const source =
|
||||
sourceNodeFor(context, input.file.path, input.value.module_key) ??
|
||||
input.asset;
|
||||
addStaticInferenceEdge(context, {
|
||||
source,
|
||||
target: role,
|
||||
file: input.file,
|
||||
range: input.value.location,
|
||||
coverage: input.coverage,
|
||||
relation: "loads",
|
||||
properties: { mechanism: input.value.mechanism },
|
||||
});
|
||||
linkElectronRoleToAsset(context, {
|
||||
role,
|
||||
anchor: input.file,
|
||||
path: resolvedPath,
|
||||
range: input.value.location,
|
||||
coverage: input.coverage,
|
||||
});
|
||||
};
|
||||
|
||||
const addSourceMapEdge = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: FindingInput<StaticSourceMap>,
|
||||
): void => {
|
||||
const resolvedPath = resolveArtifactPath(
|
||||
input.value.declared_url,
|
||||
input.file.path,
|
||||
context.filesByPath,
|
||||
);
|
||||
const resolvedFile =
|
||||
resolvedPath === null ? undefined : context.filesByPath.get(resolvedPath);
|
||||
const resolvedNode =
|
||||
resolvedPath === null ? undefined : context.fileNodes.get(resolvedPath);
|
||||
const target =
|
||||
resolvedFile?.kind === "source-map" && resolvedNode !== undefined
|
||||
? resolvedNode
|
||||
: context.accumulator.addNode({
|
||||
kind: "source-map",
|
||||
identity: artifactLocalIdentity(
|
||||
input.file.sha256,
|
||||
"unresolved-source-map",
|
||||
input.value.declared_url,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
label: input.value.declared_url,
|
||||
properties: {
|
||||
declared_url: input.value.declared_url,
|
||||
resolved_path: resolvedPath,
|
||||
available: false,
|
||||
},
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: input.file.sha256,
|
||||
path: input.file.path,
|
||||
range: input.value.location,
|
||||
operation: "discover-source-map",
|
||||
coverage: input.coverage,
|
||||
confidence: "medium",
|
||||
limitations: [
|
||||
"The declared source map was not present in the inventoried artifact.",
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
addStaticInferenceEdge(context, {
|
||||
source: input.asset,
|
||||
target,
|
||||
file: input.file,
|
||||
range: input.value.location,
|
||||
coverage: input.coverage,
|
||||
relation: "maps_to",
|
||||
properties: {
|
||||
declared_url: input.value.declared_url,
|
||||
resolved_path: resolvedPath,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const resolveReference = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
sourcePath: string,
|
||||
specifier: string,
|
||||
): ResolvedReference | null => {
|
||||
const module = context.moduleNodes.get(
|
||||
moduleLookupKey(sourcePath, specifier),
|
||||
);
|
||||
if (module !== undefined) {
|
||||
const file = context.filesByPath.get(sourcePath);
|
||||
return file === undefined
|
||||
? null
|
||||
: { path: `${sourcePath}#module:${specifier}`, file, node: module };
|
||||
}
|
||||
const path = resolveArtifactPath(specifier, sourcePath, context.filesByPath);
|
||||
if (path === null) return null;
|
||||
const file = context.filesByPath.get(path);
|
||||
const node = context.fileNodes.get(path);
|
||||
return file === undefined || node === undefined ? null : { path, file, node };
|
||||
};
|
||||
|
||||
const unresolvedReferenceNode = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
file: JavaScriptArtifactFile,
|
||||
reference: StaticReference,
|
||||
coverage: JavaScriptArtifactGraphCoverage,
|
||||
): ApplicationNode =>
|
||||
context.accumulator.addNode({
|
||||
kind: "javascript-module",
|
||||
identity: artifactLocalIdentity(
|
||||
file.sha256,
|
||||
"unresolved-reference",
|
||||
`${reference.kind}:${reference.specifier ?? reference.expression ?? "[dynamic]"}`,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
label: reference.specifier,
|
||||
properties: {
|
||||
reference_kind: reference.kind,
|
||||
specifier: reference.specifier,
|
||||
expression: reference.expression,
|
||||
resolution: "unresolved",
|
||||
},
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: file.sha256,
|
||||
path: file.path,
|
||||
range: reference.location,
|
||||
operation: "resolve-static-reference",
|
||||
coverage,
|
||||
confidence: "low",
|
||||
limitations: [
|
||||
"The static reference could not be resolved within the inventoried artifact.",
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,501 @@
|
||||
import type { ArtifactInventorySnapshot } from "./ArtifactInventory.js";
|
||||
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
|
||||
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
|
||||
import type {
|
||||
JavaScriptArtifactContainer,
|
||||
JavaScriptArtifactFile,
|
||||
JavaScriptArtifactFileKind,
|
||||
} from "./JavaScriptArtifactFiles.js";
|
||||
import type { JavaScriptArtifactGraphAccumulator } from "./JavaScriptArtifactGraphAccumulator.js";
|
||||
import {
|
||||
addArtifactContainsEdge,
|
||||
addAstContainsEdge,
|
||||
addUnavailableStaticParseScope,
|
||||
artifactLocalIdentity,
|
||||
createElectronRoleNode,
|
||||
javascriptAnalysisCoverage,
|
||||
linkElectronRoleToAsset,
|
||||
moduleLookupKey,
|
||||
resolveArtifactPath,
|
||||
type JavaScriptArtifactGraphContext,
|
||||
} from "./JavaScriptArtifactGraphContext.js";
|
||||
import {
|
||||
artifactObservationEvidence,
|
||||
astObservationEvidence,
|
||||
completeReconstructionCoverage,
|
||||
staticInferenceEvidence,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
|
||||
interface PackageRoleInput {
|
||||
readonly packageNode: ApplicationNode;
|
||||
readonly packageFile: JavaScriptArtifactFile;
|
||||
readonly kind: "electron-main" | "electron-renderer";
|
||||
readonly declaredPath: string | null;
|
||||
}
|
||||
|
||||
/** Create the exact root artifact node from the inventory manifest. */
|
||||
export const createJavaScriptArtifactRootNode = (
|
||||
accumulator: JavaScriptArtifactGraphAccumulator,
|
||||
snapshot: ArtifactInventorySnapshot,
|
||||
): ApplicationNode => {
|
||||
const root = snapshot.nodes.find(
|
||||
({ artifact_id: id }) => id === snapshot.manifest.root_artifact_id,
|
||||
);
|
||||
if (root === undefined)
|
||||
throw new TypeError("Artifact inventory root is missing");
|
||||
return accumulator.addNode({
|
||||
kind: "artifact",
|
||||
identity: {
|
||||
strategy: "content-digest",
|
||||
stability: "global-exact",
|
||||
sha256: root.sha256,
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: "artifact root",
|
||||
properties: {
|
||||
format: snapshot.manifest.root_format,
|
||||
bytes: root.size,
|
||||
inventory_manifest_id: snapshot.manifest.manifest_id,
|
||||
inventory_graph_sha256: snapshot.manifest.graph_sha256,
|
||||
inventory_artifact_id: root.artifact_id,
|
||||
},
|
||||
evidence: artifactObservationEvidence({
|
||||
sha256: root.sha256,
|
||||
path: "artifact-root",
|
||||
operation: "inventory-root",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
limitations: [
|
||||
"artifact-root is a path-independent alias; the application result retains the canonical local input path.",
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
/** Project nested ASAR containers inventoried inside a directory. */
|
||||
export const addJavaScriptArtifactContainers = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
): void => {
|
||||
for (const container of context.fileSet.containers) {
|
||||
const node = context.accumulator.addNode({
|
||||
kind: "artifact",
|
||||
identity: {
|
||||
strategy: "content-digest",
|
||||
stability: "global-exact",
|
||||
sha256: container.sha256,
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: container.path,
|
||||
properties: containerProperties(container),
|
||||
evidence: artifactObservationEvidence({
|
||||
sha256: container.sha256,
|
||||
path: container.path,
|
||||
operation: "inventory-nested-asar",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
context.containerNodes.set(container.sha256, node);
|
||||
context.accumulator.addEdge({
|
||||
source_node_id: context.root.node_id,
|
||||
target_node_id: node.node_id,
|
||||
relation: "contains",
|
||||
properties: { path: container.path, format: "asar" },
|
||||
evidence: artifactObservationEvidence({
|
||||
sha256: context.snapshot.manifest.root_sha256,
|
||||
path: container.path,
|
||||
operation: "inventory-nested-asar",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
}),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/** Project relevant files, ASAR entries, and explicit unavailable parse scopes. */
|
||||
export const addJavaScriptArtifactFiles = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
): void => {
|
||||
for (const analyzed of context.analysis.files) {
|
||||
const { file } = analyzed;
|
||||
const target = createFileTarget(context, file, analyzed.javascript);
|
||||
context.fileNodes.set(file.path, target);
|
||||
if (file.kind === "javascript") context.assetNodes.set(file.path, target);
|
||||
const entry = createAsarEntry(context, file);
|
||||
const parent =
|
||||
context.containerNodes.get(file.container_sha256) ?? context.root;
|
||||
if (entry === undefined)
|
||||
addArtifactContainsEdge(context, {
|
||||
source: parent,
|
||||
target,
|
||||
file,
|
||||
operation: "inventory-file",
|
||||
});
|
||||
else {
|
||||
addArtifactContainsEdge(context, {
|
||||
source: parent,
|
||||
target: entry,
|
||||
file,
|
||||
operation: "inventory-entry",
|
||||
});
|
||||
context.accumulator.addEdge({
|
||||
source_node_id: entry.node_id,
|
||||
target_node_id: target.node_id,
|
||||
relation: "maps_to",
|
||||
properties: { sha256: file.sha256 },
|
||||
evidence: artifactObservationEvidence({
|
||||
sha256: file.container_sha256,
|
||||
path: file.path,
|
||||
operation: "map-entry-content",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (
|
||||
file.kind === "javascript" &&
|
||||
(analyzed.javascript === null ||
|
||||
analyzed.javascript.parse_status === "failed")
|
||||
)
|
||||
addUnavailableStaticParseScope(context, {
|
||||
file,
|
||||
asset: target,
|
||||
operation: "parse-javascript",
|
||||
limitation: file.text.included
|
||||
? "JavaScript syntax could not be parsed."
|
||||
: `JavaScript text was unavailable: ${file.text.reason}.`,
|
||||
});
|
||||
const packageValue = context.analysis.packages.find(
|
||||
({ path }) => path === file.path,
|
||||
);
|
||||
if (
|
||||
packageValue?.status !== undefined &&
|
||||
packageValue.status !== "included"
|
||||
)
|
||||
addUnavailableStaticParseScope(context, {
|
||||
file,
|
||||
asset: target,
|
||||
operation: "parse-package-json",
|
||||
limitation:
|
||||
packageValue.limitation ?? "Package metadata could not be parsed.",
|
||||
});
|
||||
const sourceMap = context.analysis.source_maps.find(
|
||||
({ path }) => path === file.path,
|
||||
);
|
||||
if (
|
||||
sourceMap !== undefined &&
|
||||
(sourceMap.status === "invalid" || sourceMap.status === "not-approved")
|
||||
)
|
||||
addUnavailableStaticParseScope(context, {
|
||||
file,
|
||||
asset: target,
|
||||
operation: "parse-local-source-map",
|
||||
limitation:
|
||||
sourceMap.limitation ?? "Source-map content could not be parsed.",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/** Project package metadata and its declared Electron roles. */
|
||||
export const addJavaScriptPackageNodes = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
): ApplicationNode[] => {
|
||||
const roots: ApplicationNode[] = [];
|
||||
for (const packageValue of context.analysis.packages) {
|
||||
const file = context.filesByPath.get(packageValue.path);
|
||||
if (file === undefined) continue;
|
||||
const node = context.accumulator.addNode({
|
||||
kind: "package",
|
||||
identity: artifactLocalIdentity(file.sha256, "package-json", file.path),
|
||||
observations: [
|
||||
{
|
||||
label: packageValue.name ?? file.path,
|
||||
properties: {
|
||||
path: file.path,
|
||||
name: packageValue.name,
|
||||
version: packageValue.version,
|
||||
main: packageValue.main,
|
||||
renderer: packageValue.renderer,
|
||||
parse_status: packageValue.status,
|
||||
},
|
||||
evidence: artifactObservationEvidence({
|
||||
sha256: file.sha256,
|
||||
path: file.path,
|
||||
operation: "parse-package-json",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
limitations:
|
||||
packageValue.limitation === null ? [] : [packageValue.limitation],
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
if (roots.length === 0) {
|
||||
roots.push(node);
|
||||
context.accumulator.addEdge({
|
||||
source_node_id: node.node_id,
|
||||
target_node_id: context.root.node_id,
|
||||
relation: "contains",
|
||||
properties: { basis: "package-metadata-within-artifact" },
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: file.sha256,
|
||||
path: file.path,
|
||||
operation: "associate-package-artifact",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
}),
|
||||
});
|
||||
} else
|
||||
addArtifactContainsEdge(context, {
|
||||
source: context.root,
|
||||
target: node,
|
||||
file,
|
||||
operation: "inventory-package",
|
||||
});
|
||||
addPackageRole(context, {
|
||||
packageNode: node,
|
||||
packageFile: file,
|
||||
kind: "electron-main",
|
||||
declaredPath: packageValue.main,
|
||||
});
|
||||
addPackageRole(context, {
|
||||
packageNode: node,
|
||||
packageFile: file,
|
||||
kind: "electron-renderer",
|
||||
declaredPath: packageValue.renderer,
|
||||
});
|
||||
}
|
||||
return roots;
|
||||
};
|
||||
|
||||
/** Project Webpack/Rspack chunk and factory literals recovered from AST. */
|
||||
export const addJavaScriptBundlerNodes = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
): void => {
|
||||
for (const analyzed of context.analysis.files) {
|
||||
const { file, javascript } = analyzed;
|
||||
const asset = context.assetNodes.get(file.path);
|
||||
if (javascript === null || asset === undefined) continue;
|
||||
const coverage = javascriptAnalysisCoverage(javascript, context.input);
|
||||
for (const registration of javascript.bundler_registrations) {
|
||||
const chunkKey = `${registration.runtime}:${registration.chunk_keys.join(",")}`;
|
||||
const chunk = context.accumulator.addNode({
|
||||
kind: "javascript-chunk",
|
||||
identity: artifactLocalIdentity(file.sha256, "bundler-chunk", chunkKey),
|
||||
observations: [
|
||||
{
|
||||
label: chunkKey,
|
||||
properties: {
|
||||
path: file.path,
|
||||
bundler: registration.bundler,
|
||||
runtime: registration.runtime,
|
||||
chunk_keys: registration.chunk_keys,
|
||||
omitted_chunk_keys: registration.omitted_chunk_keys,
|
||||
unknown_chunk_keys: registration.unknown_chunk_keys,
|
||||
module_count: registration.modules.length,
|
||||
},
|
||||
evidence: astObservationEvidence({
|
||||
sha256: file.sha256,
|
||||
path: file.path,
|
||||
range: registration.location,
|
||||
operation: "extract-bundler-registration",
|
||||
coverage,
|
||||
limitations: javascript.limitations,
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
addAstContainsEdge(context, {
|
||||
source: asset,
|
||||
target: chunk,
|
||||
file,
|
||||
range: registration.location,
|
||||
coverage,
|
||||
properties: { bundler: registration.bundler },
|
||||
});
|
||||
for (const moduleValue of registration.modules) {
|
||||
const module = context.accumulator.addNode({
|
||||
kind: "javascript-module",
|
||||
identity: artifactLocalIdentity(
|
||||
file.sha256,
|
||||
`${registration.runtime}:module`,
|
||||
moduleValue.module_key,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
label: moduleValue.module_key,
|
||||
properties: {
|
||||
path: file.path,
|
||||
bundler: registration.bundler,
|
||||
runtime: registration.runtime,
|
||||
module_key: moduleValue.module_key,
|
||||
source_sha256: moduleValue.source_sha256,
|
||||
structural_fingerprint_sha256:
|
||||
moduleValue.structural_fingerprint_sha256,
|
||||
structural_fingerprint_algorithm:
|
||||
moduleValue.structural_fingerprint_algorithm,
|
||||
structural_fingerprint_status:
|
||||
moduleValue.structural_fingerprint_status,
|
||||
exports: moduleValue.exports,
|
||||
exports_truncated: moduleValue.exports_truncated,
|
||||
},
|
||||
evidence: astObservationEvidence({
|
||||
sha256: file.sha256,
|
||||
path: file.path,
|
||||
range: moduleValue.location,
|
||||
operation: "extract-bundler-module",
|
||||
coverage,
|
||||
limitations: javascript.limitations,
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
context.moduleNodes.set(
|
||||
moduleLookupKey(file.path, moduleValue.module_key),
|
||||
module,
|
||||
);
|
||||
addAstContainsEdge(context, {
|
||||
source: chunk,
|
||||
target: module,
|
||||
file,
|
||||
range: moduleValue.location,
|
||||
coverage,
|
||||
properties: { module_key: moduleValue.module_key },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const createFileTarget = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
file: JavaScriptArtifactFile,
|
||||
javascript: JavaScriptArtifactAnalysis["files"][number]["javascript"],
|
||||
): ApplicationNode => {
|
||||
const kind = artifactFileNodeKind(file.kind);
|
||||
return context.accumulator.addNode({
|
||||
kind,
|
||||
identity: {
|
||||
strategy: "content-digest",
|
||||
stability: "global-exact",
|
||||
sha256: file.sha256,
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: file.path,
|
||||
properties: {
|
||||
path: file.path,
|
||||
bytes: file.bytes,
|
||||
inventory_artifact_id: file.inventory_artifact_id,
|
||||
unpacked: file.unpacked,
|
||||
file_kind: file.kind,
|
||||
text_status: file.text.included ? "included" : file.text.reason,
|
||||
parse_status: javascript?.parse_status ?? null,
|
||||
vendor_markers: javascript?.vendors ?? [],
|
||||
},
|
||||
evidence: artifactObservationEvidence({
|
||||
sha256: file.sha256,
|
||||
path: file.path,
|
||||
operation: "inventory-relevant-file",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const artifactFileNodeKind = (
|
||||
kind: JavaScriptArtifactFileKind,
|
||||
): ApplicationNode["kind"] =>
|
||||
kind === "javascript"
|
||||
? "javascript-asset"
|
||||
: kind === "source-map"
|
||||
? "source-map"
|
||||
: kind === "native-addon"
|
||||
? "native-addon"
|
||||
: "artifact";
|
||||
|
||||
const createAsarEntry = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
file: JavaScriptArtifactFile,
|
||||
): ApplicationNode | undefined => {
|
||||
const isAsar =
|
||||
context.snapshot.manifest.root_format === "asar" ||
|
||||
file.container_sha256 !== context.snapshot.manifest.root_sha256;
|
||||
if (!isAsar) return undefined;
|
||||
return context.accumulator.addNode({
|
||||
kind: "asar-entry",
|
||||
identity: {
|
||||
strategy: "canonical-path",
|
||||
stability: "artifact-version",
|
||||
artifact_sha256: file.container_sha256,
|
||||
path: file.path,
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: file.path,
|
||||
properties: {
|
||||
entry_sha256: file.sha256,
|
||||
bytes: file.bytes,
|
||||
unpacked: file.unpacked,
|
||||
inventory_artifact_id: file.inventory_artifact_id,
|
||||
},
|
||||
evidence: artifactObservationEvidence({
|
||||
sha256: file.container_sha256,
|
||||
path: file.path,
|
||||
operation: "inventory-asar-entry",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const addPackageRole = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
input: PackageRoleInput,
|
||||
): void => {
|
||||
if (input.declaredPath === null) return;
|
||||
const resolvedPath = resolveArtifactPath(
|
||||
input.declaredPath,
|
||||
input.packageFile.path,
|
||||
context.filesByPath,
|
||||
);
|
||||
const role = createElectronRoleNode(context, {
|
||||
kind: input.kind,
|
||||
anchor: input.packageFile,
|
||||
declaredPath: input.declaredPath,
|
||||
resolvedPath,
|
||||
mechanism:
|
||||
input.kind === "electron-main"
|
||||
? "package.json:main"
|
||||
: "package.json:renderer",
|
||||
});
|
||||
context.accumulator.addEdge({
|
||||
source_node_id: input.packageNode.node_id,
|
||||
target_node_id: role.node_id,
|
||||
relation: "loads",
|
||||
properties: {
|
||||
declared_path: input.declaredPath,
|
||||
resolved_path: resolvedPath,
|
||||
},
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: input.packageFile.sha256,
|
||||
path: input.packageFile.path,
|
||||
operation: "discover-package-entrypoint",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
}),
|
||||
});
|
||||
linkElectronRoleToAsset(context, {
|
||||
role,
|
||||
anchor: input.packageFile,
|
||||
path: resolvedPath,
|
||||
});
|
||||
};
|
||||
|
||||
const containerProperties = (container: JavaScriptArtifactContainer) => ({
|
||||
path: container.path,
|
||||
format: "asar",
|
||||
bytes: container.bytes,
|
||||
inventory_artifact_id: container.inventory_artifact_id,
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { lstat, realpath } from "node:fs/promises";
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
import { AsarArtifactReader } from "../artifacts/AsarArtifactReader.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactReader,
|
||||
} from "../artifacts/ArtifactReader.js";
|
||||
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
|
||||
import type { JavaScriptApplicationGraph } from "../domain/javascriptApplicationGraph.js";
|
||||
import { analyzeJavaScriptArtifactFiles } from "./JavaScriptArtifactAnalysis.js";
|
||||
import { readJavaScriptArtifactFiles } from "./JavaScriptArtifactFiles.js";
|
||||
import { buildJavaScriptArtifactGraph } from "./JavaScriptArtifactGraphBuilder.js";
|
||||
import {
|
||||
artifactLimitsForReconstruction,
|
||||
javascriptArtifactReconstructionInputSchema,
|
||||
type JavaScriptArtifactReconstructionInput,
|
||||
} from "./JavaScriptArtifactReconstructionInput.js";
|
||||
import { scanCanonicalArtifactInventory } from "./ArtifactInventory.js";
|
||||
|
||||
/** Application-layer result retaining local diagnostics outside the canonical graph. */
|
||||
export interface JavaScriptArtifactReconstructionResult {
|
||||
readonly input_path: string;
|
||||
readonly format: "asar" | "directory";
|
||||
readonly inventory_manifest_id: string;
|
||||
readonly inventory_graph_sha256: string;
|
||||
readonly graph: JavaScriptApplicationGraph;
|
||||
readonly statistics: {
|
||||
readonly relevant_files: number;
|
||||
readonly nested_asar_containers: number;
|
||||
readonly text_files_selected: number;
|
||||
readonly text_bytes_read: number;
|
||||
readonly omitted_text_files: number;
|
||||
readonly limit_omitted_text_files: number;
|
||||
readonly policy_filtered_text_files: number;
|
||||
readonly invalid_utf8_files: number;
|
||||
readonly parsed_javascript_files: number;
|
||||
readonly visited_ast_nodes: number;
|
||||
readonly findings: number;
|
||||
readonly modules: number;
|
||||
readonly parse_failures: number;
|
||||
readonly truncated_scopes: number;
|
||||
};
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Reconstruct one local ASAR or extracted directory without executing code. */
|
||||
export const reconstructJavaScriptArtifact = async (
|
||||
rawInput: unknown,
|
||||
signal?: AbortSignal,
|
||||
): Promise<JavaScriptArtifactReconstructionResult> => {
|
||||
const input = javascriptArtifactReconstructionInputSchema.parse(rawInput);
|
||||
abortIfNeeded(signal);
|
||||
const path = await realpath(input.input_path);
|
||||
const format = await resolveFormat(path, input);
|
||||
const snapshot = await scanCanonicalArtifactInventory(
|
||||
path,
|
||||
artifactLimitsForReconstruction(input),
|
||||
signal,
|
||||
);
|
||||
if (snapshot.manifest.root_format !== format)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Artifact inventory classified ${path} as ${snapshot.manifest.root_format}, not ${format}`,
|
||||
);
|
||||
const reader = createReader(path, format);
|
||||
try {
|
||||
const files = await readJavaScriptArtifactFiles(
|
||||
reader,
|
||||
snapshot,
|
||||
input,
|
||||
signal,
|
||||
);
|
||||
const analysis = analyzeJavaScriptArtifactFiles(files, input, () =>
|
||||
performance.now(),
|
||||
);
|
||||
abortIfNeeded(signal);
|
||||
const graph = buildJavaScriptArtifactGraph(
|
||||
snapshot,
|
||||
files,
|
||||
analysis,
|
||||
input,
|
||||
);
|
||||
return {
|
||||
input_path: path,
|
||||
format,
|
||||
inventory_manifest_id: snapshot.manifest.manifest_id,
|
||||
inventory_graph_sha256: snapshot.manifest.graph_sha256,
|
||||
graph,
|
||||
statistics: {
|
||||
relevant_files: files.files.length,
|
||||
nested_asar_containers: files.containers.length,
|
||||
text_files_selected: files.text_files_selected,
|
||||
text_bytes_read: files.text_bytes_read,
|
||||
omitted_text_files: files.omitted_text_files,
|
||||
limit_omitted_text_files: files.limit_omitted_text_files,
|
||||
policy_filtered_text_files: files.policy_filtered_text_files,
|
||||
invalid_utf8_files: files.invalid_utf8_files,
|
||||
parsed_javascript_files: analysis.files.filter(
|
||||
({ javascript }) => javascript !== null,
|
||||
).length,
|
||||
visited_ast_nodes: analysis.visited_ast_nodes,
|
||||
findings: analysis.findings,
|
||||
modules: analysis.modules,
|
||||
parse_failures: analysis.parse_failures,
|
||||
truncated_scopes: analysis.truncated_scopes,
|
||||
},
|
||||
limitations: analysis.limitations,
|
||||
};
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
};
|
||||
|
||||
const resolveFormat = async (
|
||||
path: string,
|
||||
input: JavaScriptArtifactReconstructionInput,
|
||||
): Promise<"asar" | "directory"> => {
|
||||
const metadata = await lstat(path);
|
||||
const observed = metadata.isDirectory()
|
||||
? "directory"
|
||||
: metadata.isFile() && path.toLowerCase().endsWith(".asar")
|
||||
? "asar"
|
||||
: undefined;
|
||||
if (observed === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`JavaScript artifact reconstruction accepts only a directory or .asar file: ${path}`,
|
||||
);
|
||||
if (input.format !== "auto" && input.format !== observed)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Requested ${input.format} input but observed ${observed}: ${path}`,
|
||||
);
|
||||
return observed;
|
||||
};
|
||||
|
||||
const createReader = (
|
||||
path: string,
|
||||
format: "asar" | "directory",
|
||||
): ArtifactReader =>
|
||||
format === "asar"
|
||||
? new AsarArtifactReader(path)
|
||||
: new DirectoryArtifactReader(path);
|
||||
|
||||
const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"JavaScript artifact reconstruction cancelled",
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ArtifactLimits } from "../artifacts/ArtifactReader.js";
|
||||
|
||||
const MAX_GRAPH_NODES = 100_000;
|
||||
const MAX_GRAPH_EDGES = 200_000;
|
||||
|
||||
const reconstructionLimitsSchema = z
|
||||
.strictObject({
|
||||
max_entries: z.number().int().min(1).max(1_000_000).default(8_000),
|
||||
max_total_artifact_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(512 * 1_024 * 1_024),
|
||||
max_artifact_entry_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(128 * 1_024 * 1_024),
|
||||
max_compression_ratio: z.number().min(1).max(100_000).default(1_000),
|
||||
max_depth: z.number().int().min(1).max(100).default(64),
|
||||
max_path_bytes: z.number().int().min(1).max(65_535).default(4_096),
|
||||
max_text_files: z.number().int().min(1).max(100_000).default(5_000),
|
||||
max_total_text_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(512 * 1_024 * 1_024)
|
||||
.default(128 * 1_024 * 1_024),
|
||||
max_text_file_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(64 * 1_024 * 1_024)
|
||||
.default(8 * 1_024 * 1_024),
|
||||
max_ast_nodes: z.number().int().min(1).max(20_000_000).default(2_000_000),
|
||||
max_findings: z.number().int().min(1).max(200_000).default(10_000),
|
||||
max_modules: z.number().int().min(1).max(100_000).default(20_000),
|
||||
max_source_map_sources: z.number().int().min(1).max(100_000).default(5_000),
|
||||
max_parse_milliseconds: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(300_000)
|
||||
.default(30_000),
|
||||
})
|
||||
.superRefine((limits, context) => {
|
||||
const projectedNodes =
|
||||
7 * limits.max_entries +
|
||||
limits.max_findings +
|
||||
limits.max_modules +
|
||||
limits.max_source_map_sources +
|
||||
1;
|
||||
if (projectedNodes > MAX_GRAPH_NODES)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["max_entries"],
|
||||
message:
|
||||
"Combined reconstruction limits can exceed the 100000-node graph contract",
|
||||
});
|
||||
const projectedEdges =
|
||||
9 * limits.max_entries +
|
||||
5 * limits.max_findings +
|
||||
limits.max_modules +
|
||||
limits.max_source_map_sources;
|
||||
if (projectedEdges > MAX_GRAPH_EDGES)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["max_entries"],
|
||||
message:
|
||||
"Combined reconstruction limits can exceed the 200000-edge graph contract",
|
||||
});
|
||||
});
|
||||
|
||||
/** Local ASAR/directory reconstruction request with explicit source-map authority. */
|
||||
export const javascriptArtifactReconstructionInputSchema = z.strictObject({
|
||||
input_path: z.string().min(1).max(16_384),
|
||||
format: z.enum(["auto", "asar", "directory"]).default("auto"),
|
||||
source_map_read_approved: z.boolean().default(false),
|
||||
limits: reconstructionLimitsSchema.default({
|
||||
max_entries: 8_000,
|
||||
max_total_artifact_bytes: 512 * 1_024 * 1_024,
|
||||
max_artifact_entry_bytes: 128 * 1_024 * 1_024,
|
||||
max_compression_ratio: 1_000,
|
||||
max_depth: 64,
|
||||
max_path_bytes: 4_096,
|
||||
max_text_files: 5_000,
|
||||
max_total_text_bytes: 128 * 1_024 * 1_024,
|
||||
max_text_file_bytes: 8 * 1_024 * 1_024,
|
||||
max_ast_nodes: 2_000_000,
|
||||
max_findings: 10_000,
|
||||
max_modules: 20_000,
|
||||
max_source_map_sources: 5_000,
|
||||
max_parse_milliseconds: 30_000,
|
||||
}),
|
||||
});
|
||||
|
||||
/** Parsed bounded reconstruction request. */
|
||||
export type JavaScriptArtifactReconstructionInput = z.infer<
|
||||
typeof javascriptArtifactReconstructionInputSchema
|
||||
>;
|
||||
|
||||
/** Project reconstruction limits into the shared artifact traversal policy. */
|
||||
export const artifactLimitsForReconstruction = (
|
||||
input: JavaScriptArtifactReconstructionInput,
|
||||
): ArtifactLimits => ({
|
||||
maxEntries: input.limits.max_entries,
|
||||
maxTotalBytes: input.limits.max_total_artifact_bytes,
|
||||
maxEntryBytes: input.limits.max_artifact_entry_bytes,
|
||||
maxCompressionRatio: input.limits.max_compression_ratio,
|
||||
maxDepth: input.limits.max_depth,
|
||||
maxPathBytes: input.limits.max_path_bytes,
|
||||
});
|
||||
@@ -21,14 +21,24 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
constructor(private readonly path: string) {}
|
||||
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
const paths = listPackage(this.path, { isPack: false }).sort(
|
||||
(left, right) => left.localeCompare(right, "en"),
|
||||
);
|
||||
let paths: string[];
|
||||
try {
|
||||
paths = listPackage(this.path, { isPack: false }).sort((left, right) =>
|
||||
left.localeCompare(right, "en"),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
throw asarFailure(this.path, "inventory", cause);
|
||||
}
|
||||
for (const listed of paths) {
|
||||
abortIfNeeded(signal);
|
||||
const path = listed.replace(/^\/+|\/+$/gu, "");
|
||||
if (path.length === 0) continue;
|
||||
const metadata = statFile(this.path, path, false);
|
||||
let metadata: ReturnType<typeof statFile>;
|
||||
try {
|
||||
metadata = statFile(this.path, path, false);
|
||||
} catch (cause: unknown) {
|
||||
throw asarFailure(this.path, `stat ${path}`, cause);
|
||||
}
|
||||
const kind =
|
||||
"files" in metadata
|
||||
? "directory"
|
||||
@@ -67,9 +77,15 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
return Promise.reject(
|
||||
new ArtifactReaderFailure("format", "ASAR entry is not a regular file"),
|
||||
);
|
||||
return Promise.resolve(
|
||||
Readable.from(extractFile(this.path, entry.adapterKey, false)),
|
||||
);
|
||||
try {
|
||||
return Promise.resolve(
|
||||
Readable.from(extractFile(this.path, entry.adapterKey, false)),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return Promise.reject(
|
||||
asarFailure(this.path, `read ${entry.path}`, cause),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
@@ -85,3 +101,16 @@ const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure("cancelled", "ASAR operation cancelled");
|
||||
};
|
||||
|
||||
const asarFailure = (
|
||||
path: string,
|
||||
operation: string,
|
||||
cause: unknown,
|
||||
): ArtifactReaderFailure =>
|
||||
cause instanceof ArtifactReaderFailure
|
||||
? cause
|
||||
: new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Malformed or unreadable ASAR during ${operation}: ${path}`,
|
||||
{ cause },
|
||||
);
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import * as t from "@babel/types";
|
||||
|
||||
/** Complete or prefix-only digest from a bounded AST traversal. */
|
||||
export interface AstFingerprint {
|
||||
readonly sha256: string;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
/** Bounded static CommonJS export names. */
|
||||
export interface StaticExports {
|
||||
readonly values: readonly string[];
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
/** Derive a rename-resistant, bounded syntax fingerprint without code execution. */
|
||||
export const fingerprintJavaScriptAst = (
|
||||
node: t.Node,
|
||||
maximumTokens: number,
|
||||
): AstFingerprint => {
|
||||
const tokens: string[] = [];
|
||||
let truncated = false;
|
||||
t.traverseFast(node, (current) => {
|
||||
if (tokens.length >= maximumTokens) {
|
||||
truncated = true;
|
||||
return t.traverseFast.stop;
|
||||
}
|
||||
tokens.push(...semanticTokens(current));
|
||||
if (tokens.length > maximumTokens) {
|
||||
tokens.length = maximumTokens;
|
||||
truncated = true;
|
||||
return t.traverseFast.stop;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
return {
|
||||
sha256: createHash("sha256").update(JSON.stringify(tokens)).digest("hex"),
|
||||
truncated,
|
||||
};
|
||||
};
|
||||
|
||||
/** Collect statically declared CommonJS/bundler export names from one factory. */
|
||||
export const collectJavaScriptExports = (
|
||||
node: t.Node,
|
||||
maximumExports: number,
|
||||
): StaticExports => {
|
||||
const exports = new Set<string>();
|
||||
let truncated = false;
|
||||
t.traverseFast(node, (current) => {
|
||||
if (exports.size >= maximumExports) {
|
||||
truncated = true;
|
||||
return t.traverseFast.stop;
|
||||
}
|
||||
if (t.isAssignmentExpression(current))
|
||||
collectAssignmentExports(
|
||||
current.left,
|
||||
current.right,
|
||||
exports,
|
||||
maximumExports,
|
||||
);
|
||||
if (t.isCallExpression(current))
|
||||
collectCallExports(current, exports, maximumExports);
|
||||
return undefined;
|
||||
});
|
||||
return {
|
||||
values: [...exports].sort(compareCodePoints),
|
||||
truncated,
|
||||
};
|
||||
};
|
||||
|
||||
const semanticTokens = (node: t.Node): string[] => {
|
||||
const tokens = [`node:${node.type}`];
|
||||
if (t.isStringLiteral(node)) tokens.push(`string:${bounded(node.value)}`);
|
||||
else if (t.isNumericLiteral(node))
|
||||
tokens.push(`number:${String(node.value)}`);
|
||||
else if (t.isBooleanLiteral(node))
|
||||
tokens.push(`boolean:${String(node.value)}`);
|
||||
else if (t.isRegExpLiteral(node))
|
||||
tokens.push(`regexp:${bounded(node.pattern)}/${node.flags}`);
|
||||
else if (t.isBinaryExpression(node) || t.isLogicalExpression(node))
|
||||
tokens.push(`operator:${node.operator}`);
|
||||
else if (t.isUnaryExpression(node) || t.isUpdateExpression(node))
|
||||
tokens.push(`operator:${node.operator}`);
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const property = propertyName(node.property);
|
||||
if (property !== "") tokens.push(`property:${bounded(property)}`);
|
||||
}
|
||||
if ((t.isObjectProperty(node) || t.isObjectMethod(node)) && !node.computed) {
|
||||
const key = propertyName(node.key);
|
||||
if (key !== "") tokens.push(`key:${bounded(key)}`);
|
||||
}
|
||||
return tokens;
|
||||
};
|
||||
|
||||
const collectAssignmentExports = (
|
||||
left: t.LVal | t.OptionalMemberExpression,
|
||||
right: t.Expression,
|
||||
output: Set<string>,
|
||||
maximum: number,
|
||||
): void => {
|
||||
const path = memberPath(left);
|
||||
if (path === "exports" || path === "module.exports") {
|
||||
if (t.isObjectExpression(right)) collectObjectKeys(right, output, maximum);
|
||||
else addExport(output, "default", maximum);
|
||||
return;
|
||||
}
|
||||
if (path.startsWith("exports."))
|
||||
addExport(output, path.slice("exports.".length), maximum);
|
||||
if (path.startsWith("module.exports."))
|
||||
addExport(output, path.slice("module.exports.".length), maximum);
|
||||
};
|
||||
|
||||
const collectCallExports = (
|
||||
call: t.CallExpression,
|
||||
output: Set<string>,
|
||||
maximum: number,
|
||||
): void => {
|
||||
const callee = memberPath(call.callee);
|
||||
if (callee === "Object.defineProperty") {
|
||||
const target = memberPath(call.arguments[0]);
|
||||
const name = stringValue(call.arguments[1]);
|
||||
if ((target === "exports" || target === "module.exports") && name)
|
||||
addExport(output, name, maximum);
|
||||
}
|
||||
if (!callee.endsWith(".d")) return;
|
||||
const target = memberPath(call.arguments[0]);
|
||||
const declarations = call.arguments[1];
|
||||
if (
|
||||
(target === "exports" || target === "module.exports") &&
|
||||
t.isObjectExpression(declarations)
|
||||
)
|
||||
collectObjectKeys(declarations, output, maximum);
|
||||
};
|
||||
|
||||
const collectObjectKeys = (
|
||||
object: t.ObjectExpression,
|
||||
output: Set<string>,
|
||||
maximum: number,
|
||||
): void => {
|
||||
for (const property of object.properties) {
|
||||
if (output.size >= maximum) return;
|
||||
if (!t.isObjectProperty(property) && !t.isObjectMethod(property)) continue;
|
||||
const name = propertyName(property.key);
|
||||
if (name !== "") addExport(output, name, maximum);
|
||||
}
|
||||
};
|
||||
|
||||
const addExport = (
|
||||
output: Set<string>,
|
||||
name: string,
|
||||
maximum: number,
|
||||
): void => {
|
||||
if (output.size < maximum) output.add(name.slice(0, 4_096));
|
||||
};
|
||||
|
||||
const memberPath = (node: t.Node | null | undefined, depth = 0): string => {
|
||||
if (depth >= 128) return "[deep]";
|
||||
if (node === undefined || node === null) return "";
|
||||
if (t.isIdentifier(node) || t.isPrivateName(node))
|
||||
return t.isIdentifier(node) ? node.name : "";
|
||||
if (t.isThisExpression(node)) return "this";
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const object = t.isNode(node.object)
|
||||
? memberPath(node.object, depth + 1)
|
||||
: "";
|
||||
const property = propertyName(node.property);
|
||||
return object === "" ? property : `${object}.${property}`;
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
const propertyName = (node: t.Node): string => {
|
||||
if (t.isIdentifier(node)) return node.name;
|
||||
if (t.isStringLiteral(node) || t.isNumericLiteral(node))
|
||||
return String(node.value);
|
||||
return "";
|
||||
};
|
||||
|
||||
const stringValue = (node: t.Node | null | undefined): string | undefined =>
|
||||
t.isStringLiteral(node) ? node.value : undefined;
|
||||
|
||||
const bounded = (value: string): string => value.slice(0, 1_024);
|
||||
|
||||
const compareCodePoints = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
@@ -0,0 +1,494 @@
|
||||
import { parse } from "@babel/parser";
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import {
|
||||
collectJavaScriptExports,
|
||||
fingerprintJavaScriptAst,
|
||||
} from "./javascriptAstFingerprint.js";
|
||||
import {
|
||||
STATIC_ROUTE_CALL_NAMES,
|
||||
argumentValue,
|
||||
calleeName,
|
||||
chunkRuntime,
|
||||
compareCodePoints,
|
||||
detectVendors,
|
||||
endpointArgument,
|
||||
failedJavaScriptStaticAnalysis,
|
||||
factoryRequireName,
|
||||
moduleFactory,
|
||||
modulePropertyName,
|
||||
prefixedArgument,
|
||||
propertyName,
|
||||
range,
|
||||
rangeForOffsets,
|
||||
registrationKey,
|
||||
sanitizeCandidate,
|
||||
sha256Text,
|
||||
sortedUnique,
|
||||
sourceSlice,
|
||||
staticArrayValues,
|
||||
staticPath,
|
||||
storageKind,
|
||||
stringValue,
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
import {
|
||||
createJavaScriptAnalysisAccumulator,
|
||||
type JavaScriptAnalysisAccumulator as AnalysisAccumulator,
|
||||
type JavaScriptEndpointInput as EndpointInput,
|
||||
type JavaScriptFindingContext as FindingContext,
|
||||
type JavaScriptModuleRange as ModuleRange,
|
||||
type JavaScriptReferenceInput as ReferenceInput,
|
||||
type LocatedJavaScriptFinding as Located,
|
||||
type LocatedJavaScriptFindingInput as LocatedInput,
|
||||
} from "./javascriptStaticAnalysisState.js";
|
||||
import type {
|
||||
JavaScriptBundlerModule,
|
||||
JavaScriptStaticAnalysis,
|
||||
JavaScriptStaticAnalysisLimits,
|
||||
} from "./javascriptStaticAnalysisTypes.js";
|
||||
|
||||
/** Parse one bounded JavaScript artifact and recover static structure only. */
|
||||
export const analyzeJavaScriptStaticSource = (
|
||||
source: string,
|
||||
limits: JavaScriptStaticAnalysisLimits,
|
||||
): JavaScriptStaticAnalysis => {
|
||||
let file: ReturnType<typeof parse>;
|
||||
try {
|
||||
file = parse(source, {
|
||||
sourceType: "unambiguous",
|
||||
errorRecovery: true,
|
||||
plugins: ["jsx", "typescript"],
|
||||
});
|
||||
} catch {
|
||||
return failedJavaScriptStaticAnalysis();
|
||||
}
|
||||
const accumulator = createJavaScriptAnalysisAccumulator();
|
||||
if (limits.now() > limits.deadline) accumulator.truncated = true;
|
||||
if (!accumulator.truncated)
|
||||
t.traverseFast(file, (node) => {
|
||||
accumulator.visitedNodes += 1;
|
||||
if (
|
||||
accumulator.visitedNodes > limits.maxAstNodes ||
|
||||
(accumulator.visitedNodes % 1_024 === 0 &&
|
||||
limits.now() > limits.deadline)
|
||||
) {
|
||||
accumulator.truncated = true;
|
||||
return t.traverseFast.stop;
|
||||
}
|
||||
inspectNode(source, node, accumulator, limits);
|
||||
return undefined;
|
||||
});
|
||||
addSourceMapDirectives(source, accumulator, limits.maxFindings);
|
||||
const parserErrors = file.errors.length;
|
||||
const limitations = [
|
||||
...(parserErrors === 0
|
||||
? []
|
||||
: [
|
||||
"The parser recovered from syntax errors; affected facts are partial.",
|
||||
]),
|
||||
...(accumulator.truncated
|
||||
? ["AST analysis stopped at the configured node or time bound."]
|
||||
: []),
|
||||
...(accumulator.droppedFindings === 0
|
||||
? []
|
||||
: ["Static findings were truncated at the configured finding bound."]),
|
||||
...(accumulator.structuralTruncation
|
||||
? ["Bundler metadata reached a per-record structural bound."]
|
||||
: []),
|
||||
...(accumulator.unknownFindings === 0
|
||||
? []
|
||||
: [
|
||||
"One or more bundler registration keys were dynamic and remain unknown.",
|
||||
]),
|
||||
"JavaScript syntax was parsed as data and was never evaluated.",
|
||||
];
|
||||
return {
|
||||
parse_status:
|
||||
accumulator.truncated || accumulator.droppedFindings > 0
|
||||
? "truncated"
|
||||
: parserErrors > 0 || accumulator.unknownFindings > 0
|
||||
? "partial"
|
||||
: "complete",
|
||||
parse_error_count: parserErrors,
|
||||
visited_ast_nodes: Math.min(accumulator.visitedNodes, limits.maxAstNodes),
|
||||
dropped_findings: accumulator.droppedFindings,
|
||||
references: finalizeLocated(accumulator.references, accumulator.modules),
|
||||
endpoints: finalizeLocated(accumulator.endpoints, accumulator.modules),
|
||||
storage: finalizeLocated(accumulator.storage, accumulator.modules),
|
||||
bundler_registrations: sortedUnique(
|
||||
accumulator.registrations,
|
||||
registrationKey,
|
||||
),
|
||||
role_paths: finalizeLocated(accumulator.roles, accumulator.modules),
|
||||
source_map_urls: accumulator.sourceMaps,
|
||||
vendors: detectVendors(source),
|
||||
limitations,
|
||||
};
|
||||
};
|
||||
|
||||
const inspectNode = (
|
||||
source: string,
|
||||
node: t.Node,
|
||||
accumulator: AnalysisAccumulator,
|
||||
limits: JavaScriptStaticAnalysisLimits,
|
||||
): void => {
|
||||
const findings: FindingContext = {
|
||||
source,
|
||||
accumulator,
|
||||
maximum: limits.maxFindings,
|
||||
};
|
||||
if (t.isCallExpression(node)) {
|
||||
inspectBundlerRegistration(source, node, accumulator, limits);
|
||||
inspectCall(node, findings);
|
||||
} else if (t.isNewExpression(node)) inspectCall(node, findings);
|
||||
if (
|
||||
(t.isImportDeclaration(node) || t.isExportAllDeclaration(node)) &&
|
||||
node.source !== undefined
|
||||
)
|
||||
addReference(findings, {
|
||||
node,
|
||||
kind: "static-import",
|
||||
specifier: node.source.value,
|
||||
});
|
||||
else if (t.isExportNamedDeclaration(node) && node.source != null)
|
||||
addReference(findings, {
|
||||
node,
|
||||
kind: "static-import",
|
||||
specifier: node.source.value,
|
||||
});
|
||||
else if (t.isImportExpression(node))
|
||||
addReference(findings, {
|
||||
node,
|
||||
kind: "dynamic-import",
|
||||
specifier: stringValue(node.source),
|
||||
});
|
||||
if (t.isObjectProperty(node)) {
|
||||
inspectRouteProperty(node, findings);
|
||||
inspectRoleProperty(node, findings);
|
||||
}
|
||||
};
|
||||
|
||||
const inspectCall = (
|
||||
node: t.CallExpression | t.NewExpression,
|
||||
context: FindingContext,
|
||||
): void => {
|
||||
const { accumulator } = context;
|
||||
const name = calleeName(node.callee);
|
||||
const first = stringValue(node.arguments[0]);
|
||||
const module = moduleAt(node.start, accumulator.modules);
|
||||
const moduleRequire =
|
||||
module?.requireName !== null && name === module?.requireName;
|
||||
if (
|
||||
name === "require" ||
|
||||
name.endsWith(".require") ||
|
||||
name.includes("__webpack_require__") ||
|
||||
moduleRequire
|
||||
)
|
||||
addReference(context, {
|
||||
node,
|
||||
kind: "require",
|
||||
specifier: argumentValue(node.arguments[0]),
|
||||
});
|
||||
if (name.endsWith(".e") && name.includes("require"))
|
||||
addReference(context, {
|
||||
node,
|
||||
kind: "dynamic-import",
|
||||
specifier: prefixedArgument("chunk:", node.arguments[0]),
|
||||
});
|
||||
if (name === "Worker" || name.endsWith(".Worker"))
|
||||
addReference(context, { node, kind: "worker", specifier: first });
|
||||
if (name.endsWith("serviceWorker.register"))
|
||||
addReference(context, { node, kind: "service-worker", specifier: first });
|
||||
inspectEndpointCall(node, name, first, context);
|
||||
inspectStorageCall(node, name, first, context);
|
||||
if (name.endsWith("loadFile") && first !== undefined)
|
||||
addLocated(context, {
|
||||
collection: accumulator.roles,
|
||||
key: `role\0renderer\0${first}`,
|
||||
node,
|
||||
value: {
|
||||
role: "renderer",
|
||||
path: first,
|
||||
mechanism: `call:${name}`,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const inspectBundlerRegistration = (
|
||||
source: string,
|
||||
call: t.CallExpression,
|
||||
accumulator: AnalysisAccumulator,
|
||||
limits: JavaScriptStaticAnalysisLimits,
|
||||
): void => {
|
||||
const runtime = chunkRuntime(call);
|
||||
const entry = call.arguments[0];
|
||||
if (runtime === undefined || !t.isArrayExpression(entry)) return;
|
||||
const chunkIds = entry.elements[0];
|
||||
const table = entry.elements[1];
|
||||
if (!t.isArrayExpression(chunkIds) || !t.isObjectExpression(table)) return;
|
||||
const modules: JavaScriptBundlerModule[] = [];
|
||||
for (const property of table.properties) {
|
||||
const factory = moduleFactory(property);
|
||||
if (factory === undefined) continue;
|
||||
if (accumulator.moduleCount >= limits.maxModules) {
|
||||
accumulator.droppedFindings += 1;
|
||||
continue;
|
||||
}
|
||||
accumulator.moduleCount += 1;
|
||||
const key = modulePropertyName(property);
|
||||
if (key.startsWith("[computed@") || key.startsWith("[unknown@"))
|
||||
accumulator.unknownFindings += 1;
|
||||
const exactSource = sourceSlice(source, factory);
|
||||
const fingerprint = fingerprintJavaScriptAst(
|
||||
factory,
|
||||
Math.min(limits.maxAstNodes, 100_000),
|
||||
);
|
||||
const exportsValue = collectJavaScriptExports(factory, 256);
|
||||
if (fingerprint.truncated || exportsValue.truncated) {
|
||||
accumulator.droppedFindings += 1;
|
||||
accumulator.structuralTruncation = true;
|
||||
}
|
||||
modules.push({
|
||||
module_key: key,
|
||||
source_sha256: sha256Text(exactSource),
|
||||
structural_fingerprint_sha256: fingerprint.truncated
|
||||
? null
|
||||
: fingerprint.sha256,
|
||||
structural_fingerprint_algorithm: fingerprint.truncated
|
||||
? null
|
||||
: ("babel-ast-v1" as const),
|
||||
structural_fingerprint_status: fingerprint.truncated
|
||||
? ("truncated" as const)
|
||||
: ("complete" as const),
|
||||
exports: exportsValue.values,
|
||||
exports_truncated: exportsValue.truncated,
|
||||
location: range(factory),
|
||||
});
|
||||
if (typeof factory.start === "number" && typeof factory.end === "number")
|
||||
accumulator.modules.push({
|
||||
start: factory.start,
|
||||
end: factory.end,
|
||||
key,
|
||||
requireName: factoryRequireName(factory),
|
||||
});
|
||||
}
|
||||
const chunkKeys = staticArrayValues(
|
||||
chunkIds,
|
||||
Math.min(256, limits.maxFindings),
|
||||
);
|
||||
if (chunkKeys.omitted > 0) {
|
||||
accumulator.droppedFindings += chunkKeys.omitted;
|
||||
accumulator.structuralTruncation = true;
|
||||
}
|
||||
accumulator.unknownFindings += chunkKeys.unknown;
|
||||
const registration = {
|
||||
bundler: runtime.toLowerCase().includes("rspack")
|
||||
? ("rspack" as const)
|
||||
: ("webpack" as const),
|
||||
runtime,
|
||||
chunk_keys: chunkKeys.values,
|
||||
omitted_chunk_keys: chunkKeys.omitted,
|
||||
unknown_chunk_keys: chunkKeys.unknown,
|
||||
modules: modules.sort((left, right) =>
|
||||
compareCodePoints(left.module_key, right.module_key),
|
||||
),
|
||||
location: range(call),
|
||||
};
|
||||
addBounded(
|
||||
accumulator,
|
||||
`registration\0${registrationKey(registration)}`,
|
||||
limits.maxFindings,
|
||||
() => accumulator.registrations.push(registration),
|
||||
);
|
||||
};
|
||||
|
||||
const inspectEndpointCall = (
|
||||
node: t.CallExpression | t.NewExpression,
|
||||
name: string,
|
||||
first: string | undefined,
|
||||
context: FindingContext,
|
||||
): void => {
|
||||
const route = STATIC_ROUTE_CALL_NAMES.some(
|
||||
(candidate) => name === candidate || name.endsWith(`.${candidate}`),
|
||||
);
|
||||
if (route && first !== undefined)
|
||||
addEndpoint(context, {
|
||||
node,
|
||||
kind: "route",
|
||||
value: first,
|
||||
mechanism: `call:${name}`,
|
||||
});
|
||||
const endpoint = endpointArgument(name, node.arguments);
|
||||
if (endpoint !== undefined)
|
||||
addEndpoint(context, {
|
||||
node,
|
||||
kind: "network",
|
||||
value: endpoint,
|
||||
mechanism: `call:${name}`,
|
||||
});
|
||||
};
|
||||
|
||||
const inspectRouteProperty = (
|
||||
node: t.ObjectProperty,
|
||||
context: FindingContext,
|
||||
): void => {
|
||||
const key = propertyName(node.key);
|
||||
if ((key === "path" || key === "route") && t.isStringLiteral(node.value))
|
||||
addEndpoint(context, {
|
||||
node,
|
||||
kind: "route",
|
||||
value: node.value.value,
|
||||
mechanism: `property:${key}`,
|
||||
});
|
||||
};
|
||||
|
||||
const inspectRoleProperty = (
|
||||
node: t.ObjectProperty,
|
||||
context: FindingContext,
|
||||
): void => {
|
||||
if (propertyName(node.key) !== "preload") return;
|
||||
const path = staticPath(node.value);
|
||||
if (path === undefined) return;
|
||||
addLocated(context, {
|
||||
collection: context.accumulator.roles,
|
||||
key: `role\0preload\0${path}`,
|
||||
node,
|
||||
value: {
|
||||
role: "preload",
|
||||
path,
|
||||
mechanism: "property:preload",
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const inspectStorageCall = (
|
||||
node: t.CallExpression | t.NewExpression,
|
||||
name: string,
|
||||
first: string | undefined,
|
||||
context: FindingContext,
|
||||
): void => {
|
||||
const storage = storageKind(name);
|
||||
if (storage === undefined) return;
|
||||
addLocated(context, {
|
||||
collection: context.accumulator.storage,
|
||||
key: `storage\0${storage}\0${first ?? ""}`,
|
||||
node,
|
||||
value: {
|
||||
kind: storage,
|
||||
name: first ?? null,
|
||||
mechanism: `call:${name}`,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const addReference = (context: FindingContext, input: ReferenceInput): void => {
|
||||
const boundedSpecifier = input.specifier?.slice(0, 4_096) ?? null;
|
||||
const expression =
|
||||
boundedSpecifier === null
|
||||
? sourceSlice(context.source, input.node).slice(0, 4_096)
|
||||
: null;
|
||||
addLocated(context, {
|
||||
collection: context.accumulator.references,
|
||||
key: `reference\0${input.kind}\0${boundedSpecifier ?? expression}`,
|
||||
node: input.node,
|
||||
value: {
|
||||
kind: input.kind,
|
||||
specifier: boundedSpecifier,
|
||||
expression,
|
||||
module_key: null,
|
||||
location: range(input.node),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const addEndpoint = (context: FindingContext, input: EndpointInput): void =>
|
||||
addLocated(context, {
|
||||
collection: context.accumulator.endpoints,
|
||||
key: `endpoint\0${input.kind}\0${input.value}`,
|
||||
node: input.node,
|
||||
value: {
|
||||
kind: input.kind,
|
||||
value: sanitizeCandidate(input.value),
|
||||
mechanism: input.mechanism,
|
||||
module_key: null,
|
||||
location: range(input.node),
|
||||
},
|
||||
});
|
||||
|
||||
const addLocated = <Value extends { readonly module_key: string | null }>(
|
||||
context: FindingContext,
|
||||
input: LocatedInput<Value>,
|
||||
): void =>
|
||||
addBounded(
|
||||
context.accumulator,
|
||||
`${input.key}\0${String(input.node.start)}`,
|
||||
context.maximum,
|
||||
() =>
|
||||
input.collection.push({
|
||||
offset: input.node.start ?? -1,
|
||||
value: input.value,
|
||||
}),
|
||||
);
|
||||
|
||||
const addBounded = (
|
||||
accumulator: AnalysisAccumulator,
|
||||
key: string,
|
||||
maximum: number,
|
||||
add: () => void,
|
||||
): void => {
|
||||
if (accumulator.seen.has(key)) return;
|
||||
const count =
|
||||
accumulator.references.length +
|
||||
accumulator.endpoints.length +
|
||||
accumulator.storage.length +
|
||||
accumulator.roles.length +
|
||||
accumulator.sourceMaps.length +
|
||||
accumulator.registrations.length;
|
||||
if (count >= maximum) {
|
||||
accumulator.droppedFindings += 1;
|
||||
return;
|
||||
}
|
||||
accumulator.seen.add(key);
|
||||
add();
|
||||
};
|
||||
|
||||
const finalizeLocated = <Value extends { readonly module_key: string | null }>(
|
||||
values: readonly Located<Value>[],
|
||||
modules: readonly ModuleRange[],
|
||||
): Value[] =>
|
||||
values.map(({ offset, value }) => ({
|
||||
...value,
|
||||
module_key: moduleAt(offset, modules)?.key ?? null,
|
||||
}));
|
||||
|
||||
const moduleAt = (
|
||||
offset: number | null | undefined,
|
||||
modules: readonly ModuleRange[],
|
||||
): ModuleRange | undefined => {
|
||||
if (offset === null || offset === undefined) return undefined;
|
||||
return modules.find(({ start, end }) => offset >= start && offset <= end);
|
||||
};
|
||||
|
||||
const addSourceMapDirectives = (
|
||||
source: string,
|
||||
accumulator: AnalysisAccumulator,
|
||||
maximum: number,
|
||||
): void => {
|
||||
for (const match of source.matchAll(
|
||||
/\/\/[#@]\s*sourceMappingURL\s*=\s*([^\s]+)/gu,
|
||||
)) {
|
||||
const declared = match[1]?.slice(0, 4_096);
|
||||
if (declared === undefined) continue;
|
||||
const start = match.index;
|
||||
const location = rangeForOffsets(source, start, start + match[0].length);
|
||||
addBounded(accumulator, `source-map\0${declared}`, maximum, () =>
|
||||
accumulator.sourceMaps.push({ declared_url: declared, location }),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,355 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { posix } from "node:path";
|
||||
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import { sanitizeBrowserUrl } from "./browserObservation.js";
|
||||
import type {
|
||||
JavaScriptBundlerRegistration,
|
||||
JavaScriptSourceRange,
|
||||
JavaScriptStaticAnalysis,
|
||||
JavaScriptStaticStorage,
|
||||
} from "./javascriptStaticAnalysisTypes.js";
|
||||
|
||||
/** Explicit result for source text that Babel cannot parse. */
|
||||
export const failedJavaScriptStaticAnalysis = (): JavaScriptStaticAnalysis => ({
|
||||
parse_status: "failed",
|
||||
parse_error_count: 1,
|
||||
visited_ast_nodes: 0,
|
||||
dropped_findings: 0,
|
||||
references: [],
|
||||
endpoints: [],
|
||||
storage: [],
|
||||
bundler_registrations: [],
|
||||
role_paths: [],
|
||||
source_map_urls: [],
|
||||
vendors: [],
|
||||
limitations: [
|
||||
"JavaScript source could not be parsed; absence of findings is not evidence of absence.",
|
||||
"JavaScript syntax was parsed as data and was never evaluated.",
|
||||
],
|
||||
});
|
||||
|
||||
/** Recognize the bounded runtime name for a Webpack/Rspack push call. */
|
||||
export const chunkRuntime = (call: t.CallExpression): string | undefined => {
|
||||
if (
|
||||
!t.isMemberExpression(call.callee) &&
|
||||
!t.isOptionalMemberExpression(call.callee)
|
||||
)
|
||||
return undefined;
|
||||
if (propertyName(call.callee.property) !== "push") return undefined;
|
||||
return findChunkRuntime(call.callee.object, 0);
|
||||
};
|
||||
|
||||
const findChunkRuntime = (node: t.Node, depth: number): string | undefined => {
|
||||
if (depth >= 128) return undefined;
|
||||
if (t.isIdentifier(node) && /(?:webpack|rspack)Chunk/iu.test(node.name))
|
||||
return node.name.slice(0, 4_096);
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const property = propertyName(node.property);
|
||||
if (/(?:webpack|rspack)Chunk/iu.test(property))
|
||||
return property.slice(0, 4_096);
|
||||
return t.isNode(node.object)
|
||||
? findChunkRuntime(node.object, depth + 1)
|
||||
: undefined;
|
||||
}
|
||||
if (t.isAssignmentExpression(node))
|
||||
return (
|
||||
findChunkRuntime(node.left, depth + 1) ??
|
||||
findChunkRuntime(node.right, depth + 1)
|
||||
);
|
||||
if (t.isLogicalExpression(node) || t.isBinaryExpression(node))
|
||||
return (
|
||||
findChunkRuntime(node.left, depth + 1) ??
|
||||
findChunkRuntime(node.right, depth + 1)
|
||||
);
|
||||
if (t.isParenthesizedExpression(node) || t.isTSAsExpression(node))
|
||||
return findChunkRuntime(node.expression, depth + 1);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Return a literal function factory from one module-table property. */
|
||||
export const moduleFactory = (
|
||||
property: t.ObjectMethod | t.ObjectProperty | t.SpreadElement,
|
||||
):
|
||||
| t.FunctionExpression
|
||||
| t.ArrowFunctionExpression
|
||||
| t.ObjectMethod
|
||||
| undefined => {
|
||||
if (t.isObjectMethod(property)) return property;
|
||||
if (
|
||||
t.isObjectProperty(property) &&
|
||||
(t.isFunctionExpression(property.value) ||
|
||||
t.isArrowFunctionExpression(property.value))
|
||||
)
|
||||
return property.value;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Derive a bounded literal or explicitly computed module key. */
|
||||
export const modulePropertyName = (
|
||||
property: t.ObjectMethod | t.ObjectProperty | t.SpreadElement,
|
||||
): string =>
|
||||
t.isObjectMethod(property) || t.isObjectProperty(property)
|
||||
? property.computed &&
|
||||
!t.isStringLiteral(property.key) &&
|
||||
!t.isNumericLiteral(property.key)
|
||||
? `[computed@${String(property.start ?? -1)}]`
|
||||
: propertyName(property.key).slice(0, 4_096) ||
|
||||
`[unknown@${String(property.start ?? -1)}]`
|
||||
: `[unknown@${String(property.start ?? -1)}]`;
|
||||
|
||||
/** Read the factory-local bundler require parameter when declared. */
|
||||
export const factoryRequireName = (
|
||||
factory: t.FunctionExpression | t.ArrowFunctionExpression | t.ObjectMethod,
|
||||
): string | null => {
|
||||
const parameter = factory.params[2];
|
||||
return t.isIdentifier(parameter) ? parameter.name.slice(0, 4_096) : null;
|
||||
};
|
||||
|
||||
/** Collect bounded unique literal values and explicit omissions from an array. */
|
||||
export const staticArrayValues = (
|
||||
array: t.ArrayExpression,
|
||||
maximum: number,
|
||||
): {
|
||||
readonly values: readonly string[];
|
||||
readonly omitted: number;
|
||||
readonly unknown: number;
|
||||
} => {
|
||||
const staticValues = array.elements.flatMap((element) => {
|
||||
const value = argumentValue(element);
|
||||
return value === undefined ? [] : [value.slice(0, 4_096)];
|
||||
});
|
||||
const values = [...new Set(staticValues)].sort(compareCodePoints);
|
||||
return {
|
||||
values: values.slice(0, maximum),
|
||||
omitted: Math.max(0, values.length - maximum),
|
||||
unknown: array.elements.length - staticValues.length,
|
||||
};
|
||||
};
|
||||
|
||||
/** Resolve a bounded path composed only from inert literal syntax. */
|
||||
export const staticPath = (node: t.Node): string | undefined =>
|
||||
staticPathAt(node, 0);
|
||||
|
||||
const staticPathAt = (node: t.Node, depth: number): string | undefined => {
|
||||
if (depth >= 128) return undefined;
|
||||
if (t.isStringLiteral(node)) return node.value.slice(0, 4_096);
|
||||
if (t.isTemplateLiteral(node) && node.expressions.length === 0) {
|
||||
const value = node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw;
|
||||
return value?.slice(0, 4_096);
|
||||
}
|
||||
if (t.isBinaryExpression(node, { operator: "+" })) {
|
||||
const left = staticPathAt(node.left, depth + 1);
|
||||
const right = staticPathAt(node.right, depth + 1);
|
||||
return left === undefined || right === undefined
|
||||
? undefined
|
||||
: `${left}${right}`.slice(0, 4_096);
|
||||
}
|
||||
if (t.isCallExpression(node) || t.isNewExpression(node))
|
||||
return staticCallPath(node, depth);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const staticCallPath = (
|
||||
node: t.CallExpression | t.NewExpression,
|
||||
depth: number,
|
||||
): string | undefined => {
|
||||
const name = calleeName(node.callee);
|
||||
if (name === "URL" || name.endsWith(".URL"))
|
||||
return stringValue(node.arguments[0]);
|
||||
if (!name.endsWith(".join") && !name.endsWith(".resolve") && name !== "join")
|
||||
return undefined;
|
||||
const parts: string[] = [];
|
||||
for (const argument of node.arguments) {
|
||||
if (t.isIdentifier(argument, { name: "__dirname" })) continue;
|
||||
const value = t.isNode(argument)
|
||||
? staticPathAt(argument, depth + 1)
|
||||
: undefined;
|
||||
if (value === undefined) return undefined;
|
||||
parts.push(value);
|
||||
}
|
||||
return parts.length === 0 ? undefined : posix.join(...parts).slice(0, 4_096);
|
||||
};
|
||||
|
||||
/** Select the literal URL argument for recognized network callees. */
|
||||
export const endpointArgument = (
|
||||
name: string,
|
||||
args: readonly (
|
||||
| t.Expression
|
||||
| t.SpreadElement
|
||||
| t.JSXNamespacedName
|
||||
| t.ArgumentPlaceholder
|
||||
)[],
|
||||
): string | undefined => {
|
||||
if (name === "fetch" || name.endsWith(".fetch") || name === "WebSocket")
|
||||
return stringValue(args[0]);
|
||||
if (name.endsWith(".open") && stringValue(args[1]) !== undefined)
|
||||
return stringValue(args[1]);
|
||||
if (
|
||||
["get", "post", "put", "patch", "delete", "request"].some(
|
||||
(method) => name === method || name.endsWith(`.${method}`),
|
||||
)
|
||||
)
|
||||
return stringValue(args[0]);
|
||||
if (name.endsWith("loadURL")) return stringValue(args[0]);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Classify a recognized storage API call name. */
|
||||
export const storageKind = (
|
||||
name: string,
|
||||
): JavaScriptStaticStorage["kind"] | undefined => {
|
||||
if (name.includes("localStorage.")) return "local-storage";
|
||||
if (name.includes("sessionStorage.")) return "session-storage";
|
||||
if (name.endsWith("indexedDB.open")) return "indexed-db";
|
||||
if (name.endsWith("caches.open")) return "cache-storage";
|
||||
if (name === "Database" || name.endsWith(".Database")) return "sqlite";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Produce a dotted bounded callee name from member syntax. */
|
||||
export const calleeName = (node: t.Node): string => calleeNameAt(node, 0);
|
||||
|
||||
const calleeNameAt = (node: t.Node, depth: number): string => {
|
||||
if (depth >= 128) return "[deep]";
|
||||
if (t.isIdentifier(node)) return node.name.slice(0, 4_096);
|
||||
if (t.isImport(node)) return "import";
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const object = t.isNode(node.object)
|
||||
? calleeNameAt(node.object, depth + 1)
|
||||
: "";
|
||||
const property = propertyName(node.property);
|
||||
return (object === "" ? property : `${object}.${property}`).slice(0, 4_096);
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
/** Read a literal property name without evaluating computed syntax. */
|
||||
export const propertyName = (node: t.Node): string => {
|
||||
if (t.isIdentifier(node)) return node.name.slice(0, 4_096);
|
||||
if (t.isStringLiteral(node) || t.isNumericLiteral(node))
|
||||
return String(node.value).slice(0, 4_096);
|
||||
return "";
|
||||
};
|
||||
|
||||
/** Return a string literal value without evaluating an expression. */
|
||||
export const stringValue = (
|
||||
node: t.Node | null | undefined,
|
||||
): string | undefined =>
|
||||
t.isStringLiteral(node) ? node.value.slice(0, 4_096) : undefined;
|
||||
|
||||
/** Return a string or numeric argument literal. */
|
||||
export const argumentValue = (
|
||||
node: t.Node | null | undefined,
|
||||
): string | undefined => {
|
||||
if (t.isStringLiteral(node) || t.isNumericLiteral(node))
|
||||
return String(node.value).slice(0, 4_096);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Prefix a static argument value when one is available. */
|
||||
export const prefixedArgument = (
|
||||
prefix: string,
|
||||
node: t.Node | null | undefined,
|
||||
): string | undefined => {
|
||||
const value = argumentValue(node);
|
||||
return value === undefined ? undefined : `${prefix}${value}`;
|
||||
};
|
||||
|
||||
/** Retain the exact bounded source span represented by an AST node. */
|
||||
export const sourceSlice = (source: string, node: t.Node): string =>
|
||||
typeof node.start !== "number" || typeof node.end !== "number"
|
||||
? ""
|
||||
: source.slice(node.start, node.end);
|
||||
|
||||
/** Convert Babel locations into the stable graph source-range shape. */
|
||||
export const range = (node: t.Node): JavaScriptSourceRange => ({
|
||||
start: {
|
||||
line: node.loc?.start.line ?? 1,
|
||||
column: node.loc?.start.column ?? 0,
|
||||
},
|
||||
end: {
|
||||
line: node.loc?.end.line ?? node.loc?.start.line ?? 1,
|
||||
column: node.loc?.end.column ?? node.loc?.start.column ?? 0,
|
||||
},
|
||||
});
|
||||
|
||||
/** Convert exact text offsets into a source range. */
|
||||
export const rangeForOffsets = (
|
||||
source: string,
|
||||
start: number,
|
||||
end: number,
|
||||
): JavaScriptSourceRange => ({
|
||||
start: pointForOffset(source, start),
|
||||
end: pointForOffset(source, end),
|
||||
});
|
||||
|
||||
const pointForOffset = (source: string, offset: number) => {
|
||||
const before = source.slice(0, offset);
|
||||
const lines = before.split("\n");
|
||||
return { line: lines.length, column: lines.at(-1)?.length ?? 0 };
|
||||
};
|
||||
|
||||
/** Observe known bundler/framework marker strings without claiming dependency use. */
|
||||
export const detectVendors = (source: string): string[] =>
|
||||
vendorPatterns.flatMap(({ name, patterns }) =>
|
||||
patterns.some((pattern) => source.includes(pattern)) ? [name] : [],
|
||||
);
|
||||
|
||||
/** Remove credentials, fragments, and query values from endpoint candidates. */
|
||||
export const sanitizeCandidate = (value: string): string => {
|
||||
const bounded = value.slice(0, 4_096);
|
||||
try {
|
||||
const parsed = new URL(bounded, "https://rea.invalid");
|
||||
const sanitized = sanitizeBrowserUrl(parsed.href).url;
|
||||
return parsed.origin === "https://rea.invalid"
|
||||
? sanitized.replace("https://rea.invalid", "")
|
||||
: sanitized;
|
||||
} catch {
|
||||
return bounded.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
}
|
||||
};
|
||||
|
||||
/** Commit the static semantic content used to deduplicate registrations. */
|
||||
export const registrationKey = (
|
||||
registration: JavaScriptBundlerRegistration,
|
||||
): string =>
|
||||
`${registration.runtime}\0${registration.chunk_keys.join("\0")}\0${String(registration.omitted_chunk_keys)}\0${String(registration.unknown_chunk_keys)}\0${registration.modules.map(({ module_key: key, source_sha256: digest }) => `${key}:${digest}`).join("\0")}`;
|
||||
|
||||
/** Sort values by a deterministic unique semantic key. */
|
||||
export const sortedUnique = <Value>(
|
||||
values: readonly Value[],
|
||||
key: (value: Value) => string,
|
||||
): Value[] =>
|
||||
[...new Map(values.map((value) => [key(value), value])).values()].sort(
|
||||
(left, right) => compareCodePoints(key(left), key(right)),
|
||||
);
|
||||
|
||||
/** Hash exact UTF-8 source text. */
|
||||
export const sha256Text = (value: string): string =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
|
||||
/** Compare strings by Unicode code point for canonical ordering. */
|
||||
export const compareCodePoints = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
|
||||
/** Recognized route-construction call suffixes. */
|
||||
export const STATIC_ROUTE_CALL_NAMES = [
|
||||
"route",
|
||||
"addRoute",
|
||||
"useRoutes",
|
||||
"createBrowserRouter",
|
||||
"createHashRouter",
|
||||
] as const;
|
||||
|
||||
const vendorPatterns = [
|
||||
{ name: "webpack", patterns: ["__webpack_require__", "webpackChunk"] },
|
||||
{ name: "Rspack", patterns: ["__webpack_require__.f", "rspackChunk"] },
|
||||
{ name: "Vite", patterns: ["__vite__", "import.meta.hot"] },
|
||||
{ name: "React", patterns: ["React.createElement", "react/jsx-runtime"] },
|
||||
{ name: "Vue", patterns: ["__VUE__", "createApp("] },
|
||||
{ name: "Next.js", patterns: ["__NEXT_DATA__", "/_next/"] },
|
||||
{ name: "Angular", patterns: ["ɵɵdefineComponent"] },
|
||||
{ name: "Svelte", patterns: ["svelte/internal"] },
|
||||
] as const;
|
||||
@@ -0,0 +1,93 @@
|
||||
import type * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
JavaScriptBundlerRegistration,
|
||||
JavaScriptRolePath,
|
||||
JavaScriptStaticAnalysis,
|
||||
JavaScriptStaticEndpoint,
|
||||
JavaScriptStaticReference,
|
||||
JavaScriptStaticStorage,
|
||||
} from "./javascriptStaticAnalysisTypes.js";
|
||||
|
||||
/** Source offsets for one recovered bundle module factory. */
|
||||
export interface JavaScriptModuleRange {
|
||||
readonly start: number;
|
||||
readonly end: number;
|
||||
readonly key: string;
|
||||
readonly requireName: string | null;
|
||||
}
|
||||
|
||||
/** Static finding retained with its source offset until module attribution. */
|
||||
export interface LocatedJavaScriptFinding<Value> {
|
||||
readonly offset: number;
|
||||
readonly value: Value;
|
||||
}
|
||||
|
||||
/** Mutable bounded collections used during one inert AST traversal. */
|
||||
export interface JavaScriptAnalysisAccumulator {
|
||||
readonly references: LocatedJavaScriptFinding<JavaScriptStaticReference>[];
|
||||
readonly endpoints: LocatedJavaScriptFinding<JavaScriptStaticEndpoint>[];
|
||||
readonly storage: LocatedJavaScriptFinding<JavaScriptStaticStorage>[];
|
||||
readonly roles: LocatedJavaScriptFinding<JavaScriptRolePath>[];
|
||||
readonly sourceMaps: JavaScriptStaticAnalysis["source_map_urls"][number][];
|
||||
readonly registrations: JavaScriptBundlerRegistration[];
|
||||
readonly modules: JavaScriptModuleRange[];
|
||||
readonly seen: Set<string>;
|
||||
visitedNodes: number;
|
||||
droppedFindings: number;
|
||||
moduleCount: number;
|
||||
unknownFindings: number;
|
||||
structuralTruncation: boolean;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
/** Shared source, accumulator, and finding bound for helper inspections. */
|
||||
export interface JavaScriptFindingContext {
|
||||
readonly source: string;
|
||||
readonly accumulator: JavaScriptAnalysisAccumulator;
|
||||
readonly maximum: number;
|
||||
}
|
||||
|
||||
/** Candidate import, require, worker, or service-worker reference. */
|
||||
export interface JavaScriptReferenceInput {
|
||||
readonly node: t.Node;
|
||||
readonly kind: JavaScriptStaticReference["kind"];
|
||||
readonly specifier: string | undefined;
|
||||
}
|
||||
|
||||
/** Candidate route or network endpoint literal. */
|
||||
export interface JavaScriptEndpointInput {
|
||||
readonly node: t.Node;
|
||||
readonly kind: JavaScriptStaticEndpoint["kind"];
|
||||
readonly value: string;
|
||||
readonly mechanism: string;
|
||||
}
|
||||
|
||||
/** Values required to append one module-attributable static finding. */
|
||||
export interface LocatedJavaScriptFindingInput<
|
||||
Value extends { readonly module_key: string | null },
|
||||
> {
|
||||
readonly collection: LocatedJavaScriptFinding<Value>[];
|
||||
readonly key: string;
|
||||
readonly node: t.Node;
|
||||
readonly value: Value;
|
||||
}
|
||||
|
||||
/** Create isolated mutable state for one bounded source analysis. */
|
||||
export const createJavaScriptAnalysisAccumulator =
|
||||
(): JavaScriptAnalysisAccumulator => ({
|
||||
references: [],
|
||||
endpoints: [],
|
||||
storage: [],
|
||||
roles: [],
|
||||
sourceMaps: [],
|
||||
registrations: [],
|
||||
modules: [],
|
||||
seen: new Set(),
|
||||
visitedNodes: 0,
|
||||
droppedFindings: 0,
|
||||
moduleCount: 0,
|
||||
unknownFindings: 0,
|
||||
structuralTruncation: false,
|
||||
truncated: false,
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
/** One source coordinate produced by the JavaScript parser. */
|
||||
export interface JavaScriptSourcePoint {
|
||||
readonly line: number;
|
||||
readonly column: number;
|
||||
}
|
||||
|
||||
/** One exact source range within a bounded JavaScript artifact. */
|
||||
export interface JavaScriptSourceRange {
|
||||
readonly start: JavaScriptSourcePoint;
|
||||
readonly end: JavaScriptSourcePoint;
|
||||
}
|
||||
|
||||
/** A statically visible module, worker, or service-worker reference. */
|
||||
export interface JavaScriptStaticReference {
|
||||
readonly kind:
|
||||
| "static-import"
|
||||
| "dynamic-import"
|
||||
| "require"
|
||||
| "worker"
|
||||
| "service-worker";
|
||||
readonly specifier: string | null;
|
||||
readonly expression: string | null;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** A route or network endpoint literal observed in syntax. */
|
||||
export interface JavaScriptStaticEndpoint {
|
||||
readonly kind: "route" | "network";
|
||||
readonly value: string;
|
||||
readonly mechanism: string;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** A storage surface observed without executing application code. */
|
||||
export interface JavaScriptStaticStorage {
|
||||
readonly kind:
|
||||
| "local-storage"
|
||||
| "session-storage"
|
||||
| "indexed-db"
|
||||
| "cache-storage"
|
||||
| "sqlite";
|
||||
readonly name: string | null;
|
||||
readonly mechanism: string;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One exact module factory recovered from a Webpack/Rspack registration. */
|
||||
export interface JavaScriptBundlerModule {
|
||||
readonly module_key: string;
|
||||
readonly source_sha256: string;
|
||||
readonly structural_fingerprint_sha256: string | null;
|
||||
readonly structural_fingerprint_algorithm: "babel-ast-v1" | null;
|
||||
readonly structural_fingerprint_status: "complete" | "truncated";
|
||||
readonly exports: readonly string[];
|
||||
readonly exports_truncated: boolean;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One statically recognized Webpack/Rspack chunk registration. */
|
||||
export interface JavaScriptBundlerRegistration {
|
||||
readonly bundler: "webpack" | "rspack";
|
||||
readonly runtime: string;
|
||||
readonly chunk_keys: readonly string[];
|
||||
readonly omitted_chunk_keys: number;
|
||||
readonly unknown_chunk_keys: number;
|
||||
readonly modules: readonly JavaScriptBundlerModule[];
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** Static Electron role paths discovered from package or JavaScript syntax. */
|
||||
export interface JavaScriptRolePath {
|
||||
readonly role: "preload" | "renderer";
|
||||
readonly path: string;
|
||||
readonly mechanism: string;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** Bounded, deterministic AST-only analysis of one JavaScript source file. */
|
||||
export interface JavaScriptStaticAnalysis {
|
||||
readonly parse_status: "complete" | "partial" | "failed" | "truncated";
|
||||
readonly parse_error_count: number;
|
||||
readonly visited_ast_nodes: number;
|
||||
readonly dropped_findings: number;
|
||||
readonly references: readonly JavaScriptStaticReference[];
|
||||
readonly endpoints: readonly JavaScriptStaticEndpoint[];
|
||||
readonly storage: readonly JavaScriptStaticStorage[];
|
||||
readonly bundler_registrations: readonly JavaScriptBundlerRegistration[];
|
||||
readonly role_paths: readonly JavaScriptRolePath[];
|
||||
readonly source_map_urls: readonly {
|
||||
readonly declared_url: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}[];
|
||||
readonly vendors: readonly string[];
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Hard bounds applied to one AST-only JavaScript analysis. */
|
||||
export interface JavaScriptStaticAnalysisLimits {
|
||||
readonly maxAstNodes: number;
|
||||
readonly maxFindings: number;
|
||||
readonly maxModules: number;
|
||||
readonly deadline: number;
|
||||
readonly now: () => number;
|
||||
}
|
||||
Reference in New Issue
Block a user