botsService.registration.test.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import { describe, expect, it, vi } from "vitest";
  2. import * as f from "./botsService.fixtures.js";
  3. describe("botsService registration", () => {
  4. it("starts Feishu QR app registration", async () => {
  5. const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => {
  6. const body = init?.body instanceof URLSearchParams ? init.body : new URLSearchParams(String(init?.body ?? ""));
  7. if (body.get("action") === "init") {
  8. return new Response(JSON.stringify({ supported_auth_methods: ["client_secret"] }));
  9. }
  10. return new Response(JSON.stringify({
  11. device_code: "device-1",
  12. verification_uri_complete: "https://accounts.feishu.cn/verify?device_code=device-1",
  13. user_code: "ABCD",
  14. interval: 2,
  15. expire_in: 600,
  16. }));
  17. });
  18. vi.stubGlobal("fetch", fetchMock);
  19. const service = f.createBotsService({
  20. credentialService: f.createCredentialService(),
  21. repo: f.createMemoryRepo({ version: 3, bots: [] }),
  22. legacyTaskService: f.createLegacyTaskService(),
  23. broadcastService: f.createBroadcastService(),
  24. });
  25. const result = await service.beginFeishuRegistration({ domain: "feishu" });
  26. expect(result).toMatchObject({
  27. deviceCode: "device-1",
  28. userCode: "ABCD",
  29. interval: 2,
  30. domain: "feishu",
  31. pollDomain: "feishu",
  32. });
  33. expect(result.qrUrl).toContain("from=sdk");
  34. expect(result.qrUrl).toContain("source=node-sdk%2Fzcode");
  35. expect(result.qrUrl).toContain("tp=sdk");
  36. });
  37. it("starts Lark QR app registration from the SDK default Feishu issuer", async () => {
  38. const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => {
  39. const body = init?.body instanceof URLSearchParams ? init.body : new URLSearchParams(String(init?.body ?? ""));
  40. if (body.get("action") === "init") {
  41. return new Response(JSON.stringify({ supported_auth_methods: ["client_secret"] }));
  42. }
  43. return new Response(JSON.stringify({
  44. device_code: "device-lark",
  45. verification_uri_complete: "https://open.feishu.cn/page/launcher?user_code=LARK",
  46. user_code: "LARK",
  47. interval: 2,
  48. expire_in: 600,
  49. }));
  50. });
  51. vi.stubGlobal("fetch", fetchMock);
  52. const service = f.createBotsService({
  53. credentialService: f.createCredentialService(),
  54. repo: f.createMemoryRepo({ version: 3, bots: [] }),
  55. legacyTaskService: f.createLegacyTaskService(),
  56. broadcastService: f.createBroadcastService(),
  57. });
  58. const result = await service.beginFeishuRegistration({ domain: "lark" });
  59. expect(result).toMatchObject({
  60. deviceCode: "device-lark",
  61. userCode: "LARK",
  62. interval: 2,
  63. domain: "lark",
  64. pollDomain: "feishu",
  65. });
  66. expect(result.qrUrl).toBe(
  67. "https://open.feishu.cn/page/launcher?user_code=LARK&from=sdk&source=node-sdk%2Fzcode&tp=sdk",
  68. );
  69. expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
  70. "https://accounts.feishu.cn/oauth/v1/app/registration",
  71. "https://accounts.feishu.cn/oauth/v1/app/registration",
  72. ]);
  73. });
  74. it("switches Lark QR app registration polling to the Lark issuer", async () => {
  75. const fetchMock = vi.fn(async () => new Response(JSON.stringify({
  76. user_info: { open_id: "ou_owner", tenant_brand: "lark" },
  77. error: "authorization_pending",
  78. })));
  79. vi.stubGlobal("fetch", fetchMock);
  80. const service = f.createBotsService({
  81. credentialService: f.createCredentialService(),
  82. repo: f.createMemoryRepo({ version: 3, bots: [] }),
  83. legacyTaskService: f.createLegacyTaskService(),
  84. broadcastService: f.createBroadcastService(),
  85. });
  86. await expect(
  87. service.pollFeishuRegistration({
  88. deviceCode: "device-lark",
  89. domain: "lark",
  90. pollDomain: "feishu",
  91. }),
  92. ).resolves.toEqual({
  93. status: "pending",
  94. interval: 0,
  95. domain: "lark",
  96. pollDomain: "lark",
  97. });
  98. expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
  99. "https://accounts.feishu.cn/oauth/v1/app/registration",
  100. ]);
  101. });
  102. it("polls Feishu QR app registration success", async () => {
  103. const fetchMock = vi.fn(async () => new Response(JSON.stringify({
  104. client_id: "cli_xxx",
  105. client_secret: "secret",
  106. user_info: { open_id: "ou_owner", tenant_brand: "feishu" },
  107. })));
  108. vi.stubGlobal("fetch", fetchMock);
  109. const service = f.createBotsService({
  110. credentialService: f.createCredentialService(),
  111. repo: f.createMemoryRepo({ version: 3, bots: [] }),
  112. legacyTaskService: f.createLegacyTaskService(),
  113. broadcastService: f.createBroadcastService(),
  114. });
  115. await expect(
  116. service.pollFeishuRegistration({ deviceCode: "device-1", domain: "feishu" }),
  117. ).resolves.toEqual({
  118. status: "success",
  119. appId: "cli_xxx",
  120. appSecret: "secret",
  121. domain: "feishu",
  122. openId: "ou_owner",
  123. });
  124. expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
  125. "https://accounts.feishu.cn/oauth/v1/app/registration",
  126. ]);
  127. });
  128. it("polls Lark QR app registration success after domain switch", async () => {
  129. const fetchMock = vi.fn(async () => new Response(JSON.stringify({
  130. client_id: "cli_lark",
  131. client_secret: "secret",
  132. user_info: { open_id: "ou_owner", tenant_brand: "lark" },
  133. })));
  134. vi.stubGlobal("fetch", fetchMock);
  135. const service = f.createBotsService({
  136. credentialService: f.createCredentialService(),
  137. repo: f.createMemoryRepo({ version: 3, bots: [] }),
  138. legacyTaskService: f.createLegacyTaskService(),
  139. broadcastService: f.createBroadcastService(),
  140. });
  141. await expect(
  142. service.pollFeishuRegistration({
  143. deviceCode: "device-lark",
  144. domain: "lark",
  145. pollDomain: "lark",
  146. }),
  147. ).resolves.toEqual({
  148. status: "success",
  149. appId: "cli_lark",
  150. appSecret: "secret",
  151. domain: "lark",
  152. openId: "ou_owner",
  153. });
  154. expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
  155. "https://accounts.larksuite.com/oauth/v1/app/registration",
  156. ]);
  157. });
  158. it("backfills the Feishu bot name when saving scanned credentials", async () => {
  159. const fetchMock = vi.fn(async (url: string) => {
  160. if (url.endsWith("/tenant_access_token/internal")) {
  161. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  162. }
  163. if (url.endsWith("/application/v6/applications/cli_xxx?lang=zh_cn")) {
  164. return new Response(JSON.stringify({ code: 999, msg: "not ready" }));
  165. }
  166. if (url.endsWith("/application/v6/applications/me?lang=zh_cn")) {
  167. return new Response(JSON.stringify({
  168. code: 0,
  169. data: {
  170. app: {
  171. app_name: "ZCode Assistant",
  172. },
  173. },
  174. }));
  175. }
  176. return new Response(JSON.stringify({ code: 999, msg: "unexpected request" }));
  177. });
  178. vi.stubGlobal("fetch", fetchMock);
  179. const repo = f.createMemoryRepo({ version: 3, bots: [] });
  180. const service = f.createBotsService({
  181. credentialService: f.createCredentialService(),
  182. repo,
  183. legacyTaskService: f.createLegacyTaskService(),
  184. });
  185. const saved = await service.saveBot({
  186. bot: {
  187. id: "feishu-1",
  188. name: "Feishu bot",
  189. provider: "feishu",
  190. enabled: false,
  191. feishuAppId: "cli_xxx",
  192. allowedWorkspaces: ["*"],
  193. allowedCommands: f.defaultUserCommands,
  194. currentOptions: {},
  195. replyMode: "assistant_changes",
  196. },
  197. credentialValue: "secret",
  198. });
  199. expect(saved.name).toBe("ZCode Assistant");
  200. expect((await repo.readConfig()).bots[0]?.name).toBe("ZCode Assistant");
  201. expect(fetchMock).toHaveBeenCalledTimes(3);
  202. service.disposeAll();
  203. });
  204. });