external-links-checks.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import assert from "node:assert/strict";
  2. import { app, type BrowserWindow, type WebContents } from "electron";
  3. // 使用生产桥接与手势校验;只替换最终 opener,避免测试启动系统浏览器。
  4. export async function checkExternalLinks(
  5. win: BrowserWindow,
  6. guest: WebContents,
  7. read: (code: string) => Promise<any>,
  8. ) {
  9. assert.deepEqual(await read("Object.keys(window.zcode).sort()"), [
  10. "openExternal",
  11. "sendFollowUpMessage",
  12. "setWidgetState",
  13. "widgetState",
  14. ]);
  15. const inspect = () => win.webContents.executeJavaScript("window.inspectReact()");
  16. const wait = (predicate: string, execute = read) =>
  17. execute(`new Promise((resolve,reject)=>{
  18. const end=Date.now()+5000;
  19. const tick=()=>{if(${predicate})resolve(true);else if(Date.now()>end)reject(new Error('Link condition timed out: '+${JSON.stringify(predicate)}));else requestAnimationFrame(tick)};
  20. tick();
  21. })`).catch(async (error) => {
  22. process.stderr.write(
  23. JSON.stringify({
  24. host: await inspect(),
  25. guest: await read(
  26. "({events:window.linkEvents,errors:window.linkErrors,probe:document.getElementById('link-probe').outerHTML,point:document.getElementById('link-probe').getBoundingClientRect().toJSON()})",
  27. ),
  28. shell: await guest.mainFrame.executeJavaScript(
  29. "document.querySelector('iframe').getBoundingClientRect().toJSON()",
  30. ),
  31. }) + "\n",
  32. );
  33. throw error;
  34. });
  35. const click = async (button: "left" | "middle" = "left", modifiers: string[] = []) => {
  36. app.focus({ steal: true });
  37. win.focus();
  38. guest.focus();
  39. const point = await read(`(() => {
  40. const r=document.getElementById('link-probe').getBoundingClientRect();
  41. return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)};
  42. })()`);
  43. await win.webContents.capturePage();
  44. // CDP 能命中嵌套 iframe,但不发 Electron input-event;先用原生修饰键登记手势。
  45. guest.sendInputEvent({ type: "keyDown", keyCode: "Shift" });
  46. guest.sendInputEvent({ type: "keyUp", keyCode: "Shift" });
  47. guest.debugger.attach("1.3");
  48. try {
  49. const keys = modifiers.includes("meta") ? 4 : modifiers.includes("control") ? 2 : 0;
  50. await guest.debugger.sendCommand("Input.dispatchMouseEvent", {
  51. type: "mousePressed",
  52. ...point,
  53. button,
  54. buttons: button === "middle" ? 4 : 1,
  55. clickCount: 1,
  56. modifiers: keys,
  57. });
  58. await guest.debugger.sendCommand("Input.dispatchMouseEvent", {
  59. type: "mouseReleased",
  60. ...point,
  61. button,
  62. buttons: 0,
  63. clickCount: 1,
  64. modifiers: keys,
  65. });
  66. } finally {
  67. guest.debugger.detach();
  68. }
  69. };
  70. await read(`(() => {
  71. const probe=document.createElement('a');probe.id='link-probe';
  72. probe.style.cssText='position:fixed;top:4px;left:4px;z-index:99999;padding:12px;background:white;color:black';
  73. probe.innerHTML='<span>Open subscription</span>';document.body.append(probe);
  74. window.linkErrors=[];
  75. window.linkEvents=[];
  76. for(const type of ['pointerdown','pointerup','click','auxclick'])document.addEventListener(type,event=>window.linkEvents.push({type,trusted:event.isTrusted,target:event.target.outerHTML,x:event.clientX,y:event.clientY}),true);
  77. window.addEventListener('zcode:error',event=>window.linkErrors.push(String(event.detail)));
  78. })()`);
  79. const originalUrl = await read("location.href");
  80. let expected = 0;
  81. const openedOnce = async (url: string) => {
  82. expected++;
  83. await wait(`window.inspectReact().opened.length===${expected}`, (code) =>
  84. win.webContents.executeJavaScript(code),
  85. );
  86. assert.equal((await inspect()).opened.at(-1), url);
  87. assert.equal(await read("location.href"), originalUrl);
  88. assert.equal(await read("window.starts"), 1);
  89. };
  90. for (const target of ["", "_blank", "_self"]) {
  91. await read(
  92. `Object.assign(document.getElementById('link-probe'),{href:'https://example.com/subscribe',target:${JSON.stringify(target)}})`,
  93. );
  94. await click();
  95. await openedOnce("https://example.com/subscribe");
  96. }
  97. await click("left", [process.platform === "darwin" ? "meta" : "control"]);
  98. await openedOnce("https://example.com/subscribe");
  99. await click("middle");
  100. await openedOnce("https://example.com/subscribe");
  101. await read("document.getElementById('link-probe').focus()");
  102. guest.sendInputEvent({ type: "keyDown", keyCode: "Shift" });
  103. guest.sendInputEvent({ type: "keyUp", keyCode: "Shift" });
  104. guest.debugger.attach("1.3");
  105. try {
  106. await guest.debugger.sendCommand("Input.dispatchKeyEvent", {
  107. type: "keyDown",
  108. key: "Enter",
  109. code: "Enter",
  110. windowsVirtualKeyCode: 13,
  111. nativeVirtualKeyCode: 13,
  112. });
  113. await guest.debugger.sendCommand("Input.dispatchKeyEvent", {
  114. type: "keyUp",
  115. key: "Enter",
  116. code: "Enter",
  117. windowsVirtualKeyCode: 13,
  118. nativeVirtualKeyCode: 13,
  119. });
  120. } finally {
  121. guest.debugger.detach();
  122. }
  123. await openedOnce("https://example.com/subscribe");
  124. // 页面可取消默认行为,避免自定义点击处理与委托处理重复打开。
  125. await read(`document.getElementById('link-probe').onclick=event=>{
  126. event.preventDefault();window.linkResult=window.zcode.openExternal({href:'http://example.com/script'}).then(()=>'',String);
  127. }`);
  128. await click();
  129. await wait("window.linkResult");
  130. assert.equal(await read("window.linkResult"), "");
  131. await openedOnce("http://example.com/script");
  132. assert.match(
  133. await read(
  134. "window.zcode.openExternal({href:'https://example.com/automatic'}).then(()=>'',String)",
  135. ),
  136. /gesture/i,
  137. );
  138. for (const href of [
  139. "relative/path",
  140. "file:///tmp/test",
  141. "javascript:void(0)",
  142. "data:text/plain,test",
  143. ]) {
  144. assert.match(
  145. await read(`window.zcode.openExternal({href:${JSON.stringify(href)}}).then(()=>'',String)`),
  146. /URL|HTTP/i,
  147. );
  148. }
  149. await read(
  150. "document.getElementById('link-probe').onclick=null;document.getElementById('link-probe').click()",
  151. );
  152. // 合成点击不能利用之前未消费的用户手势;下载与片段也不进入 opener。
  153. await read("document.getElementById('link-probe').download='plan.html'");
  154. await click();
  155. await read(
  156. "document.getElementById('link-probe').removeAttribute('download');document.getElementById('link-probe').click()",
  157. );
  158. await read("document.getElementById('link-probe').href='#first'");
  159. await click();
  160. await wait("location.hash==='#first'");
  161. await read(
  162. "history.replaceState(null,'',location.pathname);document.getElementById('link-probe').href='file:///tmp/test'",
  163. );
  164. await click();
  165. await wait("window.linkErrors.length>0");
  166. assert.match(await read("window.linkErrors.at(-1)"), /HTTP/i);
  167. assert.equal((await inspect()).opened.length, expected);
  168. await win.webContents.executeJavaScript("window.rejectExternalOpen(true)");
  169. await read(`window.linkResult=null;document.getElementById('link-probe').onclick=event=>{
  170. event.preventDefault();window.linkResult=window.zcode.openExternal({href:'https://example.com/failure'}).then(()=>'',String);
  171. }`);
  172. await click();
  173. await wait("window.linkResult");
  174. assert.match(await read("window.linkResult"), /Fixture opener failed/);
  175. await win.webContents.executeJavaScript("window.rejectExternalOpen(false);window.holdGesture()");
  176. await read("window.linkResult=null");
  177. await click();
  178. await wait("window.inspectReact().gesturePending", (code) =>
  179. win.webContents.executeJavaScript(code),
  180. );
  181. await win.webContents.executeJavaScript("window.showReply('hidden');window.releaseGesture()");
  182. assert.match(await read("window.linkResult"), /active|closed/i);
  183. assert.match(
  184. await read(
  185. "window.zcode.openExternal({href:'https://example.com/hidden'}).then(()=>'',String)",
  186. ),
  187. /active|closed/i,
  188. );
  189. assert.equal((await inspect()).opened.length, expected);
  190. assert.deepEqual((await inspect()).messages, []);
  191. await read("document.getElementById('link-probe').remove()");
  192. await win.webContents.executeJavaScript("window.showReply('complete')");
  193. }