browser-local-html-preview.test.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/promises";
  2. import { createServer, type Server } from "node:http";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { pathToFileURL } from "node:url";
  6. import { TID_BROWSER_ADDRESS_INPUT, TID_BROWSER_WEBVIEW } from "@zcode/shared/test-ids";
  7. import { openFirstBrowserTab } from "#e2e/helpers/browser-side-pane";
  8. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  9. async function runInGuest(script: string): Promise<unknown> {
  10. return browser.execute(
  11. async (testId, code) => {
  12. const guest = document.querySelector(`[data-testid="${testId}"]`) as
  13. | (HTMLElement & { executeJavaScript(code: string): Promise<unknown> })
  14. | null;
  15. if (!guest) throw new Error("Browser guest is missing");
  16. return guest.executeJavaScript(code);
  17. },
  18. TID_BROWSER_WEBVIEW,
  19. script,
  20. );
  21. }
  22. describe("本地 HTML 预览的文件权限边界", () => {
  23. let directory: string;
  24. let fileUrl: string;
  25. let outsideUrl: string;
  26. let canonicalFileUrl: string;
  27. let server: Server;
  28. let httpUrl: string;
  29. before(async () => {
  30. server = createServer((_request, response) => {
  31. response.writeHead(200, { "content-type": "text/html" });
  32. response.end("<title>HTTP control</title><p>HTTP control</p>");
  33. });
  34. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  35. const address = server.address();
  36. if (!address || typeof address === "string") throw new Error("HTTP fixture did not start");
  37. httpUrl = `http://127.0.0.1:${address.port}/`;
  38. directory = await mkdtemp(join(tmpdir(), "zcode-html-preview-"));
  39. const preview = join(directory, "预览 空格");
  40. const outside = join(directory, "outside");
  41. await Promise.all([mkdir(preview), mkdir(outside)]);
  42. fileUrl = pathToFileURL(join(preview, "页面.html")).href;
  43. outsideUrl = pathToFileURL(join(outside, "secret.txt")).href;
  44. await Promise.all([
  45. writeFile(join(outside, "secret.txt"), "SYNTHETIC_OUTSIDE_SECRET"),
  46. writeFile(join(preview, ".env"), "SYNTHETIC_HIDDEN_SECRET"),
  47. writeFile(join(preview, "data.json"), '{"ok":true}'),
  48. writeFile(join(preview, "style.css"), "body { color: rgb(12, 34, 56); }"),
  49. writeFile(join(preview, "classic.js"), "window.classicLoaded = true;"),
  50. writeFile(join(preview, "module.js"), "window.moduleLoaded = true;"),
  51. writeFile(
  52. join(preview, "image.svg"),
  53. '<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"/>',
  54. ),
  55. writeFile(join(preview, "next.html"), "<title>next</title><p>Next page</p>"),
  56. writeFile(
  57. join(preview, "页面.html"),
  58. `<!doctype html><html><head>
  59. <title>Local HTML boundary</title><link rel="stylesheet" href="style.css">
  60. <script src="classic.js"></script><script type="module" src="module.js"></script>
  61. </head><body><img src="image.svg"><a id="next" href="next.html">Next</a></body></html>`,
  62. ),
  63. symlink(outside, join(preview, "linked"), process.platform === "win32" ? "junction" : "dir"),
  64. ]);
  65. canonicalFileUrl = pathToFileURL(await realpath(join(preview, "页面.html"))).href;
  66. });
  67. after(async () => {
  68. await rm(directory, { recursive: true, force: true });
  69. server.closeAllConnections();
  70. await new Promise<void>((resolve) => server.close(() => resolve()));
  71. });
  72. it("真实浏览器入口加载相对资源,同时拒绝越界文件并支持刷新和后退", async function () {
  73. this.timeout(240_000);
  74. await prepareV4ConversationE2E({ skipProvider: true });
  75. await openFirstBrowserTab();
  76. const input = await $(`[data-testid="${TID_BROWSER_ADDRESS_INPUT}"]`);
  77. await input.setValue(fileUrl);
  78. await browser.keys("Enter");
  79. await browser.waitUntil(
  80. async () => (await runInGuest("document.title")) === "Local HTML boundary",
  81. { timeout: 30_000, timeoutMsg: "本地 HTML 未加载" },
  82. );
  83. expect(await runInGuest("location.protocol")).toBe("zcode-html:");
  84. expect(await input.getValue()).toBe(canonicalFileUrl);
  85. await browser.waitUntil(
  86. async () =>
  87. Boolean(
  88. await runInGuest(
  89. "window.classicLoaded && window.moduleLoaded && document.querySelector('img').naturalWidth === 2",
  90. ),
  91. ),
  92. { timeout: 10_000, timeoutMsg: "相对脚本或图片未加载" },
  93. );
  94. expect(await runInGuest("getComputedStyle(document.body).color")).toBe("rgb(12, 34, 56)");
  95. expect(await runInGuest("fetch('data.json').then(r => r.json())")).toEqual({ ok: true });
  96. const results = await runInGuest(`(async () => {
  97. const forged = new URL(location.href); forged.hostname = '0'.repeat(64);
  98. const urls = [${JSON.stringify(outsideUrl)}, 'linked/secret.txt', '.env',
  99. '../outside/secret.txt', '%2e%2e%2foutside%2fsecret.txt', forged.href];
  100. return Promise.all(urls.map(async url => {
  101. try { const r = await fetch(url); return r.ok ? await r.text() : null; }
  102. catch { return null; }
  103. }));
  104. })()`);
  105. expect(results).toEqual([null, null, null, null, null, null]);
  106. // 等待加载结果后读取,避免 iframe 仍在 about:blank 时产生假通过;拒绝加载可能没有 load 事件。
  107. await runInGuest(`new Promise(resolve => {
  108. const frame = document.createElement('iframe'); frame.id = 'outside';
  109. const timeout = setTimeout(resolve, 2000);
  110. frame.onload = frame.onerror = () => { clearTimeout(timeout); resolve(); };
  111. frame.src = ${JSON.stringify(outsideUrl)}; document.body.append(frame);
  112. })`);
  113. expect(
  114. await runInGuest(`(() => {
  115. try { return document.querySelector('#outside').contentDocument?.body?.textContent?.includes('SYNTHETIC_OUTSIDE_SECRET') ?? false; }
  116. catch { return false; }
  117. })()`),
  118. ).toBe(false);
  119. const previewUrl = await runInGuest("location.href");
  120. const previousBoot = await runInGuest("performance.timeOrigin");
  121. await runInGuest("void location.reload()");
  122. await browser.waitUntil(
  123. async () =>
  124. Boolean(
  125. await runInGuest(`window.moduleLoaded && performance.timeOrigin !== ${previousBoot}`),
  126. ),
  127. {
  128. timeout: 15_000,
  129. },
  130. );
  131. await runInGuest("document.querySelector('#next').click()");
  132. await browser.waitUntil(async () => (await runInGuest("document.title")) === "next", {
  133. timeout: 15_000,
  134. });
  135. await runInGuest("history.back()");
  136. await browser.waitUntil(async () => (await runInGuest("location.href")) === previewUrl, {
  137. timeout: 15_000,
  138. });
  139. const isolation = await browser.electron.execute(async (electron, url) => {
  140. const control = new electron.BrowserWindow({
  141. show: false,
  142. webPreferences: { sandbox: true },
  143. });
  144. const denied = new electron.BrowserWindow({
  145. show: false,
  146. webPreferences: {
  147. sandbox: true,
  148. partition: "persist:zcode-embedded-browser",
  149. },
  150. });
  151. try {
  152. await control.loadURL(url);
  153. let blocked = false;
  154. try {
  155. await denied.loadURL(url);
  156. } catch {
  157. blocked = true;
  158. }
  159. return {
  160. defaultLoaded: await control.webContents.executeJavaScript("document.title"),
  161. blocked,
  162. };
  163. } finally {
  164. control.destroy();
  165. denied.destroy();
  166. }
  167. }, fileUrl);
  168. expect(isolation).toEqual({ defaultLoaded: "Local HTML boundary", blocked: true });
  169. // 同一轮 renderer 调用先发本地文件、再发 HTTP,文件校验的异步结果不能覆盖后者。
  170. await browser.execute(
  171. async (testId, localUrl, remoteUrl) => {
  172. const guest = document.querySelector(`[data-testid="${testId}"]`) as HTMLElement & {
  173. getWebContentsId(): number;
  174. };
  175. const platform = (
  176. window as Window & {
  177. zcode?: {
  178. browserViewLoadUrl(payload: { webContentsId: number; url: string }): Promise<void>;
  179. };
  180. }
  181. ).zcode;
  182. if (!platform) throw new Error("Desktop platform bridge is missing");
  183. const webContentsId = guest.getWebContentsId();
  184. await Promise.allSettled([
  185. platform.browserViewLoadUrl({ webContentsId, url: localUrl }),
  186. platform.browserViewLoadUrl({ webContentsId, url: remoteUrl }),
  187. ]);
  188. },
  189. TID_BROWSER_WEBVIEW,
  190. fileUrl,
  191. httpUrl,
  192. );
  193. expect(await runInGuest("location.href")).toBe(httpUrl);
  194. expect(await runInGuest("document.title")).toBe("HTTP control");
  195. });
  196. });