feat(electron): map static process and IPC boundaries

This commit is contained in:
N0zoM1z0
2026-07-16 07:56:13 +09:00
committed by N0zoM1z0
parent 3988a866f1
commit 3fa2304bc7
279 changed files with 7481 additions and 775 deletions
+203
View File
@@ -0,0 +1,203 @@
import type { ElectronIpcFinding } from "../domain/electronStaticAnalysisTypes.js";
import type { ElectronBoundarySummary } from "../domain/javascriptApplicationAnalysis.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import { resolveArtifactPath } from "./JavaScriptArtifactGraphContext.js";
/** One IPC fact retaining its exact owning artifact for graph projection. */
export interface ElectronIpcRecord {
readonly key: string;
readonly file: JavaScriptArtifactFile;
readonly finding: ElectronIpcFinding;
}
/** An unambiguous literal renderer-to-main static pairing. */
export interface ElectronIpcPairing {
readonly transmission: ElectronIpcRecord;
readonly handler: ElectronIpcRecord;
}
/** Pairing state for one renderer transmission without overclaiming ambiguity. */
export interface ElectronIpcPairingState {
readonly transmission: ElectronIpcRecord;
readonly candidates: readonly ElectronIpcRecord[];
readonly status: "paired" | "ambiguous" | "unpaired";
}
/** Flatten all per-file IPC facts into deterministic application records. */
export const collectElectronIpcRecords = (
analysis: JavaScriptArtifactAnalysis,
): readonly ElectronIpcRecord[] =>
analysis.files
.flatMap(({ file, javascript }) =>
(javascript?.electron.ipc ?? []).map((finding) => ({
key: ipcRecordKey(file.path, finding),
file,
finding,
})),
)
.sort((left, right) => compareCodePoints(left.key, right.key));
/** Match only exact literal channels and retain ambiguous matches separately. */
export const classifyElectronIpcPairings = (
records: readonly ElectronIpcRecord[],
): readonly ElectronIpcPairingState[] => {
const handlers = records.filter(isMainHandler);
return records.filter(isPairableRendererTransmission).map((transmission) => {
const candidates =
transmission.finding.channel === null
? []
: handlers.filter(
(handler) =>
handler.finding.channel === transmission.finding.channel &&
compatibleIpcModes(transmission.finding, handler.finding),
);
return {
transmission,
candidates,
status:
candidates.length === 1
? "paired"
: candidates.length > 1
? "ambiguous"
: "unpaired",
};
});
};
/** Return only pairings supported by one unique literal main handler. */
export const unambiguousElectronIpcPairings = (
records: readonly ElectronIpcRecord[],
): readonly ElectronIpcPairing[] =>
classifyElectronIpcPairings(records).flatMap((state) => {
const handler = state.candidates[0];
return state.status === "paired" && handler !== undefined
? [{ transmission: state.transmission, handler }]
: [];
});
/** Summarize static Electron findings without treating gaps as absence. */
export const summarizeElectronBoundaries = (
analysis: JavaScriptArtifactAnalysis,
): ElectronBoundarySummary => {
const files = new Map(analysis.files.map(({ file }) => [file.path, file]));
const javascript = analysis.files.flatMap(({ javascript: value }) =>
value === null ? [] : [value],
);
const windows = javascript.flatMap(
({ electron }) => electron.browser_windows,
);
const bridges = javascript.flatMap(
({ electron }) => electron.context_bridge_apis,
);
const validations = javascript.flatMap(
({ electron }) => electron.sender_validations,
);
const utilities = analysis.files.flatMap(({ file, javascript: value }) =>
(value?.electron.utility_processes ?? []).map((finding) => ({
file,
finding,
})),
);
const nativeBindings = analysis.files.flatMap(({ file, javascript: value }) =>
(value?.electron.native_addon_bindings ?? []).map((finding) => ({
file,
finding,
})),
);
const ipc = collectElectronIpcRecords(analysis);
const pairing = classifyElectronIpcPairings(ipc);
const literalChannels = new Set(
ipc.flatMap(({ finding }) =>
finding.channel === null ? [] : [finding.channel],
),
);
return {
browser_windows: windows.length,
explicit_web_preferences: windows.reduce(
(count, window) => count + window.web_preferences.length,
0,
),
preload_entrypoints: windows.filter(
({ preload_path: path }) => path !== null,
).length,
context_bridge_apis: bridges.length,
exposed_api_members: bridges.reduce(
(count, bridge) => count + bridge.members.length,
0,
),
ipc: {
operations: ipc.length,
literal_channels: literalChannels.size,
dynamic_channel_operations: ipc.filter(
({ finding }) => finding.channel === null,
).length,
renderer_transmissions: ipc.filter(isRendererTransmission).length,
renderer_listeners: ipc.filter(
({ finding }) =>
finding.side === "renderer" && finding.mode === "listen",
).length,
main_handlers: ipc.filter(isMainHandler).length,
paired_renderer_transmissions: pairing.filter(
({ status }) => status === "paired",
).length,
ambiguous_renderer_transmissions: pairing.filter(
({ status }) => status === "ambiguous",
).length,
unpaired_literal_renderer_transmissions: pairing.filter(
({ status, transmission }) =>
status === "unpaired" && transmission.finding.channel !== null,
).length,
},
sender_validation_observations: validations.length,
utility_processes: utilities.length,
resolved_utility_entrypoints: utilities.filter(({ file, finding }) =>
resolvesToFile(file, finding.module_path, files),
).length,
native_addon_bindings: nativeBindings.length,
resolved_native_addon_bindings: nativeBindings.filter(({ file, finding }) =>
resolvesToFile(file, finding.specifier, files, "native-addon"),
).length,
};
};
const compatibleIpcModes = (
transmission: ElectronIpcFinding,
handler: ElectronIpcFinding,
): boolean =>
transmission.mode === "invoke"
? handler.mode === "handle"
: transmission.operation === "send-to-host"
? false
: transmission.mode === "send" && handler.mode === "listen";
const isRendererTransmission = ({ finding }: ElectronIpcRecord): boolean =>
finding.side === "renderer" &&
(finding.mode === "send" || finding.mode === "invoke");
const isPairableRendererTransmission = (record: ElectronIpcRecord): boolean =>
isRendererTransmission(record) && record.finding.operation !== "send-to-host";
const isMainHandler = ({ finding }: ElectronIpcRecord): boolean =>
finding.side === "main" &&
(finding.mode === "listen" || finding.mode === "handle");
const resolvesToFile = (
file: JavaScriptArtifactFile,
specifier: string | null,
files: ReadonlyMap<string, JavaScriptArtifactFile>,
kind?: JavaScriptArtifactFile["kind"],
): boolean => {
if (specifier === null) return false;
const resolved = resolveArtifactPath(specifier, file.path, files);
return (
resolved !== null &&
(kind === undefined || files.get(resolved)?.kind === kind)
);
};
const ipcRecordKey = (path: string, finding: ElectronIpcFinding): string =>
`${path}\0${String(finding.location.start.line)}:${String(finding.location.start.column)}\0${finding.side}\0${finding.operation}`;
const compareCodePoints = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
+13
View File
@@ -0,0 +1,13 @@
import type { JavaScriptArtifactGraphContext } from "./JavaScriptArtifactGraphContext.js";
import { addElectronIpcBoundaries } from "./ElectronBoundaryGraphIpc.js";
import { addElectronNativeBoundaries } from "./ElectronBoundaryGraphNative.js";
import { addElectronWindowBoundaries } from "./ElectronBoundaryGraphWindows.js";
/** Add every static Electron process and security-boundary fact to the JAG. */
export const addElectronBoundaries = (
context: JavaScriptArtifactGraphContext,
): void => {
addElectronWindowBoundaries(context);
addElectronIpcBoundaries(context);
addElectronNativeBoundaries(context);
};
@@ -0,0 +1,127 @@
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
import { sha256Text } from "../domain/javascriptStaticAnalysisHelpers.js";
import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import type {
JavaScriptArtifactGraphContext,
JavaScriptArtifactGraphCoverage,
} from "./JavaScriptArtifactGraphContext.js";
import {
astObservationEvidence,
staticInferenceEvidence,
} from "./JavaScriptArtifactGraphEvidence.js";
/** Values for one Electron syntax relationship retained in the graph. */
export interface ElectronGraphEdgeInput {
readonly source: ApplicationNode;
readonly target: ApplicationNode;
readonly file: JavaScriptArtifactFile;
readonly range: JavaScriptSourceRange;
readonly coverage: JavaScriptArtifactGraphCoverage;
readonly relation:
| "contains"
| "loads"
| "imports"
| "maps_to"
| "exposes"
| "sends"
| "invokes"
| "handles";
readonly operation: string;
readonly properties: Readonly<Record<string, unknown>>;
readonly confidence?: "high" | "medium" | "low";
readonly limitations?: readonly string[];
}
/** Resolve the file or recovered bundle module that owns one finding. */
export const electronFindingSourceNode = (
context: JavaScriptArtifactGraphContext,
file: JavaScriptArtifactFile,
moduleKey: string | null,
): ApplicationNode | undefined =>
moduleKey === null
? (context.assetNodes.get(file.path) ?? context.fileNodes.get(file.path))
: context.moduleNodes.get(`${file.path}\0${moduleKey}`);
/** Observation-scoped identity shared safely across different artifact files. */
export const electronObservationIdentity = (
context: JavaScriptArtifactGraphContext,
scope: string,
key: string,
) => ({
strategy: "observation-fingerprint" as const,
stability: "observation-only" as const,
observation_sha256: sha256Text(
`${context.snapshot.manifest.root_sha256}\0${scope}\0${key}`,
),
scope: scope.slice(0, 4_096),
});
/** Add a direct AST syntax relationship. */
export const addElectronAstEdge = (
context: JavaScriptArtifactGraphContext,
input: ElectronGraphEdgeInput,
): void => {
context.accumulator.addEdge({
source_node_id: input.source.node_id,
target_node_id: input.target.node_id,
relation: input.relation,
properties: input.properties,
evidence: astObservationEvidence({
sha256: input.file.sha256,
path: input.file.path,
range: input.range,
operation: input.operation,
coverage: input.coverage,
...(input.limitations === undefined
? {}
: { limitations: input.limitations }),
}),
});
};
/** Add an Electron relationship that static syntax suggests but cannot prove. */
export const addElectronInferenceEdge = (
context: JavaScriptArtifactGraphContext,
input: ElectronGraphEdgeInput,
): void => {
context.accumulator.addEdge({
source_node_id: input.source.node_id,
target_node_id: input.target.node_id,
relation: input.relation,
properties: input.properties,
evidence: staticInferenceEvidence({
sha256: input.file.sha256,
path: input.file.path,
range: input.range,
operation: input.operation,
coverage: input.coverage,
...(input.confidence === undefined
? {}
: { confidence: input.confidence }),
...(input.limitations === undefined
? {}
: { limitations: input.limitations }),
}),
});
};
/** Deterministic source-range key for artifact-local graph identities. */
export const electronRangeKey = (range: JavaScriptSourceRange): string =>
`${String(range.start.line)}:${String(range.start.column)}-${String(range.end.line)}:${String(range.end.column)}`;
/** Test exact source-range containment without assuming runtime reachability. */
export const electronRangeContains = (
outer: JavaScriptSourceRange,
inner: JavaScriptSourceRange,
): boolean =>
comparePoint(outer.start, inner.start) <= 0 &&
comparePoint(outer.end, inner.end) >= 0;
const comparePoint = (
left: JavaScriptSourceRange["start"],
right: JavaScriptSourceRange["start"],
): number =>
left.line === right.line
? left.column - right.column
: left.line - right.line;
+345
View File
@@ -0,0 +1,345 @@
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
import type { ElectronSenderValidationFinding } from "../domain/electronStaticAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import {
artifactLocalIdentity,
javascriptAnalysisCoverage,
type JavaScriptArtifactGraphContext,
type JavaScriptArtifactGraphCoverage,
} from "./JavaScriptArtifactGraphContext.js";
import { astObservationEvidence } from "./JavaScriptArtifactGraphEvidence.js";
import {
collectElectronIpcRecords,
unambiguousElectronIpcPairings,
type ElectronIpcRecord,
} from "./ElectronBoundaryAnalysis.js";
import {
addElectronAstEdge,
addElectronInferenceEdge,
electronFindingSourceNode,
electronObservationIdentity,
electronRangeContains,
electronRangeKey,
} from "./ElectronBoundaryGraphContext.js";
interface IpcGraphState {
readonly context: JavaScriptArtifactGraphContext;
readonly records: readonly ElectronIpcRecord[];
readonly channels: Map<string, ApplicationNode>;
readonly handlers: Map<string, ApplicationNode>;
readonly sources: Map<string, ApplicationNode>;
}
interface IpcHandlerInput {
readonly context: JavaScriptArtifactGraphContext;
readonly record: ElectronIpcRecord;
readonly source: ApplicationNode;
readonly channel: ApplicationNode;
readonly coverage: JavaScriptArtifactGraphCoverage;
}
interface ValidationObservationInput {
readonly context: JavaScriptArtifactGraphContext;
readonly file: JavaScriptArtifactFile;
readonly validation: ElectronSenderValidationFinding;
readonly target: ApplicationNode;
readonly coverage: JavaScriptArtifactGraphCoverage;
}
/** Project IPC syntax, handler locations, validations, and exact pairings. */
export const addElectronIpcBoundaries = (
context: JavaScriptArtifactGraphContext,
): void => {
const state: IpcGraphState = {
context,
records: collectElectronIpcRecords(context.analysis),
channels: new Map(),
handlers: new Map(),
sources: new Map(),
};
for (const record of state.records) addIpcRecord(state, record);
addValidationObservations(state);
addLiteralPairings(state);
};
const addIpcRecord = (
state: IpcGraphState,
record: ElectronIpcRecord,
): void => {
const { context } = state;
const coverage = coverageFor(context, record.file);
if (coverage === undefined) return;
const source = electronFindingSourceNode(
context,
record.file,
record.finding.module_key,
);
if (source === undefined) return;
state.sources.set(record.key, source);
const channel = addChannelNode(context, record, coverage);
state.channels.set(record.key, channel);
if (record.finding.mode === "listen" || record.finding.mode === "handle") {
const handler = addHandlerNode({
context,
record,
source,
channel,
coverage,
});
state.handlers.set(record.key, handler);
return;
}
addElectronInferenceEdge(context, {
source,
target: channel,
file: record.file,
range: record.finding.location,
coverage,
relation: record.finding.mode === "invoke" ? "invokes" : "sends",
operation: "map-ipc-transmission",
properties: {
side: record.finding.side,
operation: record.finding.operation,
channel: record.finding.channel,
channel_expression: record.finding.channel_expression,
resolution: record.finding.channel === null ? "dynamic" : "literal",
},
});
};
const addChannelNode = (
context: JavaScriptArtifactGraphContext,
record: ElectronIpcRecord,
coverage: JavaScriptArtifactGraphCoverage,
): ApplicationNode => {
const { finding, file } = record;
const identityKey =
finding.channel === null
? `dynamic:${record.key}`
: `literal:${finding.channel}`;
return context.accumulator.addNode({
kind: "ipc-channel",
identity: electronObservationIdentity(
context,
"electron-ipc-channel",
identityKey,
),
observations: [
{
label: finding.channel ?? finding.channel_expression,
properties: {
side: finding.side,
operation: finding.operation,
mode: finding.mode,
channel: finding.channel,
channel_expression: finding.channel_expression,
resolution: finding.channel === null ? "dynamic" : "literal",
},
evidence: astObservationEvidence({
sha256: file.sha256,
path: file.path,
range: finding.location,
operation: "observe-ipc-channel-expression",
coverage,
limitations:
finding.channel === null
? [
"The channel expression is dynamic; its runtime value and pairings remain unknown.",
]
: [],
}),
},
],
});
};
const addHandlerNode = (input: IpcHandlerInput): ApplicationNode => {
const { context, record, source, channel, coverage } = input;
const { finding, file } = record;
const handlerRange = finding.handler_location ?? finding.location;
const handler = context.accumulator.addNode({
kind: "ipc-handler",
identity: artifactLocalIdentity(
file.sha256,
"electron-ipc-handler",
`${finding.side}:${finding.operation}:${finding.channel ?? finding.channel_expression ?? "[missing]"}:${electronRangeKey(handlerRange)}`,
),
observations: [
{
label: finding.channel,
properties: {
side: finding.side,
operation: finding.operation,
mode: finding.mode,
channel: finding.channel,
channel_expression: finding.channel_expression,
handler_kind: finding.handler_kind,
handler_location: finding.handler_location,
},
evidence: astObservationEvidence({
sha256: file.sha256,
path: file.path,
range: handlerRange,
operation: "observe-ipc-handler",
coverage,
}),
},
],
});
addElectronAstEdge(context, {
source,
target: handler,
file,
range: handlerRange,
coverage,
relation: "contains",
operation: "locate-ipc-handler",
properties: { side: finding.side, operation: finding.operation },
});
addElectronInferenceEdge(context, {
source: handler,
target: channel,
file,
range: finding.location,
coverage,
relation: "handles",
operation: "map-ipc-handler-registration",
properties: {
channel: finding.channel,
channel_expression: finding.channel_expression,
resolution: finding.channel === null ? "dynamic" : "literal",
},
});
return handler;
};
const addLiteralPairings = (state: IpcGraphState): void => {
for (const pairing of unambiguousElectronIpcPairings(state.records)) {
const source = state.sources.get(pairing.transmission.key);
const handler = state.handlers.get(pairing.handler.key);
const coverage = coverageFor(state.context, pairing.transmission.file);
if (source === undefined || handler === undefined || coverage === undefined)
continue;
addElectronInferenceEdge(state.context, {
source,
target: handler,
file: pairing.transmission.file,
range: pairing.transmission.finding.location,
coverage,
relation:
pairing.transmission.finding.mode === "invoke" ? "invokes" : "sends",
operation: "pair-ipc-literal-channel",
properties: {
channel: pairing.transmission.finding.channel,
pairing_basis: "unique-exact-literal-channel",
handler_path: pairing.handler.file.path,
handler_operation: pairing.handler.finding.operation,
},
limitations: [
"Literal channel equality does not prove that the handler is registered or reachable at runtime.",
],
});
}
};
const addValidationObservations = (state: IpcGraphState): void => {
for (const analyzed of state.context.analysis.files) {
const { file, javascript } = analyzed;
if (javascript === null) continue;
const coverage = javascriptAnalysisCoverage(
javascript,
state.context.input,
);
for (const validation of javascript.electron.sender_validations) {
const handlerRecord = containingHandler(state.records, file, validation);
const target =
handlerRecord === undefined
? electronFindingSourceNode(
state.context,
file,
validation.module_key,
)
: state.handlers.get(handlerRecord.key);
if (target !== undefined)
addValidationObservation({
context: state.context,
file,
validation,
target,
coverage,
});
}
}
};
const addValidationObservation = (input: ValidationObservationInput): void => {
const { context, file, validation, target, coverage } = input;
context.accumulator.addNode({
kind: target.kind,
identity: target.identity,
observations: [
{
label: `${validation.subject} validation candidate`,
properties: {
fact_kind: "sender-validation-candidate",
subject: validation.subject,
mechanism: validation.mechanism,
expected: validation.expected,
enforcement: validation.enforcement,
},
evidence: astObservationEvidence({
sha256: file.sha256,
path: file.path,
range: validation.location,
operation: "observe-ipc-sender-validation-candidate",
coverage,
limitations: [
"A comparison or string check is visible, but static syntax alone does not prove rejection, ordering, or complete sender validation.",
],
}),
},
],
});
};
const containingHandler = (
records: readonly ElectronIpcRecord[],
file: JavaScriptArtifactFile,
validation: ElectronSenderValidationFinding,
): ElectronIpcRecord | undefined =>
records
.filter(
(record) =>
record.file.path === file.path &&
record.finding.handler_location !== null &&
electronRangeContains(
record.finding.handler_location,
validation.location,
),
)
.sort(
(left, right) =>
rangeMagnitude(left.finding.handler_location) -
rangeMagnitude(right.finding.handler_location),
)[0];
const rangeMagnitude = (
range: ElectronIpcRecord["finding"]["handler_location"],
): number =>
range === null
? Number.MAX_SAFE_INTEGER
: (range.end.line - range.start.line) * 1_000_000 +
range.end.column -
range.start.column;
const coverageFor = (
context: JavaScriptArtifactGraphContext,
file: JavaScriptArtifactFile,
): JavaScriptArtifactGraphCoverage | undefined => {
const javascript = context.analysis.files.find(
({ file: candidate }) => candidate.path === file.path,
)?.javascript;
return javascript === null || javascript === undefined
? undefined
: javascriptAnalysisCoverage(javascript, context.input);
};
@@ -0,0 +1,114 @@
import type { ElectronNativeAddonBindingFinding } from "../domain/electronStaticAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import {
javascriptAnalysisCoverage,
resolveArtifactPath,
type JavaScriptArtifactGraphContext,
type JavaScriptArtifactGraphCoverage,
} from "./JavaScriptArtifactGraphContext.js";
import { astObservationEvidence } from "./JavaScriptArtifactGraphEvidence.js";
import {
addElectronInferenceEdge,
electronFindingSourceNode,
electronObservationIdentity,
electronRangeKey,
} from "./ElectronBoundaryGraphContext.js";
interface NativeBindingInput {
readonly context: JavaScriptArtifactGraphContext;
readonly file: JavaScriptArtifactFile;
readonly value: ElectronNativeAddonBindingFinding;
readonly coverage: JavaScriptArtifactGraphCoverage;
}
/** Project JavaScript-requested native addon binding and re-export surfaces. */
export const addElectronNativeBoundaries = (
context: JavaScriptArtifactGraphContext,
): void => {
for (const analyzed of context.analysis.files) {
const { file, javascript } = analyzed;
if (javascript === null) continue;
const coverage = javascriptAnalysisCoverage(javascript, context.input);
for (const value of javascript.electron.native_addon_bindings)
addNativeBinding({ context, file, value, coverage });
}
};
const addNativeBinding = (input: NativeBindingInput): void => {
const { context, file, value, coverage } = input;
const source = electronFindingSourceNode(context, file, value.module_key);
if (source === undefined) return;
const resolved = resolveArtifactPath(
value.specifier,
file.path,
context.filesByPath,
);
const addon = resolved === null ? undefined : context.fileNodes.get(resolved);
const binding = context.accumulator.addNode({
kind: "native-export",
identity: electronObservationIdentity(
context,
"javascript-requested-native-export",
`${file.path}:${value.specifier}:${value.binding_kind}:${value.members.join("\0")}:${electronRangeKey(value.location)}`,
),
observations: [
{
label: value.members.join(", "),
properties: {
specifier: value.specifier,
binding_kind: value.binding_kind,
requested_members: value.members,
members_truncated: value.members_truncated,
resolved_path: resolved,
native_export_verification: "not-performed",
},
evidence: astObservationEvidence({
sha256: file.sha256,
path: file.path,
range: value.location,
operation: "observe-native-addon-binding",
coverage,
limitations: [
"JavaScript syntax identifies requested member names; it does not prove that the native binary exports or implements them.",
],
}),
},
],
});
addElectronInferenceEdge(context, {
source,
target: binding,
file,
range: value.location,
coverage,
relation: value.binding_kind === "re-export" ? "exposes" : "imports",
operation: "map-native-addon-binding",
properties: {
specifier: value.specifier,
binding_kind: value.binding_kind,
requested_members: value.members,
},
limitations: [
"Requested JavaScript members are not verified native exports.",
],
});
if (addon === undefined || resolved === null) return;
addElectronInferenceEdge(context, {
source: addon,
target: binding,
file,
range: value.location,
coverage,
relation: "exposes",
operation: "associate-native-addon-requested-exports",
properties: {
resolved_path: resolved,
requested_members: value.members,
verified: false,
},
confidence: "medium",
limitations: [
"The .node artifact path is resolved, but requested JavaScript members have not been verified against native symbols.",
],
});
};
@@ -0,0 +1,260 @@
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
import type {
ElectronBrowserWindowFinding,
ElectronContextBridgeFinding,
ElectronUtilityProcessFinding,
} from "../domain/electronStaticAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import {
artifactLocalIdentity,
createElectronRoleNode,
javascriptAnalysisCoverage,
linkElectronRoleToAsset,
resolveArtifactPath,
type JavaScriptArtifactGraphContext,
type JavaScriptArtifactGraphCoverage,
} from "./JavaScriptArtifactGraphContext.js";
import { astObservationEvidence } from "./JavaScriptArtifactGraphEvidence.js";
import {
addElectronAstEdge,
addElectronInferenceEdge,
electronFindingSourceNode,
electronRangeKey,
} from "./ElectronBoundaryGraphContext.js";
interface FindingInput<Value> {
readonly context: JavaScriptArtifactGraphContext;
readonly file: JavaScriptArtifactFile;
readonly source: ApplicationNode;
readonly value: Value;
readonly coverage: JavaScriptArtifactGraphCoverage;
}
/** Project BrowserWindow, contextBridge, preload, and utility-process facts. */
export const addElectronWindowBoundaries = (
context: JavaScriptArtifactGraphContext,
): void => {
for (const analyzed of context.analysis.files) {
const { file, javascript } = analyzed;
if (javascript === null) continue;
const coverage = javascriptAnalysisCoverage(javascript, context.input);
for (const value of javascript.electron.browser_windows) {
const source = electronFindingSourceNode(context, file, value.module_key);
if (source !== undefined)
addBrowserWindow({ context, file, source, value, coverage });
}
for (const value of javascript.electron.context_bridge_apis) {
const source = electronFindingSourceNode(context, file, value.module_key);
if (source !== undefined)
addContextBridge({ context, file, source, value, coverage });
}
for (const value of javascript.electron.utility_processes) {
const source = electronFindingSourceNode(context, file, value.module_key);
if (source !== undefined)
addUtilityProcess({ context, file, source, value, coverage });
}
}
};
const addBrowserWindow = (
input: FindingInput<ElectronBrowserWindowFinding>,
): void => {
const { context, file, value, coverage } = input;
const window = context.accumulator.addNode({
kind: "browser-window",
identity: artifactLocalIdentity(
file.sha256,
"electron-browser-window",
electronRangeKey(value.location),
),
observations: [
{
label: `BrowserWindow@${electronRangeKey(value.location)}`,
properties: {
source_path: file.path,
options_status: value.options_status,
web_preferences_status: value.web_preferences_status,
web_preferences: value.web_preferences,
omitted_web_preferences: value.omitted_web_preferences,
preload_path: value.preload_path,
absence_means_default: false,
},
evidence: astObservationEvidence({
sha256: file.sha256,
path: file.path,
range: value.location,
operation: "observe-browser-window-construction",
coverage,
limitations: [
"Only explicitly present webPreferences are reported; omitted properties are not interpreted as Electron defaults.",
],
}),
},
],
});
addElectronAstEdge(context, {
source: input.source,
target: window,
file,
range: value.location,
coverage,
relation: "contains",
operation: "locate-browser-window-construction",
properties: { source_path: file.path },
});
addWindowPreload(input, window);
};
const addWindowPreload = (
input: FindingInput<ElectronBrowserWindowFinding>,
window: ApplicationNode,
): void => {
const declared = input.value.preload_path;
if (declared === null) return;
const resolved = resolveArtifactPath(
declared,
input.file.path,
input.context.filesByPath,
);
const role = createElectronRoleNode(input.context, {
kind: "electron-preload",
anchor: input.file,
declaredPath: declared,
resolvedPath: resolved,
mechanism: "BrowserWindow:webPreferences.preload",
range: input.value.location,
coverage: input.coverage,
});
addElectronInferenceEdge(input.context, {
source: window,
target: role,
file: input.file,
range: input.value.location,
coverage: input.coverage,
relation: "loads",
operation: "associate-browser-window-preload",
properties: { declared_path: declared, resolved_path: resolved },
});
linkElectronRoleToAsset(input.context, {
role,
anchor: input.file,
path: resolved,
range: input.value.location,
coverage: input.coverage,
});
};
const addContextBridge = (
input: FindingInput<ElectronContextBridgeFinding>,
): void => {
const { context, file, value, coverage } = input;
const bridge = context.accumulator.addNode({
kind: "context-bridge-api",
identity: artifactLocalIdentity(
file.sha256,
"electron-context-bridge",
`${value.world}:${value.api_key ?? value.api_key_expression ?? "[missing]"}:${electronRangeKey(value.location)}`,
),
observations: [
{
label: value.api_key,
properties: {
world: value.world,
world_id: value.world_id,
api_key: value.api_key,
api_key_expression: value.api_key_expression,
api_status: value.api_status,
members: value.members,
unknown_members: value.unknown_members,
omitted_members: value.omitted_members,
},
evidence: astObservationEvidence({
sha256: file.sha256,
path: file.path,
range: value.location,
operation: "observe-context-bridge-api",
coverage,
}),
},
],
});
addElectronInferenceEdge(context, {
source: input.source,
target: bridge,
file,
range: value.location,
coverage,
relation: "exposes",
operation: "map-context-bridge-exposure",
properties: {
world: value.world,
api_key: value.api_key,
resolution: value.api_key === null ? "dynamic" : "literal",
},
});
};
const addUtilityProcess = (
input: FindingInput<ElectronUtilityProcessFinding>,
): void => {
const { context, file, value, coverage } = input;
const utility = context.accumulator.addNode({
kind: "electron-utility",
identity: artifactLocalIdentity(
file.sha256,
"electron-utility-process",
`${value.module_path ?? value.module_expression ?? "[missing]"}:${electronRangeKey(value.location)}`,
),
observations: [
{
label: value.service_name ?? value.module_path,
properties: {
module_path: value.module_path,
module_expression: value.module_expression,
service_name: value.service_name,
},
evidence: astObservationEvidence({
sha256: file.sha256,
path: file.path,
range: value.location,
operation: "observe-utility-process-fork",
coverage,
}),
},
],
});
addElectronInferenceEdge(context, {
source: input.source,
target: utility,
file,
range: value.location,
coverage,
relation: "loads",
operation: "map-utility-process-launch",
properties: {
declared_path: value.module_path,
expression: value.module_expression,
},
});
if (value.module_path === null) return;
const resolved = resolveArtifactPath(
value.module_path,
file.path,
context.filesByPath,
);
const target =
resolved === null
? undefined
: (context.assetNodes.get(resolved) ?? context.fileNodes.get(resolved));
if (target === undefined) return;
addElectronInferenceEdge(context, {
source: utility,
target,
file,
range: value.location,
coverage,
relation: "maps_to",
operation: "resolve-utility-process-entrypoint",
properties: { resolved_path: resolved },
});
};
@@ -25,6 +25,13 @@ export const ARTIFACT_GRAPH_PROVIDER = {
version: "1",
} as const;
/** Provider identity for deterministic static JavaScript application analysis. */
export const JAVASCRIPT_APPLICATION_PROVIDER = {
id: "rea-javascript-application",
name: "REA JavaScript application analyzer",
version: "1",
} as const;
/** Provider identity for deterministic cross-artifact comparisons. */
export const ARTIFACT_COMPARISON_PROVIDER = {
id: "rea-artifact-comparison",
@@ -0,0 +1,46 @@
import {
createEvidence,
type Evidence,
type EvidenceObservation,
} from "../domain/evidence.js";
import type {
AnalyzeJavaScriptApplicationInput,
JavaScriptApplicationAnalysisResult,
} from "../domain/javascriptApplicationAnalysis.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { JAVASCRIPT_APPLICATION_PROVIDER } from "./InvestigationProviders.js";
/** Create Evidence v2 for one deterministic local JavaScript application graph. */
export const createJavaScriptApplicationEvidence = (
input: AnalyzeJavaScriptApplicationInput,
result: JavaScriptApplicationAnalysisResult,
): Evidence =>
createEvidence(
{
path: result.input_path,
sha256: result.root_artifact_sha256,
format: result.format,
},
JAVASCRIPT_APPLICATION_PROVIDER,
{
predicateType: "rea.javascript-application-analysis/v1",
operation: "analyze_javascript_application",
parameters: parameters(input),
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "derived",
authority: "shipped-artifact",
environment: null,
limitations: result.limitations,
locations: [{ kind: "artifact-path", path: "artifact-root" }],
},
);
const parameters = (
input: AnalyzeJavaScriptApplicationInput,
): EvidenceObservation["parameters"] => ({
format: input.format,
approved: input.approved,
source_map_read_approved: input.source_map_read_approved,
limits: input.limits,
});
@@ -0,0 +1,109 @@
import { z } from "zod";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import {
analyzeJavaScriptApplicationInputSchema,
javascriptApplicationAnalysisResultSchema,
} from "../domain/javascriptApplicationAnalysis.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisProtocolError,
ArtifactOperationError,
PermissionRequiredError,
type AnalysisError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { Evidence } from "../domain/evidence.js";
import type { ExecutionOptions } from "./AnalysisProvider.js";
import { createJavaScriptApplicationEvidence } from "./JavaScriptApplicationEvidence.js";
import { reconstructJavaScriptArtifact } from "./JavaScriptArtifactReconstruction.js";
import type { PermissionAuthority } from "./PermissionAuthority.js";
const OPERATION = "analyze_javascript_application" as const;
/** Authorize and statically analyze one local JavaScript/Electron application. */
export const analyzeJavaScriptApplication = async (
authority: PermissionAuthority | undefined,
rawInput: unknown,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const parsed = analyzeJavaScriptApplicationInputSchema.safeParse(rawInput);
if (!parsed.success) return err(new AnalysisInputError(OPERATION));
if (authority === undefined)
return err(
new AnalysisCapabilityUnavailableError(
"rea-javascript-application",
OPERATION,
"JavaScript application permission policy is not configured",
),
);
const authorized = await authority.authorize(
{
capability: "investigation_input",
roots: [parsed.data.input_path],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: `${OPERATION}:${parsed.data.input_path}`,
},
"read",
);
if (!authorized.ok)
return err(
authorized.error instanceof PermissionRequiredError
? authorized.error
: new ArtifactOperationError(OPERATION, "path", {
logicalPath: parsed.data.input_path,
declaredSha256: null,
calculatedSha256: null,
unpacked: false,
}),
);
await options.progress?.report({
phase: "analyze_javascript_application",
completed: 0,
total: 1,
message: "Inventorying and parsing approved application artifacts",
});
try {
const reconstructed = await reconstructJavaScriptArtifact(
{
input_path: parsed.data.input_path,
format: parsed.data.format,
source_map_read_approved: parsed.data.source_map_read_approved,
limits: parsed.data.limits,
},
options.signal,
);
const { electron_summary: summary, ...application } = reconstructed;
const result = javascriptApplicationAnalysisResultSchema.parse({
schema_version: 1,
...application,
summary,
limitations: reconstructed.graph.limitations,
});
await options.progress?.report({
phase: "analyze_javascript_application",
completed: 1,
total: 1,
message: "Application graph and Electron boundaries reconstructed",
terminal: true,
});
return ok(createJavaScriptApplicationEvidence(parsed.data, result));
} catch (cause: unknown) {
if (cause instanceof ArtifactReaderFailure)
return err(
new ArtifactOperationError(OPERATION, cause.reason, cause.details),
);
if (cause instanceof z.ZodError)
return err(
new AnalysisProtocolError(
"JavaScript application analysis produced an invalid result",
{ cause },
),
);
return err(new ArtifactOperationError(OPERATION, "io"));
}
};
@@ -414,7 +414,13 @@ const findingCount = (analysis: JavaScriptStaticAnalysis): number =>
analysis.storage.length +
analysis.role_paths.length +
analysis.source_map_urls.length +
analysis.bundler_registrations.length;
analysis.bundler_registrations.length +
analysis.electron.browser_windows.length +
analysis.electron.context_bridge_apis.length +
analysis.electron.ipc.length +
analysis.electron.sender_validations.length +
analysis.electron.utility_processes.length +
analysis.electron.native_addon_bindings.length;
const rangeForOffsets = (
text: string,
@@ -27,6 +27,11 @@ import {
createJavaScriptArtifactRootNode,
} from "./JavaScriptArtifactGraphStructure.js";
import type { JavaScriptArtifactReconstructionInput } from "./JavaScriptArtifactReconstructionInput.js";
import { addElectronBoundaries } from "./ElectronBoundaryGraph.js";
import {
classifyElectronIpcPairings,
collectElectronIpcRecords,
} from "./ElectronBoundaryAnalysis.js";
/** Project bounded artifact and AST facts into JavaScript Application Graph v1. */
export const buildJavaScriptArtifactGraph = (
@@ -55,6 +60,7 @@ export const buildJavaScriptArtifactGraph = (
const packageRoots = addJavaScriptPackageNodes(context);
addJavaScriptBundlerNodes(context);
addJavaScriptStaticFindings(context);
addElectronBoundaries(context);
addJavaScriptHtmlRoles(context);
addJavaScriptSourceMapOriginals(context);
const coverage = graphCoverage(context);
@@ -82,11 +88,16 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
const malformedStructuredData =
context.analysis.packages.some(({ status }) => status !== "included") ||
context.analysis.source_maps.some(({ status }) => status === "invalid");
const partialJavaScript = context.analysis.files.some(
({ javascript }) =>
javascript !== null && javascript.parse_status === "partial",
);
const unknownGap =
context.analysis.parse_failures > 0 ||
context.fileSet.invalid_utf8_files > 0 ||
sourceMapPolicyGap ||
malformedStructuredData;
malformedStructuredData ||
partialJavaScript;
if (context.analysis.truncated_scopes > 0)
return partialReconstructionCoverage(
reconstructionLimits(context.input),
@@ -111,21 +122,69 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
const graphLimitations = (
context: JavaScriptArtifactGraphContext,
coverage: "complete" | "partial" | "unknown" | "unavailable",
): string[] => [
...context.analysis.limitations,
"Webpack/Rspack factories were recovered from AST literals; REA did not invoke push handlers or bundle bootstrap code.",
"Static imports, entrypoints, workers, endpoints, and storage relationships do not prove runtime execution.",
...(context.accumulator.omittedObservations() === 0
? []
: [
"Repeated content identities exceeded the per-node observation bound; containment edges still preserve inventoried paths.",
]),
...(coverage === "complete"
? []
: [
"Graph coverage is incomplete; unavailable facts remain explicit and must not be read as absence.",
]),
];
): string[] => {
const ipc = collectElectronIpcRecords(context.analysis);
const pairings = classifyElectronIpcPairings(ipc);
const electronFindings = context.analysis.files.reduce(
(count, { javascript }) =>
count +
(javascript === null
? 0
: javascript.electron.browser_windows.length +
javascript.electron.context_bridge_apis.length +
javascript.electron.ipc.length +
javascript.electron.sender_validations.length +
javascript.electron.utility_processes.length +
javascript.electron.native_addon_bindings.length),
0,
);
return [
...context.analysis.limitations,
"Webpack/Rspack factories were recovered from AST literals; REA did not invoke push handlers or bundle bootstrap code.",
"Static imports, entrypoints, workers, endpoints, and storage relationships do not prove runtime execution.",
...(electronFindings === 0
? []
: [
"Electron relationships are derived from inert syntax; runtime registration, reachability, defaults, and enforcement remain unproven.",
]),
...(ipc.some(({ finding }) => finding.channel === null)
? [
"Dynamic IPC channel expressions remain unresolved and are never paired by textual similarity.",
]
: []),
...(pairings.some(({ status }) => status === "ambiguous")
? [
"Some literal IPC channels have multiple compatible main handlers; ambiguous calls are not paired to any handler.",
]
: []),
...(context.analysis.files.some(
({ javascript }) =>
(javascript?.electron.sender_validations.length ?? 0) > 0,
)
? [
"Sender, frame, URL, and origin checks are observations only; REA does not claim that they enforce a complete authorization policy.",
]
: []),
...(context.analysis.files.some(
({ javascript }) =>
(javascript?.electron.native_addon_bindings.length ?? 0) > 0,
)
? [
"Native member names are requested by JavaScript syntax and are not verified binary exports in this workflow.",
]
: []),
...(context.accumulator.omittedObservations() === 0
? []
: [
"Repeated content identities exceeded the per-node observation bound; containment edges still preserve inventoried paths.",
]),
...(coverage === "complete"
? []
: [
"Graph coverage is incomplete; unavailable facts remain explicit and must not be read as absence.",
]),
];
};
const reconstructionLimits = (input: JavaScriptArtifactReconstructionInput) => [
{
@@ -42,20 +42,30 @@ export const artifactObservationEvidence = (
/** Exact AST syntax evidence with an actionable source range. */
export const astObservationEvidence = (
input: EvidenceInput & { readonly range: JavaScriptSourceRange },
): ApplicationGraphEvidence => ({
authority: "ast-static-analysis",
state: "observed",
confidence: "exact",
artifact: artifactReference(input.sha256),
location: {
available: true,
value: { kind: "source-range", source: input.path, ...input.range },
},
extractor: { ...EXTRACTOR, operation: input.operation },
coverage: input.coverage,
limitations: [...(input.limitations ?? [])],
evidence_ids: [],
});
): ApplicationGraphEvidence => {
const limitations = [
...(input.limitations ?? []),
...(input.coverage.status === "complete"
? []
: [
"AST coverage is incomplete; omitted or dynamic facts must not be interpreted as absence.",
]),
];
return {
authority: "ast-static-analysis",
state: "observed",
confidence: "exact",
artifact: artifactReference(input.sha256),
location: {
available: true,
value: { kind: "source-range", source: input.path, ...input.range },
},
extractor: { ...EXTRACTOR, operation: input.operation },
coverage: input.coverage,
limitations,
evidence_ids: [],
};
};
/** Explicit static relationship inference; never promoted to observation. */
export const staticInferenceEvidence = (
@@ -8,6 +8,7 @@ import {
} from "../artifacts/ArtifactReader.js";
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import type { JavaScriptApplicationGraph } from "../domain/javascriptApplicationGraph.js";
import type { ElectronBoundarySummary } from "../domain/javascriptApplicationAnalysis.js";
import { analyzeJavaScriptArtifactFiles } from "./JavaScriptArtifactAnalysis.js";
import { readJavaScriptArtifactFiles } from "./JavaScriptArtifactFiles.js";
import { buildJavaScriptArtifactGraph } from "./JavaScriptArtifactGraphBuilder.js";
@@ -17,14 +18,17 @@ import {
type JavaScriptArtifactReconstructionInput,
} from "./JavaScriptArtifactReconstructionInput.js";
import { scanCanonicalArtifactInventory } from "./ArtifactInventory.js";
import { summarizeElectronBoundaries } from "./ElectronBoundaryAnalysis.js";
/** Application-layer result retaining local diagnostics outside the canonical graph. */
export interface JavaScriptArtifactReconstructionResult {
readonly input_path: string;
readonly format: "asar" | "directory";
readonly root_artifact_sha256: string;
readonly inventory_manifest_id: string;
readonly inventory_graph_sha256: string;
readonly graph: JavaScriptApplicationGraph;
readonly electron_summary: ElectronBoundarySummary;
readonly statistics: {
readonly relevant_files: number;
readonly nested_asar_containers: number;
@@ -84,9 +88,11 @@ export const reconstructJavaScriptArtifact = async (
return {
input_path: path,
format,
root_artifact_sha256: snapshot.manifest.root_sha256,
inventory_manifest_id: snapshot.manifest.manifest_id,
inventory_graph_sha256: snapshot.manifest.graph_sha256,
graph,
electron_summary: summarizeElectronBoundaries(analysis),
statistics: {
relevant_files: files.files.length,
nested_asar_containers: files.containers.length,
@@ -1,101 +1,19 @@
import { z } from "zod";
import type { ArtifactLimits } from "../artifacts/ArtifactReader.js";
const MAX_GRAPH_NODES = 100_000;
const MAX_GRAPH_EDGES = 200_000;
const reconstructionLimitsSchema = z
.strictObject({
max_entries: z.number().int().min(1).max(1_000_000).default(8_000),
max_total_artifact_bytes: z
.number()
.int()
.min(1)
.max(Number.MAX_SAFE_INTEGER)
.default(512 * 1_024 * 1_024),
max_artifact_entry_bytes: z
.number()
.int()
.min(1)
.max(Number.MAX_SAFE_INTEGER)
.default(128 * 1_024 * 1_024),
max_compression_ratio: z.number().min(1).max(100_000).default(1_000),
max_depth: z.number().int().min(1).max(100).default(64),
max_path_bytes: z.number().int().min(1).max(65_535).default(4_096),
max_text_files: z.number().int().min(1).max(100_000).default(5_000),
max_total_text_bytes: z
.number()
.int()
.min(1)
.max(512 * 1_024 * 1_024)
.default(128 * 1_024 * 1_024),
max_text_file_bytes: z
.number()
.int()
.min(1)
.max(64 * 1_024 * 1_024)
.default(8 * 1_024 * 1_024),
max_ast_nodes: z.number().int().min(1).max(20_000_000).default(2_000_000),
max_findings: z.number().int().min(1).max(200_000).default(10_000),
max_modules: z.number().int().min(1).max(100_000).default(20_000),
max_source_map_sources: z.number().int().min(1).max(100_000).default(5_000),
max_parse_milliseconds: z
.number()
.int()
.min(1)
.max(300_000)
.default(30_000),
})
.superRefine((limits, context) => {
const projectedNodes =
7 * limits.max_entries +
limits.max_findings +
limits.max_modules +
limits.max_source_map_sources +
1;
if (projectedNodes > MAX_GRAPH_NODES)
context.addIssue({
code: "custom",
path: ["max_entries"],
message:
"Combined reconstruction limits can exceed the 100000-node graph contract",
});
const projectedEdges =
9 * limits.max_entries +
5 * limits.max_findings +
limits.max_modules +
limits.max_source_map_sources;
if (projectedEdges > MAX_GRAPH_EDGES)
context.addIssue({
code: "custom",
path: ["max_entries"],
message:
"Combined reconstruction limits can exceed the 200000-edge graph contract",
});
});
import {
JAVASCRIPT_APPLICATION_ANALYSIS_DEFAULT_LIMITS,
javascriptApplicationAnalysisLimitsSchema,
} from "../domain/javascriptApplicationAnalysis.js";
/** Local ASAR/directory reconstruction request with explicit source-map authority. */
export const javascriptArtifactReconstructionInputSchema = z.strictObject({
input_path: z.string().min(1).max(16_384),
format: z.enum(["auto", "asar", "directory"]).default("auto"),
source_map_read_approved: z.boolean().default(false),
limits: reconstructionLimitsSchema.default({
max_entries: 8_000,
max_total_artifact_bytes: 512 * 1_024 * 1_024,
max_artifact_entry_bytes: 128 * 1_024 * 1_024,
max_compression_ratio: 1_000,
max_depth: 64,
max_path_bytes: 4_096,
max_text_files: 5_000,
max_total_text_bytes: 128 * 1_024 * 1_024,
max_text_file_bytes: 8 * 1_024 * 1_024,
max_ast_nodes: 2_000_000,
max_findings: 10_000,
max_modules: 20_000,
max_source_map_sources: 5_000,
max_parse_milliseconds: 30_000,
}),
limits: javascriptApplicationAnalysisLimitsSchema.default(
JAVASCRIPT_APPLICATION_ANALYSIS_DEFAULT_LIMITS,
),
});
/** Parsed bounded reconstruction request. */
+1
View File
@@ -38,6 +38,7 @@ export const CLI_COMMANDS = Object.freeze({
compareWebScreenshots: "compare-web-screenshots",
listElectronTargets: "list-electron-targets",
inspectElectronPage: "inspect-electron-page",
analyzeJavaScriptApplication: "analyze-javascript-application",
});
/** Ordered primary CLI inventory; aliases are intentionally excluded. */
+97 -1
View File
@@ -4,6 +4,7 @@ import {
inspectElectronPage,
listElectronTargets,
} from "./application/ElectronObservationService.js";
import { analyzeJavaScriptApplication } from "./application/JavaScriptApplicationService.js";
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
import { CdpElectronProvider } from "./browser/CdpElectronProvider.js";
import { logCliCommand } from "./cliLogging.js";
@@ -12,6 +13,7 @@ import {
inspectElectronPageInputSchema,
listElectronTargetsInputSchema,
} from "./domain/electronObservation.js";
import { analyzeJavaScriptApplicationInputSchema } from "./domain/javascriptApplicationAnalysis.js";
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
import type { JsonValue } from "./domain/jsonValue.js";
import type { Logger } from "./logger.js";
@@ -29,6 +31,14 @@ const scopeOptions = {
export const registerElectronCommands = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
): void => {
registerElectronObservationCommands(cli, logger);
registerJavaScriptApplicationCommand(cli, logger);
};
const registerElectronObservationCommands = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.listElectronTargets, {
description: "List root-confined file pages from Electron CDP",
@@ -117,6 +127,92 @@ export const registerElectronCommands = (
});
};
const registerJavaScriptApplicationCommand = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.analyzeJavaScriptApplication, {
description:
"Statically reconstruct an approved JavaScript/Electron application",
args: z.object({
path: z.string().describe("Absolute ASAR or extracted application path"),
}),
options: z.object({
approved: z.boolean().default(false),
format: z.enum(["auto", "asar", "directory"]).default("auto"),
sourceMapReadApproved: z.boolean().default(false),
maxEntries: z.number().int().min(1).default(8_000),
maxTotalArtifactBytes: z
.number()
.int()
.min(1)
.default(512 * 1_024 * 1_024),
maxArtifactEntryBytes: z
.number()
.int()
.min(1)
.default(128 * 1_024 * 1_024),
maxCompressionRatio: z.number().min(1).default(1_000),
maxDepth: z.number().int().min(1).default(64),
maxPathBytes: z.number().int().min(1).default(4_096),
maxTextFiles: z.number().int().min(1).default(5_000),
maxTotalTextBytes: z
.number()
.int()
.min(1)
.default(128 * 1_024 * 1_024),
maxTextFileBytes: z
.number()
.int()
.min(1)
.default(8 * 1_024 * 1_024),
maxAstNodes: z.number().int().min(1).default(2_000_000),
maxFindings: z.number().int().min(1).default(8_000),
maxModules: z.number().int().min(1).default(20_000),
maxSourceMapSources: z.number().int().min(1).default(5_000),
maxParseMilliseconds: z.number().int().min(1).default(30_000),
}),
run: ({ args, options }) =>
logCliCommand(
logger,
CLI_COMMANDS.analyzeJavaScriptApplication,
async () => {
const context = await electronContext();
if (!context.ok) return context.error;
const parsed = analyzeJavaScriptApplicationInputSchema.safeParse({
input_path: args.path,
approved: options.approved,
format: options.format,
source_map_read_approved: options.sourceMapReadApproved,
limits: {
max_entries: options.maxEntries,
max_total_artifact_bytes: options.maxTotalArtifactBytes,
max_artifact_entry_bytes: options.maxArtifactEntryBytes,
max_compression_ratio: options.maxCompressionRatio,
max_depth: options.maxDepth,
max_path_bytes: options.maxPathBytes,
max_text_files: options.maxTextFiles,
max_total_text_bytes: options.maxTotalTextBytes,
max_text_file_bytes: options.maxTextFileBytes,
max_ast_nodes: options.maxAstNodes,
max_findings: options.maxFindings,
max_modules: options.maxModules,
max_source_map_sources: options.maxSourceMapSources,
max_parse_milliseconds: options.maxParseMilliseconds,
},
});
if (!parsed.success)
return inputError("analyze_javascript_application");
const result = await analyzeJavaScriptApplication(
context.authority,
parsed.data,
);
return result.ok ? result.value : cliError(result.error);
},
),
});
};
const electronContext = async () => {
const config = parseConfig(process.env);
if (!config.ok) return { ok: false as const, error: cliError(config.error) };
@@ -137,6 +233,6 @@ const inputError = (operation: string): JsonValue =>
const cliError = (
error: Parameters<typeof projectAnalysisError>[0],
): JsonValue => ({
error: "Electron observation failed",
error: "Electron analysis failed",
...projectAnalysisError(error),
});
+32
View File
@@ -6,6 +6,10 @@ import {
inspectElectronPageInputSchema,
listElectronTargetsInputSchema,
} from "../domain/electronObservation.js";
import {
analyzeJavaScriptApplicationInputSchema,
javascriptApplicationAnalysisResultSchema,
} from "../domain/javascriptApplicationAnalysis.js";
const listOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
@@ -13,6 +17,9 @@ const listOutputSchema = evidenceEnvelopeSchema
const inspectionOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: electronPageInspectionSchema });
const applicationOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: javascriptApplicationAnalysisResultSchema });
const endpoint = "http://127.0.0.1:9223";
const root = "/Applications/Example.app/Contents/Resources";
@@ -81,4 +88,29 @@ export const ELECTRON_TOOL_CONTRACTS = [
},
],
},
{
name: "analyze_javascript_application",
description:
"Statically reconstruct one approved local ASAR or extracted JavaScript application as Evidence v2 and JavaScript Application Graph v1. Maps BrowserWindow preferences, preload and contextBridge APIs, literal and dynamic IPC, handler locations, sender-validation observations, utility processes, and requested native addon bindings without executing JavaScript; source-map contents require separate approval.",
kind: "electron-provider",
inputSchema: analyzeJavaScriptApplicationInputSchema,
outputSchema: applicationOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Analyze one approved local Electron application",
input: {
input_path: "/Applications/Example.app/Contents/Resources/app.asar",
format: "auto",
approved: true,
source_map_read_approved: false,
},
},
],
},
] as const satisfies readonly ToolContract[];
+16
View File
@@ -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);
};
+258
View File
@@ -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;
};
+216
View File
@@ -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;
};
+210
View File
@@ -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");
};
+118
View File
@@ -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[];
}
+161
View File
@@ -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 };
};
+4 -1
View File
@@ -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"
+185
View File
@@ -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
>;
+69 -71
View File
@@ -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[];
}
+1 -1
View File
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
serverSdkVersion: "2.0.0-beta.4",
clientSdkVersion: "2.0.0-beta.4",
coreSdkVersion: "2.0.0-beta.4",
skillVersion: "14",
skillVersion: "15",
} as const;
+22 -1
View File
@@ -2,6 +2,7 @@ import type { McpServer } from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySession.js";
import type { ElectronObservationPort } from "../application/ElectronObservationPort.js";
import { analyzeJavaScriptApplication } from "../application/JavaScriptApplicationService.js";
import {
inspectElectronPage,
listElectronTargets,
@@ -12,6 +13,7 @@ import {
inspectElectronPageInputSchema,
listElectronTargetsInputSchema,
} from "../domain/electronObservation.js";
import { analyzeJavaScriptApplicationInputSchema } from "../domain/javascriptApplicationAnalysis.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
import { toCallToolResult } from "./toolResult.js";
@@ -30,7 +32,8 @@ export const registerElectronTools = (
server: McpServer,
options: ElectronToolRegistration,
): void => {
const [listContract, inspectContract] = ELECTRON_TOOL_CONTRACTS;
const [listContract, inspectContract, analyzeContract] =
ELECTRON_TOOL_CONTRACTS;
server.registerTool(
listContract.name,
toolRegistrationOptions(listContract),
@@ -74,6 +77,24 @@ export const registerElectronTools = (
return evidenceResult(options, inspectContract, result.value);
},
);
server.registerTool(
analyzeContract.name,
toolRegistrationOptions(analyzeContract),
async (input, context) => {
const parsed = analyzeJavaScriptApplicationInputSchema.parse(input);
const result = await logToolExecution(
options.logger,
analyzeContract.name,
() =>
analyzeJavaScriptApplication(options.permissionAuthority, parsed, {
signal: context.mcpReq.signal,
progress: mcpProgressReporter(context),
}),
);
if (!result.ok) return toCallToolResult(result, analyzeContract);
return evidenceResult(options, analyzeContract, result.value);
},
);
};
const evidenceResult = (