office-preview-security.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import { copyFile, mkdir, readFile, rm } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. import {
  5. TID_BROWSER_ADDRESS_INPUT,
  6. TID_SIDE_PANE_FULL_VIEW_TOGGLE,
  7. TID_SIDE_PANE_FULL_VIEW_MINIMIZE,
  8. TID_V4_COMPOSER_INPUT,
  9. TID_WORKSPACE_FILE_TREE_ROW,
  10. testId,
  11. } from "@zcode/shared/test-ids";
  12. import {
  13. clearAppData,
  14. DEFAULT_WORKSPACE,
  15. waitForDefaultWorkspaceReady,
  16. } from "#e2e/helpers/desktop-app";
  17. import { openProjectFileTree } from "#e2e/helpers/project-sidebar";
  18. const ROOT = join(DEFAULT_WORKSPACE, "E2E_OFFICE_SECURITY");
  19. const FIXTURES = fileURLToPath(
  20. new URL("../../../../fixtures/fs/office-preview-security/", import.meta.url),
  21. );
  22. // 只打开合成文档;标记脚本不读取文件、执行命令或向外传输数据。
  23. describe("内置 Office 预览安全边界", () => {
  24. before(async () => {
  25. await mkdir(ROOT, { recursive: true });
  26. for (const name of ["tooltip.pptx", "links.xlsx"]) {
  27. await copyFile(join(FIXTURES, name), join(ROOT, name));
  28. }
  29. await waitForDefaultWorkspaceReady();
  30. await openProjectFileTree(DEFAULT_WORKSPACE);
  31. await clickFile(ROOT);
  32. await $(`[data-testid="${TID_SIDE_PANE_FULL_VIEW_TOGGLE}"]`).click();
  33. // 完整视图的操作栏只在输入框聚焦时出现,收起浮窗后再操作文档工具栏。
  34. await $(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`).click();
  35. await $(`[data-testid="${TID_SIDE_PANE_FULL_VIEW_MINIMIZE}"]`).waitForClickable();
  36. await $(`[data-testid="${TID_SIDE_PANE_FULL_VIEW_MINIMIZE}"]`).click();
  37. });
  38. after(async () => {
  39. await browser.electron.restoreAllMocks();
  40. await clearAppData();
  41. await rm(ROOT, { recursive: true, force: true });
  42. });
  43. afterEach(async function () {
  44. if (this.currentTest?.state !== "failed") return;
  45. await browser.saveScreenshot(
  46. join(
  47. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ROOT,
  48. `${this.currentTest.title.slice(0, 5)}-failure.png`,
  49. ),
  50. );
  51. console.info(
  52. "[office-preview DOM]",
  53. await browser.execute(() => ({
  54. text: document.body.innerText,
  55. tabs: [...document.querySelectorAll<HTMLElement>("[data-side-pane-tab-id]")].map((el) => ({
  56. id: el.dataset.sidePaneTabId,
  57. state: el.dataset.state,
  58. })),
  59. })),
  60. );
  61. });
  62. it("OPS01:PPTX 气泡 tooltip 把 HTML 系列名显示为文本", async () => {
  63. await clickFile(join(ROOT, "tooltip.pptx"));
  64. const chart = $(
  65. '[data-zcode-pptx-render-surface="true"].pointer-events-auto [_echarts_instance_]',
  66. );
  67. await chart.waitForDisplayed({ timeout: 30000 });
  68. // 夹具只有一个蓝色气泡;从真实 Canvas 像素定位,避免 fit 缩放后固定坐标漏掉气泡。
  69. let bubble: { x: number; y: number } | null = null;
  70. await browser.waitUntil(
  71. async () => {
  72. bubble = await browser.execute(() => {
  73. const canvas = document.querySelector<HTMLCanvasElement>(
  74. '[data-zcode-pptx-render-surface="true"].pointer-events-auto [_echarts_instance_] canvas',
  75. );
  76. if (!canvas) return null;
  77. const pixels = canvas
  78. .getContext("2d")!
  79. .getImageData(0, 0, canvas.width, canvas.height).data;
  80. let x = 0,
  81. y = 0,
  82. count = 0;
  83. for (let i = 0; i < pixels.length; i += 4) {
  84. if (
  85. pixels[i + 3]! > 100 &&
  86. pixels[i + 2]! > pixels[i]! + 40 &&
  87. pixels[i + 2]! > pixels[i + 1]! + 20
  88. ) {
  89. x += (i / 4) % canvas.width;
  90. y += Math.floor(i / 4 / canvas.width);
  91. count++;
  92. }
  93. }
  94. if (count < 100) return null;
  95. const rect = canvas.getBoundingClientRect();
  96. return {
  97. x: rect.left + (x / count / canvas.width) * rect.width,
  98. y: rect.top + (y / count / canvas.height) * rect.height,
  99. };
  100. });
  101. return bubble !== null;
  102. },
  103. { timeout: 10000, timeoutMsg: "气泡未完成绘制" },
  104. );
  105. const point = bubble! as { x: number; y: number };
  106. await browser.performActions([
  107. {
  108. type: "pointer",
  109. id: "office-pointer",
  110. parameters: { pointerType: "mouse" },
  111. actions: [
  112. { type: "pointerMove", x: Math.round(point.x), y: Math.round(point.y), duration: 0 },
  113. ],
  114. },
  115. ]);
  116. await browser.waitUntil(
  117. () =>
  118. browser.execute(() => document.body.innerText.includes('<img src="office-preview-probe"')),
  119. { timeout: 5000, timeoutMsg: "未出现字面文本 tooltip,不能把未触发当作通过" },
  120. );
  121. expect(
  122. await browser.execute(() => ({
  123. injected: Boolean(document.querySelector('img[src="office-preview-probe"]')),
  124. executed: (window as Window & { __officePreviewXss?: number }).__officePreviewXss ?? 0,
  125. })),
  126. ).toEqual({ injected: false, executed: 0 });
  127. // 仅替代系统路径选择;真实执行打印和文件写入,覆盖同一渲染器的导出入口。
  128. const exportedPath = join(
  129. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ROOT,
  130. "office-preview-export.pdf",
  131. );
  132. const saveDialog = await browser.electron.mock("dialog", "showSaveDialog");
  133. await saveDialog.mockResolvedValueOnce({ canceled: false, filePath: exportedPath });
  134. try {
  135. await $('button[aria-label="Export as PDF"], button[aria-label="导出为 PDF"]').click();
  136. await browser.waitUntil(
  137. async () => {
  138. try {
  139. const pdf = await readFile(exportedPath);
  140. return pdf.length > 1000 && pdf.subarray(0, 5).toString() === "%PDF-";
  141. } catch (error) {
  142. if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
  143. throw error;
  144. }
  145. },
  146. { timeout: 20000, timeoutMsg: "PPTX 未导出有效 PDF" },
  147. );
  148. } finally {
  149. await saveDialog.mockRestore();
  150. }
  151. expect(
  152. await browser.execute(
  153. () => (window as Window & { __officePreviewXss?: number }).__officePreviewXss ?? 0,
  154. ),
  155. ).toBe(0);
  156. }).timeout(60000);
  157. it("OPS02:XLSX Canvas、形状、图片外链经过统一校验", async () => {
  158. await clickFile(join(ROOT, "links.xlsx"));
  159. await $('[data-office-preview-kind="excel"] canvas').waitForDisplayed({ timeout: 30000 });
  160. const fileTab = await $('[data-side-pane-tab-id][data-state="active"]').getAttribute(
  161. "data-side-pane-tab-id",
  162. );
  163. await browser.execute(() => {
  164. const state = window as Window & {
  165. __officeNativeOpens?: string[];
  166. __officeOriginalOpen?: typeof window.open;
  167. };
  168. state.__officeNativeOpens = [];
  169. state.__officeOriginalOpen = window.open;
  170. // 仅记录是否绕过宿主回调;危险请求不真的打开窗口。
  171. window.open = (url) => {
  172. state.__officeNativeOpens!.push(String(url));
  173. return null;
  174. };
  175. });
  176. try {
  177. for (let row = 0; row < 5; row++) await clickCell(row);
  178. await $('[title="OPS_UNSAFE_SHAPE"]').click();
  179. const image = $('[data-office-preview-kind="excel"] img');
  180. await image.waitForExist();
  181. const location = await image.getLocation();
  182. const size = await image.getSize();
  183. await clickPoint(location.x + size.width / 2, location.y + size.height / 2);
  184. expect(
  185. await browser.execute(
  186. () => (window as Window & { __officeNativeOpens?: string[] }).__officeNativeOpens,
  187. ),
  188. ).toEqual([]);
  189. expect(await $(`[data-testid="${TID_BROWSER_ADDRESS_INPUT}"]`).isExisting()).toBe(false);
  190. await clickCell(6);
  191. await waitForBrowserUrl("127.0.0.1:9/office-preview");
  192. expect(
  193. await browser.execute(
  194. () => (window as Window & { __officeNativeOpens?: string[] }).__officeNativeOpens,
  195. ),
  196. ).toEqual([]);
  197. await $(`[data-side-pane-tab-id="${fileTab}"]`).click();
  198. await $('[title="OPS_UNSAFE_SHAPE"]').waitForDisplayed();
  199. await clickCell(7);
  200. await browser.waitUntil(
  201. async () =>
  202. (await $(
  203. '[data-office-preview-kind="excel"] [role="tab"][aria-selected="true"]',
  204. ).getText()) === "Details",
  205. );
  206. } finally {
  207. await browser.execute(() => {
  208. const state = window as Window & { __officeOriginalOpen?: typeof window.open };
  209. if (state.__officeOriginalOpen) window.open = state.__officeOriginalOpen;
  210. });
  211. }
  212. }).timeout(60000);
  213. it("OPS03:主窗口拒绝危险 popup,合法外链不创建原生窗口", async () => {
  214. const initialUrl = await browser.getUrl();
  215. const initialWindows = await browser.electron.execute((electron) =>
  216. electron.BrowserWindow.getAllWindows().map((win) => win.id),
  217. );
  218. for (const url of [
  219. "javascript:window.__officePreviewXss=1",
  220. "data:text/html,blocked",
  221. "file:///office-preview-blocked",
  222. "zcode://office-preview-blocked",
  223. ]) {
  224. await browser.execute((target) => {
  225. window.open(target, "_blank");
  226. }, url);
  227. }
  228. await browser.execute(
  229. () =>
  230. new Promise<void>((resolve) =>
  231. requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
  232. ),
  233. );
  234. expect(await browser.getUrl()).toBe(initialUrl);
  235. expect(
  236. await browser.electron.execute((electron) =>
  237. electron.BrowserWindow.getAllWindows().map((win) => win.id),
  238. ),
  239. ).toEqual(initialWindows);
  240. await browser.execute(() => {
  241. window.open("http://127.0.0.1:9/office-popup", "_blank");
  242. });
  243. await waitForBrowserUrl("127.0.0.1:9/office-popup");
  244. expect(
  245. await browser.electron.execute((electron) =>
  246. electron.BrowserWindow.getAllWindows().map((win) => win.id),
  247. ),
  248. ).toEqual(initialWindows);
  249. expect(
  250. await browser.execute(
  251. () => (window as Window & { __officePreviewXss?: number }).__officePreviewXss ?? 0,
  252. ),
  253. ).toBe(0);
  254. }).timeout(30000);
  255. });
  256. async function waitForBrowserUrl(url: string) {
  257. await browser.waitUntil(
  258. async () => {
  259. for (const input of await $$(`[data-testid="${TID_BROWSER_ADDRESS_INPUT}"]`)) {
  260. if ((await input.isDisplayed()) && (await input.getValue()).includes(url)) return true;
  261. }
  262. return false;
  263. },
  264. { timeout: 10000, timeoutMsg: `未显示受控浏览器地址 ${url}` },
  265. );
  266. }
  267. async function clickFile(path: string) {
  268. await browser.waitUntil(
  269. () =>
  270. browser.execute(
  271. (id) => {
  272. const row = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  273. (element) => element.dataset.testid === id,
  274. );
  275. row?.click();
  276. return Boolean(row);
  277. },
  278. testId(TID_WORKSPACE_FILE_TREE_ROW, path),
  279. ),
  280. { timeout: 15000, timeoutMsg: `文件树中找不到 ${path}` },
  281. );
  282. }
  283. async function clickCell(row: number) {
  284. const point = await browser.execute((index) => {
  285. const canvas = document.querySelector<HTMLCanvasElement>(
  286. '[data-office-preview-kind="excel"] canvas',
  287. )!;
  288. // Canvas 有向视口外扩展的预绘制区域,点击坐标必须相对实际滚动视口。
  289. let viewport = canvas.parentElement;
  290. while (viewport && !["auto", "scroll"].includes(getComputedStyle(viewport).overflowY)) {
  291. viewport = viewport.parentElement;
  292. }
  293. const rect = viewport!.getBoundingClientRect();
  294. // 夹具固定行高 30pt(40px)加 1px 网格线,列头为 24px。
  295. return { x: rect.left + 85, y: rect.top + 24 + index * 41 + 20 };
  296. }, row);
  297. await clickPoint(point.x, point.y);
  298. }
  299. async function clickPoint(x: number, y: number) {
  300. await browser.performActions([
  301. {
  302. type: "pointer",
  303. id: "office-pointer",
  304. parameters: { pointerType: "mouse" },
  305. actions: [
  306. { type: "pointerMove", x: Math.round(x), y: Math.round(y), duration: 0 },
  307. { type: "pointerDown", button: 0 },
  308. { type: "pointerUp", button: 0 },
  309. ],
  310. },
  311. ]);
  312. await browser.releaseActions();
  313. }