fix(javascript): trace wrapped Electron IPC paths in large bundles (#1874)

Co-authored-by: David <17119984+fengdwx@users.noreply.github.com>
This commit is contained in:
David
2026-10-12 09:28:59 +08:00
committed by GitHub
co-authored by David
parent d93fbda390
commit 87b9793c53
46 changed files with 3213 additions and 355 deletions
@@ -175,7 +175,7 @@ const addValidation = (
});
};
const ipcDescriptor = (
export const ipcDescriptor = (
path: readonly string[] | undefined,
): ElectronIpcDescriptor | undefined => {
if (path?.length !== 2) return undefined;
@@ -201,6 +201,7 @@ const ipcDescriptor = (
operation: "send-to-host",
mode: "send",
};
case "addListener":
case "on":
return { side: "renderer", operation: "on", mode: "listen" };
case "once":
@@ -209,6 +210,7 @@ const ipcDescriptor = (
}
const main = object === "ipcMain" ? operation : undefined;
switch (main) {
case "addListener":
case "on":
return { side: "main", operation: "on", mode: "listen" };
case "once":
@@ -52,6 +52,7 @@ export type ElectronContextBridgeApiKey =
/** One contextBridge API declaration without executing its API object. */
export type ElectronContextBridgeFinding = ElectronContextBridgeApiKey & {
readonly resolution_basis?: "wrapper-substitution";
readonly world: "main" | "isolated";
readonly world_id: ElectronStaticValue | null;
readonly api_status: "object-literal" | "dynamic" | "missing";
@@ -112,6 +113,8 @@ type ElectronIpcHandler =
};
interface ElectronIpcFindingContext {
/** Absent on direct syntax observations; wrappers require inferred evidence. */
readonly resolution_basis?: "wrapper-substitution";
readonly module_key: string | null;
/** Recovered factory runtime; absent in older or unbundled findings. */
readonly module_runtime?: string;
@@ -192,4 +195,34 @@ export interface ElectronStaticFindings {
readonly sender_validations: readonly ElectronSenderValidationFinding[];
readonly utility_processes: readonly ElectronUtilityProcessFinding[];
readonly native_addon_bindings: readonly ElectronNativeAddonBindingFinding[];
/** Source-bound candidate paths through bundled exports and IPC closures. */
readonly call_paths?: readonly ElectronCallPath[];
}
export interface ElectronCallPathStep {
readonly kind:
| "exposure"
| "factory"
| "function"
| "call"
| "ipc"
| "terminal";
readonly label: string;
readonly location: JavaScriptSourceRange;
readonly module_key: string | null;
readonly module_runtime: string | null;
}
/** A statically substituted candidate, never a runtime reachability claim. */
export interface ElectronCallPath {
readonly entry_kind: "bridge-member" | "ipc-handler";
readonly entry: string;
readonly channel: string | null;
readonly terminal: string;
readonly resolution: "candidate";
readonly steps: readonly ElectronCallPathStep[];
readonly conditions: readonly {
readonly expression: string;
readonly location: JavaScriptSourceRange;
}[];
}
@@ -0,0 +1,260 @@
import { describe, expect, it } from "vitest";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
const bundle = (entry: string) => `(() => {
const modules = {
2(module) { module.exports = require("electron"); },
5(module,exports,load) {
const electron=load(2);
Object.defineProperty(exports,"__esModule",{value:true});
exports.sender = function(channel) {return (...args)=>send(channel,...args)};
function send(channel,...args) {electron.ipcRenderer.send(channel,...args)}
exports.events = {addListener(channel,handler) {
const guarded = (event,...args) => {if (allowed(event)) handler(event,...args)};
return electron.ipcMain.addListener(channel,guarded);
}};
},
9(module,exports,load) {const electron=load(2), helper=load(5); ${entry}}
};
function load(id) {const m={exports:{}};modules[id].call(m.exports,m,m.exports,load);return m.exports;}
load(9);
})();`;
describe("wrapped Electron control-flow alternatives", () => {
it.each(["flag ? copy : cut", "flag ? copy : unknownHandler", "choose()"])(
"does not select one IPC handler from %s",
(handler) => {
const result = analyzeJavaScriptStaticSource(`
const e = require("electron");
const copy = event => event.sender.copy();
const cut = event => event.sender.cut();
function choose() { if (flag) return copy; }
function register(channel, handler) { e.ipcMain.on(channel, handler); }
register("test:copy", ${handler});
`);
expect(result.electron.ipc).toContainEqual(
expect.objectContaining({
channel: "test:copy",
side: "main",
handler_kind: "dynamic-expression",
resolution_basis: "wrapper-substitution",
}),
);
expect(result.electron.call_paths ?? []).toEqual([]);
expect(result.parse_status).toBe("partial");
},
);
it.each(["'ready'", "false", "0", "''", "({})", "(()=>{})"])(
"short-circuits nullish fallback for %s in callbacks and seed calls",
(left) => {
for (const source of [
`e.ipcMain.on("test:copy", event => { ${left} ?? event.sender.copy(); });`,
`${left} ?? e.ipcMain.on("test:copy", event => event.sender.copy());`,
`e.ipcMain.on("test:copy", event => { const selected = ${left} ?? (()=>event.sender.copy()); selected(); });`,
])
expect(
analyzeJavaScriptStaticSource(`const e=require("electron");${source}`)
.electron.call_paths ?? [],
).toEqual([]);
},
);
it.each(["null", "undefined", "void 0"])(
"follows nullish fallback for %s",
(left) => {
const result = analyzeJavaScriptStaticSource(`const e=require("electron");
${left} ?? e.ipcMain.on("test:copy", event => { ${left} ?? event.sender.copy(); });`);
expect(result.electron.call_paths).toContainEqual(
expect.objectContaining({
terminal: "ipc-event.sender.copy",
conditions: [],
}),
);
},
);
it("retains a nullish guard for unknown fallback rather than a falsy guard", () => {
for (const source of [
`e.ipcMain.on("test:copy", event => { value ?? event.sender.copy(); });`,
`value ?? e.ipcMain.on("test:copy", event => event.sender.copy());`,
]) {
const result = analyzeJavaScriptStaticSource(
`const e=require("electron");${source}`,
);
expect(result.electron.call_paths).toContainEqual(
expect.objectContaining({
terminal: "ipc-event.sender.copy",
conditions: [
expect.objectContaining({
expression: "(value) === null || (value) === undefined",
}),
],
}),
);
}
});
it.each([
"if (flag) return copy; else return cut; return dead;",
"if (flag) { return copy; } return cut;",
"if (flag) { if (other) return copy; else return cut; } else return cut; return dead;",
])("retains every possible factory return: %s", (body) => {
const result = analyzeJavaScriptStaticSource(`const e=require("electron");
const copy=()=>e.ipcRenderer.send("test:copy"), cut=()=>e.ipcRenderer.send("test:cut"), dead=()=>e.ipcRenderer.send("test:dead");
function choose(){${body}}
e.contextBridge.exposeInMainWorld("desktop", {copy:choose()});`);
expect(
[
...new Set(result.electron.call_paths?.map((path) => path.channel)),
].sort(),
).toEqual(["test:copy", "test:cut"]);
});
});
describe("wrapped Electron call paths", () => {
it("connects exposed closures to IPC sends and text clipboard calls", () => {
const result = analyzeJavaScriptStaticSource(
bundle(`
const text = value => navigator.clipboard.writeText(value);
const api={copy:helper.sender("example:copy"),copyText:text};
electron.contextBridge.exposeInMainWorld("desktop",api);
`),
);
expect(result.electron.context_bridge_apis).toMatchObject([
{ api_key: "desktop", members: ["copy", "copyText"] },
]);
expect(result.electron.ipc).toContainEqual(
expect.objectContaining({
side: "renderer",
channel: "example:copy",
operation: "send",
}),
);
expect(result.electron.call_paths).toEqual(
expect.arrayContaining([
expect.objectContaining({
entry: "desktop.copy",
channel: "example:copy",
terminal: "electron.ipcRenderer.send",
}),
expect.objectContaining({
entry: "desktop.copyText",
terminal: "navigator.clipboard.writeText",
}),
]),
);
});
it("substitutes guarded listener callbacks and preserves guard evidence", () => {
const result = analyzeJavaScriptStaticSource(
bundle(
`helper.events.addListener("example:copy",event=>event.sender.copy());`,
),
);
expect(result.electron.ipc).toContainEqual(
expect.objectContaining({
side: "main",
channel: "example:copy",
operation: "on",
}),
);
expect(result.electron.call_paths).toContainEqual(
expect.objectContaining({
entry_kind: "ipc-handler",
channel: "example:copy",
terminal: "ipc-event.sender.copy",
conditions: [expect.objectContaining({ expression: "allowed(event)" })],
}),
);
});
it("does not identify overwritten Electron namespaces or shadowed require", () => {
for (const source of [
`const e=require("electron");e.ipcMain={on(){}};e.ipcMain.on("bad",event=>event.sender.copy());`,
`function require(){return {ipcMain:{on(){}}}};const e=require("electron");e.ipcMain.on("bad",event=>event.sender.copy());`,
])
expect(
analyzeJavaScriptStaticSource(source).electron.call_paths ?? [],
).toEqual([]);
});
it("does not follow a statically false callback branch", () => {
const result = analyzeJavaScriptStaticSource(
bundle(
`helper.events.addListener("example:copy",event=>{if(false)event.sender.copy()});`,
),
);
expect(result.electron.call_paths ?? []).toEqual([]);
});
it("retains early rejection guards and excludes calls after definite returns", () => {
const guarded = analyzeJavaScriptStaticSource(
`const e=require("electron");e.ipcMain.on("guard",event=>{if(!allowed(event))return;event.sender.copy()});`,
);
expect(guarded.electron.call_paths).toContainEqual(
expect.objectContaining({
conditions: [
expect.objectContaining({ expression: "!(!allowed(event))" }),
],
}),
);
for (const body of [
"return;event.sender.copy()",
"if(true)return;event.sender.copy()",
"if(false)event.sender.copy()",
])
expect(
analyzeJavaScriptStaticSource(
`const e=require("electron");e.ipcMain.on("dead",event=>{${body}});`,
).electron.call_paths ?? [],
).toEqual([]);
expect(
analyzeJavaScriptStaticSource(
`const e=require("electron");if(false)e.ipcMain.on("dead",event=>event.sender.copy());`,
).electron.call_paths ?? [],
).toEqual([]);
});
it("rejects dynamic channels, computed overwrites, unknown spreads and reassigned callback parameters", () => {
for (const entry of [
`helper.events.addListener(runtimeChannel,event=>event.sender.copy());`,
`electron[runtimeKey]={};electron.ipcMain.on("bad",event=>event.sender.copy());`,
`const api={copy:helper.sender("bad"),...unknownApi};electron.contextBridge.exposeInMainWorld("desktop",api);`,
`helper.events.addListener("bad",event=>{event=other;event.sender.copy()});`,
])
expect(
analyzeJavaScriptStaticSource(bundle(entry)).electron.call_paths ?? [],
).toEqual([]);
});
it("resolves renamed default and namespace import helpers from their syntax", () => {
const result = analyzeJavaScriptStaticSource(
bundle(`
const defaultImport=x=>x&&x.__esModule?x:{default:x};
function namespaceImport(x){if(x&&x.__esModule)return x;return unknownWrap(x)}
const E=defaultImport(load(2)),H=namespaceImport(load(5));
E.default.contextBridge.exposeInMainWorld("renamed",{copy:(0,H.sender)("test:renamed")});
`),
);
expect(result.electron.call_paths).toContainEqual(
expect.objectContaining({
entry: "renamed.copy",
channel: "test:renamed",
terminal: "electron.ipcRenderer.send",
}),
);
expect(
result.electron.call_paths
?.flatMap((p) => p.steps)
.every((step) => step.label.length > 0),
).toBe(true);
});
it("does not trust helper names or follow returns after a definite throw", () => {
for (const helper of [
`function __toESM() {return {ipcRenderer:{send(){}}}}`,
`function __toESM(value) {throw Error("inert");return value;}`,
`function __toESM(value) {if(true){throw Error("inert")}return value;}`,
]) {
const result = analyzeJavaScriptStaticSource(`
const electron = require("electron");
${helper}
const wrapped = __toESM(electron);
electron.contextBridge.exposeInMainWorld("desktop",{
copy:()=>wrapped.ipcRenderer.send("test:copy")
});
`);
expect(result.electron.call_paths ?? []).toEqual([]);
}
});
});
@@ -0,0 +1,461 @@
import * as t from "@babel/types";
import { JavaScriptSymbolicBindings } from "./javascriptSymbolicBindings.js";
import {
symbolicVariants,
symbolicTruth,
symbolicUnknown,
type SymbolicValue,
type SymbolicEnvironment,
type SymbolicFunction,
} from "./javascriptSymbolicValues.js";
import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js";
import type { JavaScriptAnalysisAccumulator } from "./javascriptStaticAnalysisState.js";
import type {
ElectronCallPath,
ElectronCallPathStep,
ElectronIpcDescriptor,
ElectronIpcFinding,
} from "./electronStaticAnalysisTypes.js";
import {
childNodes,
traverseJavaScriptAst,
} from "./javascriptSemanticTraversal.js";
import { range, calleeName } from "./javascriptStaticAnalysisHelpers.js";
import { ipcDescriptor } from "./electronStaticAnalysisIpc.js";
import {
symbolicDefiniteExit,
symbolicLogicalRight,
} from "./javascriptSymbolicControlFlow.js";
const callLabel = (node: t.Node): string =>
t.isSequenceExpression(node)
? callLabel(node.expressions.at(-1) ?? node)
: calleeName(node) || "local call";
interface PathContext {
readonly entryNode: t.Node;
readonly entry: string;
readonly entryKind: ElectronCallPath["entry_kind"] | null;
readonly channel: string | null;
readonly steps: readonly ElectronCallPathStep[];
readonly conditions: ElectronCallPath["conditions"];
readonly active: ReadonlySet<t.Function>;
}
/** Substitutes inert wrapper syntax; every emitted path remains a candidate. */
export const collectElectronWrappedCallPaths = (
program: t.Program,
state: JavaScriptSemanticAnalysisState,
source: string,
accumulator: JavaScriptAnalysisAccumulator,
): readonly ElectronCallPath[] => {
// Bounds repeated interprocedural expansion independently of bundle bytes.
// Exhaustion is reported as unknown coverage, never as a negative finding.
let remainingVisits = 1_000_000;
const resolver = new JavaScriptSymbolicBindings(state, program);
const paths: ElectronCallPath[] = [];
const seen = new Set<string>();
const step = (
node: t.Node,
kind: ElectronCallPathStep["kind"],
label: string,
): ElectronCallPathStep => {
const module = accumulator.moduleRangeIndex.find(node.start);
return {
kind,
label,
location: range(node),
module_key: module?.key ?? null,
module_runtime: module?.runtime ?? null,
};
};
const condition = (
context: PathContext,
node: t.Node,
positive: boolean | "nullish" = true,
): PathContext => {
const expression = source
.slice(node.start ?? 0, node.end ?? 0)
.slice(0, 512);
return {
...context,
conditions: [
...context.conditions,
{
expression:
positive === "nullish"
? `(${expression}) === null || (${expression}) === undefined`
: positive
? expression
: `!(${expression})`,
location: range(node),
},
],
};
};
const emit = (
context: PathContext,
node: t.Node,
terminal: string,
channel = context.channel,
): void => {
if (context.entryKind === null) return;
const path: ElectronCallPath = {
entry_kind: context.entryKind,
entry: context.entry,
channel,
terminal,
resolution: "candidate",
steps: [...context.steps, step(node, "terminal", terminal)],
conditions: context.conditions,
};
const key = JSON.stringify(path);
if (seen.has(key)) return;
seen.add(key);
paths.push(path);
};
const functionBody = (
fn: SymbolicFunction,
args: readonly SymbolicValue[],
context: PathContext,
): void => {
if (context.active.has(fn.node)) return;
const name =
(t.isFunctionExpression(fn.node) || t.isFunctionDeclaration(fn.node)) &&
fn.node.id
? fn.node.id.name
: "closure";
walk(fn.node.body, resolver.bind(fn, args), {
...context,
steps: [
...context.steps,
...fn.origins.map((n) =>
step(
n,
"factory",
t.isCallExpression(n) ? callLabel(n.callee) : "factory",
),
),
step(fn.node, "function", name),
],
active: new Set([...context.active, fn.node]),
});
};
const ipc = (
node: t.CallExpression | t.OptionalCallExpression,
descriptor: ElectronIpcDescriptor,
args: readonly SymbolicValue[],
context: PathContext,
endpoint: string,
): void => {
const first = args[0];
if (first?.kind !== "literal" || typeof first.value !== "string") return;
const channel = first.value;
const location = range(context.entryNode);
const handlers = symbolicVariants(
args[1] ?? symbolicUnknown("missing handler"),
);
// A channel registration must not acquire one arbitrary handler from a union.
// Keep the unresolved registration so it still competes with other handlers.
const fn =
handlers.length === 1 && handlers[0]?.kind === "function"
? handlers[0]
: undefined;
const handlerNode = node.arguments[1];
const finding: ElectronIpcFinding =
descriptor.mode === "send" || descriptor.mode === "invoke"
? {
...descriptor,
channel,
channel_expression: null,
handler_kind: null,
handler_location: null,
module_key: null,
location,
}
: fn
? {
...descriptor,
channel,
channel_expression: null,
handler_kind: "inline-function",
handler_location: range(fn.node),
module_key: null,
location,
}
: handlerNode
? {
...descriptor,
channel,
channel_expression: null,
handler_kind: "dynamic-expression",
handler_location: range(handlerNode),
module_key: null,
location,
}
: {
...descriptor,
channel,
channel_expression: null,
handler_kind: "missing",
handler_location: null,
module_key: null,
location,
};
const duplicate = accumulator.ipc.some(
({ value }) =>
value.side === finding.side &&
value.operation === finding.operation &&
value.channel === channel &&
[JSON.stringify(location), JSON.stringify(range(node))].includes(
JSON.stringify(value.location),
),
);
if (!duplicate) {
accumulator.ipc.push({
offset: context.entryNode.start ?? -1,
value: { ...finding, resolution_basis: "wrapper-substitution" },
});
if (descriptor.mode !== "send" && descriptor.mode !== "invoke" && !fn)
accumulator.unknownFindings += 1;
}
if (descriptor.mode === "send" || descriptor.mode === "invoke") {
emit(context, node, endpoint, channel);
return;
}
if (descriptor.side === "main" && fn)
functionBody(
fn,
[
{ kind: "external", path: ["ipc-event"] },
symbolicUnknown("IPC payload"),
],
{
...context,
entryKind: "ipc-handler",
entry: channel,
channel,
steps: [...context.steps, step(node, "ipc", endpoint)],
},
);
};
const bridge = (
node: t.CallExpression | t.OptionalCallExpression,
args: readonly SymbolicValue[],
context: PathContext,
): void => {
const key = args[0];
const object = args[1];
if (key?.kind !== "literal" || typeof key.value !== "string" || !object)
return;
const members = [...resolver.members(object)].sort();
const location = range(node);
const existing = accumulator.contextBridgeApis.find(
({ value }) =>
JSON.stringify(value.location) === JSON.stringify(location),
);
const finding = {
world: "main" as const,
world_id: null,
api_key: key.value,
api_key_expression: null,
api_status: "dynamic" as const,
resolution_basis: "wrapper-substitution" as const,
members,
unknown_members: resolver.unknownMembers(object),
module_key: null,
location,
};
if (existing)
existing.value.members.length === 0 &&
accumulator.contextBridgeApis.splice(
accumulator.contextBridgeApis.indexOf(existing),
1,
{ offset: node.start ?? -1, value: finding },
);
else
accumulator.contextBridgeApis.push({
offset: node.start ?? -1,
value: finding,
});
for (const name of members) {
const value = resolver.property(object, name);
for (const fn of symbolicVariants(value))
if (fn.kind === "function") {
functionBody(
fn,
fn.node.params.map(() => symbolicUnknown("public API argument")),
{
...context,
entryNode: node,
entryKind: "bridge-member",
entry: `${key.value}.${name}`,
channel: null,
steps: [step(node, "exposure", `${key.value}.${name}`)],
active: new Set(),
},
);
}
}
};
const call = (
node: t.CallExpression | t.OptionalCallExpression,
env: SymbolicEnvironment,
context: PathContext,
): void => {
const value = resolver.evaluate(node.callee, env);
const args = resolver.arguments(node, env);
for (const callee of symbolicVariants(value)) {
if (callee.kind === "function") {
functionBody(callee, args, {
...context,
steps: [...context.steps, step(node, "call", callLabel(node.callee))],
});
} else if (callee.kind === "external") {
const path = callee.path;
const endpoint = path.join(".");
if (/^electron(?:\/(?:main|renderer|common))?$/u.test(path[0] ?? "")) {
const descriptor = ipcDescriptor(path.slice(1));
if (descriptor) ipc(node, descriptor, args, context, endpoint);
else if (
path.slice(1).join(".") === "contextBridge.exposeInMainWorld"
)
bridge(node, args, context);
else if (path[1] === "clipboard") emit(context, node, endpoint);
} else if (
(path[0] === "navigator" && path[1] === "clipboard") ||
(path[0] === "ipc-event" && path[1] === "sender")
)
emit(context, node, endpoint);
}
}
};
function walk(
node: t.Node,
env: SymbolicEnvironment,
context: PathContext,
): void {
if (--remainingVisits < 0 || t.isFunction(node) || t.isClass(node)) return;
if (t.isBlockStatement(node)) {
let next = context;
for (const statement of node.body) {
walk(statement, env, next);
if (symbolicDefiniteExit(statement)) break;
if (t.isIfStatement(statement)) {
const truth = symbolicTruth(resolver.evaluate(statement.test, env));
if (truth !== undefined) {
if (
symbolicDefiniteExit(
truth ? statement.consequent : statement.alternate,
)
)
break;
} else if (symbolicDefiniteExit(statement.consequent))
next = condition(next, statement.test, false);
else if (symbolicDefiniteExit(statement.alternate))
next = condition(next, statement.test);
}
}
return;
}
if (t.isIfStatement(node) || t.isConditionalExpression(node)) {
const truth = symbolicTruth(resolver.evaluate(node.test, env));
if (truth !== false)
walk(
node.consequent,
env,
truth === undefined ? condition(context, node.test) : context,
);
if (truth !== true && node.alternate)
walk(
node.alternate,
env,
truth === undefined ? condition(context, node.test, false) : context,
);
return;
}
if (t.isLogicalExpression(node)) {
walk(node.left, env, context);
const right = symbolicLogicalRight(
node.operator,
resolver.evaluate(node.left, env),
);
if (right === false) return;
walk(
node.right,
env,
right === undefined
? condition(
context,
node.left,
node.operator === "??" ? "nullish" : node.operator === "&&",
)
: context,
);
return;
}
if (t.isCallExpression(node) || t.isOptionalCallExpression(node))
call(node, env, context);
for (const child of childNodes(node)) walk(child, env, context);
}
traverseJavaScriptAst(program, {
enter: (node) => {
if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node))
return;
if (!t.isStringLiteral(node.arguments[0])) return;
const env = resolver.environmentAt(node);
let context: PathContext = {
entryNode: node,
entry: "",
entryKind: null,
channel: null,
steps: [],
conditions: [],
active: new Set(),
};
for (
let child: t.Node = node, parent = state.parentsByNode.get(child);
parent && !t.isFunction(parent);
child = parent, parent = state.parentsByNode.get(child)
) {
if (t.isIfStatement(parent) || t.isConditionalExpression(parent)) {
if (child === parent.test) continue;
const truth = symbolicTruth(resolver.evaluate(parent.test, env));
const positive = child === parent.consequent;
if (truth !== undefined && truth !== positive) return;
if (truth === undefined)
context = condition(context, parent.test, positive);
} else if (t.isLogicalExpression(parent) && child === parent.right) {
const right = symbolicLogicalRight(
parent.operator,
resolver.evaluate(parent.left, env),
);
if (right === false) return;
if (right === undefined)
context = condition(
context,
parent.left,
parent.operator === "??" ? "nullish" : parent.operator === "&&",
);
} else if (t.isBlockStatement(parent)) {
const index = parent.body.findIndex(
(statement) => statement === child,
);
if (
index >= 0 &&
parent.body
.slice(0, index)
.some((statement) => symbolicDefiniteExit(statement))
)
return;
}
}
call(node, env, context);
},
});
if (remainingVisits < 0 || resolver.truncated) {
accumulator.unknownFindings += 1;
accumulator.electronCallPathLimitReached = true;
}
return paths;
};
@@ -0,0 +1,22 @@
import { expect, it } from "vitest";
import { javaScriptAnalysisResourceControlsSchema } from "./javascriptAnalysisResourceControls.js";
it("keeps omitted operational choices absent and validates explicit semantic budgets", () => {
expect(javaScriptAnalysisResourceControlsSchema.parse({})).toEqual({});
expect(
javaScriptAnalysisResourceControlsSchema.parse({
max_semantic_nodes: 750_000,
max_semantic_nodes_per_file: 700_000,
}),
).toEqual({
max_semantic_nodes: 750_000,
max_semantic_nodes_per_file: 700_000,
});
for (const value of [0, -1, 1.5, 1_000_001, Infinity, NaN]) {
for (const key of ["max_semantic_nodes", "max_semantic_nodes_per_file"])
expect(
javaScriptAnalysisResourceControlsSchema.safeParse({ [key]: value })
.success,
).toBe(false);
}
});
@@ -6,8 +6,13 @@ import type { ApplicationCoverage } from "./javascriptApplicationEvidenceSchemas
export const JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS = {
heapMb: 1024,
timeoutMs: 300_000,
semanticNodes: 100_000,
semanticNodesPerFile: 20_000,
} as const;
/** Maximum caller-selected node capacity; heap and transfer admission still apply. */
export const JAVASCRIPT_SEMANTIC_NODE_MAXIMUM = 1_000_000;
/** Project observed execution limits without inventing unmeasured values. */
export const javaScriptAnalysisCoverageLimits = (
limits: Readonly<Record<string, JsonValue>> | null,
@@ -37,6 +42,24 @@ export const javaScriptAnalysisCoverageLimits = (
/** Optional operational choices; omission keeps them out of Evidence parameters. */
export const javaScriptAnalysisResourceControlsSchema = z.strictObject({
max_semantic_nodes: z
.number()
.int()
.min(1)
.max(JAVASCRIPT_SEMANTIC_NODE_MAXIMUM)
.optional()
.describe(
"Maximum retained semantic nodes across the application; defaults to 100000. Worker heap and parent result admission remain enforced.",
),
max_semantic_nodes_per_file: z
.number()
.int()
.min(1)
.max(JAVASCRIPT_SEMANTIC_NODE_MAXIMUM)
.optional()
.describe(
"Maximum retained semantic nodes per source file; defaults to 20000, additionally bounded by max_semantic_nodes and memory/transfer limits.",
),
max_heap_mb: z
.number()
.int()
@@ -24,6 +24,7 @@ export const JAVASCRIPT_APPLICATION_NODE_KINDS = [
"javascript-asset",
"javascript-chunk",
"javascript-module",
"javascript-expression",
"source-map",
"source-module",
"browser-window",
@@ -37,6 +37,14 @@ export const estimateJavaScriptStaticApplicationProjection = (
}
for (const binding of facts.electron.native_addon_bindings)
records += binding.members.length * 3;
for (const path of facts.electron.call_paths ?? []) {
// One contextual node and edge per step, with repeated guards and identity.
records += path.steps.length * 4 + 8;
repeatedBytes +=
Buffer.byteLength(JSON.stringify(path.conditions)) *
path.steps.length *
2;
}
const metadataBytes = 2048 + Buffer.byteLength(sourcePath) * 4;
return (checkpointBytes * 4 + repeatedBytes + records * metadataBytes) * 8;
};
@@ -0,0 +1,111 @@
import * as t from "@babel/types";
import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
import { moduleFactory } from "./javascriptStaticAnalysisHelpers.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
/** A literal module table dispatched by a standalone CommonJS-style runtime. */
interface JavaScriptBootstrap {
readonly body: t.BlockStatement;
readonly table: t.ObjectExpression;
readonly loaderName: string;
}
/** Recognize syntax, never invoke a bootstrap or infer it from variable names. */
export const javascriptBootstrapAt = (
call: t.CallExpression,
): JavaScriptBootstrap | undefined => {
if (
(!t.isFunctionExpression(call.callee) &&
!t.isArrowFunctionExpression(call.callee)) ||
!t.isBlockStatement(call.callee.body) ||
call.callee.params.length !== 0 ||
call.arguments.length !== 0
)
return undefined;
const body = call.callee.body;
const tables = new Map<string, t.ObjectExpression>();
for (const statement of body.body) {
if (!t.isVariableDeclaration(statement)) continue;
for (const declaration of statement.declarations) {
if (
t.isIdentifier(declaration.id) &&
t.isObjectExpression(declaration.init) &&
declaration.init.properties.length > 0 &&
declaration.init.properties.every(
(property) => moduleFactory(property) !== undefined,
)
)
tables.set(declaration.id.name, declaration.init);
}
}
if (tables.size === 0) return undefined;
for (const loader of body.body) {
if (
!t.isFunctionDeclaration(loader) ||
loader.id === null ||
loader.id === undefined ||
loader.params.length !== 1
)
continue;
const parameter = loader.params[0];
if (!t.isIdentifier(parameter)) continue;
const loaderName = loader.id.name;
let tableName: string | undefined;
traverseJavaScriptAst(loader.body, {
enter: (node, _parent, ancestors) => {
if (
!t.isCallExpression(node) ||
ancestors().some((node) => t.isFunction(node))
)
return;
const candidate = dispatchedTableName(node, loaderName, parameter.name);
if (candidate !== undefined && tables.has(candidate))
tableName = candidate;
},
});
const table = tableName === undefined ? undefined : tables.get(tableName);
if (table !== undefined && tableName !== undefined)
return { body, table, loaderName };
}
return undefined;
};
const dispatchedTableName = (
call: t.CallExpression,
loaderName: string,
keyName: string,
): string | undefined => {
const member = call.callee;
const viaCall =
t.isMemberExpression(member) &&
semanticStaticPropertyKey(member.property, member.computed) === "call";
const dispatch =
viaCall && t.isMemberExpression(member) ? member.object : member;
if (
!t.isMemberExpression(dispatch) ||
!dispatch.computed ||
!t.isIdentifier(dispatch.object) ||
!t.isIdentifier(dispatch.property, { name: keyName })
)
return undefined;
const args = viaCall ? call.arguments.slice(1) : call.arguments;
const [module, exports, require] = args;
if (
args.length !== 3 ||
!t.isIdentifier(module) ||
!t.isMemberExpression(exports) ||
!t.isIdentifier(exports.object, { name: module.name }) ||
semanticStaticPropertyKey(exports.property, exports.computed) !==
"exports" ||
!t.isIdentifier(require, { name: loaderName })
)
return undefined;
if (
viaCall &&
(!t.isNode(call.arguments[0]) ||
!t.isNodesEquivalent(call.arguments[0], exports))
)
return undefined;
return dispatch.object.name;
};
@@ -82,7 +82,12 @@ const kindMatches = (
({ properties }) => properties.endpoint_kind === "route",
)
);
if (kind === "api") return node.kind === "context-bridge-api";
if (kind === "api")
return (
node.kind === "context-bridge-api" ||
(node.kind === "javascript-expression" &&
node.observations.some((o) => o.properties.step_kind === "exposure"))
);
if (kind === "channel") return node.kind === "ipc-channel";
if (kind === "module")
return ["javascript-asset", "javascript-module", "source-module"].includes(
@@ -217,7 +217,9 @@ const pathTo = (
const isTerminal = (node: ApplicationNode): boolean =>
["endpoint", "storage", "native-addon", "native-export", "unknown"].includes(
node.kind,
);
) ||
(node.kind === "javascript-expression" &&
node.observations.some((o) => o.properties.step_kind === "terminal"));
const factSummary = (
nodes: readonly ApplicationNode[],
@@ -9,6 +9,85 @@ const resultValue = (body: string) =>
"result",
).returnSites[0]?.value;
describe("bounded paths through dynamic selectors and class origins", () => {
it("bounds linked-list walks through class instances", () => {
const start = performance.now();
const analysis = analyzeJavaScriptSemantics(`
class List { tail = null; }
export function walk() {
const list = new List();
let node = list.tail;
while (node) { use(node.value.parent); node = node.previous; }
return 42;
}
`);
expect(onlyCallable(analysis, "walk").returnSites[0]?.value).toEqual({
status: "literal",
value: 42,
});
expect(performance.now() - start).toBeLessThan(2000);
}, 30000);
it("retains effects through class getter aliases while bounding loop paths", () => {
expect(
resultValue(`
const shared = { value: 1 };
class List { get tail() { return { value: shared }; } }
let node = new List().tail;
while (node) { use(node.value); node = node.previous; }
return shared.value;
`)?.status,
).toBe("unknown");
});
it("bounds dynamic-key setter loops that also create literal containers", () => {
const start = performance.now();
const analysis = analyzeJavaScriptSemantics(`
export function set(root, keys, value) {
let node = root;
for (const [index, key] of keys.entries()) {
if (index === keys.length - 1) { node[key] = value; return root; }
const child = node[key];
if (isObject(child)) { node = child; continue; }
const fresh = isIndex(keys[index + 1]) ? [] : {};
node[key] = fresh;
node = fresh;
}
return root;
}
export function unaffected() { return 42; }
`);
expect(onlyCallable(analysis, "unaffected").returnSites[0]?.value).toEqual({
status: "literal",
value: 42,
});
expect(onlyCallable(analysis, "set").returnSites[0]?.value.status).toBe(
"unknown",
);
expect(performance.now() - start).toBeLessThan(2000);
}, 30000);
it("retains shared-child mutations reached by dynamic-key alias loops", () => {
expect(
resultValue(`
const shared = { value: 1 };
const source = { child: { next: shared }, keep: 3 };
let node = source.child;
while (flag) { node = node[key] || {}; node.value = 2; }
return shared.value;
`)?.status,
).toBe("unknown");
expect(
resultValue(`
const source = { child: { value: 1 }, keep: 3 };
let node = source.child;
while (flag) { node = node[key] || {}; node.value = 2; }
return source.keep;
`),
).toEqual({ status: "literal", value: 3 });
});
});
describe("bounded member path propagation", () => {
it("bounds cyclic member paths with no observed container origin", () => {
const branches = Array.from(
@@ -121,6 +121,15 @@ export const analyzeParsedJavaScriptReferences = (
return collectSemanticReferences(file.program, state, name);
};
/** Share the lexical index with bounded, demand-driven boundary analyses. */
export function* indexJavaScriptBindingsSteps(
program: t.Program,
): Generator<void, JavaScriptSemanticAnalysisState> {
const state = createState(program);
yield* collectDefinitionsSteps(program, state);
return state;
}
/** Recover semantics from an already parsed JavaScript artifact. */
export const analyzeParsedJavaScriptSemantics = (
file: ParsedJavaScriptSource,
@@ -718,6 +718,9 @@ const referencedValues = (
type MutationObservableOrigin =
| t.ObjectExpression
| t.ArrayExpression
| t.ClassDeclaration
| t.ClassExpression
| t.NewExpression
| "ambient"
| "array"
| "array-prototype"
@@ -808,11 +811,6 @@ const observableMutationPaths = (
const observer = bindingNodes.get(binding.bindingId);
if (observer === undefined) continue;
for (const initializer of binding.initializers) {
const expression = unwrapJavaScriptExpression(initializer.node).node;
// Preserve member paths through class values and local instances so
// getter-result aliases can be resolved at the accessor boundary.
if (t.isClass(expression) || t.isNewExpression(expression))
(observer.origins ??= new Set()).add("opaque");
link(
project(expressionNode(initializer.node), initializer.projection),
observer,
@@ -837,7 +835,14 @@ const observableMutationPaths = (
const selected = pendingExpressions.pop();
if (selected === undefined) break;
const { expression, observer } = selected;
if (t.isObjectExpression(expression) || t.isArrayExpression(expression))
// Keep class/getter projections distinct so cycle pruning does not
// discard observable escapes through a shared getter result.
if (
t.isObjectExpression(expression) ||
t.isArrayExpression(expression) ||
t.isClass(expression) ||
t.isNewExpression(expression)
)
(observer.origins ??= new Set()).add(expression);
else if (t.isIdentifier(expression)) {
const binding = resolveSemanticBindingState(
@@ -1,4 +1,5 @@
import * as t from "@babel/types";
import { collectElectronWrappedCallPaths } from "./electronWrappedCallPaths.js";
import {
ELECTRON_IDENTITY_LIMITATION,
ELECTRON_MODULE,
@@ -27,6 +28,7 @@ import {
} from "./javascriptStaticAnalysisCalls.js";
import {
inspectBundlerRegistration,
inspectBundlerBootstrap,
inspectEsbuildWrapper,
} from "./javascriptStaticAnalysisBundler.js";
import { finalizeLocatedFindings } from "./javascriptStaticAnalysisFindings.js";
@@ -38,6 +40,7 @@ import {
import type { JavaScriptStaticAnalysis } from "./javascriptStaticAnalysisTypes.js";
import {
classifyParsedJavaScriptElectronBindingsSteps,
indexJavaScriptBindingsSteps,
classifyParsedJavaScriptRpcClientRootsSteps,
classifyParsedJavaScriptOpenReceivers,
type JavaScriptOpenReceiverFact,
@@ -90,6 +93,13 @@ export function* analyzeParsedJavaScriptStaticSourceSteps(
electronBindings,
rpcScan: createJavaScriptRpcScan(source, clientRoots),
});
const bindings = yield* indexJavaScriptBindingsSteps(file.program);
accumulator.electronCallPaths = collectElectronWrappedCallPaths(
file.program,
bindings,
source,
accumulator,
);
addSourceMapDirectives(source, file.comments ?? [], accumulator);
return finalizeStaticAnalysis(source, file, accumulator);
}
@@ -114,6 +124,16 @@ const finalizeStaticAnalysis = (
): JavaScriptStaticAnalysis => {
const parserErrors = file.errors.length;
const limitations = [
...(accumulator.electronCallPaths?.length
? [
"Bundled Electron call paths use static argument and closure substitutions. Conditions, ambient helper overrides, runtime reachability and arbitrary side effects remain unproven.",
]
: []),
...(accumulator.electronCallPathLimitReached
? [
"Electron wrapper expansion reached its resource budget (1000000 visits/substitutions or depth 128); additional paths remain unknown.",
]
: []),
...(parserErrors === 0
? []
: [
@@ -162,6 +182,9 @@ const finalizeStaticAnalysis = (
source_map_urls: accumulator.sourceMaps,
vendors: detectVendors(source),
electron: {
...(accumulator.electronCallPaths?.length
? { call_paths: accumulator.electronCallPaths }
: {}),
browser_windows: finalizeLocatedFindings(
accumulator.browserWindows,
accumulator.moduleRangeIndex,
@@ -198,6 +221,7 @@ const inspectNode = (
const { source, accumulator } = findings;
inspectElectronStaticNode(node, findings);
if (t.isCallExpression(node)) {
inspectBundlerBootstrap(source, node, accumulator);
inspectBundlerRegistration(source, node, accumulator);
inspectEsbuildWrapper(source, node, accumulator);
inspectCall(source, node, findings);
@@ -1,4 +1,5 @@
import * as t from "@babel/types";
import { javascriptBootstrapAt } from "./javascriptBootstrap.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
@@ -77,6 +78,61 @@ export const inspectBundlerRegistration = (
);
};
/** Recover standalone Webpack tables whose factories are called by a local loader. */
export const inspectBundlerBootstrap = (
source: string,
call: t.CallExpression,
accumulator: AnalysisAccumulator,
): void => {
const bootstrap = javascriptBootstrapAt(call);
if (bootstrap === undefined) return;
const runtime = `webpack-bootstrap@${String(call.start ?? 0)}`;
const recovered = recoverBundlerModules(
source,
bootstrap.table,
runtime,
accumulator,
);
const entries: string[] = [];
let unknownEntries = 0;
traverseJavaScriptAst(bootstrap.body, {
enter: (node, _parent, ancestors) => {
if (
!t.isCallExpression(node) ||
ancestors().some((node) => t.isFunction(node)) ||
!t.isIdentifier(node.callee, { name: bootstrap.loaderName })
)
return;
const value = argumentValue(node.arguments[0]);
if (value === undefined) unknownEntries++;
else entries.push(value);
},
});
const registration: JavaScriptBundlerRegistration = {
bundler: "webpack",
runtime,
chunk_keys: [`bootstrap@${String(call.start ?? 0)}`],
unknown_chunk_keys: 0,
runtime_require_name: bootstrap.loaderName,
runtime_module_cache_status: "not-observed",
entry_module_keys: uniqueValues(entries).values,
unknown_entry_module_keys: unknownEntries,
async_chunk_keys: recovered.asyncChunkKeys,
unknown_async_chunk_keys: recovered.unknownAsyncChunkKeys,
modules: recovered.modules.sort((left, right) =>
compareUnicodeCodePoints(left.module_key, right.module_key),
),
location: range(call),
};
accumulator.unknownFindings +=
unknownEntries + recovered.unknownAsyncChunkKeys;
addFindingOnce(
accumulator,
`registration\0${registrationKey(registration)}`,
() => accumulator.registrations.push(registration),
);
};
/** Inspect esbuild helper wrappers and recover their literal module tables. */
export const inspectEsbuildWrapper = (
source: string,
@@ -3,6 +3,53 @@ import { expect, it } from "vitest";
import { JavaScriptModuleRangeIndex } from "./javascriptStaticAnalysisFindings.js";
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
it.each(["direct", "call"])(
"recovers standalone module factories dispatched with %s",
(style) => {
const dispatch =
style === "call"
? "modules[id].call(module.exports, module, module.exports, load)"
: "modules[id](module, module.exports, load)";
const source = `(() => {
const modules = {
17(module, exports, req) { exports.read = req(23); },
23(module) { module.exports = require("electron"); }
};
const cache = {};
function load(id) {
if (cache[id]) return cache[id].exports;
const module = cache[id] = { exports: {} };
${dispatch};
return module.exports;
}
load(17);
})();`;
const analysis = analyzeJavaScriptStaticSource(source);
expect(analysis.bundler_registrations).toMatchObject([
{
bundler: "webpack",
entry_module_keys: ["17"],
modules: [{ module_key: "17" }, { module_key: "23" }],
},
]);
expect(analysis.references).toEqual(
expect.arrayContaining([
expect.objectContaining({ specifier: "23", module_key: "17" }),
expect.objectContaining({ specifier: "electron", module_key: "23" }),
]),
);
},
);
it("does not infer a bootstrap from a function table without a matching loader", () => {
const analysis = analyzeJavaScriptStaticSource(`(() => {
const handlers = { 17(module) { module.exports = require("electron"); } };
function load(id) { return handlers[id](userInput); }
load(17);
})();`);
expect(analysis.bundler_registrations).toEqual([]);
});
it("preserves first insertion precedence and inclusive interval bounds", () => {
const nested = new JavaScriptModuleRangeIndex(100);
expect(nested.find(0)).toBeUndefined();
@@ -10,6 +10,7 @@ import type {
JavaScriptStaticStorage,
} from "./javascriptStaticAnalysisTypes.js";
import type {
ElectronCallPath,
ElectronBrowserWindowFinding,
ElectronContextBridgeFinding,
ElectronIpcFinding,
@@ -36,6 +37,8 @@ export interface LocatedJavaScriptFinding<Value> {
/** Mutable collections used during one inert AST traversal. */
export interface JavaScriptAnalysisAccumulator {
electronCallPaths?: readonly ElectronCallPath[];
electronCallPathLimitReached?: boolean;
readonly references: LocatedJavaScriptFinding<JavaScriptStaticReference>[];
readonly endpoints: LocatedJavaScriptFinding<JavaScriptStaticEndpoint>[];
readonly storage: LocatedJavaScriptFinding<JavaScriptStaticStorage>[];
@@ -0,0 +1,55 @@
import { expect, it } from "vitest";
import * as t from "@babel/types";
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
import { indexJavaScriptBindingsSteps } from "./javascriptSemanticAnalysis.js";
import {
completeSemanticSteps,
traverseJavaScriptAst,
} from "./javascriptSemanticTraversal.js";
import { JavaScriptSymbolicBindings } from "./javascriptSymbolicBindings.js";
import { symbolicVariants } from "./javascriptSymbolicValues.js";
it("substitutes numeric modules, named exports and captured wrapper arguments", () => {
const parsed = parseJavaScriptSource(`(() => {
const modules = {
4(module) { module.exports = require("electron"); },
8(module, exports, load) {
const electron = load(4);
exports.sender = function(channel) { return (...args) => electron.ipcRenderer.send(channel,...args); };
},
12(module, exports, load) { const helpers = load(8); const api = {copy: helpers.sender("test:copy")}; inspect(api.copy); }
};
function load(id) { const m = {exports:{}}; modules[id](m,m.exports,load); return m.exports; }
load(12);
})();`)!;
const state = completeSemanticSteps(
indexJavaScriptBindingsSteps(parsed.program),
);
const resolver = new JavaScriptSymbolicBindings(state, parsed.program);
let found = false;
traverseJavaScriptAst(parsed.program, {
enter: (node) => {
if (
!t.isCallExpression(node) ||
!t.isIdentifier(node.callee, { name: "inspect" })
)
return;
const value = resolver.evaluate(node.arguments[0]);
const fn = symbolicVariants(value).find((v) => v.kind === "function");
expect(fn?.kind).toBe("function");
if (fn?.kind !== "function" || !t.isCallExpression(fn.node.body))
throw new Error("closure missing");
const env = resolver.bind(fn, []);
expect(resolver.evaluate(fn.node.body.callee, env)).toEqual({
kind: "external",
path: ["electron", "ipcRenderer", "send"],
});
expect(resolver.arguments(fn.node.body, env)[0]).toEqual({
kind: "literal",
value: "test:copy",
});
found = true;
},
});
expect(found).toBe(true);
});
@@ -0,0 +1,616 @@
import * as t from "@babel/types";
import {
semanticStaticPropertyKey,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
import { javascriptBootstrapAt } from "./javascriptBootstrap.js";
import { symbolicLogicalRight } from "./javascriptSymbolicControlFlow.js";
import {
moduleFactory,
modulePropertyName,
} from "./javascriptStaticAnalysisHelpers.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import {
resolveSemanticBindingState,
semanticResolutionBlocked,
type JavaScriptSemanticAnalysisState,
} from "./javascriptSemanticState.js";
import {
symbolicUnion,
symbolicUnknown,
symbolicVariants,
symbolicTruth,
type SymbolicValue,
type SymbolicEnvironment,
type SymbolicFunction,
} from "./javascriptSymbolicValues.js";
interface PropertyWrite {
readonly path: readonly string[];
readonly value: t.Node;
readonly site: t.Node;
}
interface SymbolicReturnFlow {
readonly values: readonly SymbolicValue[];
readonly fallsThrough: boolean;
}
const emptyEnvironment: SymbolicEnvironment = { values: new Map() };
/** Demand-driven substitutions for local bindings, closures and literal module tables. */
export class JavaScriptSymbolicBindings {
readonly #writes = new Map<string, PropertyWrite[]>();
readonly #environments = new WeakMap<t.Node, SymbolicEnvironment>();
readonly #cache = new WeakMap<
SymbolicEnvironment,
WeakMap<t.Node, SymbolicValue>
>();
readonly #active = new Set<t.Node>();
readonly #activeFunctions = new Set<t.Function>();
readonly #exportAliases = new Map<string, string>();
readonly #moduleBindings = new Set<string>();
readonly #replacements = new Map<string, t.Node>();
readonly #propertyActive = new WeakMap<object, Set<string>>();
readonly #mutated = new Set<string>();
readonly #namespaceOwners = new Map<string, t.Function>();
readonly #unsafeExports = new Set<string>();
#remainingEvaluations = 1_000_000;
#depth = 0;
truncated = false;
constructor(
readonly state: JavaScriptSemanticAnalysisState,
program: t.Program,
) {
traverseJavaScriptAst(program, {
enter: (node) => {
if (t.isCallExpression(node)) this.#indexBootstrap(node);
},
});
traverseJavaScriptAst(program, {
enter: (node) => {
if (t.isAssignmentExpression(node))
this.#indexWrite(node.left, node.right, node);
if (
t.isCallExpression(node) &&
t.isMemberExpression(node.callee) &&
t.isIdentifier(node.callee.object, { name: "Object" }) &&
!resolveSemanticBindingState(state, node.callee.object, "Object") &&
semanticStaticPropertyKey(
node.callee.property,
node.callee.computed,
) === "defineProperty"
) {
const [target, key, descriptor] = node.arguments;
if (
t.isIdentifier(target) &&
t.isStringLiteral(key) &&
t.isObjectExpression(descriptor)
) {
const value = descriptor.properties.find(
(p) =>
t.isObjectProperty(p) &&
semanticStaticPropertyKey(p.key, p.computed) === "value",
);
if (t.isObjectProperty(value))
this.#addWrite(target, [key.value], value.value, node);
}
}
},
});
}
environmentAt(node: t.Node): SymbolicEnvironment {
let current: t.Node | undefined = node;
while (current) {
const found = this.#environments.get(current);
if (found) return found;
current = this.state.parentsByNode.get(current);
}
return emptyEnvironment;
}
evaluate(
input: t.Node | null | undefined,
environment?: SymbolicEnvironment,
): SymbolicValue {
if (!input) return { kind: "literal", value: undefined };
if (--this.#remainingEvaluations < 0 || this.#depth >= 128) {
this.truncated = true;
return symbolicUnknown("symbolic resource limit");
}
const node = unwrapJavaScriptExpression(input).node;
const env = environment ?? this.environmentAt(node);
const cache = this.#cache.get(env) ?? new WeakMap<t.Node, SymbolicValue>();
this.#cache.set(env, cache);
const cached = cache.get(node);
if (cached) return cached;
if (this.#active.has(node)) return symbolicUnknown("cyclic binding");
this.#active.add(node);
this.#depth += 1;
try {
const value = this.#evaluate(node, env);
cache.set(node, value);
return value;
} finally {
this.#active.delete(node);
this.#depth -= 1;
}
}
property(value: SymbolicValue, key: string): SymbolicValue {
const active = this.#propertyActive.get(value) ?? new Set<string>();
if (active.has(key)) return symbolicUnknown("cyclic property");
active.add(key);
this.#propertyActive.set(value, active);
try {
return this.#property(value, key);
} finally {
active.delete(key);
}
}
#property(value: SymbolicValue, key: string): SymbolicValue {
if (value.kind === "union")
return symbolicUnion(value.values.map((v) => this.property(v, key)));
if (value.kind === "external")
return { kind: "external", path: [...value.path, key] };
if (value.kind === "record")
return value.values.get(key) ?? symbolicUnknown("missing property");
if (value.kind === "namespace") {
if (
this.#mutated.has(value.bindingId) ||
this.#unsafeExports.has(`${value.bindingId}:${key}`)
)
return symbolicUnknown("ambiguous export writes");
const replacement = this.#replacements.get(value.bindingId);
if (replacement)
return this.property(
this.evaluate(replacement, value.environment),
key,
);
const writes = (this.#writes.get(value.bindingId) ?? []).filter(
(w) => w.path.length === 1 && w.path[0] === key,
);
const write = writes.at(-1);
return write
? this.evaluate(write.value, value.environment)
: symbolicUnknown("unresolved module export");
}
if (value.kind === "object") {
for (const p of [...value.node.properties].reverse()) {
if (t.isSpreadElement(p)) {
const spread = this.evaluate(p.argument, value.environment);
const found = this.property(spread, key);
if (found.kind !== "unknown") return found;
if (
this.unknownMembers(spread) > 0 ||
this.members(spread).includes(key)
)
return found;
} else if (semanticStaticPropertyKey(p.key, p.computed) === key) {
return t.isObjectMethod(p) && p.kind !== "method"
? symbolicUnknown("accessor property")
: this.evaluate(
t.isObjectProperty(p) ? p.value : p,
value.environment,
);
} else if (semanticStaticPropertyKey(p.key, p.computed) === null)
return symbolicUnknown("dynamic property overwrite");
}
}
if (value.kind === "array" && /^\d+$/u.test(key))
return value.values[Number(key)] ?? symbolicUnknown("missing argument");
return symbolicUnknown("unresolved property");
}
members(
value: SymbolicValue,
active = new Set<SymbolicValue>(),
): readonly string[] {
if (active.has(value)) return [];
active.add(value);
if (value.kind === "union")
return [...new Set(value.values.flatMap((v) => this.members(v, active)))];
if (value.kind === "record") return [...value.values.keys()];
if (value.kind === "namespace") {
const replacement = this.#replacements.get(value.bindingId);
return replacement
? this.members(this.evaluate(replacement, value.environment), active)
: [
...new Set(
(this.#writes.get(value.bindingId) ?? []).flatMap((w) =>
w.path.length === 1 ? w.path : [],
),
),
];
}
if (value.kind !== "object") return [];
return [
...new Set(
value.node.properties.flatMap((p) =>
t.isSpreadElement(p)
? this.members(this.evaluate(p.argument, value.environment), active)
: [semanticStaticPropertyKey(p.key, p.computed)].filter(
(k): k is string => k !== null,
),
),
),
];
}
unknownMembers(
value: SymbolicValue,
active = new Set<SymbolicValue>(),
): number {
if (active.has(value)) return 1;
active.add(value);
if (value.kind === "union")
return value.values.reduce(
(sum, v) => sum + this.unknownMembers(v, active),
0,
);
if (value.kind === "record") return 0;
if (value.kind === "namespace") {
if (this.#mutated.has(value.bindingId)) return 1;
const replacement = this.#replacements.get(value.bindingId);
return replacement
? this.unknownMembers(
this.evaluate(replacement, value.environment),
active,
)
: 0;
}
if (value.kind !== "object") return 1;
return value.node.properties.reduce(
(sum, p) =>
sum +
(t.isSpreadElement(p)
? this.unknownMembers(
this.evaluate(p.argument, value.environment),
new Set(active),
)
: Number(semanticStaticPropertyKey(p.key, p.computed) === null)),
0,
);
}
bind(
fn: SymbolicFunction,
args: readonly SymbolicValue[],
): SymbolicEnvironment {
const values = new Map<string, SymbolicValue>();
fn.node.params.forEach((param, index) => {
const target = t.isRestElement(param) ? param.argument : param;
if (!t.isIdentifier(target)) return;
const binding = resolveSemanticBindingState(
this.state,
target,
target.name,
);
if (binding)
values.set(
binding.bindingId,
t.isRestElement(param)
? { kind: "array", values: args.slice(index) }
: (args[index] ?? symbolicUnknown("runtime parameter")),
);
});
return { values, parent: fn.environment };
}
arguments(
node: t.CallExpression | t.OptionalCallExpression,
env: SymbolicEnvironment,
): readonly SymbolicValue[] {
return node.arguments.flatMap((a) => {
if (!t.isSpreadElement(a)) return [this.evaluate(a, env)];
const value = this.evaluate(a.argument, env);
return value.kind === "array"
? value.values
: [symbolicUnknown("dynamic spread arguments")];
});
}
#evaluate(node: t.Node, env: SymbolicEnvironment): SymbolicValue {
if (
t.isStringLiteral(node) ||
t.isNumericLiteral(node) ||
t.isBooleanLiteral(node)
)
return { kind: "literal", value: node.value };
if (t.isNullLiteral(node)) return { kind: "literal", value: null };
if (t.isFunction(node))
return { kind: "function", node, environment: env, origins: [] };
if (t.isObjectExpression(node))
return { kind: "object", node, environment: env };
if (t.isIdentifier(node)) return this.#identifier(node, env);
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
const key = semanticStaticPropertyKey(node.property, node.computed);
return key === null
? symbolicUnknown("dynamic member")
: this.property(this.evaluate(node.object, env), key);
}
if (t.isSequenceExpression(node))
return this.evaluate(node.expressions.at(-1), env);
if (t.isAssignmentExpression(node)) return this.evaluate(node.right, env);
if (t.isAwaitExpression(node)) return this.evaluate(node.argument, env);
if (t.isUnaryExpression(node)) {
const value = this.evaluate(node.argument, env);
if (node.operator === "void")
return { kind: "literal", value: undefined };
const truth = symbolicTruth(value);
if (node.operator === "!" && truth !== undefined)
return { kind: "literal", value: !truth };
}
if (t.isConditionalExpression(node)) {
const truth = symbolicTruth(this.evaluate(node.test, env));
return truth === undefined
? symbolicUnion([
this.evaluate(node.consequent, env),
this.evaluate(node.alternate, env),
])
: this.evaluate(truth ? node.consequent : node.alternate, env);
}
if (t.isLogicalExpression(node)) {
const left = this.evaluate(node.left, env);
const right = symbolicLogicalRight(node.operator, left);
if (right !== undefined)
return right ? this.evaluate(node.right, env) : left;
return symbolicUnion([left, this.evaluate(node.right, env)]);
}
if (t.isCallExpression(node) || t.isOptionalCallExpression(node))
return this.#call(node, env);
return symbolicUnknown(`unsupported ${node.type}`);
}
#identifier(node: t.Identifier, env: SymbolicEnvironment): SymbolicValue {
const binding = resolveSemanticBindingState(this.state, node, node.name);
if (
!binding &&
node.name === "undefined" &&
!semanticResolutionBlocked(this.state, node, node.name)
)
return { kind: "literal", value: undefined };
if (!binding)
return !semanticResolutionBlocked(this.state, node, node.name) &&
["require", "navigator", "String", "Boolean"].includes(node.name)
? { kind: "external", path: [node.name] }
: symbolicUnknown("unbound identifier");
if (binding.definitions.some((d) => d.kind === "assignment"))
return symbolicUnknown("reassigned binding");
if (this.#mutated.has(binding.bindingId))
return symbolicUnknown("dynamic member writes");
for (let e: SymbolicEnvironment | undefined = env; e; e = e.parent) {
const value = e.values.get(binding.bindingId);
if (value) return value;
}
if (this.#writes.has(binding.bindingId))
return symbolicUnknown("overwritten object members");
const initializer =
binding.initializers.length === 1 ? binding.initializers[0] : undefined;
if (!initializer)
return symbolicUnknown("missing or ambiguous initializer");
if (this.state.conditionalInitializers.has(initializer.node))
return symbolicUnknown("conditional initializer");
let value = this.evaluate(initializer.node, env);
for (const key of initializer.projection) {
if (key === null) return symbolicUnknown("dynamic destructuring");
value = this.property(value, String(key));
}
return value;
}
#call(
node: t.CallExpression | t.OptionalCallExpression,
env: SymbolicEnvironment,
): SymbolicValue {
const callee = this.evaluate(node.callee, env);
const args = this.arguments(node, env);
return symbolicUnion(
symbolicVariants(callee).map((value) => {
if (value.kind === "loader") {
const key = args[0];
return key?.kind === "literal"
? (value.modules.get(String(key.value)) ??
symbolicUnknown("missing module"))
: symbolicUnknown("dynamic module");
}
if (value.kind === "external" && value.path.join(".") === "require") {
const spec = args[0];
return spec?.kind === "literal" && typeof spec.value === "string"
? { kind: "external", path: [spec.value] }
: symbolicUnknown("dynamic require");
}
if (value.kind !== "function" || this.#activeFunctions.has(value.node))
return symbolicUnknown("unresolved or recursive call");
this.#activeFunctions.add(value.node);
try {
const bound = this.bind(value, args);
const result = t.isBlockStatement(value.node.body)
? this.#returns(value.node.body.body, bound)
: this.evaluate(value.node.body, bound);
return symbolicUnion(
symbolicVariants(result).map((v) =>
v.kind === "function"
? { ...v, origins: [...value.origins, node, ...v.origins] }
: v,
),
);
} finally {
this.#activeFunctions.delete(value.node);
}
}),
);
}
#returns(
statements: readonly t.Statement[],
env: SymbolicEnvironment,
): SymbolicValue {
const flow = this.#returnFlow(statements, env);
return symbolicUnion([
...flow.values,
...(flow.fallsThrough
? [{ kind: "literal" as const, value: undefined }]
: []),
]);
}
#returnFlow(
statements: readonly t.Statement[],
env: SymbolicEnvironment,
depth = 0,
): SymbolicReturnFlow {
const possible: SymbolicValue[] = [];
for (const statement of statements) {
if (--this.#remainingEvaluations < 0 || depth >= 128) {
this.truncated = true;
return {
values: [...possible, symbolicUnknown("symbolic resource limit")],
fallsThrough: false,
};
}
if (t.isThrowStatement(statement))
return {
values: [...possible, symbolicUnknown("wrapper exits by throwing")],
fallsThrough: false,
};
if (t.isReturnStatement(statement))
return {
values: [...possible, this.evaluate(statement.argument, env)],
fallsThrough: false,
};
if (t.isBlockStatement(statement)) {
const flow = this.#returnFlow(statement.body, env, depth + 1);
possible.push(...flow.values);
if (!flow.fallsThrough)
return { values: possible, fallsThrough: false };
}
if (t.isIfStatement(statement)) {
const truth = symbolicTruth(this.evaluate(statement.test, env));
const branches =
truth === undefined
? [statement.consequent, statement.alternate]
: [truth ? statement.consequent : statement.alternate];
const flows = branches.map((branch) =>
this.#returnFlow(branch ? [branch] : [], env, depth + 1),
);
possible.push(...flows.flatMap((flow) => flow.values));
if (flows.every((flow) => !flow.fallsThrough))
return { values: possible, fallsThrough: false };
}
}
return { values: possible, fallsThrough: true };
}
#indexBootstrap(call: t.CallExpression): void {
const bootstrap = javascriptBootstrapAt(call);
if (!bootstrap) return;
const modules = new Map<string, SymbolicValue>();
for (const property of bootstrap.table.properties) {
const factory = moduleFactory(property);
if (!factory) continue;
const values = new Map<string, SymbolicValue>();
const environment = { values };
const first = factory.params[0];
const second = factory.params[1];
const third = factory.params[2];
const binding = (n: t.Node | undefined) =>
t.isIdentifier(n)
? resolveSemanticBindingState(this.state, n, n.name)?.bindingId
: undefined;
const moduleId = binding(first);
const exportsId = binding(second);
const loaderId = binding(third);
const namespaceId = `${String(factory.start)}:exports`;
this.#namespaceOwners.set(namespaceId, factory);
const namespace: SymbolicValue = {
kind: "namespace",
bindingId: namespaceId,
environment,
};
if (moduleId) {
values.set(moduleId, {
kind: "record",
values: new Map([["exports", namespace]]),
});
this.#exportAliases.set(moduleId, namespaceId);
this.#moduleBindings.add(moduleId);
}
if (exportsId) {
values.set(exportsId, namespace);
this.#exportAliases.set(exportsId, namespaceId);
}
if (loaderId) values.set(loaderId, { kind: "loader", modules });
this.#environments.set(factory, environment);
modules.set(modulePropertyName(property), namespace);
}
}
#indexWrite(target: t.Node, value: t.Node, site: t.Node): void {
const path: string[] = [];
let root = target;
let dynamic = false;
while (t.isMemberExpression(root)) {
const key = semanticStaticPropertyKey(root.property, root.computed);
if (key === null) dynamic = true;
else path.unshift(key);
root = root.object;
}
if (dynamic && t.isIdentifier(root)) {
const binding = resolveSemanticBindingState(this.state, root, root.name);
if (binding)
this.#mutated.add(
this.#exportAliases.get(binding.bindingId) ?? binding.bindingId,
);
return;
}
if (t.isIdentifier(root)) this.#addWrite(root, path, value, site);
}
#addWrite(
root: t.Identifier,
path: readonly string[],
value: t.Node,
site: t.Node,
): void {
const binding = resolveSemanticBindingState(this.state, root, root.name);
if (!binding) return;
const alias = this.#exportAliases.get(binding.bindingId);
if (this.#moduleBindings.has(binding.bindingId) && path[0] !== "exports")
return;
const key = alias ?? binding.bindingId;
const selected = this.#moduleBindings.has(binding.bindingId)
? path.slice(1)
: path;
if (alias) {
const owner = this.#namespaceOwners.get(alias);
for (
let parent = this.state.parentsByNode.get(site);
parent && parent !== owner;
parent = this.state.parentsByNode.get(parent)
) {
if (
t.isFunction(parent) ||
t.isIfStatement(parent) ||
t.isConditionalExpression(parent) ||
t.isLogicalExpression(parent) ||
t.isLoop(parent) ||
t.isSwitchCase(parent) ||
t.isTryStatement(parent)
) {
if (selected.length === 0) this.#mutated.add(key);
else this.#unsafeExports.add(`${key}:${selected[0] ?? ""}`);
return;
}
}
}
if (alias && selected.length === 0) {
this.#replacements.set(key, value);
return;
}
const writes = this.#writes.get(key) ?? [];
writes.push({ path: selected, value, site });
this.#writes.set(key, writes);
}
}
@@ -0,0 +1,53 @@
import * as t from "@babel/types";
import {
symbolicTruth,
type SymbolicValue,
} from "./javascriptSymbolicValues.js";
/** Whether short-circuit evaluation reaches the right operand; unknown stays unknown. */
export const symbolicLogicalRight = (
operator: t.LogicalExpression["operator"],
left: SymbolicValue,
): boolean | undefined => {
if (left.kind === "union") {
const choices = left.values.map((value) =>
symbolicLogicalRight(operator, value),
);
return choices.length > 0 &&
choices.every((choice) => choice === choices[0])
? choices[0]
: undefined;
}
if (operator === "??") {
if (left.kind === "literal")
return left.value === null || left.value === undefined;
return [
"function",
"object",
"namespace",
"array",
"record",
"loader",
].includes(left.kind)
? false
: undefined;
}
const truth = symbolicTruth(left);
return truth === undefined ? undefined : operator === "&&" ? truth : !truth;
};
/** Only definite synchronous exits; unsupported control flow stays unknown. */
export const symbolicDefiniteExit = (
node: t.Node | null | undefined,
depth = 0,
): boolean => {
if (!node || depth >= 128) return false;
if (t.isReturnStatement(node) || t.isThrowStatement(node)) return true;
if (t.isBlockStatement(node))
return node.body.some((child) => symbolicDefiniteExit(child, depth + 1));
return (
t.isIfStatement(node) &&
symbolicDefiniteExit(node.consequent, depth + 1) &&
symbolicDefiniteExit(node.alternate, depth + 1)
);
};
@@ -0,0 +1,64 @@
import type * as t from "@babel/types";
/** A lexical substitution environment, never a JavaScript execution context. */
export interface SymbolicEnvironment {
readonly values: ReadonlyMap<string, SymbolicValue>;
readonly parent?: SymbolicEnvironment;
}
export interface SymbolicFunction {
readonly kind: "function";
readonly node: t.Function;
readonly environment: SymbolicEnvironment;
readonly origins: readonly t.Node[];
}
export type SymbolicValue =
| { readonly kind: "unknown"; readonly reason: string }
| {
readonly kind: "literal";
readonly value: string | number | boolean | null | undefined;
}
| { readonly kind: "external"; readonly path: readonly string[] }
| {
readonly kind: "object";
readonly node: t.ObjectExpression;
readonly environment: SymbolicEnvironment;
}
| {
readonly kind: "namespace";
readonly bindingId: string;
readonly environment: SymbolicEnvironment;
}
| {
readonly kind: "loader";
readonly modules: ReadonlyMap<string, SymbolicValue>;
}
| { readonly kind: "array"; readonly values: readonly SymbolicValue[] }
| {
readonly kind: "record";
readonly values: ReadonlyMap<string, SymbolicValue>;
}
| { readonly kind: "union"; readonly values: readonly SymbolicValue[] }
| SymbolicFunction;
export const symbolicUnknown = (reason: string): SymbolicValue => ({
kind: "unknown",
reason,
});
export const symbolicVariants = (
value: SymbolicValue,
): readonly SymbolicValue[] =>
value.kind === "union" ? value.values : [value];
export const symbolicUnion = (
values: readonly SymbolicValue[],
): SymbolicValue => {
const unique = [...new Set(values.flatMap(symbolicVariants))];
return unique.length === 1 ? unique[0]! : { kind: "union", values: unique };
};
export const symbolicTruth = (value: SymbolicValue): boolean | undefined =>
value.kind === "literal"
? Boolean(value.value)
: ["function", "object", "namespace", "array"].includes(value.kind)
? true
: undefined;