main.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import {
  2. app,
  3. BrowserWindow,
  4. clipboard,
  5. nativeImage,
  6. ipcMain,
  7. protocol,
  8. session,
  9. webContents,
  10. } from "electron";
  11. import assert from "node:assert/strict";
  12. import { readFile, writeFile } from "node:fs/promises";
  13. import { join } from "node:path";
  14. import { legacyStorage, checkClearing } from "./storage-checks.js";
  15. import { checkPagePointerInput } from "./pointer-input.js";
  16. import {
  17. installPluginSandboxHost,
  18. PLUGIN_SANDBOX_PRIVILEGED_SCHEME,
  19. } from "../../src/main/pluginSandbox/index.js";
  20. const [root, profile, mode] = process.argv.slice(2);
  21. app.setPath("userData", profile!);
  22. protocol.registerSchemesAsPrivileged([PLUGIN_SANDBOX_PRIVILEGED_SCHEME]);
  23. // 旧分区探针会先关闭临时窗口;完整测试结束前不能触发 Electron 默认退出。
  24. app.on("window-all-closed", () => {});
  25. app
  26. .whenReady()
  27. .then(async () => {
  28. const oldPartition = "persist:plugin-sandbox-v1-" + "b".repeat(64);
  29. const old = session.fromPartition(oldPartition);
  30. assert.deepEqual(
  31. await legacyStorage(oldPartition, mode === "write"),
  32. mode === "empty" ? { local: null, indexed: null } : { local: "legacy", indexed: 7 },
  33. );
  34. const unrelated = session.fromPartition("persist:unrelated-fixture");
  35. const cookie = {
  36. url: "https://fixture.invalid",
  37. name: "fixture",
  38. value: "retained",
  39. expirationDate: Date.now() / 1000 + 3600,
  40. };
  41. if (mode === "write") {
  42. await old.cookies.set(cookie);
  43. await unrelated.cookies.set(cookie);
  44. } else {
  45. assert.equal((await old.cookies.get({ name: "fixture" })).length, mode === "empty" ? 0 : 1);
  46. assert.equal((await unrelated.cookies.get({ name: "fixture" })).length, 1);
  47. }
  48. // 冷启动计时只包含待测宿主页,不把旧分区探针窗口的启动耗时算入。
  49. const started = performance.now();
  50. const host = installPluginSandboxHost({
  51. rendererDir: root!,
  52. aliasDir: root!,
  53. preloadPath: join(root!, "guest.cjs"),
  54. logger: {
  55. info: (...args) => process.stdout.write(JSON.stringify(args) + "\n"),
  56. warn: (...args) => process.stderr.write(JSON.stringify(args) + "\n"),
  57. },
  58. });
  59. const win = new BrowserWindow({
  60. show: false,
  61. width: 1000,
  62. height: 700,
  63. webPreferences: {
  64. preload: join(root!, "preload.cjs"),
  65. webviewTag: true,
  66. backgroundThrottling: false,
  67. },
  68. });
  69. win.webContents.on("console-message", (event) =>
  70. process.stderr.write(String(event.message) + "\n"),
  71. );
  72. const pending: string[] = [];
  73. win.webContents.on("will-attach-webview", (event, webPreferences, params) => {
  74. const result = host.configureGuest({
  75. webPreferences,
  76. params,
  77. ownerWebContentsId: win.webContents.id,
  78. });
  79. if (!result.ok) event.preventDefault();
  80. else pending.push(result.sandboxId);
  81. });
  82. win.webContents.on("did-attach-webview", (_event, guest) =>
  83. host.attachGuest({ guest, hostWebContents: win.webContents, sandboxId: pending.shift()! }),
  84. );
  85. const html = await readFile(join(root!, "widget.html"), "utf8");
  86. let generation = 0;
  87. const register = () =>
  88. host.registerFromHost({
  89. instance: {
  90. runtimeId: "fixture",
  91. generation: ++generation,
  92. token: crypto.randomUUID(),
  93. appIdentity: "a".repeat(64),
  94. },
  95. ownerWebContentsId: win.webContents.id,
  96. workspacePath: "/fixture",
  97. sessionId: "fixture",
  98. pluginId: "fixture",
  99. serverName: "fixture",
  100. scopeId: "fixture",
  101. html,
  102. });
  103. const handle = register();
  104. let first = true;
  105. let htmlReads = 0;
  106. session
  107. .fromPartition(handle.partition)
  108. .webRequest.onCompleted({ urls: ["zcode-sandbox://*/*"] }, (event) => {
  109. if (event.url.includes("/index.html")) htmlReads++;
  110. });
  111. ipcMain.handle("fixture-handle", () => {
  112. if (first) {
  113. first = false;
  114. return handle;
  115. }
  116. return register();
  117. });
  118. ipcMain.handle("fixture-config", () => null);
  119. await win.loadFile(join(root!, "host.html"));
  120. await win.webContents.executeJavaScript("window.harnessReady");
  121. const guest = webContents
  122. .getAllWebContents()
  123. .find((contents) => contents.getType() === "webview")!;
  124. assert.ok(guest);
  125. if (mode === "write") {
  126. // 回归 Electron 44 的异步剪贴板:从受信 renderer 调用生产 IPC,再读回真实 PNG。
  127. const viewportSize = await guest.executeJavaScript(
  128. "({ width: innerWidth, height: innerHeight })",
  129. );
  130. const request = {
  131. sandboxId: handle.sandboxId,
  132. initId: handle.initId,
  133. viewportSize,
  134. captureRect: { x: 0, y: 0, width: 64, height: 64 },
  135. };
  136. await win.webContents.executeJavaScript(
  137. `window.harness.copyImage(${JSON.stringify(request)})`,
  138. );
  139. const items = await clipboard.read();
  140. const image = items.find((item) => item.types.includes("image/png"));
  141. assert.ok(image, "clipboard must contain PNG after successful IPC");
  142. const png = Buffer.from(await (await image.getType("image/png")).arrayBuffer());
  143. assert.ok(png.length > 8);
  144. const scale = await guest.executeJavaScript("devicePixelRatio");
  145. assert.deepEqual(nativeImage.createFromBuffer(png).getSize(), {
  146. width: Math.round(64 * scale),
  147. height: Math.round(64 * scale),
  148. });
  149. await assert.rejects(
  150. win.webContents.executeJavaScript(
  151. `window.harness.copyImage(${JSON.stringify({ ...request, initId: handle.initId + 1 })})`,
  152. ),
  153. /no longer available/,
  154. );
  155. process.stdout.write("PASS E44-CLIP: native PNG round-trip and stale identity rejection\n");
  156. }
  157. const frame = guest.mainFrame.frames.find((frame) => frame.url.includes("/instance/"))!;
  158. await frame.executeJavaScript("window.fixtureReady");
  159. const initialState =
  160. "({ counter: document.querySelector('#counter').textContent, input: document.querySelector('#input').value, scroll: document.querySelector('#scroll').scrollTop, starts: window.starts })";
  161. assert.deepEqual(await frame.executeJavaScript(initialState), {
  162. counter: "0",
  163. input: "",
  164. scroll: 0,
  165. starts: 1,
  166. });
  167. if (mode === "write")
  168. assert.deepEqual(await frame.executeJavaScript("window.storageRoundTrip(false)"), {
  169. local: null,
  170. indexed: null,
  171. });
  172. const coldMs = performance.now() - started;
  173. await win.webContents.executeJavaScript("window.switchPage(false)");
  174. const storage = await frame.executeJavaScript(`window.storageRoundTrip(${mode === "write"})`);
  175. assert.deepEqual(
  176. storage,
  177. mode === "empty" ? { local: null, indexed: null } : { local: "42", indexed: 42 },
  178. );
  179. // 用 Chromium 输入事件走 React onClick/onChange,避免直接改 DOM 掩盖受控状态丢失。
  180. guest.debugger.attach("1.3");
  181. for (const selector of ["#counter", "#input"]) {
  182. const point = await frame.executeJavaScript(
  183. `(() => { const r = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return {x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2)}; })()`,
  184. );
  185. await guest.debugger.sendCommand("Input.dispatchMouseEvent", {
  186. type: "mousePressed",
  187. ...point,
  188. button: "left",
  189. clickCount: 1,
  190. });
  191. await guest.debugger.sendCommand("Input.dispatchMouseEvent", {
  192. type: "mouseReleased",
  193. ...point,
  194. button: "left",
  195. clickCount: 1,
  196. });
  197. }
  198. await guest.debugger.sendCommand("Input.insertText", { text: "retained" });
  199. guest.debugger.detach();
  200. await frame.executeJavaScript(
  201. "document.querySelector('#scroll').scrollTop = 123; new Promise(requestAnimationFrame)",
  202. );
  203. const active = webContents.getAllWebContents().length;
  204. const times: number[] = [];
  205. const dispatchTimes: number[] = [];
  206. const listenerCounts = new Map<boolean, number>();
  207. for (let n = 0; n < 40; n++) {
  208. const start = performance.now();
  209. const counts = await win.webContents.executeJavaScript(`window.switchPage(${n % 2 === 0})`);
  210. times.push(performance.now() - start);
  211. const side = n % 2 === 0;
  212. if (!listenerCounts.has(side)) listenerCounts.set(side, counts.listeners);
  213. dispatchTimes.push(counts.dispatchMs);
  214. const { dispatchMs: _dispatch, ...stable } = counts;
  215. assert.deepEqual(stable, {
  216. handshakes: 1,
  217. views: 1,
  218. listeners: listenerCounts.get(n % 2 === 0),
  219. });
  220. assert.equal(htmlReads, 1);
  221. assert.equal(webContents.getAllWebContents().length, active);
  222. assert.equal(
  223. guest.id,
  224. webContents.getAllWebContents().find((contents) => contents.getType() === "webview")!.id,
  225. );
  226. }
  227. assert.deepEqual(
  228. await frame.executeJavaScript(
  229. "({ counter: document.querySelector('#counter').textContent, input: document.querySelector('#input').value, scroll: document.querySelector('#scroll').scrollTop, starts: window.starts })",
  230. ),
  231. { counter: "1", input: "retained", scroll: 123, starts: 1 },
  232. );
  233. for (const position of ["inline", "sidebar", "preview"]) {
  234. await win.webContents.executeJavaScript(`window.switchPage(${position === "sidebar"})`);
  235. if (position === "preview")
  236. await win.webContents.executeJavaScript("window.previewPage(true)");
  237. await checkPagePointerInput(win, guest);
  238. if (position === "preview")
  239. await win.webContents.executeJavaScript("window.previewPage(false)");
  240. assert.equal(guest.isDestroyed(), false);
  241. }
  242. await writeFile(
  243. join(root!, `switch-${mode}.png`),
  244. (await win.webContents.capturePage()).toPNG(),
  245. );
  246. await writeFile(
  247. join(root!, `metrics-${mode}.json`),
  248. JSON.stringify(
  249. {
  250. mode,
  251. coldMs,
  252. switches: times.length,
  253. switchObservedMedianMs: [...times].sort((a, b) => a - b)[20],
  254. switchDispatchMedianMs: [...dispatchTimes].sort((a, b) => a - b)[20],
  255. webContents: active,
  256. handshakes: 1,
  257. htmlReads,
  258. listeners: { inline: listenerCounts.get(false), sidebar: listenerCounts.get(true) },
  259. storage,
  260. },
  261. null,
  262. 2,
  263. ),
  264. );
  265. assert.equal(await frame.executeJavaScript("window.readWidget()"), null);
  266. await frame.executeJavaScript("window.saveWidget({ saved: 7 })");
  267. assert.deepEqual(await win.webContents.executeJavaScript("window.recyclePage()"), {
  268. views: 0,
  269. state: { saved: 7 },
  270. });
  271. assert.equal(
  272. webContents.getAllWebContents().filter((c) => c.getType() === "webview").length,
  273. 0,
  274. );
  275. for (const retry of [false, true]) {
  276. await win.webContents.executeJavaScript(`window.restorePage(${retry})`);
  277. const restoredGuest = webContents.getAllWebContents().find((c) => c.getType() === "webview")!;
  278. const restored = restoredGuest.mainFrame.frames.find((f) => f.url.includes("/instance/"))!;
  279. await restored.executeJavaScript("window.fixtureReady");
  280. assert.deepEqual(await restored.executeJavaScript(initialState), {
  281. counter: "0",
  282. input: "",
  283. scroll: 0,
  284. starts: 1,
  285. });
  286. assert.deepEqual(
  287. await restored.executeJavaScript("window.readWidget()"),
  288. retry ? null : { saved: 7 },
  289. );
  290. assert.deepEqual(await restored.executeJavaScript("window.storageRoundTrip(false)"), storage);
  291. assert.equal(webContents.getAllWebContents().length, active);
  292. }
  293. if (mode === "read") {
  294. await checkClearing({
  295. root: root!,
  296. partition: handle.partition,
  297. oldPartition,
  298. host,
  299. win,
  300. register,
  301. });
  302. assert.equal(
  303. webContents.getAllWebContents().filter((contents) => contents.getType() === "webview")
  304. .length,
  305. 0,
  306. );
  307. assert.equal((await old.cookies.get({ name: "fixture" })).length, 0);
  308. assert.equal((await unrelated.cookies.get({ name: "fixture" })).length, 1);
  309. assert.throws(() => host.registerFromHost({} as never), /being cleared/);
  310. }
  311. session.fromPartition(handle.partition).flushStorageData();
  312. await old.cookies.flushStore();
  313. await unrelated.cookies.flushStore();
  314. win.destroy();
  315. app.exit(0);
  316. })
  317. .catch((error) => {
  318. process.stderr.write(String(error.stack ?? error));
  319. app.exit(1);
  320. });