main.ts 11 KB

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