fix(javascript): trace nested Electron bridge members (#2745)
* fix(javascript): trace nested Electron bridge members * fix(javascript): preserve shallow Electron bridge paths * fix(javascript): preserve exact Electron bridge member paths * fix(javascript): preserve exact Electron bridge paths * fix(javascript): preserve bridge entry ownership * fix(javascript): preserve bridge path identity * fix(javascript): normalize typed feature seeds before tracing * test(javascript): normalize direct selector seed inputs * refactor(javascript): consume normalized feature seed defaults --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
@@ -219,6 +219,8 @@ export interface ElectronCallPathStep {
|
||||
export interface ElectronCallPath {
|
||||
readonly entry_kind: "bridge-member" | "ipc-handler";
|
||||
readonly entry: string;
|
||||
/** Exact bridge API and property segments; `entry` remains display text. */
|
||||
readonly entry_path?: readonly string[];
|
||||
readonly channel: string | null;
|
||||
readonly terminal: string;
|
||||
readonly resolution: "candidate";
|
||||
|
||||
@@ -153,6 +153,13 @@ const collectMembersAt = (
|
||||
state.unknown += 1;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
t.isObjectProperty(property) &&
|
||||
!property.computed &&
|
||||
!property.shorthand &&
|
||||
name === "__proto__"
|
||||
)
|
||||
continue;
|
||||
const segments = [...prefix, name];
|
||||
const path = segments.join(".");
|
||||
state.members.push(path);
|
||||
|
||||
@@ -357,6 +357,83 @@ it("preserves guarded alternatives in direct exposed object literals", () => {
|
||||
]),
|
||||
);
|
||||
});
|
||||
it("preserves bridge member segments and excludes prototype setters", () => {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const e=require("electron");
|
||||
const write=()=>e.ipcRenderer.send("write");
|
||||
e.contextBridge.exposeInMainWorld("desktop", {
|
||||
"nested.write": write,
|
||||
nested: { write },
|
||||
__proto__: { inherited: write },
|
||||
["__proto__"]: { own: write },
|
||||
});
|
||||
`);
|
||||
expect(result.electron.call_paths).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
entry: "desktop.nested.write",
|
||||
entry_path: ["desktop", "nested.write"],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
entry: "desktop.nested.write",
|
||||
entry_path: ["desktop", "nested", "write"],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
entry: "desktop.__proto__.own",
|
||||
entry_path: ["desktop", "__proto__", "own"],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(result.electron.call_paths).not.toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
entry_path: ["desktop", "__proto__", "inherited"],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
it("follows an explicit object-literal prototype lookup in a bridge wrapper", () => {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const e=require("electron");
|
||||
const prototype={send:()=>e.ipcRenderer.send("through-prototype")};
|
||||
const object={__proto__:prototype};
|
||||
e.contextBridge.exposeInMainWorld("desktop", {
|
||||
action:()=>object.__proto__.send(),
|
||||
});
|
||||
`);
|
||||
expect(result.electron.call_paths).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
entry_path: ["desktop", "action"],
|
||||
channel: "through-prototype",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
it("does not spread a large nested bridge member list into function arguments", () => {
|
||||
const members = Array.from(
|
||||
{ length: 125_000 },
|
||||
(_, index) => `m${index}(){}`,
|
||||
).join(",");
|
||||
const source = `const e=require("electron");e.contextBridge.exposeInMainWorld("desktop",{nested:{${members}}});`;
|
||||
expect(() => analyzeJavaScriptStaticSource(source)).not.toThrow();
|
||||
});
|
||||
it("reports nested bridge depth truncation while retaining shallow paths", () => {
|
||||
const nested =
|
||||
Array.from({ length: 130 }, (_, index) => `level${index}:{`).join("") +
|
||||
`deep:()=>e.ipcRenderer.send("deep")` +
|
||||
"}".repeat(130);
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const e=require("electron");
|
||||
e.contextBridge.exposeInMainWorld("desktop", {
|
||||
shallow:()=>e.ipcRenderer.send("shallow"), ${nested}
|
||||
});
|
||||
`);
|
||||
expect(result.electron.call_paths).toContainEqual(
|
||||
expect.objectContaining({ entry: "desktop.shallow", channel: "shallow" }),
|
||||
);
|
||||
expect(result.limitations.join(" ")).toContain("depth 128");
|
||||
});
|
||||
it("preserves conditions when a wrapper dispatches through conditional external methods", () => {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const e=require("electron");
|
||||
|
||||
@@ -44,6 +44,7 @@ const callLabel = (node: t.Node): string =>
|
||||
interface PathContext {
|
||||
readonly entryNode: t.Node;
|
||||
readonly entry: string;
|
||||
readonly entryPath?: readonly string[];
|
||||
readonly entryKind: ElectronCallPath["entry_kind"] | null;
|
||||
readonly channel: string | null;
|
||||
readonly steps: readonly ElectronCallPathStep[];
|
||||
@@ -122,6 +123,37 @@ export const collectElectronWrappedCallPaths = (
|
||||
};
|
||||
const hasConditions = (value: SymbolicValue): boolean =>
|
||||
symbolicVariants(value).some((variant) => variant.conditions?.length);
|
||||
function* bridgeMemberFunctions(
|
||||
value: SymbolicValue,
|
||||
segments: readonly string[] = [],
|
||||
active = new Set<SymbolicValue>(),
|
||||
): Generator<{
|
||||
readonly name: string;
|
||||
readonly path: readonly string[];
|
||||
readonly fn: SymbolicFunction;
|
||||
}> {
|
||||
if (active.has(value)) return;
|
||||
if (active.size >= 128) {
|
||||
accumulator.unknownFindings += 1;
|
||||
accumulator.electronCallPathLimitReached = true;
|
||||
return;
|
||||
}
|
||||
const nested = new Set(active);
|
||||
nested.add(value);
|
||||
for (const member of [...resolver.members(value)].sort()) {
|
||||
if (--remainingVisits < 0) return;
|
||||
const path = [...segments, member];
|
||||
const name = path.join(".");
|
||||
for (const variant of symbolicVariants(
|
||||
resolver.property(value, member),
|
||||
)) {
|
||||
if (variant.kind === "function") yield { name, path, fn: variant };
|
||||
else if (resolver.members(variant).length > 0)
|
||||
yield* bridgeMemberFunctions(variant, path, nested);
|
||||
}
|
||||
if (remainingVisits < 0) return;
|
||||
}
|
||||
}
|
||||
const isolatedBridgeCall = (
|
||||
node: t.CallExpression | t.OptionalCallExpression,
|
||||
):
|
||||
@@ -167,6 +199,10 @@ export const collectElectronWrappedCallPaths = (
|
||||
const path: ElectronCallPath = {
|
||||
entry_kind: context.entryKind,
|
||||
entry: context.entry,
|
||||
...(context.entryKind !== "bridge-member" ||
|
||||
context.entryPath === undefined
|
||||
? {}
|
||||
: { entry_path: context.entryPath }),
|
||||
channel,
|
||||
terminal,
|
||||
resolution: "candidate",
|
||||
@@ -405,27 +441,25 @@ export const collectElectronWrappedCallPaths = (
|
||||
offset: node.start ?? -1,
|
||||
value: finding,
|
||||
});
|
||||
for (const name of members) {
|
||||
const value = resolver.property(object, name);
|
||||
for (const fn of symbolicVariants(value))
|
||||
if (fn.kind === "function") {
|
||||
const memberContext = metadataContext(keyContext, fn);
|
||||
if (!memberContext) continue;
|
||||
functionBody(
|
||||
fn,
|
||||
fn.node.params.map(() => symbolicUnknown("public API argument")),
|
||||
{
|
||||
...memberContext,
|
||||
entryNode: node,
|
||||
entryKind: "bridge-member",
|
||||
entry: `${key.value}.${name}`,
|
||||
channel: null,
|
||||
steps: [step(node, "exposure", `${key.value}.${name}`)],
|
||||
active: new Set(),
|
||||
},
|
||||
node,
|
||||
);
|
||||
}
|
||||
for (const { name, path, fn } of bridgeMemberFunctions(object)) {
|
||||
const memberContext = metadataContext(keyContext, fn);
|
||||
if (!memberContext) continue;
|
||||
const entry = `${key.value}.${name}`;
|
||||
functionBody(
|
||||
fn,
|
||||
fn.node.params.map(() => symbolicUnknown("public API argument")),
|
||||
{
|
||||
...memberContext,
|
||||
entryNode: node,
|
||||
entryKind: "bridge-member",
|
||||
entry,
|
||||
entryPath: [key.value, ...path],
|
||||
channel: null,
|
||||
steps: [step(node, "exposure", entry)],
|
||||
active: new Set(),
|
||||
},
|
||||
node,
|
||||
);
|
||||
}
|
||||
};
|
||||
const call = (
|
||||
|
||||
@@ -11,7 +11,10 @@ import {
|
||||
} from "./javascriptApplicationGraph.fixture.js";
|
||||
import { findApplicationFeatureSeeds } from "./javascriptFeatureSeed.js";
|
||||
import { traceApplicationFeature } from "./javascriptFeatureTrace.js";
|
||||
import type { ApplicationFeatureSeed } from "./javascriptFeatureTraceSchemas.js";
|
||||
import {
|
||||
applicationFeatureSeedSchema,
|
||||
type ApplicationFeatureSeed,
|
||||
} from "./javascriptFeatureTraceSchemas.js";
|
||||
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
|
||||
import type { JsonValue } from "../jsonValue.js";
|
||||
|
||||
@@ -268,6 +271,32 @@ describe("feature seed selection controls", () => {
|
||||
});
|
||||
|
||||
describe("public feature trace from contextBridge source members", () => {
|
||||
it.each(["openProject", "missingProject"])(
|
||||
"normalizes optional seed defaults before deriving trace identity for %s",
|
||||
(value) => {
|
||||
const input = {
|
||||
sourceEvidenceId,
|
||||
graph: contextBridgeGraph(),
|
||||
nativeEvidence: [],
|
||||
direction: "both" as const,
|
||||
};
|
||||
const omitted = traceApplicationFeature({
|
||||
...input,
|
||||
seed: { kind: "api", value },
|
||||
});
|
||||
const explicit = traceApplicationFeature({
|
||||
...input,
|
||||
seed: {
|
||||
kind: "api",
|
||||
value,
|
||||
match: null,
|
||||
case_sensitive: false,
|
||||
},
|
||||
});
|
||||
expect(omitted).toEqual(explicit);
|
||||
},
|
||||
);
|
||||
|
||||
it("traces one exact member seed through the public feature workflow", () => {
|
||||
const mode = {
|
||||
value: "openProject",
|
||||
@@ -381,12 +410,13 @@ const sourceEvidenceId = `ev_${"b".repeat(64)}`;
|
||||
const seed = (
|
||||
kind: ApplicationFeatureSeed["kind"],
|
||||
value = "openProject",
|
||||
): ApplicationFeatureSeed => ({
|
||||
kind,
|
||||
value,
|
||||
match: "exact",
|
||||
case_sensitive: true,
|
||||
});
|
||||
): ApplicationFeatureSeed =>
|
||||
applicationFeatureSeedSchema.parse({
|
||||
kind,
|
||||
value,
|
||||
match: "exact",
|
||||
case_sensitive: true,
|
||||
});
|
||||
|
||||
const memberNode = (
|
||||
kind: ApplicationNode["kind"],
|
||||
|
||||
@@ -52,10 +52,28 @@ const seedMatch = (
|
||||
]
|
||||
: [];
|
||||
if (!kindMatches(node, seed.kind)) return [];
|
||||
const requestedEntryPath =
|
||||
seed.kind === "api" && "entry_path" in seed ? seed.entry_path : undefined;
|
||||
if (
|
||||
seed.kind === "api" &&
|
||||
requestedEntryPath !== undefined &&
|
||||
!node.observations.some(({ properties }) => {
|
||||
const entryPath = properties.entry_path;
|
||||
return (
|
||||
Array.isArray(entryPath) &&
|
||||
entryPath.length === requestedEntryPath.length &&
|
||||
entryPath.every(
|
||||
(segment, index) => segment === requestedEntryPath[index],
|
||||
)
|
||||
);
|
||||
})
|
||||
)
|
||||
return [];
|
||||
const mode = featureSeedMatchMode(seed);
|
||||
const query = normalized(seed.value, seed.case_sensitive);
|
||||
const caseSensitive = seed.case_sensitive;
|
||||
const query = normalized(seed.value, caseSensitive);
|
||||
const match = candidateFields(node, seed.kind).find((candidate) => {
|
||||
const value = normalized(candidate.value, seed.case_sensitive);
|
||||
const value = normalized(candidate.value, caseSensitive);
|
||||
return mode === "exact" ? value === query : value.includes(query);
|
||||
});
|
||||
return match === undefined
|
||||
|
||||
@@ -12,6 +12,8 @@ import type {
|
||||
} from "./javascriptApplicationGraphSchemas.js";
|
||||
import {
|
||||
applicationFeatureTraceResultSchema,
|
||||
applicationFeatureSeedSchema,
|
||||
type ApplicationFeatureSeedInput,
|
||||
type ApplicationFeatureTraceResult,
|
||||
type TraceApplicationFeatureInput,
|
||||
} from "./javascriptFeatureTraceSchemas.js";
|
||||
@@ -30,14 +32,18 @@ export interface ApplicationFeatureTraceProjectionInput {
|
||||
readonly sourceEvidenceId: string;
|
||||
readonly graph: JavaScriptApplicationGraph;
|
||||
readonly nativeEvidence: readonly Evidence[];
|
||||
readonly seed: TraceApplicationFeatureInput["seed"];
|
||||
readonly seed: ApplicationFeatureSeedInput;
|
||||
readonly direction: TraceApplicationFeatureInput["direction"];
|
||||
}
|
||||
|
||||
/** Trace a literal feature through its complete reachable, authority-preserving JAG. */
|
||||
export const traceApplicationFeature = (
|
||||
input: ApplicationFeatureTraceProjectionInput,
|
||||
source: ApplicationFeatureTraceProjectionInput,
|
||||
): ApplicationFeatureTraceResult => {
|
||||
const input = {
|
||||
...source,
|
||||
seed: applicationFeatureSeedSchema.parse(source.seed),
|
||||
};
|
||||
const allSeedMatches = findApplicationFeatureSeeds(
|
||||
input.graph.nodes,
|
||||
input.seed,
|
||||
|
||||
@@ -17,33 +17,65 @@ export const featureSeedMatchMode = (seed: {
|
||||
}): "exact" | "contains" =>
|
||||
seed.match ?? (seed.kind === "string" ? "contains" : "exact");
|
||||
|
||||
const literalSeedKinds = [
|
||||
"route",
|
||||
"string",
|
||||
"api",
|
||||
"channel",
|
||||
"module",
|
||||
"native-export",
|
||||
] as const;
|
||||
const apiSeedSchema = z.union([
|
||||
z.strictObject({
|
||||
kind: z.literal("api"),
|
||||
value: boundedTextSchema,
|
||||
match: z.enum(["exact", "contains"]).nullable().default(null),
|
||||
case_sensitive: z.boolean().default(false),
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("api"),
|
||||
value: z.literal(""),
|
||||
match: z.literal("exact"),
|
||||
case_sensitive: z.boolean().default(false),
|
||||
}),
|
||||
]);
|
||||
|
||||
const apiPathSeedSchema = z.union([
|
||||
z.strictObject({
|
||||
kind: z.literal("api"),
|
||||
value: boundedTextSchema,
|
||||
match: z.enum(["exact", "contains"]).nullable().default(null),
|
||||
case_sensitive: z.boolean().default(false),
|
||||
entry_path: z.array(z.string()).min(1),
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("api"),
|
||||
value: z.literal(""),
|
||||
match: z.literal("exact"),
|
||||
case_sensitive: z.boolean().default(false),
|
||||
entry_path: z.array(z.string()).min(1),
|
||||
}),
|
||||
]);
|
||||
|
||||
/**
|
||||
* Literal starting point for one application feature trace. An empty value,
|
||||
* such as the channel in `ipcMain.handle("")`, must be an explicit exact
|
||||
* literal seed: empty containment would select every node.
|
||||
*/
|
||||
const applicationFeatureSeedSchema = z.union([
|
||||
export const applicationFeatureSeedSchema = z.union([
|
||||
z.strictObject({
|
||||
kind: z.enum(["node-id", ...literalSeedKinds]),
|
||||
kind: z.enum([
|
||||
"node-id",
|
||||
"route",
|
||||
"string",
|
||||
"channel",
|
||||
"module",
|
||||
"native-export",
|
||||
]),
|
||||
value: boundedTextSchema,
|
||||
match: z.enum(["exact", "contains"]).nullable().default(null),
|
||||
case_sensitive: z.boolean().default(false),
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.enum(literalSeedKinds),
|
||||
kind: z.enum(["route", "string", "channel", "module", "native-export"]),
|
||||
value: z.literal(""),
|
||||
match: z.literal("exact"),
|
||||
case_sensitive: z.boolean().default(false),
|
||||
}),
|
||||
apiSeedSchema,
|
||||
apiPathSeedSchema,
|
||||
]);
|
||||
|
||||
/** Check unique native identities before projecting an application trace. */
|
||||
@@ -156,7 +188,10 @@ export const applicationFeatureTraceResultSchema = z.strictObject({
|
||||
export type TraceApplicationFeatureInput = z.infer<
|
||||
typeof traceApplicationFeatureInputSchema
|
||||
>;
|
||||
export type ApplicationFeatureSeed = z.infer<
|
||||
export type ApplicationFeatureSeed = z.output<
|
||||
typeof applicationFeatureSeedSchema
|
||||
>;
|
||||
export type ApplicationFeatureSeedInput = z.input<
|
||||
typeof applicationFeatureSeedSchema
|
||||
>;
|
||||
export type ApplicationFeatureTraceResult = z.infer<
|
||||
|
||||
@@ -47,6 +47,14 @@ interface SymbolicReturnFlow {
|
||||
readonly fallsThrough: boolean;
|
||||
}
|
||||
const emptyEnvironment: SymbolicEnvironment = { values: new Map() };
|
||||
const isObjectPrototypeSetter = (
|
||||
property: t.ObjectMethod | t.ObjectProperty,
|
||||
name: string,
|
||||
): boolean =>
|
||||
t.isObjectProperty(property) &&
|
||||
!property.computed &&
|
||||
!property.shorthand &&
|
||||
name === "__proto__";
|
||||
|
||||
/** Demand-driven substitutions for local bindings, closures and literal module tables. */
|
||||
export class JavaScriptSymbolicBindings {
|
||||
@@ -243,15 +251,30 @@ export class JavaScriptSymbolicBindings {
|
||||
index = null;
|
||||
break;
|
||||
}
|
||||
if (isObjectPrototypeSetter(property, name)) continue;
|
||||
properties.set(name, property);
|
||||
}
|
||||
this.#literalPropertyIndex.set(value.node, index);
|
||||
}
|
||||
if (index !== null) {
|
||||
const property = index.get(key);
|
||||
return property === undefined
|
||||
? symbolicUnknown("missing property")
|
||||
: this.#objectPropertyValue(property, value.environment);
|
||||
if (property !== undefined)
|
||||
return this.#objectPropertyValue(property, value.environment);
|
||||
if (key === "__proto__") {
|
||||
const prototypeSetter = [...value.node.properties]
|
||||
.reverse()
|
||||
.filter(
|
||||
(candidate): candidate is t.ObjectMethod | t.ObjectProperty =>
|
||||
!t.isSpreadElement(candidate),
|
||||
)
|
||||
.find((candidate) => isObjectPrototypeSetter(candidate, key));
|
||||
if (prototypeSetter !== undefined)
|
||||
return this.#objectPropertyValue(
|
||||
prototypeSetter,
|
||||
value.environment,
|
||||
);
|
||||
}
|
||||
return symbolicUnknown("missing property");
|
||||
}
|
||||
for (const p of [...value.node.properties].reverse()) {
|
||||
if (t.isSpreadElement(p)) {
|
||||
@@ -314,7 +337,8 @@ export class JavaScriptSymbolicBindings {
|
||||
t.isSpreadElement(p)
|
||||
? this.members(this.evaluate(p.argument, value.environment), active)
|
||||
: [semanticStaticPropertyKey(p.key, p.computed)].filter(
|
||||
(k): k is string => k !== null,
|
||||
(k): k is string =>
|
||||
k !== null && !isObjectPrototypeSetter(p, k),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
Reference in New Issue
Block a user