desktopOAuthDeepLink.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import { mkdtempSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import { PlatformChannels } from "@zcode/shared";
  6. const electronMocks = vi.hoisted(() => ({
  7. appShow: vi.fn(),
  8. showMessageBoxSync: vi.fn(() => 0),
  9. getFocusedWindow: vi.fn(),
  10. getAllWindows: vi.fn(),
  11. setAsDefaultProtocolClient: vi.fn(() => true),
  12. }));
  13. const fsMocks = vi.hoisted(() => ({
  14. statSync: vi.fn(),
  15. }));
  16. vi.mock("node:fs", async (importOriginal) => {
  17. const actual = await importOriginal<typeof import("node:fs")>();
  18. fsMocks.statSync.mockImplementation(actual.statSync);
  19. return {
  20. ...actual,
  21. statSync: fsMocks.statSync,
  22. };
  23. });
  24. vi.mock("electron", () => ({
  25. app: {
  26. getPath: vi.fn(() => "/tmp"),
  27. get isPackaged() {
  28. return false;
  29. },
  30. setAsDefaultProtocolClient: electronMocks.setAsDefaultProtocolClient,
  31. show: electronMocks.appShow,
  32. },
  33. BrowserWindow: {
  34. getFocusedWindow: electronMocks.getFocusedWindow,
  35. getAllWindows: electronMocks.getAllWindows,
  36. },
  37. dialog: {
  38. showMessageBoxSync: electronMocks.showMessageBoxSync,
  39. },
  40. }));
  41. const tempDirs: string[] = [];
  42. beforeEach(() => {
  43. vi.resetModules();
  44. electronMocks.appShow.mockClear();
  45. electronMocks.showMessageBoxSync.mockReset();
  46. electronMocks.showMessageBoxSync.mockReturnValue(0);
  47. electronMocks.getFocusedWindow.mockReset();
  48. electronMocks.getAllWindows.mockReset();
  49. electronMocks.setAsDefaultProtocolClient.mockClear();
  50. fsMocks.statSync.mockClear();
  51. });
  52. afterEach(() => {
  53. for (const dir of tempDirs.splice(0)) {
  54. rmSync(dir, { recursive: true, force: true });
  55. }
  56. });
  57. describe("desktopOAuthDeepLink workspace open routing", () => {
  58. it("缓存冷启动时命中未就绪窗口的 workspace open 请求,等 renderer ready 后再投递", async () => {
  59. const workspacePath = createTempWorkspace();
  60. const targetWindow = createMockWindow(7);
  61. const logger = { info: vi.fn(), warn: vi.fn() };
  62. electronMocks.getFocusedWindow.mockReturnValue(targetWindow);
  63. electronMocks.getAllWindows.mockReturnValue([targetWindow]);
  64. const { deliverPendingDeepLink, handleDeepLink } =
  65. await import("../src/main/desktopOAuthDeepLink.js");
  66. const handled = handleDeepLink(buildWorkspaceOpenUrl(workspacePath), logger);
  67. expect(handled).toBe(true);
  68. expect(targetWindow.webContents.send).not.toHaveBeenCalled();
  69. expect(logger.warn).toHaveBeenCalledWith(
  70. "[deep-link] 工作区打开请求命中未就绪窗口,先缓存等待 renderer ready",
  71. { windowId: 7, path: workspacePath },
  72. );
  73. expect(electronMocks.showMessageBoxSync).toHaveBeenCalled();
  74. deliverPendingDeepLink(targetWindow.webContents);
  75. expect(targetWindow.webContents.send).toHaveBeenCalledWith(
  76. PlatformChannels.OpenWorkspacePath,
  77. workspacePath,
  78. );
  79. });
  80. it("renderer ready 后收到 workspace open 请求时立即投递", async () => {
  81. const workspacePath = createTempWorkspace();
  82. const targetWindow = createMockWindow(11);
  83. const logger = { info: vi.fn(), warn: vi.fn() };
  84. electronMocks.getFocusedWindow.mockReturnValue(targetWindow);
  85. electronMocks.getAllWindows.mockReturnValue([targetWindow]);
  86. const { deliverPendingDeepLink, handleDeepLink } =
  87. await import("../src/main/desktopOAuthDeepLink.js");
  88. deliverPendingDeepLink(targetWindow.webContents);
  89. targetWindow.webContents.send.mockClear();
  90. const handled = handleDeepLink(buildWorkspaceOpenUrl(workspacePath), logger);
  91. expect(handled).toBe(true);
  92. expect(targetWindow.webContents.send).toHaveBeenCalledWith(
  93. PlatformChannels.OpenWorkspacePath,
  94. workspacePath,
  95. );
  96. expect(electronMocks.showMessageBoxSync).toHaveBeenCalled();
  97. });
  98. it("工作区打开路由使用业务窗口解析器,不会选中 CUA 辅助浮层", async () => {
  99. const workspacePath = createTempWorkspace();
  100. const cuaIndicatorWindow = createMockWindow(12);
  101. const applicationWindow = createMockWindow(13);
  102. const logger = { info: vi.fn(), warn: vi.fn() };
  103. electronMocks.getFocusedWindow.mockReturnValue(null);
  104. electronMocks.getAllWindows.mockReturnValue([cuaIndicatorWindow, applicationWindow]);
  105. const { deliverPendingDeepLink, handleOpenWorkspacePath } =
  106. await import("../src/main/desktopOAuthDeepLink.js");
  107. deliverPendingDeepLink(applicationWindow.webContents);
  108. expect(
  109. handleOpenWorkspacePath(workspacePath, logger, {
  110. resolveApplicationWindow: () => applicationWindow,
  111. }),
  112. ).toBe(true);
  113. expect(applicationWindow.webContents.send).toHaveBeenCalledWith(
  114. PlatformChannels.OpenWorkspacePath,
  115. workspacePath,
  116. );
  117. expect(cuaIndicatorWindow.webContents.send).not.toHaveBeenCalled();
  118. });
  119. it("workspace open 确认弹窗使用调用方注入的 locale 文案", async () => {
  120. const workspacePath = createTempWorkspace();
  121. const targetWindow = createMockWindow(21);
  122. const logger = { info: vi.fn(), warn: vi.fn() };
  123. electronMocks.getFocusedWindow.mockReturnValue(targetWindow);
  124. electronMocks.getAllWindows.mockReturnValue([targetWindow]);
  125. const { deliverPendingDeepLink, handleDeepLink, resolveExternalWorkspaceOpenDialogCopy } =
  126. await import("../src/main/desktopOAuthDeepLink.js");
  127. deliverPendingDeepLink(targetWindow.webContents);
  128. targetWindow.webContents.send.mockClear();
  129. const handled = handleDeepLink(buildWorkspaceOpenUrl(workspacePath), logger, {
  130. confirmationCopy: resolveExternalWorkspaceOpenDialogCopy("zh-CN"),
  131. });
  132. expect(handled).toBe(true);
  133. expect(electronMocks.showMessageBoxSync).toHaveBeenCalledWith(
  134. targetWindow,
  135. expect.objectContaining({
  136. buttons: ["打开文件夹", "取消"],
  137. title: "打开外部 ZCode 链接?",
  138. }),
  139. );
  140. expect(targetWindow.webContents.send).toHaveBeenCalledWith(
  141. PlatformChannels.OpenWorkspacePath,
  142. workspacePath,
  143. );
  144. });
  145. it("没有父窗口时 workspace open 确认弹窗仍同步阻塞并缓存请求", async () => {
  146. const workspacePath = createTempWorkspace();
  147. const logger = { info: vi.fn(), warn: vi.fn() };
  148. electronMocks.getFocusedWindow.mockReturnValue(null);
  149. electronMocks.getAllWindows.mockReturnValue([]);
  150. const { deliverPendingDeepLink, handleDeepLink } =
  151. await import("../src/main/desktopOAuthDeepLink.js");
  152. const handled = handleDeepLink(buildWorkspaceOpenUrl(workspacePath), logger);
  153. expect(handled).toBe(false);
  154. expect(electronMocks.showMessageBoxSync).toHaveBeenCalledWith(
  155. expect.objectContaining({
  156. buttons: ["Open folder", "Cancel"],
  157. title: "Open external ZCode link?",
  158. }),
  159. );
  160. expect(logger.warn).toHaveBeenCalledWith(
  161. "[deep-link] 工作区打开请求暂未命中窗口,先缓存等待 renderer ready",
  162. { path: workspacePath },
  163. );
  164. const targetWindow = createMockWindow(22);
  165. deliverPendingDeepLink(targetWindow.webContents);
  166. expect(targetWindow.webContents.send).toHaveBeenCalledWith(
  167. PlatformChannels.OpenWorkspacePath,
  168. workspacePath,
  169. );
  170. });
  171. it("没有父窗口且用户取消时不缓存 workspace open 请求", async () => {
  172. const workspacePath = createTempWorkspace();
  173. const logger = { info: vi.fn(), warn: vi.fn() };
  174. electronMocks.showMessageBoxSync.mockReturnValue(1);
  175. electronMocks.getFocusedWindow.mockReturnValue(null);
  176. electronMocks.getAllWindows.mockReturnValue([]);
  177. const { deliverPendingDeepLink, handleDeepLink } =
  178. await import("../src/main/desktopOAuthDeepLink.js");
  179. const handled = handleDeepLink(buildWorkspaceOpenUrl(workspacePath), logger);
  180. expect(handled).toBe(true);
  181. expect(electronMocks.showMessageBoxSync).toHaveBeenCalledWith(expect.any(Object));
  182. expect(logger.warn).toHaveBeenCalledWith("[deep-link] 用户取消打开外部链接工作区", {
  183. path: workspacePath,
  184. });
  185. const targetWindow = createMockWindow(23);
  186. deliverPendingDeepLink(targetWindow.webContents);
  187. expect(targetWindow.webContents.send).not.toHaveBeenCalled();
  188. });
  189. it("用户取消 deep link 确认时不投递 workspace open 请求", async () => {
  190. const workspacePath = createTempWorkspace();
  191. const targetWindow = createMockWindow(12);
  192. const logger = { info: vi.fn(), warn: vi.fn() };
  193. electronMocks.showMessageBoxSync.mockReturnValue(1);
  194. electronMocks.getFocusedWindow.mockReturnValue(targetWindow);
  195. electronMocks.getAllWindows.mockReturnValue([targetWindow]);
  196. const { deliverPendingDeepLink, handleDeepLink } =
  197. await import("../src/main/desktopOAuthDeepLink.js");
  198. deliverPendingDeepLink(targetWindow.webContents);
  199. targetWindow.webContents.send.mockClear();
  200. const handled = handleDeepLink(buildWorkspaceOpenUrl(workspacePath), logger);
  201. expect(handled).toBe(true);
  202. expect(targetWindow.webContents.send).not.toHaveBeenCalled();
  203. expect(logger.warn).toHaveBeenCalledWith("[deep-link] 用户取消打开外部链接工作区", {
  204. path: workspacePath,
  205. });
  206. });
  207. it.each([
  208. ["标准 UNC", "\\\\attacker\\share"],
  209. ["正斜杠 UNC", "//attacker/share"],
  210. ["extended UNC", "\\\\?\\UNC\\attacker\\share"],
  211. ])("拒绝 %s workspace deep link,且拒绝前不触碰文件系统", async (_label, workspacePath) => {
  212. const targetWindow = createMockWindow(14);
  213. const logger = { info: vi.fn(), warn: vi.fn() };
  214. electronMocks.getFocusedWindow.mockReturnValue(targetWindow);
  215. electronMocks.getAllWindows.mockReturnValue([targetWindow]);
  216. const { handleDeepLink } = await import("../src/main/desktopOAuthDeepLink.js");
  217. const handled = handleDeepLink(buildWorkspaceOpenUrl(workspacePath), logger);
  218. expect(handled).toBe(false);
  219. expect(fsMocks.statSync).not.toHaveBeenCalled();
  220. expect(electronMocks.showMessageBoxSync).not.toHaveBeenCalled();
  221. expect(targetWindow.webContents.send).not.toHaveBeenCalled();
  222. expect(logger.warn).toHaveBeenCalledWith("[deep-link] 网络工作区路径已拒绝", {
  223. path: workspacePath,
  224. });
  225. });
  226. it("没有就绪窗口时默认不缓存 workspace open 请求", async () => {
  227. const workspacePath = createTempWorkspace();
  228. const logger = { info: vi.fn(), warn: vi.fn() };
  229. electronMocks.getFocusedWindow.mockReturnValue(null);
  230. electronMocks.getAllWindows.mockReturnValue([]);
  231. const { deliverPendingDeepLink, handleOpenWorkspacePath } =
  232. await import("../src/main/desktopOAuthDeepLink.js");
  233. const handled = handleOpenWorkspacePath(workspacePath, logger);
  234. expect(handled).toBe(false);
  235. expect(logger.warn).toHaveBeenCalledWith("[deep-link] 工作区打开请求暂未命中窗口,已忽略", {
  236. path: workspacePath,
  237. });
  238. const targetWindow = createMockWindow(13);
  239. deliverPendingDeepLink(targetWindow.webContents);
  240. expect(targetWindow.webContents.send).not.toHaveBeenCalled();
  241. });
  242. it("workspace open 被 gate 阻止时不缓存也不投递", async () => {
  243. const workspacePath = createTempWorkspace();
  244. const targetWindow = createMockWindow(17);
  245. const logger = { info: vi.fn(), warn: vi.fn() };
  246. const onWorkspaceOpenBlocked = vi.fn();
  247. electronMocks.getFocusedWindow.mockReturnValue(targetWindow);
  248. electronMocks.getAllWindows.mockReturnValue([targetWindow]);
  249. const { deliverPendingDeepLink, handleDeepLink } =
  250. await import("../src/main/desktopOAuthDeepLink.js");
  251. const handled = handleDeepLink(buildWorkspaceOpenUrl(workspacePath), logger, {
  252. canOpenWorkspace: () => false,
  253. onWorkspaceOpenBlocked,
  254. });
  255. expect(handled).toBe(true);
  256. expect(onWorkspaceOpenBlocked).toHaveBeenCalledWith(workspacePath);
  257. expect(targetWindow.webContents.send).not.toHaveBeenCalled();
  258. expect(logger.warn).toHaveBeenCalledWith("[deep-link] 工作区打开请求被当前启动 gate 阻止", {
  259. path: workspacePath,
  260. });
  261. deliverPendingDeepLink(targetWindow.webContents);
  262. expect(targetWindow.webContents.send).not.toHaveBeenCalled();
  263. });
  264. });
  265. describe("desktopOAuthDeepLink OAuth routing", () => {
  266. it("归因-only 回调不消费 OAuth state 路由,真实授权码回调才消费", async () => {
  267. vi.useFakeTimers();
  268. try {
  269. const targetWindow = createMockWindow(31);
  270. const logger = { info: vi.fn(), warn: vi.fn() };
  271. electronMocks.getAllWindows.mockReturnValue([targetWindow]);
  272. const { handleDeepLink, registerOAuthState } =
  273. await import("../src/main/desktopOAuthDeepLink.js");
  274. registerOAuthState(31, { state: "state-001", provider: "bigmodel" });
  275. expect(
  276. handleDeepLink("zcode://oauth/callback?state=state-001&utm_source=google", logger),
  277. ).toBe(true);
  278. expect(targetWindow.webContents.send).toHaveBeenCalledWith(
  279. PlatformChannels.OAuthCallback,
  280. "zcode://oauth/callback?state=state-001&utm_source=google",
  281. );
  282. targetWindow.webContents.send.mockClear();
  283. expect(
  284. handleDeepLink("zcode://oauth/callback?authCode=auth-001&state=state-001", logger),
  285. ).toBe(true);
  286. expect(targetWindow.webContents.send).toHaveBeenCalledWith(
  287. PlatformChannels.OAuthCallback,
  288. "zcode://oauth/callback?authCode=auth-001&state=state-001",
  289. );
  290. targetWindow.webContents.send.mockClear();
  291. expect(
  292. handleDeepLink("zcode://oauth/callback?authCode=auth-002&state=state-001", logger),
  293. ).toBe(false);
  294. expect(targetWindow.webContents.send).not.toHaveBeenCalled();
  295. expect(logger.warn).toHaveBeenLastCalledWith(
  296. "[deep-link] OAuth 回调未命中目标窗口,先缓存等待 renderer ready",
  297. {
  298. state: "state-001",
  299. hasRouteTarget: false,
  300. },
  301. );
  302. } finally {
  303. vi.useRealTimers();
  304. }
  305. });
  306. });
  307. function createTempWorkspace(): string {
  308. const dir = mkdtempSync(join(tmpdir(), "zcode-workspace-open-"));
  309. tempDirs.push(dir);
  310. return dir;
  311. }
  312. function createMockWindow(webContentsId: number) {
  313. return {
  314. webContents: {
  315. id: webContentsId,
  316. send: vi.fn(),
  317. },
  318. focus: vi.fn(),
  319. isMinimized: vi.fn(() => false),
  320. isVisible: vi.fn(() => true),
  321. restore: vi.fn(),
  322. show: vi.fn(),
  323. };
  324. }
  325. function buildWorkspaceOpenUrl(workspacePath: string): string {
  326. return `zcode://workspace/open?path=${encodeURIComponent(workspacePath)}`;
  327. }
  328. function buildShareImportUrl(shareCode: string): string {
  329. return `zcode://share/import?code=${encodeURIComponent(shareCode)}`;
  330. }
  331. describe("desktopOAuthDeepLink share import routing", () => {
  332. it("share import 路由使用业务窗口解析器,不会选中 CUA 辅助浮层", async () => {
  333. const cuaIndicatorWindow = createMockWindow(41);
  334. const applicationWindow = createMockWindow(42);
  335. const logger = { info: vi.fn(), warn: vi.fn() };
  336. electronMocks.getFocusedWindow.mockReturnValue(cuaIndicatorWindow);
  337. electronMocks.getAllWindows.mockReturnValue([cuaIndicatorWindow, applicationWindow]);
  338. const { deliverPendingDeepLink, handleDeepLink } =
  339. await import("../src/main/desktopOAuthDeepLink.js");
  340. deliverPendingDeepLink(applicationWindow.webContents);
  341. expect(
  342. handleDeepLink(buildShareImportUrl("share-code-1"), logger, {
  343. resolveApplicationWindow: () => applicationWindow,
  344. }),
  345. ).toBe(true);
  346. expect(applicationWindow.webContents.send).toHaveBeenCalledWith(PlatformChannels.ShareImport, {
  347. shareCode: "share-code-1",
  348. });
  349. expect(cuaIndicatorWindow.webContents.send).not.toHaveBeenCalled();
  350. });
  351. it("pending share import 只投递给目标窗口,其他窗口先 ready 也不投递", async () => {
  352. const targetWindow = createMockWindow(51);
  353. const otherWindow = createMockWindow(52);
  354. const logger = { info: vi.fn(), warn: vi.fn() };
  355. electronMocks.getFocusedWindow.mockReturnValue(targetWindow);
  356. electronMocks.getAllWindows.mockReturnValue([targetWindow, otherWindow]);
  357. const { deliverPendingDeepLink, handleDeepLink } =
  358. await import("../src/main/desktopOAuthDeepLink.js");
  359. // 目标窗口存在但 renderer 未 ready:缓存并绑定目标窗口。
  360. expect(handleDeepLink(buildShareImportUrl("share-code-2"), logger)).toBe(true);
  361. expect(targetWindow.webContents.send).not.toHaveBeenCalled();
  362. // 其他窗口先 ready:不得把导入意图投递到非目标窗口(导入会写入该窗口 workspace)。
  363. deliverPendingDeepLink(otherWindow.webContents);
  364. expect(otherWindow.webContents.send).not.toHaveBeenCalledWith(
  365. PlatformChannels.ShareImport,
  366. expect.anything(),
  367. );
  368. // 目标窗口 ready 后才投递。
  369. deliverPendingDeepLink(targetWindow.webContents);
  370. expect(targetWindow.webContents.send).toHaveBeenCalledWith(PlatformChannels.ShareImport, {
  371. shareCode: "share-code-2",
  372. });
  373. });
  374. it("目标窗口关闭时清理 pending share import,不会投递给后续 ready 的窗口", async () => {
  375. const targetWindow = createMockWindow(61);
  376. const laterWindow = createMockWindow(62);
  377. const logger = { info: vi.fn(), warn: vi.fn() };
  378. electronMocks.getFocusedWindow.mockReturnValue(targetWindow);
  379. electronMocks.getAllWindows.mockReturnValue([targetWindow]);
  380. const { clearOAuthRoutesForWindow, deliverPendingDeepLink, handleDeepLink } =
  381. await import("../src/main/desktopOAuthDeepLink.js");
  382. expect(handleDeepLink(buildShareImportUrl("share-code-3"), logger)).toBe(true);
  383. clearOAuthRoutesForWindow(61);
  384. deliverPendingDeepLink(laterWindow.webContents);
  385. expect(laterWindow.webContents.send).not.toHaveBeenCalledWith(
  386. PlatformChannels.ShareImport,
  387. expect.anything(),
  388. );
  389. });
  390. it("冷启动无窗口时缓存 share import,首个 ready 的窗口投递", async () => {
  391. const firstWindow = createMockWindow(71);
  392. const logger = { info: vi.fn(), warn: vi.fn() };
  393. electronMocks.getFocusedWindow.mockReturnValue(null);
  394. electronMocks.getAllWindows.mockReturnValue([]);
  395. const { deliverPendingDeepLink, handleDeepLink } =
  396. await import("../src/main/desktopOAuthDeepLink.js");
  397. expect(handleDeepLink(buildShareImportUrl("share-code-4"), logger)).toBe(false);
  398. deliverPendingDeepLink(firstWindow.webContents);
  399. expect(firstWindow.webContents.send).toHaveBeenCalledWith(PlatformChannels.ShareImport, {
  400. shareCode: "share-code-4",
  401. });
  402. });
  403. });