Skip to content

Commit 8dc1cfc

Browse files
committed
fix(desktop): verify callable preload bridge APIs
1 parent eb42690 commit 8dc1cfc

3 files changed

Lines changed: 121 additions & 51 deletions

File tree

‎apps/desktop/scripts/verify-preload-bundle.mjs‎

Lines changed: 81 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
import * as NodeEvents from "node:events";
2+
import * as NodeFS from "node:fs";
13
import * as NodeFSP from "node:fs/promises";
4+
import * as NodeTimers from "node:timers";
25
import * as NodeURL from "node:url";
6+
import * as NodeVM from "node:vm";
37
import { parse } from "acorn";
48

59
const expectedDesktopBridgeApis = [
@@ -8,30 +12,17 @@ const expectedDesktopBridgeApis = [
812
"pickFolder",
913
];
1014
const clerkPasskeysGlobal = "__clerk_internal_electron_passkeys";
15+
const preloadExecutionTimeoutMs = 1_000;
16+
const desktopPackage = JSON.parse(
17+
NodeFS.readFileSync(new URL("../package.json", import.meta.url), "utf8"),
18+
);
19+
const electronVersion = desktopPackage.dependencies.electron;
1120

1221
const isSyntaxNode = (value) =>
1322
typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
1423

15-
const readStaticName = (node) => {
16-
if (node.type === "Identifier") return node.name;
17-
if (node.type === "Literal" && typeof node.value === "string") return node.value;
18-
return undefined;
19-
};
20-
21-
const readMemberName = (node) => {
22-
if (node.type !== "MemberExpression") return undefined;
23-
if (!node.computed && node.property.type === "Identifier") return node.property.name;
24-
return readStaticName(node.property);
25-
};
26-
27-
const isContextBridge = (node) =>
28-
(node.type === "Identifier" && node.name === "contextBridge") ||
29-
(node.type === "MemberExpression" && readMemberName(node) === "contextBridge");
30-
3124
const inspectBundle = (source) => {
3225
const runtimeImports = [];
33-
const exposedGlobals = new Set();
34-
const desktopBridgeApis = new Set();
3526
const visit = (node) => {
3627
if (node.type === "ImportExpression") {
3728
throw new Error("Desktop preload bundle contains a dynamic import() call");
@@ -50,25 +41,6 @@ const inspectBundle = (source) => {
5041
}
5142
}
5243

53-
if (
54-
node.type === "CallExpression" &&
55-
node.callee.type === "MemberExpression" &&
56-
readMemberName(node.callee) === "exposeInMainWorld" &&
57-
isContextBridge(node.callee.object)
58-
) {
59-
const [globalName, api] = node.arguments;
60-
const name = globalName === undefined ? undefined : readStaticName(globalName);
61-
if (name !== undefined) exposedGlobals.add(name);
62-
63-
if (name === "desktopBridge" && api?.type === "ObjectExpression") {
64-
for (const property of api.properties) {
65-
if (property.type !== "Property") continue;
66-
const propertyName = readStaticName(property.key);
67-
if (propertyName !== undefined) desktopBridgeApis.add(propertyName);
68-
}
69-
}
70-
}
71-
7244
for (const child of Object.values(node)) {
7345
if (Array.isArray(child)) {
7446
for (const item of child) {
@@ -81,20 +53,69 @@ const inspectBundle = (source) => {
8153
};
8254

8355
visit(parse(source, { ecmaVersion: "latest", sourceType: "script" }));
84-
return { desktopBridgeApis, exposedGlobals, runtimeImports };
56+
return runtimeImports;
8557
};
8658

87-
export const verifyPreloadBundle = (source) => {
88-
const { desktopBridgeApis, exposedGlobals, runtimeImports } = inspectBundle(source);
89-
const missingApis = expectedDesktopBridgeApis.filter((api) => !desktopBridgeApis.has(api));
90-
if (!exposedGlobals.has("desktopBridge")) missingApis.unshift("desktopBridge exposure");
91-
if (!exposedGlobals.has(clerkPasskeysGlobal)) missingApis.push(`${clerkPasskeysGlobal} exposure`);
59+
const createSandboxModules = (exposedGlobals) => {
60+
const ipcRenderer = {
61+
invoke: () => Promise.resolve(undefined),
62+
on: () => undefined,
63+
removeListener: () => undefined,
64+
sendSync: () => undefined,
65+
};
66+
const electron = {
67+
contextBridge: {
68+
exposeInMainWorld: (name, api) => exposedGlobals.set(name, api),
69+
},
70+
ipcRenderer,
71+
};
9272

93-
if (missingApis.length > 0) {
94-
throw new Error(`Desktop preload bundle is missing executable APIs: ${missingApis.join(", ")}`);
95-
}
73+
return new Map([
74+
["electron", electron],
75+
["electron/common", electron],
76+
["electron/renderer", electron],
77+
["events", NodeEvents.default],
78+
["node:events", NodeEvents.default],
79+
["timers", NodeTimers.default],
80+
["node:timers", NodeTimers.default],
81+
["url", NodeURL.default],
82+
["node:url", NodeURL.default],
83+
]);
84+
};
85+
86+
const executeBundle = (source, sandboxModules) => {
87+
const sandboxProcess = {
88+
contextIsolated: true,
89+
// oxlint-disable-next-line t3code/no-global-process-runtime -- This standalone CI verifier supplies the preload's host platform without loading Effect.
90+
platform: process.platform,
91+
versions: { electron: electronVersion },
92+
};
93+
const requireSandboxModule = (moduleName) => {
94+
if (!sandboxModules.has(moduleName)) {
95+
throw new Error(
96+
`Unsupported sandbox module requested during preload execution: ${moduleName}`,
97+
);
98+
}
99+
return sandboxModules.get(moduleName);
100+
};
101+
102+
NodeVM.runInNewContext(
103+
source,
104+
{
105+
process: sandboxProcess,
106+
require: requireSandboxModule,
107+
},
108+
{
109+
filename: "desktop-preload.cjs",
110+
timeout: preloadExecutionTimeoutMs,
111+
},
112+
);
113+
};
96114

97-
const sandboxModules = new Set(["electron", "events", "timers", "url"]);
115+
export const verifyPreloadBundle = (source) => {
116+
const runtimeImports = inspectBundle(source);
117+
const exposedGlobals = new Map();
118+
const sandboxModules = createSandboxModules(exposedGlobals);
98119
const unsupportedImports = [...new Set(runtimeImports)]
99120
.filter((moduleName) => !sandboxModules.has(moduleName))
100121
.toSorted();
@@ -104,6 +125,19 @@ export const verifyPreloadBundle = (source) => {
104125
`Desktop preload bundle contains unsupported sandbox imports: ${unsupportedImports.join(", ")}`,
105126
);
106127
}
128+
129+
executeBundle(source, sandboxModules);
130+
131+
const desktopBridge = exposedGlobals.get("desktopBridge");
132+
const missingApis = expectedDesktopBridgeApis.filter(
133+
(api) => typeof desktopBridge?.[api] !== "function",
134+
);
135+
if (!exposedGlobals.has("desktopBridge")) missingApis.unshift("desktopBridge exposure");
136+
if (!exposedGlobals.has(clerkPasskeysGlobal)) missingApis.push(`${clerkPasskeysGlobal} exposure`);
137+
138+
if (missingApis.length > 0) {
139+
throw new Error(`Desktop preload bundle is missing executable APIs: ${missingApis.join(", ")}`);
140+
}
107141
};
108142

109143
if (process.argv[1] && NodeURL.pathToFileURL(process.argv[1]).href === import.meta.url) {

‎apps/desktop/scripts/verify-preload-bundle.test.mjs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,31 @@ describe("desktop preload bundle verifier", () => {
2626
);
2727
});
2828

29+
it("rejects a required API whose exposed value is not callable", () => {
30+
assert.throws(
31+
() =>
32+
verifyPreloadBundle(
33+
validPreload.replace(
34+
"getClientPlatform: () => process.platform,",
35+
"getClientPlatform: undefined,",
36+
),
37+
),
38+
/missing executable APIs: getClientPlatform/,
39+
);
40+
});
41+
42+
it("accepts a required API exposed through a function alias", () => {
43+
assert.doesNotThrow(() =>
44+
verifyPreloadBundle(`
45+
const readClientPlatform = () => process.platform;
46+
${validPreload.replace(
47+
"getClientPlatform: () => process.platform,",
48+
"getClientPlatform: readClientPlatform,",
49+
)}
50+
`),
51+
);
52+
});
53+
2954
it("rejects dynamic imports with comments before the opening parenthesis", () => {
3055
assert.throws(
3156
() =>
@@ -54,6 +79,19 @@ describe("desktop preload bundle verifier", () => {
5479
);
5580
});
5681

82+
it("accepts Electron sandbox module aliases", () => {
83+
assert.doesNotThrow(() =>
84+
verifyPreloadBundle(`
85+
${validPreload}
86+
require("electron/common");
87+
require("electron/renderer");
88+
require("node:events");
89+
require("node:timers");
90+
require("node:url");
91+
`),
92+
);
93+
});
94+
5795
it("ignores require-like text in strings and comments", () => {
5896
assert.doesNotThrow(() =>
5997
verifyPreloadBundle(`

‎docs/internals/ci.md‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,8 @@ and pushes to `main`:
88
- **Check**: `vp check` (format and lint; this repo sets `typeCheck: false` in its lint options),
99
then `vpr typecheck` for the workspace type check. The same job
1010
builds the desktop pipeline (`vp run build:desktop`) and verifies the preload bundle exists and
11-
still exports its expected symbols without runtime imports that Electron's sandbox cannot load.
12-
`vp pack` can preserve dynamic imports in CommonJS output, including comments between `import`
13-
and `(`, so the verifier parses module syntax instead of matching that syntax with a regular
14-
expression.
11+
uses only imports that Electron's sandbox can load. The verifier parses imports, then executes the
12+
trusted artifact with controlled bridge stubs to confirm that its required APIs are callable.
1513
- **Test**: `vp run test` across the workspace.
1614
- **Mobile Native Static Analysis**: `vp run lint:mobile` on macOS, wrapping
1715
`scripts/mobile-native-static-check.ts`. A cheap Linux **Mobile Native Changes** job gates it:

0 commit comments

Comments
 (0)