botsWeixinProvider.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { createCipheriv } from "node:crypto";
  3. import type { BotConfig } from "@zcode/shared";
  4. import { createWeixinBotProvider, getWeixinUpdates } from "../src/bots/providers/weixinProvider.js";
  5. import { beginWeixinRegistration, pollWeixinRegistration } from "../src/bots/providers/weixinRegistration.js";
  6. afterEach(() => {
  7. vi.unstubAllGlobals();
  8. });
  9. function encryptWeixinCdnFixture(data: Buffer, key: Buffer): Buffer {
  10. const cipher = createCipheriv("aes-128-ecb", key, null);
  11. return Buffer.concat([cipher.update(data), cipher.final()]);
  12. }
  13. function createWeixinBot(overrides: Partial<BotConfig> = {}): BotConfig {
  14. return {
  15. id: "weixin-1",
  16. name: "Weixin",
  17. provider: "weixin" as const,
  18. enabled: true,
  19. credentialRef: "weixin-token",
  20. providerUserId: "bot-1@im.bot",
  21. allowedWorkspaces: ["*"],
  22. allowedCommands: {
  23. status: true,
  24. new: true,
  25. workspace: true,
  26. model: true,
  27. thoughtLevel: true,
  28. sandboxMode: true,
  29. approvalPolicy: true,
  30. reply: true,
  31. },
  32. currentOptions: {},
  33. replyMode: "assistant_changes" as const,
  34. ...overrides,
  35. };
  36. }
  37. describe("weixin bot provider", () => {
  38. it("parses Weixin iLink getupdates messages", async () => {
  39. const fetchMock = vi.fn(async () => new Response(JSON.stringify({
  40. ret: 0,
  41. get_updates_buf: "buf-2",
  42. msgs: [
  43. {
  44. message_id: 1001,
  45. message_type: 1,
  46. from_user_id: "wx_user",
  47. context_token: "ctx-1",
  48. msg: {
  49. sender_name: "User",
  50. item_list: [{ type: 1, text_item: { text: "/状态" } }],
  51. },
  52. },
  53. ],
  54. })));
  55. vi.stubGlobal("fetch", fetchMock);
  56. const result = await getWeixinUpdates({
  57. bot: createWeixinBot(),
  58. deps: { loadCredential: vi.fn(async () => "token") },
  59. buf: "buf-1",
  60. });
  61. expect(fetchMock).toHaveBeenCalledWith(
  62. "https://ilinkai.weixin.qq.com/ilink/bot/getupdates",
  63. expect.objectContaining({
  64. method: "POST",
  65. headers: {
  66. "content-type": "application/json",
  67. Authorization: "Bearer token",
  68. AuthorizationType: "ilink_bot_token",
  69. "X-WECHAT-UIN": expect.any(String),
  70. },
  71. body: JSON.stringify({ base_info: { channel_version: "2.0.0" }, get_updates_buf: "buf-1" }),
  72. }),
  73. );
  74. expect(result.buf).toBe("buf-2");
  75. expect(result.messages).toEqual([
  76. {
  77. botId: "weixin-1",
  78. text: "/状态",
  79. actor: {
  80. provider: "weixin",
  81. botId: "weixin-1",
  82. providerUserId: "wx_user",
  83. displayName: "User",
  84. chatType: "private",
  85. chatId: undefined,
  86. providerMessageId: "1001",
  87. providerContextToken: "ctx-1",
  88. },
  89. },
  90. ]);
  91. });
  92. it("does not apply the ordinary 15-second deadline to idle getupdates", async () => {
  93. vi.useFakeTimers();
  94. const external = new AbortController();
  95. let providerSignal: AbortSignal | undefined;
  96. const fetchMock = vi.fn(
  97. (_input: string | URL | Request, init?: RequestInit) =>
  98. new Promise<Response>((_resolve, reject) => {
  99. providerSignal = init?.signal ?? undefined;
  100. init?.signal?.addEventListener(
  101. "abort",
  102. () => reject(init.signal?.reason ?? new Error("aborted")),
  103. { once: true },
  104. );
  105. }),
  106. );
  107. vi.stubGlobal("fetch", fetchMock);
  108. const polling = getWeixinUpdates({
  109. bot: createWeixinBot(),
  110. deps: { loadCredential: vi.fn(async () => "token") },
  111. signal: external.signal,
  112. });
  113. const rejection = expect(polling).rejects.toBeDefined();
  114. await vi.advanceTimersByTimeAsync(15_000);
  115. expect(providerSignal?.aborted).toBe(false);
  116. external.abort(new Error("runtime disposed"));
  117. await rejection;
  118. vi.useRealTimers();
  119. });
  120. it("reads nested Weixin message ids for inbound dedupe", async () => {
  121. const fetchMock = vi.fn(async () => new Response(JSON.stringify({
  122. ret: 0,
  123. msgs: [
  124. {
  125. message_type: 1,
  126. from_user_id: "wx_user",
  127. msg: {
  128. message_id: 2001,
  129. item_list: [{ type: 1, text_item: { text: "继续" } }],
  130. },
  131. },
  132. ],
  133. })));
  134. vi.stubGlobal("fetch", fetchMock);
  135. const result = await getWeixinUpdates({
  136. bot: createWeixinBot(),
  137. deps: { loadCredential: vi.fn(async () => "token") },
  138. });
  139. expect(result.messages[0]?.actor.providerMessageId).toBe("2001");
  140. });
  141. it("parses Weixin mixed text and media item_list into attachments", async () => {
  142. const fetchMock = vi.fn(async () => new Response(JSON.stringify({
  143. ret: 0,
  144. msgs: [
  145. {
  146. message_id: 1002,
  147. message_type: 1,
  148. from_user_id: "wx_user",
  149. msg: {
  150. item_list: [
  151. { type: 1, text_item: { text: "帮我看一下" } },
  152. {
  153. type: 2,
  154. image_item: {
  155. file_id: "img-1",
  156. file_name: "demo.png",
  157. mime_type: "image/png",
  158. size: 123,
  159. },
  160. },
  161. ],
  162. },
  163. },
  164. ],
  165. })));
  166. vi.stubGlobal("fetch", fetchMock);
  167. const result = await getWeixinUpdates({
  168. bot: createWeixinBot(),
  169. deps: { loadCredential: vi.fn(async () => "token") },
  170. });
  171. expect(result.messages[0]).toMatchObject({
  172. text: "帮我看一下",
  173. attachments: [
  174. {
  175. id: "img-1",
  176. kind: "image",
  177. filename: "demo.png",
  178. mimeType: "image/png",
  179. sizeBytes: 123,
  180. providerFileId: "img-1",
  181. },
  182. ],
  183. });
  184. });
  185. it("parses Weixin file_item media metadata into SVG attachments", async () => {
  186. const fetchMock = vi.fn(async () => new Response(JSON.stringify({
  187. ret: 0,
  188. msgs: [
  189. {
  190. message_id: 1004,
  191. message_type: 1,
  192. from_user_id: "wx_user",
  193. item_list: [
  194. {
  195. type: 4,
  196. file_item: {
  197. file_name: "WeChat-Icon-Logo.wine.svg",
  198. media: {
  199. md5: "svg-md5",
  200. len: 456,
  201. },
  202. },
  203. },
  204. ],
  205. },
  206. ],
  207. })));
  208. vi.stubGlobal("fetch", fetchMock);
  209. const result = await getWeixinUpdates({
  210. bot: createWeixinBot(),
  211. deps: { loadCredential: vi.fn(async () => "token") },
  212. });
  213. expect(result.messages[0]).toMatchObject({
  214. text: "",
  215. attachments: [
  216. {
  217. id: "svg-md5",
  218. kind: "image",
  219. filename: "WeChat-Icon-Logo.wine.svg",
  220. mimeType: "image/svg+xml",
  221. sizeBytes: 456,
  222. providerFileId: "svg-md5",
  223. },
  224. ],
  225. });
  226. });
  227. it("parses Weixin image_item media id into image attachments", async () => {
  228. const fetchMock = vi.fn(async () => new Response(JSON.stringify({
  229. ret: 0,
  230. msgs: [
  231. {
  232. message_id: 1005,
  233. message_type: 1,
  234. from_user_id: "wx_user",
  235. item_list: [
  236. {
  237. type: 2,
  238. image_item: {
  239. aeskey: "image-aes-key",
  240. media: 123456,
  241. mid_size: 117378,
  242. thumb_size: 4096,
  243. thumb_height: 160,
  244. thumb_width: 160,
  245. },
  246. },
  247. ],
  248. },
  249. ],
  250. })));
  251. vi.stubGlobal("fetch", fetchMock);
  252. const result = await getWeixinUpdates({
  253. bot: createWeixinBot(),
  254. deps: { loadCredential: vi.fn(async () => "token") },
  255. });
  256. expect(result.messages[0]).toMatchObject({
  257. text: "",
  258. attachments: [
  259. {
  260. id: "123456",
  261. kind: "image",
  262. filename: "weixin-image-1.jpg",
  263. mimeType: "image/jpeg",
  264. sizeBytes: 117378,
  265. providerFileId: "123456",
  266. },
  267. ],
  268. });
  269. });
  270. it("parses Weixin image_item nested full_url into downloadable image attachments", async () => {
  271. const fetchMock = vi.fn(async () => new Response(JSON.stringify({
  272. ret: 0,
  273. msgs: [
  274. {
  275. message_id: 1006,
  276. message_type: 1,
  277. from_user_id: "wx_user",
  278. item_list: [
  279. {
  280. type: 2,
  281. image_item: {
  282. aeskey: "outer-aes-key",
  283. media: {
  284. encrypt_query_param: "encrypted-query",
  285. aes_key: "nested-aes-key",
  286. full_url: "https://weixin.example.test/image.jpg",
  287. },
  288. mid_size: 2048,
  289. },
  290. },
  291. ],
  292. },
  293. ],
  294. })));
  295. vi.stubGlobal("fetch", fetchMock);
  296. const result = await getWeixinUpdates({
  297. bot: createWeixinBot(),
  298. deps: { loadCredential: vi.fn(async () => "token") },
  299. });
  300. expect(result.messages[0]).toMatchObject({
  301. text: "",
  302. attachments: [
  303. {
  304. id: "encrypted-query",
  305. kind: "image",
  306. filename: "weixin-image-1.jpg",
  307. mimeType: "image/jpeg",
  308. sizeBytes: 2048,
  309. providerFileId: "encrypted-query",
  310. downloadUrl: "https://weixin.example.test/image.jpg",
  311. providerMetadata: {
  312. weixinAesKey: "nested-aes-key",
  313. },
  314. },
  315. ],
  316. });
  317. });
  318. it("decrypts Weixin CDN attachment downloads", async () => {
  319. const key = Buffer.from("00112233445566778899aabbccddeeff", "hex");
  320. const plaintext = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]);
  321. const encrypted = encryptWeixinCdnFixture(plaintext, key);
  322. vi.stubGlobal("fetch", vi.fn(async () => new Response(encrypted)));
  323. const provider = createWeixinBotProvider({
  324. loadCredential: vi.fn(async () => "token"),
  325. });
  326. const downloaded = await provider.downloadAttachment?.(
  327. createWeixinBot(),
  328. {
  329. id: "encrypted-query",
  330. kind: "image",
  331. filename: "weixin-image-1.jpg",
  332. mimeType: "image/jpeg",
  333. downloadUrl: "https://weixin.example.test/image.jpg",
  334. providerMetadata: {
  335. weixinAesKey: key.toString("base64"),
  336. },
  337. },
  338. );
  339. expect(Buffer.from(downloaded?.data ?? [])).toEqual(plaintext);
  340. });
  341. it("preserves attachments when Weixin polling re-enters the callback parser", () => {
  342. const provider = createWeixinBotProvider({
  343. loadCredential: vi.fn(async () => "token"),
  344. });
  345. expect(
  346. provider.parseCallback({
  347. botId: "weixin-1",
  348. messages: [
  349. {
  350. id: "1003",
  351. from: "wx_user",
  352. text: "",
  353. attachments: [
  354. {
  355. id: "img-1",
  356. kind: "image",
  357. filename: "demo.png",
  358. mimeType: "image/png",
  359. providerFileId: "img-1",
  360. providerMetadata: {
  361. weixinAesKey: "00112233445566778899aabbccddeeff",
  362. },
  363. },
  364. ],
  365. },
  366. ],
  367. }),
  368. ).toEqual([
  369. expect.objectContaining({
  370. text: "",
  371. attachments: [
  372. expect.objectContaining({
  373. id: "img-1",
  374. kind: "image",
  375. providerMetadata: {
  376. weixinAesKey: "00112233445566778899aabbccddeeff",
  377. },
  378. }),
  379. ],
  380. }),
  381. ]);
  382. });
  383. it("ignores webhookUrl when calling the built-in Weixin iLink API", async () => {
  384. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ret: 0, get_updates_buf: "", msgs: [] })));
  385. vi.stubGlobal("fetch", fetchMock);
  386. await getWeixinUpdates({
  387. bot: createWeixinBot({ webhookUrl: "https://webhook.example.test/reply" }),
  388. deps: { loadCredential: vi.fn(async () => "token") },
  389. });
  390. expect(fetchMock.mock.calls[0]?.[0]).toBe("https://ilinkai.weixin.qq.com/ilink/bot/getupdates");
  391. });
  392. it("sends replies through Weixin iLink sendmessage", async () => {
  393. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ret: 0 })));
  394. vi.stubGlobal("fetch", fetchMock);
  395. const provider = createWeixinBotProvider({
  396. loadCredential: vi.fn(async () => "token"),
  397. });
  398. await provider.send(createWeixinBot(), {
  399. botId: "weixin-1",
  400. provider: "weixin",
  401. providerUserId: "wx_user",
  402. text: "hello",
  403. providerContextToken: "ctx-1",
  404. });
  405. expect(fetchMock).toHaveBeenCalledWith(
  406. "https://ilinkai.weixin.qq.com/ilink/bot/sendmessage",
  407. expect.objectContaining({
  408. method: "POST",
  409. body: expect.any(String),
  410. }),
  411. );
  412. expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toEqual({
  413. base_info: { channel_version: "2.0.0" },
  414. msg: {
  415. from_user_id: "bot-1@im.bot",
  416. to_user_id: "wx_user",
  417. client_id: expect.any(String),
  418. message_type: 2,
  419. message_state: 2,
  420. context_token: "ctx-1",
  421. item_list: [{ type: 1, text_item: { text: "hello" } }],
  422. },
  423. });
  424. });
  425. it("normalizes multiline replies to hard text line breaks", async () => {
  426. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ret: 0 })));
  427. vi.stubGlobal("fetch", fetchMock);
  428. const provider = createWeixinBotProvider({
  429. loadCredential: vi.fn(async () => "token"),
  430. });
  431. await provider.send(createWeixinBot(), {
  432. botId: "weixin-1",
  433. provider: "weixin",
  434. providerUserId: "wx_user",
  435. text: ["Workspace: z-code", "Model: DeepSeek/deepseek-v4-flash", "State: completed"].join("\n"),
  436. });
  437. const body = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string) as {
  438. msg?: { item_list?: Array<{ text_item?: { text?: string } }> };
  439. };
  440. expect(body.msg?.item_list?.[0]?.text_item?.text).toBe(
  441. ["Workspace: z-code", "Model: DeepSeek/deepseek-v4-flash", "State: completed"].join("\r\n"),
  442. );
  443. });
  444. it("sends typing through Weixin iLink sendtyping", async () => {
  445. const fetchMock = vi.fn(async (url: string) => new Response(JSON.stringify(
  446. url.endsWith("/getconfig") ? { ret: 0, typing_ticket: "ticket-1" } : { ret: 0 },
  447. )));
  448. vi.stubGlobal("fetch", fetchMock);
  449. const provider = createWeixinBotProvider({
  450. loadCredential: vi.fn(async () => "token"),
  451. });
  452. await provider.sendTyping?.(createWeixinBot(), { providerUserId: "wx_user", providerContextToken: "ctx-1" });
  453. expect(fetchMock).toHaveBeenNthCalledWith(
  454. 1,
  455. "https://ilinkai.weixin.qq.com/ilink/bot/getconfig",
  456. expect.objectContaining({
  457. method: "POST",
  458. body: JSON.stringify({ base_info: { channel_version: "2.0.0" }, ilink_user_id: "wx_user", context_token: "ctx-1" }),
  459. }),
  460. );
  461. expect(fetchMock).toHaveBeenNthCalledWith(
  462. 2,
  463. "https://ilinkai.weixin.qq.com/ilink/bot/sendtyping",
  464. expect.objectContaining({
  465. method: "POST",
  466. body: JSON.stringify({ base_info: { channel_version: "2.0.0" }, ilink_user_id: "wx_user", typing_ticket: "ticket-1", status: 1 }),
  467. }),
  468. );
  469. });
  470. it("starts and polls built-in Weixin QR login", async () => {
  471. const fetchMock = vi.fn(async (url: string) => {
  472. if (url.endsWith("/get_bot_qrcode?bot_type=3")) {
  473. return new Response(JSON.stringify({
  474. ret: 0,
  475. qrcode: "qr-key-1",
  476. qrcode_img_content: "https://liteapp.weixin.qq.com/q/login-1",
  477. expires_in: 90,
  478. }));
  479. }
  480. return new Response(JSON.stringify({ ret: 0, status: "confirmed", bot_token: "bot-token", ilink_bot_id: "bot-1" }));
  481. });
  482. vi.stubGlobal("fetch", fetchMock);
  483. const started = await beginWeixinRegistration();
  484. expect(started.qrCode).toBe("qr-key-1");
  485. expect(started.qrUrl).toBe("https://liteapp.weixin.qq.com/q/login-1");
  486. expect(started).not.toHaveProperty("baseUrl");
  487. const result = await pollWeixinRegistration({ qrCode: started.qrCode });
  488. expect(result).toEqual({
  489. status: "success",
  490. botToken: "bot-token",
  491. botId: "bot-1",
  492. });
  493. expect(fetchMock).toHaveBeenNthCalledWith(
  494. 2,
  495. "https://ilinkai.weixin.qq.com/ilink/bot/get_qrcode_status?qrcode=qr-key-1",
  496. expect.objectContaining({ method: "GET" }),
  497. );
  498. });
  499. it("keeps Weixin QR polling pending when status request times out", async () => {
  500. const fetchMock = vi.fn(async () => {
  501. throw new DOMException("The operation was aborted due to timeout", "TimeoutError");
  502. });
  503. vi.stubGlobal("fetch", fetchMock);
  504. await expect(pollWeixinRegistration({ qrCode: "qr-key-1" })).resolves.toEqual({
  505. status: "pending",
  506. interval: 3,
  507. });
  508. });
  509. });