app-control-navigation-blocked-navigation.runtime.test.mjs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. // 运行时回归:导航守卫拦截外部顶层导航后,App 控制导航的 renderer 登记仍然有效。
  2. // Electron 44 对被 will-navigate 拦截的主框架导航仍先发出 did-start-navigation;登记若按导航开始失效,
  3. // 拦截之后 OpenSession 等请求会一直返回 renderer-unavailable。登记应只在导航真正提交(reload 等)时失效。
  4. // 从源码抽取生产中的 guardWindowNavigation / isAppOriginMainWindowUrl、windowSurface 与
  5. // createAppControlNavigationWindow(不复制逻辑),在真实 Electron 窗口中组合验证。
  6. import assert from "node:assert/strict";
  7. import { spawn } from "node:child_process";
  8. import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises";
  9. import { createRequire } from "node:module";
  10. import { tmpdir } from "node:os";
  11. import { join, resolve } from "node:path";
  12. import test from "node:test";
  13. import ts from "typescript";
  14. const desktop = resolve(import.meta.dirname, "../..");
  15. const require = createRequire(join(desktop, "package.json"));
  16. const electronBinary = require("electron");
  17. async function extractFunctions(relativePath, names) {
  18. const path = resolve(desktop, relativePath);
  19. const source = await readFile(path, "utf8");
  20. const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
  21. const selected = file.statements.filter(
  22. (statement) => ts.isFunctionDeclaration(statement) && names.includes(statement.name?.text),
  23. );
  24. assert.equal(selected.length, names.length, `生产函数必须仍存在于 ${relativePath}`);
  25. const text = selected.map((node) => node.getText(file).replace(/^export /, "")).join("\n");
  26. return ts.transpileModule(text, {
  27. compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
  28. }).outputText;
  29. }
  30. async function productionSource() {
  31. const guard = await extractFunctions("src/main/desktopWindowChrome.ts", [
  32. "isAppOriginMainWindowUrl",
  33. "guardWindowNavigation",
  34. ]);
  35. const windowBridge = await extractFunctions("src/app-control-navigation/windowBridge.ts", [
  36. "createAppControlNavigationWindow",
  37. ]);
  38. const electronBridge = await extractFunctions("src/app-control-navigation/electronBridge.ts", [
  39. "windowSurface",
  40. ]);
  41. return [
  42. guard.replaceAll("import.meta.dirname", "__APP_MAIN_DIR__"),
  43. windowBridge,
  44. electronBridge,
  45. ].join("\n");
  46. }
  47. function harnessSource({ production, mainDir, userData }) {
  48. return `
  49. const { app, BrowserWindow } = require("electron");
  50. const { join } = require("node:path");
  51. const { pathToFileURL } = require("node:url");
  52. const __APP_MAIN_DIR__ = ${JSON.stringify(mainDir)};
  53. const APP_NAVIGATION_IPC = "zcode:app-control-navigation";
  54. const surfaces = new WeakMap();
  55. ${production}
  56. const logger = { warn: () => {} };
  57. const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
  58. const target = { workspacePath: "/workspace", taskId: "task" };
  59. app.whenReady().then(async () => {
  60. app.setPath("userData", ${JSON.stringify(userData)});
  61. const win = new BrowserWindow({
  62. show: false,
  63. webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false },
  64. });
  65. guardWindowNavigation(win.webContents, logger);
  66. const surface = windowSurface(win);
  67. await win.loadURL(pathToFileURL(join(__APP_MAIN_DIR__, "../renderer/index.html")).href);
  68. surface.register("generation-1");
  69. const replies = [];
  70. const source = { reply: (message) => replies.push(message) };
  71. const repliesFor = (requestId) => replies.filter((message) => message.requestId === requestId);
  72. await win.webContents.executeJavaScript('location.href = "https://example.com/zp-nav"');
  73. await wait(800);
  74. surface.open(source, { type: "app-navigation-open", requestId: "after-blocked", target });
  75. await wait(200);
  76. const afterBlocked = { url: win.webContents.getURL(), replies: repliesFor("after-blocked") };
  77. win.webContents.reload();
  78. await wait(1500);
  79. surface.open(source, { type: "app-navigation-open", requestId: "after-reload", target });
  80. await wait(200);
  81. const afterReload = { replies: repliesFor("after-reload") };
  82. win.destroy();
  83. console.log("RESULT " + JSON.stringify({ afterBlocked, afterReload }));
  84. app.exit(0);
  85. }).catch((error) => {
  86. console.log("ERROR " + (error && error.stack ? error.stack : String(error)));
  87. app.exit(1);
  88. });
  89. `;
  90. }
  91. test(
  92. "导航守卫拦截外部导航后 App 控制导航登记仍有效,reload 后失效",
  93. { timeout: 120000 },
  94. async () => {
  95. const base = await mkdtemp(join(tmpdir(), "zcode-app-nav-blocked-"));
  96. const mainDir = join(base, "app", "main");
  97. const rendererDir = join(base, "app", "renderer");
  98. await mkdir(mainDir, { recursive: true });
  99. await mkdir(rendererDir, { recursive: true });
  100. await writeFile(join(rendererDir, "index.html"), "<title>app</title>");
  101. const harnessPath = join(mainDir, "harness.cjs");
  102. await writeFile(
  103. harnessPath,
  104. harnessSource({
  105. production: await productionSource(),
  106. mainDir,
  107. userData: join(base, "user-data"),
  108. }),
  109. );
  110. const env = { ...process.env };
  111. delete env.ELECTRON_RENDERER_URL;
  112. delete env.ELECTRON_RUN_AS_NODE;
  113. const output = await new Promise((resolveRun, rejectRun) => {
  114. const child = spawn(electronBinary, [harnessPath], {
  115. env,
  116. stdio: ["ignore", "pipe", "pipe"],
  117. });
  118. let stdout = "";
  119. child.stdout.on("data", (chunk) => (stdout += chunk));
  120. child.stderr.on("data", () => {});
  121. child.on("error", rejectRun);
  122. child.on("exit", () => resolveRun(stdout));
  123. });
  124. const line = output
  125. .split("\n")
  126. .find((entry) => entry.startsWith("RESULT ") || entry.startsWith("ERROR "));
  127. assert.ok(line?.startsWith("RESULT "), `Electron harness 未返回结果:${output.slice(-800)}`);
  128. const { afterBlocked, afterReload } = JSON.parse(line.slice("RESULT ".length));
  129. assert.match(afterBlocked.url, /^file:/, "外部导航应被守卫拦截");
  130. assert.deepEqual(afterBlocked.replies, [], "被拦截的导航不应使 renderer 登记失效");
  131. assert.equal(afterReload.replies.length, 1, "reload 后请求应立即返回");
  132. assert.deepEqual(afterReload.replies[0].result, {
  133. status: "unavailable",
  134. reason: "renderer-unavailable",
  135. });
  136. },
  137. );