desktopOAuthDeepLink.test.ts 19 KB

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