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

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