feat(artifact): reconstruct JavaScript application structure

This commit is contained in:
N0zoM1z0
2026-07-16 06:43:30 +09:00
committed by N0zoM1z0
parent da4817abd1
commit aa46abfe1b
174 changed files with 11773 additions and 74 deletions
+186
View File
@@ -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;
+494
View File
@@ -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,
});
+108
View File
@@ -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;
}