feat(electron): map static process and IPC boundaries
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
import type * as t from "@babel/types";
|
||||
|
||||
import { inspectElectronBrowserNode } from "./electronStaticAnalysisBrowser.js";
|
||||
import { inspectElectronIpcNode } from "./electronStaticAnalysisIpc.js";
|
||||
import { inspectElectronNativeNode } from "./electronStaticAnalysisNative.js";
|
||||
import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.js";
|
||||
|
||||
/** Collect Electron-specific syntax during the shared inert AST traversal. */
|
||||
export const inspectElectronStaticNode = (
|
||||
node: t.Node,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
inspectElectronBrowserNode(node, context);
|
||||
inspectElectronIpcNode(node, context);
|
||||
inspectElectronNativeNode(node, context);
|
||||
};
|
||||
@@ -0,0 +1,258 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
ElectronBrowserWindowFinding,
|
||||
ElectronContextBridgeFinding,
|
||||
ElectronStaticValue,
|
||||
ElectronUtilityProcessFinding,
|
||||
ElectronWebPreference,
|
||||
} from "./electronStaticAnalysisTypes.js";
|
||||
import {
|
||||
boundedExpression,
|
||||
collectContextBridgeMembers,
|
||||
electronStaticValue,
|
||||
objectProperty,
|
||||
} from "./electronStaticAnalysisValues.js";
|
||||
import { addLocatedFinding } from "./javascriptStaticAnalysisFindings.js";
|
||||
import {
|
||||
argumentNode,
|
||||
calleeName,
|
||||
compareCodePoints,
|
||||
propertyName,
|
||||
range,
|
||||
staticPath,
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.js";
|
||||
|
||||
const MAX_WEB_PREFERENCES = 64;
|
||||
|
||||
/** Inspect BrowserWindow, contextBridge, and utility-process syntax. */
|
||||
export const inspectElectronBrowserNode = (
|
||||
node: t.Node,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
if (t.isNewExpression(node)) inspectBrowserWindow(node, context);
|
||||
if (!t.isCallExpression(node)) return;
|
||||
inspectContextBridge(node, context);
|
||||
inspectUtilityProcess(node, context);
|
||||
};
|
||||
|
||||
const inspectBrowserWindow = (
|
||||
node: t.NewExpression,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
const name = calleeName(node.callee);
|
||||
if (name !== "BrowserWindow" && !name.endsWith(".BrowserWindow")) return;
|
||||
const options = argumentNode(node.arguments[0]);
|
||||
const collected = collectWindowOptions(context.source, options);
|
||||
accountForStructure(context, collected.unknown, collected.omitted);
|
||||
const finding: ElectronBrowserWindowFinding = {
|
||||
options_status:
|
||||
options === undefined
|
||||
? "missing"
|
||||
: t.isObjectExpression(options)
|
||||
? "object-literal"
|
||||
: "dynamic",
|
||||
web_preferences_status: collected.status,
|
||||
web_preferences: collected.preferences,
|
||||
omitted_web_preferences: collected.omitted,
|
||||
preload_path: collected.preloadPath,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
};
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.browserWindows,
|
||||
key: `electron-window\0${name}`,
|
||||
node,
|
||||
value: finding,
|
||||
});
|
||||
};
|
||||
|
||||
const collectWindowOptions = (
|
||||
source: string,
|
||||
options: t.Node | undefined,
|
||||
): {
|
||||
readonly status: ElectronBrowserWindowFinding["web_preferences_status"];
|
||||
readonly preferences: readonly ElectronWebPreference[];
|
||||
readonly preloadPath: string | null;
|
||||
readonly unknown: number;
|
||||
readonly omitted: number;
|
||||
} => {
|
||||
if (!t.isObjectExpression(options))
|
||||
return {
|
||||
status: options === undefined ? "missing" : "dynamic",
|
||||
preferences: [],
|
||||
preloadPath: null,
|
||||
unknown: options === undefined ? 0 : 1,
|
||||
omitted: 0,
|
||||
};
|
||||
const property = objectProperty(options, "webPreferences");
|
||||
if (property === undefined)
|
||||
return {
|
||||
status: "missing",
|
||||
preferences: [],
|
||||
preloadPath: null,
|
||||
unknown: 0,
|
||||
omitted: 0,
|
||||
};
|
||||
if (!t.isObjectExpression(property.value))
|
||||
return {
|
||||
status: "dynamic",
|
||||
preferences: [],
|
||||
preloadPath: null,
|
||||
unknown: 1,
|
||||
omitted: 0,
|
||||
};
|
||||
return collectWebPreferences(source, property.value);
|
||||
};
|
||||
|
||||
const collectWebPreferences = (
|
||||
source: string,
|
||||
object: t.ObjectExpression,
|
||||
): {
|
||||
readonly status: "object-literal";
|
||||
readonly preferences: readonly ElectronWebPreference[];
|
||||
readonly preloadPath: string | null;
|
||||
readonly unknown: number;
|
||||
readonly omitted: number;
|
||||
} => {
|
||||
const preferences: ElectronWebPreference[] = [];
|
||||
let unknown = 0;
|
||||
let preloadPath: string | null = null;
|
||||
for (const property of object.properties) {
|
||||
if (t.isSpreadElement(property)) {
|
||||
unknown += 1;
|
||||
preferences.push({
|
||||
name: `[spread@${String(property.start ?? -1)}]`,
|
||||
value: electronStaticValue(source, property.argument),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const name = propertyName(property.key);
|
||||
if (name === "" || property.computed) {
|
||||
unknown += 1;
|
||||
preferences.push({
|
||||
name: `[dynamic@${String(property.start ?? -1)}]`,
|
||||
value: electronStaticValue(source, property),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (t.isObjectMethod(property)) {
|
||||
unknown += 1;
|
||||
preferences.push({
|
||||
name,
|
||||
value: electronStaticValue(source, property),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const path = name === "preload" ? staticPath(property.value) : undefined;
|
||||
if (path !== undefined) preloadPath = path;
|
||||
const value: ElectronStaticValue =
|
||||
path === undefined
|
||||
? electronStaticValue(source, property.value)
|
||||
: { status: "literal", value: path, expression: null };
|
||||
if (value.status === "dynamic") unknown += 1;
|
||||
preferences.push({ name, value });
|
||||
}
|
||||
preferences.sort((left, right) => compareCodePoints(left.name, right.name));
|
||||
return {
|
||||
status: "object-literal",
|
||||
preferences: preferences.slice(0, MAX_WEB_PREFERENCES),
|
||||
preloadPath,
|
||||
unknown,
|
||||
omitted: Math.max(0, preferences.length - MAX_WEB_PREFERENCES),
|
||||
};
|
||||
};
|
||||
|
||||
const inspectContextBridge = (
|
||||
node: t.CallExpression,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
const name = calleeName(node.callee);
|
||||
const main =
|
||||
name === "contextBridge.exposeInMainWorld" ||
|
||||
name.endsWith(".contextBridge.exposeInMainWorld");
|
||||
const isolated =
|
||||
name === "contextBridge.exposeInIsolatedWorld" ||
|
||||
name.endsWith(".contextBridge.exposeInIsolatedWorld");
|
||||
if (!main && !isolated) return;
|
||||
const keyNode = argumentNode(node.arguments[isolated ? 1 : 0]);
|
||||
const apiNode = argumentNode(node.arguments[isolated ? 2 : 1]);
|
||||
const key = electronStaticValue(context.source, keyNode);
|
||||
const api = collectContextBridgeMembers(apiNode);
|
||||
const worldId = isolated
|
||||
? electronStaticValue(context.source, argumentNode(node.arguments[0]))
|
||||
: null;
|
||||
const unknown =
|
||||
(key.status === "dynamic" ? 1 : 0) +
|
||||
(worldId?.status === "dynamic" ? 1 : 0) +
|
||||
api.unknown;
|
||||
accountForStructure(context, unknown, api.omitted);
|
||||
const finding: ElectronContextBridgeFinding = {
|
||||
world: isolated ? "isolated" : "main",
|
||||
world_id: worldId,
|
||||
api_key:
|
||||
key.status === "literal" && typeof key.value === "string"
|
||||
? key.value
|
||||
: null,
|
||||
api_key_expression: key.status === "dynamic" ? key.expression : null,
|
||||
api_status: api.status,
|
||||
members: api.members,
|
||||
unknown_members: api.unknown,
|
||||
omitted_members: api.omitted,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
};
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.contextBridgeApis,
|
||||
key: `context-bridge\0${isolated ? "isolated" : "main"}\0${finding.api_key ?? finding.api_key_expression ?? "[missing]"}`,
|
||||
node,
|
||||
value: finding,
|
||||
});
|
||||
};
|
||||
|
||||
const inspectUtilityProcess = (
|
||||
node: t.CallExpression,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
const name = calleeName(node.callee);
|
||||
if (name !== "utilityProcess.fork" && !name.endsWith(".utilityProcess.fork"))
|
||||
return;
|
||||
const moduleNode = argumentNode(node.arguments[0]);
|
||||
const modulePath =
|
||||
moduleNode === undefined ? undefined : staticPath(moduleNode);
|
||||
const options = argumentNode(node.arguments[2]);
|
||||
const serviceName =
|
||||
t.isObjectExpression(options) &&
|
||||
objectProperty(options, "serviceName") !== undefined
|
||||
? staticPath(objectProperty(options, "serviceName")?.value ?? options)
|
||||
: undefined;
|
||||
if (modulePath === undefined) context.accumulator.unknownFindings += 1;
|
||||
const finding: ElectronUtilityProcessFinding = {
|
||||
module_path: modulePath ?? null,
|
||||
module_expression:
|
||||
modulePath === undefined
|
||||
? boundedExpression(context.source, moduleNode)
|
||||
: null,
|
||||
service_name: serviceName ?? null,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
};
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.utilityProcesses,
|
||||
key: `electron-utility\0${modulePath ?? finding.module_expression ?? "[missing]"}`,
|
||||
node,
|
||||
value: finding,
|
||||
});
|
||||
};
|
||||
|
||||
const accountForStructure = (
|
||||
context: JavaScriptFindingContext,
|
||||
unknown: number,
|
||||
omitted: number,
|
||||
): void => {
|
||||
context.accumulator.unknownFindings += unknown;
|
||||
if (omitted === 0) return;
|
||||
context.accumulator.structuralTruncation = true;
|
||||
context.accumulator.droppedFindings += omitted;
|
||||
};
|
||||
@@ -0,0 +1,216 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
ElectronIpcFinding,
|
||||
ElectronSenderValidationFinding,
|
||||
} from "./electronStaticAnalysisTypes.js";
|
||||
import {
|
||||
boundedExpression,
|
||||
electronStaticValue,
|
||||
handlerKind,
|
||||
} from "./electronStaticAnalysisValues.js";
|
||||
import { addLocatedFinding } from "./javascriptStaticAnalysisFindings.js";
|
||||
import {
|
||||
argumentNode,
|
||||
calleeName,
|
||||
propertyName,
|
||||
range,
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.js";
|
||||
|
||||
interface IpcDescriptor {
|
||||
readonly side: ElectronIpcFinding["side"];
|
||||
readonly operation: ElectronIpcFinding["operation"];
|
||||
readonly mode: ElectronIpcFinding["mode"];
|
||||
}
|
||||
|
||||
/** Inspect Electron IPC operations and validation candidates. */
|
||||
export const inspectElectronIpcNode = (
|
||||
node: t.Node,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
if (t.isCallExpression(node)) {
|
||||
inspectIpcCall(node, context);
|
||||
inspectValidationCall(node, context);
|
||||
}
|
||||
if (t.isBinaryExpression(node)) inspectValidationComparison(node, context);
|
||||
};
|
||||
|
||||
const inspectIpcCall = (
|
||||
node: t.CallExpression,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
const name = calleeName(node.callee);
|
||||
const descriptor = ipcDescriptor(name);
|
||||
if (descriptor === undefined) return;
|
||||
const channelNode = argumentNode(node.arguments[0]);
|
||||
const channelValue = electronStaticValue(context.source, channelNode);
|
||||
const channel =
|
||||
channelValue.status === "literal" && typeof channelValue.value === "string"
|
||||
? channelValue.value
|
||||
: null;
|
||||
const channelExpression =
|
||||
channel === null
|
||||
? channelValue.status === "dynamic"
|
||||
? channelValue.expression
|
||||
: boundedExpression(context.source, channelNode)
|
||||
: null;
|
||||
const hasHandler =
|
||||
descriptor.mode === "listen" || descriptor.mode === "handle";
|
||||
const handlerNode = hasHandler ? argumentNode(node.arguments[1]) : undefined;
|
||||
if (channel === null) context.accumulator.unknownFindings += 1;
|
||||
if (hasHandler && handlerNode === undefined)
|
||||
context.accumulator.unknownFindings += 1;
|
||||
const finding: ElectronIpcFinding = {
|
||||
...descriptor,
|
||||
channel,
|
||||
channel_expression: channelExpression,
|
||||
handler_kind: hasHandler ? handlerKind(handlerNode) : null,
|
||||
handler_location: handlerNode === undefined ? null : range(handlerNode),
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
};
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.ipc,
|
||||
key: `electron-ipc\0${descriptor.side}\0${descriptor.operation}\0${channel ?? channelExpression ?? "[missing]"}`,
|
||||
node,
|
||||
value: finding,
|
||||
});
|
||||
};
|
||||
|
||||
const inspectValidationComparison = (
|
||||
node: t.BinaryExpression,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
if (!["==", "===", "!=", "!==", "in"].includes(node.operator)) return;
|
||||
const left = senderSubject(node.left);
|
||||
const right = senderSubject(node.right);
|
||||
if (left === undefined && right === undefined) return;
|
||||
const expected = left === undefined ? node.left : node.right;
|
||||
addValidation(context, node, {
|
||||
subject: left ?? right ?? "sender-frame",
|
||||
mechanism: `comparison:${node.operator}`,
|
||||
expected: electronStaticValue(context.source, expected),
|
||||
});
|
||||
};
|
||||
|
||||
const inspectValidationCall = (
|
||||
node: t.CallExpression,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
if (
|
||||
!t.isMemberExpression(node.callee) &&
|
||||
!t.isOptionalMemberExpression(node.callee)
|
||||
)
|
||||
return;
|
||||
const method = propertyName(node.callee.property);
|
||||
if (!["startsWith", "endsWith", "includes"].includes(method)) return;
|
||||
const subject = t.isNode(node.callee.object)
|
||||
? senderSubject(node.callee.object)
|
||||
: undefined;
|
||||
if (subject === undefined) return;
|
||||
addValidation(context, node, {
|
||||
subject,
|
||||
mechanism: `call:${method}`,
|
||||
expected: electronStaticValue(
|
||||
context.source,
|
||||
argumentNode(node.arguments[0]),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const addValidation = (
|
||||
context: JavaScriptFindingContext,
|
||||
node: t.Node,
|
||||
input: Pick<
|
||||
ElectronSenderValidationFinding,
|
||||
"subject" | "mechanism" | "expected"
|
||||
>,
|
||||
): void => {
|
||||
if (input.expected.status === "dynamic")
|
||||
context.accumulator.unknownFindings += 1;
|
||||
const finding: ElectronSenderValidationFinding = {
|
||||
...input,
|
||||
enforcement: "unknown",
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
};
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.senderValidations,
|
||||
key: `electron-validation\0${input.subject}\0${input.mechanism}\0${input.expected.status === "literal" ? String(input.expected.value) : input.expected.expression}`,
|
||||
node,
|
||||
value: finding,
|
||||
});
|
||||
};
|
||||
|
||||
const ipcDescriptor = (name: string): IpcDescriptor | undefined => {
|
||||
const renderer = suffixOperation(name, "ipcRenderer");
|
||||
if (renderer !== undefined) {
|
||||
switch (renderer) {
|
||||
case "send":
|
||||
return { side: "renderer", operation: "send", mode: "send" };
|
||||
case "sendSync":
|
||||
return { side: "renderer", operation: "send-sync", mode: "send" };
|
||||
case "invoke":
|
||||
return { side: "renderer", operation: "invoke", mode: "invoke" };
|
||||
case "postMessage":
|
||||
return {
|
||||
side: "renderer",
|
||||
operation: "post-message",
|
||||
mode: "send",
|
||||
};
|
||||
case "sendToHost":
|
||||
return {
|
||||
side: "renderer",
|
||||
operation: "send-to-host",
|
||||
mode: "send",
|
||||
};
|
||||
case "on":
|
||||
return { side: "renderer", operation: "on", mode: "listen" };
|
||||
case "once":
|
||||
return { side: "renderer", operation: "once", mode: "listen" };
|
||||
}
|
||||
}
|
||||
const main = suffixOperation(name, "ipcMain");
|
||||
switch (main) {
|
||||
case "on":
|
||||
return { side: "main", operation: "on", mode: "listen" };
|
||||
case "once":
|
||||
return { side: "main", operation: "once", mode: "listen" };
|
||||
case "handle":
|
||||
return { side: "main", operation: "handle", mode: "handle" };
|
||||
case "handleOnce":
|
||||
return { side: "main", operation: "handle-once", mode: "handle" };
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const suffixOperation = (
|
||||
name: string,
|
||||
object: "ipcRenderer" | "ipcMain",
|
||||
): string | undefined => {
|
||||
const marker = `${object}.`;
|
||||
const index = name.lastIndexOf(marker);
|
||||
if (index < 0) return undefined;
|
||||
const prefix = name.slice(0, index);
|
||||
if (prefix !== "" && !prefix.endsWith(".")) return undefined;
|
||||
const operation = name.slice(index + marker.length);
|
||||
return operation.includes(".") ? undefined : operation;
|
||||
};
|
||||
|
||||
const senderSubject = (
|
||||
node: t.Node,
|
||||
): ElectronSenderValidationFinding["subject"] | undefined => {
|
||||
const name = t.isCallExpression(node)
|
||||
? calleeName(node.callee)
|
||||
: calleeName(node);
|
||||
if (/(?:^|\.)sender\.getURL$/u.test(name)) return "sender-url";
|
||||
if (/(?:^|\.)senderFrame\.origin$/u.test(name)) return "sender-origin";
|
||||
if (/(?:^|\.)senderFrame\.url$/u.test(name)) return "sender-url";
|
||||
if (/(?:^|\.)senderFrame$/u.test(name)) return "sender-frame";
|
||||
if (/(?:^|\.)sender\.id$/u.test(name)) return "sender-id";
|
||||
if (/(?:^|\.)frameId$/u.test(name)) return "frame-id";
|
||||
if (/(?:^|\.)processId$/u.test(name)) return "process-id";
|
||||
return undefined;
|
||||
};
|
||||
@@ -0,0 +1,210 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type { ElectronNativeAddonBindingFinding } from "./electronStaticAnalysisTypes.js";
|
||||
import { addLocatedFinding } from "./javascriptStaticAnalysisFindings.js";
|
||||
import {
|
||||
argumentNode,
|
||||
calleeName,
|
||||
compareCodePoints,
|
||||
propertyName,
|
||||
range,
|
||||
stringValue,
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.js";
|
||||
|
||||
const MAX_NATIVE_MEMBERS = 64;
|
||||
|
||||
interface NativeBindingInput {
|
||||
readonly context: JavaScriptFindingContext;
|
||||
readonly node: t.Node;
|
||||
readonly specifier: string;
|
||||
readonly kind: ElectronNativeAddonBindingFinding["binding_kind"];
|
||||
readonly members: readonly string[];
|
||||
}
|
||||
|
||||
/** Inspect JavaScript-side imports and re-exports of native .node addons. */
|
||||
export const inspectElectronNativeNode = (
|
||||
node: t.Node,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
if (t.isImportDeclaration(node)) inspectImport(node, context);
|
||||
else if (t.isExportNamedDeclaration(node)) inspectNamedExport(node, context);
|
||||
else if (t.isExportAllDeclaration(node)) inspectExportAll(node, context);
|
||||
else if (t.isVariableDeclarator(node)) inspectRequireBinding(node, context);
|
||||
else if (t.isAssignmentExpression(node)) inspectReExport(node, context);
|
||||
};
|
||||
|
||||
const inspectImport = (
|
||||
node: t.ImportDeclaration,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
if (!isNativeSpecifier(node.source.value)) return;
|
||||
const members = node.specifiers.map((specifier) => {
|
||||
if (t.isImportDefaultSpecifier(specifier)) return "default";
|
||||
if (t.isImportNamespaceSpecifier(specifier)) return "*";
|
||||
return propertyName(specifier.imported) || "[dynamic-import]";
|
||||
});
|
||||
addBinding({
|
||||
context,
|
||||
node,
|
||||
specifier: node.source.value,
|
||||
kind: "import",
|
||||
members,
|
||||
});
|
||||
};
|
||||
|
||||
const inspectNamedExport = (
|
||||
node: t.ExportNamedDeclaration,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
if (
|
||||
node.source === null ||
|
||||
node.source === undefined ||
|
||||
!isNativeSpecifier(node.source.value)
|
||||
)
|
||||
return;
|
||||
const members = node.specifiers.map((specifier) => {
|
||||
if (t.isExportSpecifier(specifier)) return propertyName(specifier.local);
|
||||
return "*";
|
||||
});
|
||||
addBinding({
|
||||
context,
|
||||
node,
|
||||
specifier: node.source.value,
|
||||
kind: "re-export",
|
||||
members,
|
||||
});
|
||||
};
|
||||
|
||||
const inspectExportAll = (
|
||||
node: t.ExportAllDeclaration,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
if (node.source === undefined || !isNativeSpecifier(node.source.value))
|
||||
return;
|
||||
addBinding({
|
||||
context,
|
||||
node,
|
||||
specifier: node.source.value,
|
||||
kind: "re-export",
|
||||
members: ["*"],
|
||||
});
|
||||
};
|
||||
|
||||
const inspectRequireBinding = (
|
||||
node: t.VariableDeclarator,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
const required = nativeRequire(node.init);
|
||||
if (required === undefined) return;
|
||||
addBinding({
|
||||
context,
|
||||
node,
|
||||
specifier: required.specifier,
|
||||
kind: "require",
|
||||
members:
|
||||
required.member === null ? bindingMembers(node.id) : [required.member],
|
||||
});
|
||||
};
|
||||
|
||||
const inspectReExport = (
|
||||
node: t.AssignmentExpression,
|
||||
context: JavaScriptFindingContext,
|
||||
): void => {
|
||||
const required = nativeRequire(node.right);
|
||||
if (required === undefined || !isModuleExport(node.left)) return;
|
||||
addBinding({
|
||||
context,
|
||||
node,
|
||||
specifier: required.specifier,
|
||||
kind: "re-export",
|
||||
members: [required.member ?? exportedMember(node.left) ?? "*"],
|
||||
});
|
||||
};
|
||||
|
||||
const addBinding = (input: NativeBindingInput): void => {
|
||||
const { context, node, specifier, kind } = input;
|
||||
const unique = [
|
||||
...new Set(input.members.filter((member) => member !== "")),
|
||||
].sort(compareCodePoints);
|
||||
const members = (unique.length === 0 ? ["*"] : unique).slice(
|
||||
0,
|
||||
MAX_NATIVE_MEMBERS,
|
||||
);
|
||||
const omitted = Math.max(0, unique.length - MAX_NATIVE_MEMBERS);
|
||||
if (omitted > 0) {
|
||||
context.accumulator.structuralTruncation = true;
|
||||
context.accumulator.droppedFindings += omitted;
|
||||
}
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.nativeAddonBindings,
|
||||
key: `native-addon-binding\0${kind}\0${specifier}\0${members.join("\0")}`,
|
||||
node,
|
||||
value: {
|
||||
specifier,
|
||||
binding_kind: kind,
|
||||
members,
|
||||
members_truncated: omitted > 0,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const nativeRequire = (
|
||||
node: t.Node | null | undefined,
|
||||
):
|
||||
| { readonly specifier: string; readonly member: string | null }
|
||||
| undefined => {
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const nested = t.isNode(node.object)
|
||||
? nativeRequire(node.object)
|
||||
: undefined;
|
||||
if (nested === undefined) return undefined;
|
||||
const member = propertyName(node.property);
|
||||
return { ...nested, member: member === "" ? nested.member : member };
|
||||
}
|
||||
if (!t.isCallExpression(node)) return undefined;
|
||||
const name = calleeName(node.callee);
|
||||
if (
|
||||
name !== "require" &&
|
||||
!name.endsWith(".require") &&
|
||||
!name.includes("__webpack_require__")
|
||||
)
|
||||
return undefined;
|
||||
const specifier = stringValue(argumentNode(node.arguments[0]));
|
||||
return specifier !== undefined && isNativeSpecifier(specifier)
|
||||
? { specifier, member: null }
|
||||
: undefined;
|
||||
};
|
||||
|
||||
const bindingMembers = (pattern: t.Node): string[] => {
|
||||
if (t.isIdentifier(pattern)) return ["*"];
|
||||
if (!t.isObjectPattern(pattern)) return ["*"];
|
||||
return pattern.properties.map((property) => {
|
||||
if (t.isRestElement(property)) return "*";
|
||||
return propertyName(property.key) || "[dynamic-import]";
|
||||
});
|
||||
};
|
||||
|
||||
const isModuleExport = (node: t.Node): boolean => {
|
||||
const name = calleeName(node);
|
||||
return (
|
||||
name === "module.exports" ||
|
||||
name.startsWith("module.exports.") ||
|
||||
name.startsWith("exports.")
|
||||
);
|
||||
};
|
||||
|
||||
const exportedMember = (node: t.Node): string | undefined => {
|
||||
const name = calleeName(node);
|
||||
if (name.startsWith("module.exports."))
|
||||
return name.slice("module.exports.".length);
|
||||
if (name.startsWith("exports.")) return name.slice("exports.".length);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const isNativeSpecifier = (specifier: string): boolean => {
|
||||
const path = specifier.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
return path.toLowerCase().endsWith(".node");
|
||||
};
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { JavaScriptSourceRange } from "./javascriptStaticAnalysisTypes.js";
|
||||
|
||||
/** One inert literal or unresolved expression observed in Electron syntax. */
|
||||
export type ElectronStaticValue =
|
||||
| {
|
||||
readonly status: "literal";
|
||||
readonly value: string | number | boolean | null;
|
||||
readonly expression: null;
|
||||
}
|
||||
| {
|
||||
readonly status: "dynamic";
|
||||
readonly value: null;
|
||||
readonly expression: string;
|
||||
};
|
||||
|
||||
/** One explicitly present BrowserWindow webPreference. */
|
||||
export interface ElectronWebPreference {
|
||||
readonly name: string;
|
||||
readonly value: ElectronStaticValue;
|
||||
}
|
||||
|
||||
/** Statically visible BrowserWindow construction and preference surface. */
|
||||
export interface ElectronBrowserWindowFinding {
|
||||
readonly options_status: "object-literal" | "dynamic" | "missing";
|
||||
readonly web_preferences_status: "object-literal" | "dynamic" | "missing";
|
||||
readonly web_preferences: readonly ElectronWebPreference[];
|
||||
readonly omitted_web_preferences: number;
|
||||
readonly preload_path: string | null;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One contextBridge API declaration without executing its API object. */
|
||||
export interface ElectronContextBridgeFinding {
|
||||
readonly world: "main" | "isolated";
|
||||
readonly world_id: ElectronStaticValue | null;
|
||||
readonly api_key: string | null;
|
||||
readonly api_key_expression: string | null;
|
||||
readonly api_status: "object-literal" | "dynamic" | "missing";
|
||||
readonly members: readonly string[];
|
||||
readonly unknown_members: number;
|
||||
readonly omitted_members: number;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One statically visible Electron IPC send, invocation, listener, or handler. */
|
||||
export interface ElectronIpcFinding {
|
||||
readonly side: "renderer" | "main";
|
||||
readonly operation:
|
||||
| "send"
|
||||
| "send-sync"
|
||||
| "invoke"
|
||||
| "post-message"
|
||||
| "send-to-host"
|
||||
| "on"
|
||||
| "once"
|
||||
| "handle"
|
||||
| "handle-once";
|
||||
readonly mode: "send" | "invoke" | "listen" | "handle";
|
||||
readonly channel: string | null;
|
||||
readonly channel_expression: string | null;
|
||||
readonly handler_kind:
|
||||
| "inline-function"
|
||||
| "identifier"
|
||||
| "member-expression"
|
||||
| "dynamic-expression"
|
||||
| "missing"
|
||||
| null;
|
||||
readonly handler_location: JavaScriptSourceRange | null;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** Static check involving an IPC sender, frame, process, URL, or origin. */
|
||||
export interface ElectronSenderValidationFinding {
|
||||
readonly subject:
|
||||
| "sender-url"
|
||||
| "sender-origin"
|
||||
| "sender-frame"
|
||||
| "sender-id"
|
||||
| "frame-id"
|
||||
| "process-id";
|
||||
readonly mechanism: string;
|
||||
readonly expected: ElectronStaticValue;
|
||||
readonly enforcement: "unknown";
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One utilityProcess.fork declaration and its statically visible entrypoint. */
|
||||
export interface ElectronUtilityProcessFinding {
|
||||
readonly module_path: string | null;
|
||||
readonly module_expression: string | null;
|
||||
readonly service_name: string | null;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** JavaScript-side binding or re-export requested from one native .node addon. */
|
||||
export interface ElectronNativeAddonBindingFinding {
|
||||
readonly specifier: string;
|
||||
readonly binding_kind: "import" | "require" | "re-export";
|
||||
readonly members: readonly string[];
|
||||
readonly members_truncated: boolean;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** All Electron-specific facts collected during one shared AST traversal. */
|
||||
export interface ElectronStaticFindings {
|
||||
readonly browser_windows: readonly ElectronBrowserWindowFinding[];
|
||||
readonly context_bridge_apis: readonly ElectronContextBridgeFinding[];
|
||||
readonly ipc: readonly ElectronIpcFinding[];
|
||||
readonly sender_validations: readonly ElectronSenderValidationFinding[];
|
||||
readonly utility_processes: readonly ElectronUtilityProcessFinding[];
|
||||
readonly native_addon_bindings: readonly ElectronNativeAddonBindingFinding[];
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type { ElectronStaticValue } from "./electronStaticAnalysisTypes.js";
|
||||
import {
|
||||
compareCodePoints,
|
||||
propertyName,
|
||||
sourceSlice,
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
|
||||
const MAX_EXPRESSION_CHARACTERS = 4_096;
|
||||
|
||||
/** Preserve one literal value or the exact bounded inert expression. */
|
||||
export const electronStaticValue = (
|
||||
source: string,
|
||||
node: t.Node | null | undefined,
|
||||
): ElectronStaticValue => {
|
||||
const literal = literalValue(node);
|
||||
return literal.found
|
||||
? { status: "literal", value: literal.value, expression: null }
|
||||
: {
|
||||
status: "dynamic",
|
||||
value: null,
|
||||
expression: boundedExpression(source, node),
|
||||
};
|
||||
};
|
||||
|
||||
/** Return an actionable bounded expression without evaluating it. */
|
||||
export const boundedExpression = (
|
||||
source: string,
|
||||
node: t.Node | null | undefined,
|
||||
): string => {
|
||||
if (node === null || node === undefined) return "[missing-expression]";
|
||||
const expression = sourceSlice(source, node).trim();
|
||||
return (expression === "" ? `[${node.type}]` : expression).slice(
|
||||
0,
|
||||
MAX_EXPRESSION_CHARACTERS,
|
||||
);
|
||||
};
|
||||
|
||||
/** Read one named object property without following spreads or bindings. */
|
||||
export const objectProperty = (
|
||||
object: t.ObjectExpression,
|
||||
name: string,
|
||||
): t.ObjectProperty | undefined =>
|
||||
object.properties.find(
|
||||
(property): property is t.ObjectProperty =>
|
||||
t.isObjectProperty(property) && propertyName(property.key) === name,
|
||||
);
|
||||
|
||||
/** Classify a handler argument while retaining its exact source range. */
|
||||
export const handlerKind = (
|
||||
node: t.Node | null | undefined,
|
||||
):
|
||||
| "inline-function"
|
||||
| "identifier"
|
||||
| "member-expression"
|
||||
| "dynamic-expression"
|
||||
| "missing" => {
|
||||
if (node === null || node === undefined) return "missing";
|
||||
if (
|
||||
t.isArrowFunctionExpression(node) ||
|
||||
t.isFunctionExpression(node) ||
|
||||
t.isFunctionDeclaration(node)
|
||||
)
|
||||
return "inline-function";
|
||||
if (t.isIdentifier(node)) return "identifier";
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node))
|
||||
return "member-expression";
|
||||
return "dynamic-expression";
|
||||
};
|
||||
|
||||
/** Collect bounded dotted keys from one literal contextBridge API object. */
|
||||
export const collectContextBridgeMembers = (
|
||||
node: t.Node | null | undefined,
|
||||
maximum = 128,
|
||||
): {
|
||||
readonly status: "object-literal" | "dynamic" | "missing";
|
||||
readonly members: readonly string[];
|
||||
readonly unknown: number;
|
||||
readonly omitted: number;
|
||||
} => {
|
||||
if (node === null || node === undefined)
|
||||
return {
|
||||
status: "missing",
|
||||
members: [],
|
||||
unknown: 0,
|
||||
omitted: 0,
|
||||
};
|
||||
if (!t.isObjectExpression(node))
|
||||
return {
|
||||
status: "dynamic",
|
||||
members: [],
|
||||
unknown: 1,
|
||||
omitted: 0,
|
||||
};
|
||||
const state = { members: [] as string[], unknown: 0 };
|
||||
collectMembersAt(node, "", 0, state);
|
||||
const members = [...new Set(state.members)].sort(compareCodePoints);
|
||||
return {
|
||||
status: "object-literal",
|
||||
members: members.slice(0, maximum),
|
||||
unknown: state.unknown,
|
||||
omitted: Math.max(0, members.length - maximum),
|
||||
};
|
||||
};
|
||||
|
||||
const collectMembersAt = (
|
||||
object: t.ObjectExpression,
|
||||
prefix: string,
|
||||
depth: number,
|
||||
state: { members: string[]; unknown: number },
|
||||
): void => {
|
||||
if (depth >= 8) {
|
||||
state.unknown += 1;
|
||||
return;
|
||||
}
|
||||
for (const property of object.properties) {
|
||||
if (t.isSpreadElement(property)) {
|
||||
state.unknown += 1;
|
||||
continue;
|
||||
}
|
||||
const name = propertyName(property.key);
|
||||
if (name === "" || property.computed) {
|
||||
state.unknown += 1;
|
||||
continue;
|
||||
}
|
||||
const path = (prefix === "" ? name : `${prefix}.${name}`).slice(
|
||||
0,
|
||||
MAX_EXPRESSION_CHARACTERS,
|
||||
);
|
||||
state.members.push(path);
|
||||
if (t.isObjectProperty(property) && t.isObjectExpression(property.value))
|
||||
collectMembersAt(property.value, path, depth + 1, state);
|
||||
}
|
||||
};
|
||||
|
||||
const literalValue = (
|
||||
node: t.Node | null | undefined,
|
||||
):
|
||||
| { readonly found: true; readonly value: string | number | boolean | null }
|
||||
| { readonly found: false } => {
|
||||
if (t.isStringLiteral(node) || t.isNumericLiteral(node))
|
||||
return { found: true, value: node.value };
|
||||
if (t.isBooleanLiteral(node)) return { found: true, value: node.value };
|
||||
if (t.isNullLiteral(node)) return { found: true, value: null };
|
||||
if (t.isTemplateLiteral(node) && node.expressions.length === 0)
|
||||
return {
|
||||
found: true,
|
||||
value: (
|
||||
node.quasis[0]?.value.cooked ??
|
||||
node.quasis[0]?.value.raw ??
|
||||
""
|
||||
).slice(0, MAX_EXPRESSION_CHARACTERS),
|
||||
};
|
||||
if (
|
||||
t.isUnaryExpression(node, { operator: "-" }) &&
|
||||
t.isNumericLiteral(node.argument)
|
||||
)
|
||||
return { found: true, value: -node.argument.value };
|
||||
return { found: false };
|
||||
};
|
||||
@@ -274,7 +274,10 @@ export class ArtifactOperationError extends AnalysisError {
|
||||
readonly _tag = "ArtifactOperationError";
|
||||
|
||||
constructor(
|
||||
readonly operation: "inventory_artifact" | "extract_artifact",
|
||||
readonly operation:
|
||||
| "inventory_artifact"
|
||||
| "extract_artifact"
|
||||
| "analyze_javascript_application",
|
||||
readonly reason:
|
||||
| "cancelled"
|
||||
| "format"
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationGraphSchema } from "./javascriptApplicationGraph.js";
|
||||
|
||||
const MAX_GRAPH_NODES = 100_000;
|
||||
const MAX_GRAPH_EDGES = 200_000;
|
||||
const countSchema = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
|
||||
/** Default hard bounds for one local JavaScript application analysis. */
|
||||
export const JAVASCRIPT_APPLICATION_ANALYSIS_DEFAULT_LIMITS = {
|
||||
max_entries: 8_000,
|
||||
max_total_artifact_bytes: 512 * 1_024 * 1_024,
|
||||
max_artifact_entry_bytes: 128 * 1_024 * 1_024,
|
||||
max_compression_ratio: 1_000,
|
||||
max_depth: 64,
|
||||
max_path_bytes: 4_096,
|
||||
max_text_files: 5_000,
|
||||
max_total_text_bytes: 128 * 1_024 * 1_024,
|
||||
max_text_file_bytes: 8 * 1_024 * 1_024,
|
||||
max_ast_nodes: 2_000_000,
|
||||
max_findings: 8_000,
|
||||
max_modules: 20_000,
|
||||
max_source_map_sources: 5_000,
|
||||
max_parse_milliseconds: 30_000,
|
||||
} as const;
|
||||
|
||||
/** Combined artifact, text, AST, and graph projection bounds. */
|
||||
export const javascriptApplicationAnalysisLimitsSchema = z
|
||||
.strictObject({
|
||||
max_entries: z.number().int().min(1).max(1_000_000).default(8_000),
|
||||
max_total_artifact_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(512 * 1_024 * 1_024),
|
||||
max_artifact_entry_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(128 * 1_024 * 1_024),
|
||||
max_compression_ratio: z.number().min(1).max(100_000).default(1_000),
|
||||
max_depth: z.number().int().min(1).max(100).default(64),
|
||||
max_path_bytes: z.number().int().min(1).max(65_535).default(4_096),
|
||||
max_text_files: z.number().int().min(1).max(100_000).default(5_000),
|
||||
max_total_text_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(512 * 1_024 * 1_024)
|
||||
.default(128 * 1_024 * 1_024),
|
||||
max_text_file_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(64 * 1_024 * 1_024)
|
||||
.default(8 * 1_024 * 1_024),
|
||||
max_ast_nodes: z.number().int().min(1).max(20_000_000).default(2_000_000),
|
||||
max_findings: z.number().int().min(1).max(200_000).default(8_000),
|
||||
max_modules: z.number().int().min(1).max(100_000).default(20_000),
|
||||
max_source_map_sources: z.number().int().min(1).max(100_000).default(5_000),
|
||||
max_parse_milliseconds: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(300_000)
|
||||
.default(30_000),
|
||||
})
|
||||
.superRefine((limits, context) => {
|
||||
const projectedNodes =
|
||||
7 * limits.max_entries +
|
||||
2 * limits.max_findings +
|
||||
limits.max_modules +
|
||||
limits.max_source_map_sources +
|
||||
1;
|
||||
if (projectedNodes > MAX_GRAPH_NODES)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["max_entries"],
|
||||
message:
|
||||
"Combined application-analysis limits can exceed the 100000-node graph contract",
|
||||
});
|
||||
const projectedEdges =
|
||||
9 * limits.max_entries +
|
||||
6 * limits.max_findings +
|
||||
limits.max_modules +
|
||||
limits.max_source_map_sources;
|
||||
if (projectedEdges > MAX_GRAPH_EDGES)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["max_entries"],
|
||||
message:
|
||||
"Combined application-analysis limits can exceed the 200000-edge graph contract",
|
||||
});
|
||||
});
|
||||
|
||||
/** Public target-free request for bounded static JavaScript application analysis. */
|
||||
export const analyzeJavaScriptApplicationInputSchema = z.strictObject({
|
||||
input_path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(16_384)
|
||||
.refine(isAbsolute, "JavaScript application input path must be absolute"),
|
||||
format: z.enum(["auto", "asar", "directory"]).default("auto"),
|
||||
approved: z.literal(true),
|
||||
source_map_read_approved: z.boolean().default(false),
|
||||
limits: javascriptApplicationAnalysisLimitsSchema.default(
|
||||
JAVASCRIPT_APPLICATION_ANALYSIS_DEFAULT_LIMITS,
|
||||
),
|
||||
});
|
||||
|
||||
/** Compact counts for the high-level Electron architecture/security surface. */
|
||||
const electronBoundarySummarySchema = z.strictObject({
|
||||
browser_windows: countSchema,
|
||||
explicit_web_preferences: countSchema,
|
||||
preload_entrypoints: countSchema,
|
||||
context_bridge_apis: countSchema,
|
||||
exposed_api_members: countSchema,
|
||||
ipc: z.strictObject({
|
||||
operations: countSchema,
|
||||
literal_channels: countSchema,
|
||||
dynamic_channel_operations: countSchema,
|
||||
renderer_transmissions: countSchema,
|
||||
renderer_listeners: countSchema,
|
||||
main_handlers: countSchema,
|
||||
paired_renderer_transmissions: countSchema,
|
||||
ambiguous_renderer_transmissions: countSchema,
|
||||
unpaired_literal_renderer_transmissions: countSchema,
|
||||
}),
|
||||
sender_validation_observations: countSchema,
|
||||
utility_processes: countSchema,
|
||||
resolved_utility_entrypoints: countSchema,
|
||||
native_addon_bindings: countSchema,
|
||||
resolved_native_addon_bindings: countSchema,
|
||||
});
|
||||
|
||||
const reconstructionStatisticsSchema = z.strictObject({
|
||||
relevant_files: countSchema,
|
||||
nested_asar_containers: countSchema,
|
||||
text_files_selected: countSchema,
|
||||
text_bytes_read: countSchema,
|
||||
omitted_text_files: countSchema,
|
||||
limit_omitted_text_files: countSchema,
|
||||
policy_filtered_text_files: countSchema,
|
||||
invalid_utf8_files: countSchema,
|
||||
parsed_javascript_files: countSchema,
|
||||
visited_ast_nodes: countSchema,
|
||||
findings: countSchema,
|
||||
modules: countSchema,
|
||||
parse_failures: countSchema,
|
||||
truncated_scopes: countSchema,
|
||||
});
|
||||
|
||||
/** Strict high-level result returned inside Evidence v2. */
|
||||
export const javascriptApplicationAnalysisResultSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
input_path: z.string().min(1).max(16_384),
|
||||
format: z.enum(["asar", "directory"]),
|
||||
root_artifact_sha256: digestSchema,
|
||||
inventory_manifest_id: z.string().regex(/^agm_[a-f0-9]{64}$/u),
|
||||
inventory_graph_sha256: digestSchema,
|
||||
graph: javascriptApplicationGraphSchema,
|
||||
summary: electronBoundarySummarySchema,
|
||||
statistics: reconstructionStatisticsSchema,
|
||||
limitations: z.array(z.string().min(1).max(4_096)).max(1_000),
|
||||
});
|
||||
|
||||
/** Parsed public JavaScript application analysis request. */
|
||||
export type AnalyzeJavaScriptApplicationInput = z.infer<
|
||||
typeof analyzeJavaScriptApplicationInputSchema
|
||||
>;
|
||||
|
||||
/** Validated high-level JavaScript application analysis result. */
|
||||
export type JavaScriptApplicationAnalysisResult = z.infer<
|
||||
typeof javascriptApplicationAnalysisResultSchema
|
||||
>;
|
||||
|
||||
/** Validated high-level Electron boundary counts. */
|
||||
export type ElectronBoundarySummary = z.infer<
|
||||
typeof electronBoundarySummarySchema
|
||||
>;
|
||||
@@ -36,11 +36,15 @@ import {
|
||||
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 {
|
||||
addBoundedFinding,
|
||||
addLocatedFinding,
|
||||
finalizeLocatedFindings,
|
||||
moduleAtOffset,
|
||||
} from "./javascriptStaticAnalysisFindings.js";
|
||||
import { inspectElectronStaticNode } from "./electronStaticAnalysis.js";
|
||||
import type {
|
||||
JavaScriptBundlerModule,
|
||||
JavaScriptStaticAnalysis,
|
||||
@@ -63,6 +67,17 @@ export const analyzeJavaScriptStaticSource = (
|
||||
return failedJavaScriptStaticAnalysis();
|
||||
}
|
||||
const accumulator = createJavaScriptAnalysisAccumulator();
|
||||
traverseStaticSource(source, file, accumulator, limits);
|
||||
addSourceMapDirectives(source, accumulator, limits.maxFindings);
|
||||
return finalizeStaticAnalysis(source, file, accumulator, limits);
|
||||
};
|
||||
|
||||
const traverseStaticSource = (
|
||||
source: string,
|
||||
file: ReturnType<typeof parse>,
|
||||
accumulator: AnalysisAccumulator,
|
||||
limits: JavaScriptStaticAnalysisLimits,
|
||||
): void => {
|
||||
if (limits.now() > limits.deadline) accumulator.truncated = true;
|
||||
if (!accumulator.truncated)
|
||||
t.traverseFast(file, (node) => {
|
||||
@@ -78,7 +93,14 @@ export const analyzeJavaScriptStaticSource = (
|
||||
inspectNode(source, node, accumulator, limits);
|
||||
return undefined;
|
||||
});
|
||||
addSourceMapDirectives(source, accumulator, limits.maxFindings);
|
||||
};
|
||||
|
||||
const finalizeStaticAnalysis = (
|
||||
source: string,
|
||||
file: ReturnType<typeof parse>,
|
||||
accumulator: AnalysisAccumulator,
|
||||
limits: JavaScriptStaticAnalysisLimits,
|
||||
): JavaScriptStaticAnalysis => {
|
||||
const parserErrors = file.errors.length;
|
||||
const limitations = [
|
||||
...(parserErrors === 0
|
||||
@@ -98,7 +120,7 @@ export const analyzeJavaScriptStaticSource = (
|
||||
...(accumulator.unknownFindings === 0
|
||||
? []
|
||||
: [
|
||||
"One or more bundler registration keys were dynamic and remain unknown.",
|
||||
"One or more static keys, expressions, or Electron boundary values were dynamic and remain unknown.",
|
||||
]),
|
||||
"JavaScript syntax was parsed as data and was never evaluated.",
|
||||
];
|
||||
@@ -112,16 +134,45 @@ export const analyzeJavaScriptStaticSource = (
|
||||
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),
|
||||
references: finalizeLocatedFindings(
|
||||
accumulator.references,
|
||||
accumulator.modules,
|
||||
),
|
||||
endpoints: finalizeLocatedFindings(
|
||||
accumulator.endpoints,
|
||||
accumulator.modules,
|
||||
),
|
||||
storage: finalizeLocatedFindings(accumulator.storage, accumulator.modules),
|
||||
bundler_registrations: sortedUnique(
|
||||
accumulator.registrations,
|
||||
registrationKey,
|
||||
),
|
||||
role_paths: finalizeLocated(accumulator.roles, accumulator.modules),
|
||||
role_paths: finalizeLocatedFindings(accumulator.roles, accumulator.modules),
|
||||
source_map_urls: accumulator.sourceMaps,
|
||||
vendors: detectVendors(source),
|
||||
electron: {
|
||||
browser_windows: finalizeLocatedFindings(
|
||||
accumulator.browserWindows,
|
||||
accumulator.modules,
|
||||
),
|
||||
context_bridge_apis: finalizeLocatedFindings(
|
||||
accumulator.contextBridgeApis,
|
||||
accumulator.modules,
|
||||
),
|
||||
ipc: finalizeLocatedFindings(accumulator.ipc, accumulator.modules),
|
||||
sender_validations: finalizeLocatedFindings(
|
||||
accumulator.senderValidations,
|
||||
accumulator.modules,
|
||||
),
|
||||
utility_processes: finalizeLocatedFindings(
|
||||
accumulator.utilityProcesses,
|
||||
accumulator.modules,
|
||||
),
|
||||
native_addon_bindings: finalizeLocatedFindings(
|
||||
accumulator.nativeAddonBindings,
|
||||
accumulator.modules,
|
||||
),
|
||||
},
|
||||
limitations,
|
||||
};
|
||||
};
|
||||
@@ -137,6 +188,7 @@ const inspectNode = (
|
||||
accumulator,
|
||||
maximum: limits.maxFindings,
|
||||
};
|
||||
inspectElectronStaticNode(node, findings);
|
||||
if (t.isCallExpression(node)) {
|
||||
inspectBundlerRegistration(source, node, accumulator, limits);
|
||||
inspectCall(node, findings);
|
||||
@@ -175,7 +227,7 @@ const inspectCall = (
|
||||
const { accumulator } = context;
|
||||
const name = calleeName(node.callee);
|
||||
const first = stringValue(node.arguments[0]);
|
||||
const module = moduleAt(node.start, accumulator.modules);
|
||||
const module = moduleAtOffset(node.start, accumulator.modules);
|
||||
const moduleRequire =
|
||||
module?.requireName !== null && name === module?.requireName;
|
||||
if (
|
||||
@@ -202,7 +254,7 @@ const inspectCall = (
|
||||
inspectEndpointCall(node, name, first, context);
|
||||
inspectStorageCall(node, name, first, context);
|
||||
if (name.endsWith("loadFile") && first !== undefined)
|
||||
addLocated(context, {
|
||||
addLocatedFinding(context, {
|
||||
collection: accumulator.roles,
|
||||
key: `role\0renderer\0${first}`,
|
||||
node,
|
||||
@@ -296,7 +348,7 @@ const inspectBundlerRegistration = (
|
||||
),
|
||||
location: range(call),
|
||||
};
|
||||
addBounded(
|
||||
addBoundedFinding(
|
||||
accumulator,
|
||||
`registration\0${registrationKey(registration)}`,
|
||||
limits.maxFindings,
|
||||
@@ -351,7 +403,7 @@ const inspectRoleProperty = (
|
||||
if (propertyName(node.key) !== "preload") return;
|
||||
const path = staticPath(node.value);
|
||||
if (path === undefined) return;
|
||||
addLocated(context, {
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.roles,
|
||||
key: `role\0preload\0${path}`,
|
||||
node,
|
||||
@@ -373,7 +425,7 @@ const inspectStorageCall = (
|
||||
): void => {
|
||||
const storage = storageKind(name);
|
||||
if (storage === undefined) return;
|
||||
addLocated(context, {
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.storage,
|
||||
key: `storage\0${storage}\0${first ?? ""}`,
|
||||
node,
|
||||
@@ -393,7 +445,7 @@ const addReference = (context: FindingContext, input: ReferenceInput): void => {
|
||||
boundedSpecifier === null
|
||||
? sourceSlice(context.source, input.node).slice(0, 4_096)
|
||||
: null;
|
||||
addLocated(context, {
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.references,
|
||||
key: `reference\0${input.kind}\0${boundedSpecifier ?? expression}`,
|
||||
node: input.node,
|
||||
@@ -408,7 +460,7 @@ const addReference = (context: FindingContext, input: ReferenceInput): void => {
|
||||
};
|
||||
|
||||
const addEndpoint = (context: FindingContext, input: EndpointInput): void =>
|
||||
addLocated(context, {
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.endpoints,
|
||||
key: `endpoint\0${input.kind}\0${input.value}`,
|
||||
node: input.node,
|
||||
@@ -421,60 +473,6 @@ const addEndpoint = (context: FindingContext, input: EndpointInput): void =>
|
||||
},
|
||||
});
|
||||
|
||||
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,
|
||||
@@ -487,7 +485,7 @@ const addSourceMapDirectives = (
|
||||
if (declared === undefined) continue;
|
||||
const start = match.index;
|
||||
const location = rangeForOffsets(source, start, start + match[0].length);
|
||||
addBounded(accumulator, `source-map\0${declared}`, maximum, () =>
|
||||
addBoundedFinding(accumulator, `source-map\0${declared}`, maximum, () =>
|
||||
accumulator.sourceMaps.push({ declared_url: declared, location }),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import type {
|
||||
JavaScriptAnalysisAccumulator,
|
||||
JavaScriptFindingContext,
|
||||
JavaScriptModuleRange,
|
||||
LocatedJavaScriptFinding,
|
||||
LocatedJavaScriptFindingInput,
|
||||
} from "./javascriptStaticAnalysisState.js";
|
||||
|
||||
/** Add one module-attributable finding under the shared global finding bound. */
|
||||
export const addLocatedFinding = <
|
||||
Value extends { readonly module_key: string | null },
|
||||
>(
|
||||
context: JavaScriptFindingContext,
|
||||
input: LocatedJavaScriptFindingInput<Value>,
|
||||
): void =>
|
||||
addBoundedFinding(
|
||||
context.accumulator,
|
||||
`${input.key}\0${String(input.node.start)}`,
|
||||
context.maximum,
|
||||
() =>
|
||||
input.collection.push({
|
||||
offset: input.node.start ?? -1,
|
||||
value: input.value,
|
||||
}),
|
||||
);
|
||||
|
||||
/** Reserve one deterministic finding key before mutating an accumulator. */
|
||||
export const addBoundedFinding = (
|
||||
accumulator: JavaScriptAnalysisAccumulator,
|
||||
key: string,
|
||||
maximum: number,
|
||||
add: () => void,
|
||||
): void => {
|
||||
if (accumulator.seen.has(key)) return;
|
||||
if (accumulatedFindingCount(accumulator) >= maximum) {
|
||||
accumulator.droppedFindings += 1;
|
||||
return;
|
||||
}
|
||||
accumulator.seen.add(key);
|
||||
add();
|
||||
};
|
||||
|
||||
/** Attach recovered bundle-module ownership to findings after traversal. */
|
||||
export const finalizeLocatedFindings = <
|
||||
Value extends { readonly module_key: string | null },
|
||||
>(
|
||||
values: readonly LocatedJavaScriptFinding<Value>[],
|
||||
modules: readonly JavaScriptModuleRange[],
|
||||
): Value[] =>
|
||||
values.map(({ offset, value }) => ({
|
||||
...value,
|
||||
module_key: moduleAtOffset(offset, modules)?.key ?? null,
|
||||
}));
|
||||
|
||||
/** Locate the recovered bundle factory containing one exact source offset. */
|
||||
export const moduleAtOffset = (
|
||||
offset: number | null | undefined,
|
||||
modules: readonly JavaScriptModuleRange[],
|
||||
): JavaScriptModuleRange | undefined => {
|
||||
if (offset === null || offset === undefined) return undefined;
|
||||
return modules.find(({ start, end }) => offset >= start && offset <= end);
|
||||
};
|
||||
|
||||
const accumulatedFindingCount = (
|
||||
accumulator: JavaScriptAnalysisAccumulator,
|
||||
): number =>
|
||||
accumulator.references.length +
|
||||
accumulator.endpoints.length +
|
||||
accumulator.storage.length +
|
||||
accumulator.roles.length +
|
||||
accumulator.sourceMaps.length +
|
||||
accumulator.registrations.length +
|
||||
accumulator.browserWindows.length +
|
||||
accumulator.contextBridgeApis.length +
|
||||
accumulator.ipc.length +
|
||||
accumulator.senderValidations.length +
|
||||
accumulator.utilityProcesses.length +
|
||||
accumulator.nativeAddonBindings.length;
|
||||
@@ -24,12 +24,32 @@ export const failedJavaScriptStaticAnalysis = (): JavaScriptStaticAnalysis => ({
|
||||
role_paths: [],
|
||||
source_map_urls: [],
|
||||
vendors: [],
|
||||
electron: {
|
||||
browser_windows: [],
|
||||
context_bridge_apis: [],
|
||||
ipc: [],
|
||||
sender_validations: [],
|
||||
utility_processes: [],
|
||||
native_addon_bindings: [],
|
||||
},
|
||||
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.",
|
||||
],
|
||||
});
|
||||
|
||||
/** Normalize one Babel call/new argument into the inert node shared by inspectors. */
|
||||
export const argumentNode = (
|
||||
argument:
|
||||
| t.Expression
|
||||
| t.SpreadElement
|
||||
| t.JSXNamespacedName
|
||||
| t.ArgumentPlaceholder
|
||||
| null
|
||||
| undefined,
|
||||
): t.Node | undefined =>
|
||||
argument !== null && t.isNode(argument) ? argument : undefined;
|
||||
|
||||
/** Recognize the bounded runtime name for a Webpack/Rspack push call. */
|
||||
export const chunkRuntime = (call: t.CallExpression): string | undefined => {
|
||||
if (
|
||||
|
||||
@@ -8,6 +8,14 @@ import type {
|
||||
JavaScriptStaticReference,
|
||||
JavaScriptStaticStorage,
|
||||
} from "./javascriptStaticAnalysisTypes.js";
|
||||
import type {
|
||||
ElectronBrowserWindowFinding,
|
||||
ElectronContextBridgeFinding,
|
||||
ElectronIpcFinding,
|
||||
ElectronNativeAddonBindingFinding,
|
||||
ElectronSenderValidationFinding,
|
||||
ElectronUtilityProcessFinding,
|
||||
} from "./electronStaticAnalysisTypes.js";
|
||||
|
||||
/** Source offsets for one recovered bundle module factory. */
|
||||
export interface JavaScriptModuleRange {
|
||||
@@ -31,6 +39,12 @@ export interface JavaScriptAnalysisAccumulator {
|
||||
readonly roles: LocatedJavaScriptFinding<JavaScriptRolePath>[];
|
||||
readonly sourceMaps: JavaScriptStaticAnalysis["source_map_urls"][number][];
|
||||
readonly registrations: JavaScriptBundlerRegistration[];
|
||||
readonly browserWindows: LocatedJavaScriptFinding<ElectronBrowserWindowFinding>[];
|
||||
readonly contextBridgeApis: LocatedJavaScriptFinding<ElectronContextBridgeFinding>[];
|
||||
readonly ipc: LocatedJavaScriptFinding<ElectronIpcFinding>[];
|
||||
readonly senderValidations: LocatedJavaScriptFinding<ElectronSenderValidationFinding>[];
|
||||
readonly utilityProcesses: LocatedJavaScriptFinding<ElectronUtilityProcessFinding>[];
|
||||
readonly nativeAddonBindings: LocatedJavaScriptFinding<ElectronNativeAddonBindingFinding>[];
|
||||
readonly modules: JavaScriptModuleRange[];
|
||||
readonly seen: Set<string>;
|
||||
visitedNodes: number;
|
||||
@@ -82,6 +96,12 @@ export const createJavaScriptAnalysisAccumulator =
|
||||
roles: [],
|
||||
sourceMaps: [],
|
||||
registrations: [],
|
||||
browserWindows: [],
|
||||
contextBridgeApis: [],
|
||||
ipc: [],
|
||||
senderValidations: [],
|
||||
utilityProcesses: [],
|
||||
nativeAddonBindings: [],
|
||||
modules: [],
|
||||
seen: new Set(),
|
||||
visitedNodes: 0,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ElectronStaticFindings } from "./electronStaticAnalysisTypes.js";
|
||||
|
||||
/** One source coordinate produced by the JavaScript parser. */
|
||||
export interface JavaScriptSourcePoint {
|
||||
readonly line: number;
|
||||
@@ -95,6 +97,7 @@ export interface JavaScriptStaticAnalysis {
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}[];
|
||||
readonly vendors: readonly string[];
|
||||
readonly electron: ElectronStaticFindings;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user