weixinProvider.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /* eslint-disable max-lines -- 微信 iLink provider 集中处理轮询、文本/媒体解析、发送和 typing 协议。 */
  2. import { Buffer } from "node:buffer";
  3. import { createDecipheriv, randomInt, randomUUID } from "node:crypto";
  4. import type {
  5. BotInboundAttachment,
  6. BotConfig,
  7. BotInboundMessage,
  8. BotOutboundMessage,
  9. } from "@zcode/shared";
  10. import type { BotProviderAdapter, BotTypingTarget } from "./types.js";
  11. import { fetchBotProviderJson } from "#src/bots/providers/providerRequest.js";
  12. export const DEFAULT_WEIXIN_ILINK_BASE_URL = "https://ilinkai.weixin.qq.com";
  13. const WEIXIN_BOT_API_PREFIX = "/ilink/bot";
  14. const WEIXIN_CHANNEL_VERSION = "2.0.0";
  15. const WEIXIN_MESSAGE_TYPE_BOT = 2;
  16. const WEIXIN_MESSAGE_STATE_FINISH = 2;
  17. const WEIXIN_CDN_AES_ALGORITHM = "aes-128-ecb";
  18. const WEIXIN_GET_UPDATES_TIMEOUT_MS = 90_000;
  19. interface WeixinProviderDeps {
  20. loadCredential(key: string): Promise<string | null>;
  21. }
  22. interface WeixinGetUpdatesResult {
  23. messages: BotInboundMessage[];
  24. rawMessageDiagnostics?: string[];
  25. rawMessageCount?: number;
  26. buf?: string;
  27. }
  28. interface WeixinTestResponse {
  29. contact?: unknown;
  30. self?: unknown;
  31. profile?: unknown;
  32. ret?: number;
  33. typing_ticket?: string;
  34. }
  35. function isRecord(value: unknown): value is Record<string, unknown> {
  36. return typeof value === "object" && value !== null;
  37. }
  38. function readString(record: Record<string, unknown> | null | undefined, key: string): string {
  39. const value = record?.[key];
  40. return typeof value === "string" ? value : "";
  41. }
  42. function readNumber(record: Record<string, unknown> | null | undefined, key: string): number | null {
  43. const value = record?.[key];
  44. return typeof value === "number" && Number.isFinite(value) ? value : null;
  45. }
  46. function readNumberOrString(record: Record<string, unknown> | null | undefined, key: string): string {
  47. const value = record?.[key];
  48. if (typeof value === "string") {
  49. return value;
  50. }
  51. return typeof value === "number" && Number.isFinite(value) ? String(value) : "";
  52. }
  53. function parseWeixinAesKey(value: string): Buffer | null {
  54. const trimmed = value.trim();
  55. if (/^[a-f0-9]{32}$/iu.test(trimmed)) {
  56. return Buffer.from(trimmed, "hex");
  57. }
  58. try {
  59. const decoded = Buffer.from(trimmed, "base64");
  60. if (decoded.length === 16) {
  61. return decoded;
  62. }
  63. const decodedText = decoded.toString("utf8").trim();
  64. if (/^[a-f0-9]{32}$/iu.test(decodedText)) {
  65. return Buffer.from(decodedText, "hex");
  66. }
  67. } catch {
  68. return null;
  69. }
  70. return null;
  71. }
  72. function decryptWeixinCdnMedia(data: Uint8Array, aesKey: string): Uint8Array {
  73. const key = parseWeixinAesKey(aesKey);
  74. if (!key) {
  75. throw new Error("Weixin attachment AES key is invalid.");
  76. }
  77. // 微信 iLink CDN 返回 AES-128-ECB + PKCS7 padding 的密文字节;直接保存会得到不可识别的 data 文件。
  78. const decipher = createDecipheriv(WEIXIN_CDN_AES_ALGORITHM, key, null);
  79. return Buffer.concat([decipher.update(data), decipher.final()]);
  80. }
  81. function getWeixinApiBaseUrl(): string {
  82. // 微信 iLink 是内置通道地址,不应复用 webhookUrl,否则旧配置会把出站 Webhook 当成微信 API。
  83. return DEFAULT_WEIXIN_ILINK_BASE_URL.replace(/\/+$/u, "");
  84. }
  85. async function readAccessToken(bot: BotConfig, deps: WeixinProviderDeps): Promise<string | null> {
  86. return bot.credentialRef ? deps.loadCredential(bot.credentialRef) : null;
  87. }
  88. function buildRandomWechatUin(): string {
  89. return Buffer.from(String(randomInt(0, 0x1_0000_0000)), "utf8").toString("base64");
  90. }
  91. function buildHeaders(token: string): Record<string, string> {
  92. return {
  93. "content-type": "application/json",
  94. AuthorizationType: "ilink_bot_token",
  95. Authorization: `Bearer ${token}`,
  96. "X-WECHAT-UIN": buildRandomWechatUin(),
  97. };
  98. }
  99. function appendBaseInfo(body: unknown): unknown {
  100. if (!isRecord(body)) {
  101. return body;
  102. }
  103. return {
  104. base_info: { channel_version: WEIXIN_CHANNEL_VERSION },
  105. ...body,
  106. };
  107. }
  108. async function requestWeixinJson(
  109. bot: BotConfig,
  110. deps: WeixinProviderDeps,
  111. path: string,
  112. body?: unknown,
  113. signal?: AbortSignal,
  114. timeoutMs?: number,
  115. ): Promise<unknown> {
  116. const token = await readAccessToken(bot, deps);
  117. if (!token?.trim()) {
  118. throw new Error("Weixin iLink bot token is missing. Scan the Weixin login QR code first.");
  119. }
  120. const response = await fetchBotProviderJson<unknown>(
  121. `${getWeixinApiBaseUrl()}${WEIXIN_BOT_API_PREFIX}${path}`,
  122. {
  123. method: "POST",
  124. headers: buildHeaders(token.trim()),
  125. body: JSON.stringify(appendBaseInfo(body ?? {})),
  126. signal,
  127. },
  128. timeoutMs,
  129. );
  130. if (!response.ok) {
  131. throw new Error(`Weixin iLink ${path} failed: HTTP ${response.status}`);
  132. }
  133. const payload = response.payload;
  134. const data = isRecord(payload) ? payload : null;
  135. const ret = readNumber(data, "ret");
  136. const errcode = readNumber(data, "errcode");
  137. if ((ret !== null && ret !== 0) || (errcode !== null && errcode !== 0)) {
  138. const message = readString(data, "errmsg") || readString(data, "message") || `ret=${ret ?? ""} errcode=${errcode ?? ""}`.trim();
  139. throw new Error(`Weixin iLink ${path} failed: ${message}`);
  140. }
  141. return payload;
  142. }
  143. function unwrapData(payload: unknown): unknown {
  144. if (!isRecord(payload)) {
  145. return payload;
  146. }
  147. if ("data" in payload) {
  148. return payload.data;
  149. }
  150. return payload;
  151. }
  152. function readMessagesContainer(payload: unknown): Record<string, unknown> {
  153. const data = unwrapData(payload);
  154. return isRecord(data) ? data : {};
  155. }
  156. function readWeixinTextItem(item: unknown): string {
  157. if (!isRecord(item)) {
  158. return "";
  159. }
  160. const textItem = isRecord(item.text_item) ? item.text_item : null;
  161. return readString(textItem, "text") || readString(item, "text") || readString(item, "content");
  162. }
  163. function inferWeixinAttachmentKind(item: Record<string, unknown>): BotInboundAttachment["kind"] {
  164. if (isRecord(item.image_item)) {
  165. return "image";
  166. }
  167. const explicit = readString(item, "kind") || readString(item, "media_type") || readString(item, "mediaType") || readString(item, "type_name");
  168. const mimeType = readString(item, "mime_type") || readString(item, "mimeType");
  169. const filename = readString(item, "filename") || readString(item, "file_name") || readString(item, "name");
  170. const normalized = `${explicit} ${mimeType} ${filename}`.toLowerCase();
  171. if (normalized.includes("image") || normalized.includes("photo") || normalized.includes("picture") || /\.(svg|png|jpe?g|gif|webp|heic|bmp)$/iu.test(filename)) {
  172. return "image";
  173. }
  174. if (normalized.includes("audio") || normalized.includes("voice")) {
  175. return "audio";
  176. }
  177. if (normalized.includes("video")) {
  178. return "video";
  179. }
  180. return "file";
  181. }
  182. function readWeixinAttachmentItem(item: unknown, index: number): BotInboundAttachment | null {
  183. if (!isRecord(item)) {
  184. return null;
  185. }
  186. if (readWeixinTextItem(item)) {
  187. return null;
  188. }
  189. const media =
  190. isRecord(item.image_item) ? item.image_item :
  191. isRecord(item.file_item) ? item.file_item :
  192. isRecord(item.video_item) ? item.video_item :
  193. isRecord(item.audio_item) ? item.audio_item :
  194. isRecord(item.media_item) ? item.media_item :
  195. item;
  196. const mediaPayload = isRecord(media.media) ? media.media : null;
  197. const mediaSource = mediaPayload ? { ...media, ...mediaPayload } : media;
  198. const providerFileId =
  199. readNumberOrString(mediaSource, "file_id") ||
  200. readNumberOrString(mediaSource, "fileId") ||
  201. readNumberOrString(mediaSource, "media_id") ||
  202. readNumberOrString(mediaSource, "mediaId") ||
  203. readNumberOrString(mediaSource, "id") ||
  204. readNumberOrString(mediaSource, "encrypt_query_param") ||
  205. readNumberOrString(mediaSource, "encryptQueryParam") ||
  206. // 微信图片消息的 image_item 只返回 media 字段,没有 file_id/md5;这里将 media 作为后续下载和去重的资源标识。
  207. readNumberOrString(mediaSource, "media") ||
  208. readNumberOrString(mediaSource, "md5");
  209. const downloadUrl =
  210. readString(mediaSource, "url") ||
  211. readString(mediaSource, "download_url") ||
  212. readString(mediaSource, "downloadUrl") ||
  213. // 微信 image_item.media 内的 full_url 是实际图片下载地址,旧逻辑只读 url/download_url 会把纯图片消息丢掉。
  214. readString(mediaSource, "full_url") ||
  215. readString(mediaSource, "fullUrl");
  216. const dataBase64 =
  217. readString(mediaSource, "data_base64") ||
  218. readString(mediaSource, "dataBase64") ||
  219. readString(mediaSource, "base64");
  220. if (!providerFileId && !downloadUrl && !dataBase64) {
  221. return null;
  222. }
  223. const kind = inferWeixinAttachmentKind({ ...item, ...mediaSource });
  224. const filename =
  225. readString(mediaSource, "filename") ||
  226. readString(mediaSource, "file_name") ||
  227. readString(mediaSource, "name") ||
  228. (kind === "image" ? `weixin-image-${index + 1}.jpg` : `weixin-attachment-${index + 1}`);
  229. const mimeType =
  230. readString(mediaSource, "mime_type") ||
  231. readString(mediaSource, "mimeType") ||
  232. inferMimeTypeFromFilename(filename) ||
  233. (kind === "image" ? "image/jpeg" : kind === "audio" ? "audio/mpeg" : kind === "video" ? "video/mp4" : "application/octet-stream");
  234. const sizeBytes =
  235. readNumber(mediaSource, "size") ??
  236. readNumber(mediaSource, "sizeBytes") ??
  237. readNumber(mediaSource, "file_size") ??
  238. readNumber(mediaSource, "len") ??
  239. // image_item 没有通用 size 字段,mid_size 是实际图片资源大小,thumb_size 只用于缩略图预览。
  240. readNumber(mediaSource, "mid_size");
  241. const aesKey =
  242. readString(mediaSource, "aes_key") ||
  243. readString(mediaSource, "aesKey") ||
  244. readString(mediaSource, "aeskey");
  245. return {
  246. id: providerFileId || downloadUrl || `weixin-${index + 1}`,
  247. kind,
  248. filename,
  249. mimeType,
  250. ...(sizeBytes ? { sizeBytes } : {}),
  251. ...(providerFileId ? { providerFileId } : {}),
  252. ...(downloadUrl ? { downloadUrl } : {}),
  253. ...(dataBase64 ? { dataBase64 } : {}),
  254. ...(aesKey ? { providerMetadata: { weixinAesKey: aesKey } } : {}),
  255. };
  256. }
  257. function inferMimeTypeFromFilename(filename: string): string {
  258. if (/\.svg$/iu.test(filename)) {
  259. return "image/svg+xml";
  260. }
  261. if (/\.png$/iu.test(filename)) {
  262. return "image/png";
  263. }
  264. if (/\.jpe?g$/iu.test(filename)) {
  265. return "image/jpeg";
  266. }
  267. if (/\.gif$/iu.test(filename)) {
  268. return "image/gif";
  269. }
  270. if (/\.webp$/iu.test(filename)) {
  271. return "image/webp";
  272. }
  273. return "";
  274. }
  275. function readWeixinDirectAttachment(
  276. item: unknown,
  277. index: number,
  278. ): BotInboundAttachment | null {
  279. if (!isRecord(item)) {
  280. return null;
  281. }
  282. const kind = readString(item, "kind");
  283. if (
  284. kind !== "image" &&
  285. kind !== "audio" &&
  286. kind !== "video" &&
  287. kind !== "file"
  288. ) {
  289. return null;
  290. }
  291. const id = readString(item, "id") || `weixin-${index + 1}`;
  292. const filename = readString(item, "filename") || `${id}.${kind}`;
  293. const mimeType =
  294. readString(item, "mimeType") ||
  295. readString(item, "mime_type") ||
  296. (kind === "image" ? "image/jpeg" : kind === "audio" ? "audio/mpeg" : kind === "video" ? "video/mp4" : "application/octet-stream");
  297. const sizeBytes = readNumber(item, "sizeBytes") ?? readNumber(item, "size");
  298. const providerFileId = readString(item, "providerFileId") || readString(item, "file_id");
  299. const downloadUrl = readString(item, "downloadUrl") || readString(item, "download_url");
  300. const dataBase64 = readString(item, "dataBase64") || readString(item, "data_base64");
  301. const providerMetadata = isRecord(item.providerMetadata)
  302. ? Object.fromEntries(
  303. Object.entries(item.providerMetadata)
  304. .filter((entry): entry is [string, string] => typeof entry[1] === "string"),
  305. )
  306. : null;
  307. return {
  308. id,
  309. kind,
  310. filename,
  311. mimeType,
  312. ...(sizeBytes !== null ? { sizeBytes } : {}),
  313. ...(providerFileId ? { providerFileId } : {}),
  314. ...(downloadUrl ? { downloadUrl } : {}),
  315. ...(dataBase64 ? { dataBase64 } : {}),
  316. ...(providerMetadata && Object.keys(providerMetadata).length > 0 ? { providerMetadata } : {}),
  317. };
  318. }
  319. function readWeixinText(message: Record<string, unknown>): string {
  320. const text = readString(message, "text") || readString(message, "content") || readString(message, "message");
  321. if (text) {
  322. return text;
  323. }
  324. const inner = isRecord(message.msg) ? message.msg : isRecord(message.message) ? message.message : null;
  325. const itemList = Array.isArray(message.item_list) ? message.item_list : Array.isArray(inner?.item_list) ? inner.item_list : [];
  326. return itemList.map(readWeixinTextItem).filter(Boolean).join("\n") || readString(inner, "text") || readString(inner, "content");
  327. }
  328. function readWeixinAttachments(message: Record<string, unknown>): BotInboundAttachment[] {
  329. const inner = isRecord(message.msg) ? message.msg : isRecord(message.message) ? message.message : null;
  330. const itemList = Array.isArray(message.item_list) ? message.item_list : Array.isArray(inner?.item_list) ? inner.item_list : [];
  331. const directAttachments = Array.isArray(message.attachments)
  332. ? message.attachments
  333. : Array.isArray(inner?.attachments)
  334. ? inner.attachments
  335. : [];
  336. return [
  337. ...itemList
  338. .map((item, index) => readWeixinAttachmentItem(item, index))
  339. .filter((attachment): attachment is BotInboundAttachment => attachment !== null),
  340. ...directAttachments
  341. .map((item, index) => readWeixinDirectAttachment(item, index))
  342. .filter((attachment): attachment is BotInboundAttachment => attachment !== null),
  343. ];
  344. }
  345. function readWeixinUserId(message: Record<string, unknown>): string {
  346. const from = isRecord(message.from) ? message.from : null;
  347. const sender = isRecord(message.sender) ? message.sender : null;
  348. return (
  349. readString(message, "from_user_id") ||
  350. readString(message, "from") ||
  351. readString(message, "from_user") ||
  352. readString(message, "fromUser") ||
  353. readString(message, "user") ||
  354. readString(message, "user_id") ||
  355. readString(message, "userId") ||
  356. readString(from, "id") ||
  357. readString(from, "wxid") ||
  358. readString(sender, "id") ||
  359. readString(sender, "wxid")
  360. );
  361. }
  362. function readWeixinChatId(message: Record<string, unknown>): string | undefined {
  363. return (
  364. readString(message, "room") ||
  365. readString(message, "room_id") ||
  366. readString(message, "roomId") ||
  367. readString(message, "chat") ||
  368. readString(message, "chat_id") ||
  369. readString(message, "chatId") ||
  370. undefined
  371. );
  372. }
  373. function readWeixinDisplayName(message: Record<string, unknown>): string | undefined {
  374. const from = isRecord(message.from) ? message.from : null;
  375. const sender = isRecord(message.sender) ? message.sender : null;
  376. const inner = isRecord(message.msg) ? message.msg : isRecord(message.message) ? message.message : null;
  377. return (
  378. readString(message, "name") ||
  379. readString(message, "displayName") ||
  380. readString(message, "nickname") ||
  381. readString(from, "name") ||
  382. readString(from, "nickname") ||
  383. readString(sender, "name") ||
  384. readString(sender, "nickname") ||
  385. readString(inner, "sender_name") ||
  386. undefined
  387. );
  388. }
  389. function readWeixinMessageId(message: Record<string, unknown>): string | undefined {
  390. const inner = isRecord(message.msg) ? message.msg : isRecord(message.message) ? message.message : null;
  391. const messageId =
  392. readString(message, "id") ||
  393. readString(message, "msgid") ||
  394. readString(message, "msgId") ||
  395. readNumberOrString(message, "message_id") ||
  396. readString(inner, "id") ||
  397. readString(inner, "msgid") ||
  398. readString(inner, "msgId") ||
  399. readNumberOrString(inner, "message_id");
  400. if (messageId) {
  401. return messageId;
  402. }
  403. const numericId =
  404. readNumber(message, "id") ??
  405. readNumber(message, "msgid") ??
  406. readNumber(message, "msgId") ??
  407. readNumber(inner, "id") ??
  408. readNumber(inner, "msgid") ??
  409. readNumber(inner, "msgId");
  410. return numericId === null ? undefined : String(numericId);
  411. }
  412. function readWeixinMessages(payload: unknown): Record<string, unknown>[] {
  413. const container = readMessagesContainer(payload);
  414. const rawMessages = container.msgs ?? container.messages ?? container.updates ?? container.items ?? container.list;
  415. if (Array.isArray(rawMessages)) {
  416. return rawMessages.filter(isRecord);
  417. }
  418. if (isRecord(rawMessages)) {
  419. return [rawMessages];
  420. }
  421. return [];
  422. }
  423. function readNextBuf(payload: unknown): string | undefined {
  424. const container = readMessagesContainer(payload);
  425. return (
  426. readString(container, "get_updates_buf") ||
  427. readString(container, "buf") ||
  428. readString(container, "next_buf") ||
  429. readString(container, "nextBuf") ||
  430. readString(container, "getUpdatesBuf") ||
  431. readString(container, "syncKey") ||
  432. undefined
  433. );
  434. }
  435. function readWeixinContextToken(message: Record<string, unknown>): string | undefined {
  436. const inner = isRecord(message.msg) ? message.msg : isRecord(message.message) ? message.message : null;
  437. return (
  438. readString(message, "context_token") ||
  439. readString(message, "contextToken") ||
  440. readString(message, "context") ||
  441. readString(inner, "context_token") ||
  442. undefined
  443. );
  444. }
  445. function buildWeixinClientId(): string {
  446. return `zcode-weixin-${randomUUID()}`;
  447. }
  448. function buildWeixinText(message: BotOutboundMessage): string {
  449. // Bugfix: 微信 iLink 纯文本在不同客户端上对 LF 的处理不完全一致。
  450. // 发送前统一成 CRLF,把业务层的多行回复表达为文本硬换行,避免 /status 这类状态行被折叠。
  451. return message.text.replace(/\r\n|\r|\n/g, "\r\n");
  452. }
  453. function buildInboundMessage(botId: string, rawMessage: Record<string, unknown>): BotInboundMessage | null {
  454. if (readNumber(rawMessage, "message_type") === 2) {
  455. return null;
  456. }
  457. const text = readWeixinText(rawMessage).trim();
  458. const attachments = readWeixinAttachments(rawMessage);
  459. const userId = readWeixinUserId(rawMessage).trim();
  460. if ((!text && attachments.length === 0) || !userId) {
  461. return null;
  462. }
  463. const chatId = readWeixinChatId(rawMessage);
  464. return {
  465. botId,
  466. text,
  467. ...(attachments.length > 0 ? { attachments } : {}),
  468. actor: {
  469. provider: "weixin",
  470. botId,
  471. providerUserId: userId,
  472. displayName: readWeixinDisplayName(rawMessage),
  473. chatType: chatId ? "group" : "private",
  474. chatId,
  475. providerMessageId: readWeixinMessageId(rawMessage),
  476. providerContextToken: readWeixinContextToken(rawMessage),
  477. },
  478. };
  479. }
  480. function summarizeWeixinRawMessage(rawMessage: Record<string, unknown>, index: number): string {
  481. const inner = isRecord(rawMessage.msg) ? rawMessage.msg : isRecord(rawMessage.message) ? rawMessage.message : null;
  482. const itemList = Array.isArray(rawMessage.item_list)
  483. ? rawMessage.item_list
  484. : Array.isArray(inner?.item_list)
  485. ? inner.item_list
  486. : [];
  487. const itemTypes = itemList
  488. .filter(isRecord)
  489. .map((item) => readNumber(item, "type") ?? readNumber(item, "item_type") ?? readNumber(item, "message_type") ?? "unknown")
  490. .slice(0, 6)
  491. .join(",");
  492. const firstItem = itemList.find(isRecord);
  493. const firstMedia =
  494. isRecord(firstItem?.image_item) ? firstItem.image_item :
  495. isRecord(firstItem?.file_item) ? firstItem.file_item :
  496. isRecord(firstItem?.video_item) ? firstItem.video_item :
  497. isRecord(firstItem?.audio_item) ? firstItem.audio_item :
  498. isRecord(firstItem?.media_item) ? firstItem.media_item :
  499. null;
  500. const mediaTypes = firstMedia
  501. ? Object.entries(firstMedia)
  502. .slice(0, 8)
  503. .map(([key, value]) => `${key}:${Array.isArray(value) ? "array" : typeof value}`)
  504. .join(",")
  505. : "none";
  506. const nestedMedia = firstMedia && isRecord(firstMedia.media) ? firstMedia.media : null;
  507. const nestedMediaTypes = nestedMedia
  508. ? Object.entries(nestedMedia)
  509. .slice(0, 8)
  510. .map(([key, value]) => `${key}:${Array.isArray(value) ? "array" : typeof value}`)
  511. .join(",")
  512. : "none";
  513. return [
  514. `index=${index}`,
  515. `messageType=${readNumber(rawMessage, "message_type") ?? "none"}`,
  516. `textLen=${readWeixinText(rawMessage).trim().length}`,
  517. `attachments=${readWeixinAttachments(rawMessage).length}`,
  518. `hasUserId=${readWeixinUserId(rawMessage).trim() ? "yes" : "no"}`,
  519. `itemList=${itemList.length}`,
  520. `itemTypes=${itemTypes || "none"}`,
  521. `itemKeys=${firstItem ? Object.keys(firstItem).slice(0, 12).join(",") : "none"}`,
  522. `mediaKeys=${firstMedia ? Object.keys(firstMedia).slice(0, 12).join(",") : "none"}`,
  523. `mediaTypes=${mediaTypes}`,
  524. `nestedMediaKeys=${nestedMedia ? Object.keys(nestedMedia).slice(0, 12).join(",") : "none"}`,
  525. `nestedMediaTypes=${nestedMediaTypes}`,
  526. `keys=${Object.keys(rawMessage).slice(0, 12).join(",")}`,
  527. `innerKeys=${inner ? Object.keys(inner).slice(0, 12).join(",") : "none"}`,
  528. ].join(" ");
  529. }
  530. export async function getWeixinUpdates(params: {
  531. bot: BotConfig;
  532. deps: WeixinProviderDeps;
  533. buf?: string;
  534. signal?: AbortSignal;
  535. }): Promise<WeixinGetUpdatesResult> {
  536. const payload = await requestWeixinJson(
  537. params.bot,
  538. params.deps,
  539. "/getupdates",
  540. {
  541. get_updates_buf: params.buf ?? "",
  542. },
  543. params.signal,
  544. WEIXIN_GET_UPDATES_TIMEOUT_MS,
  545. );
  546. const rawMessages = readWeixinMessages(payload);
  547. return {
  548. rawMessageCount: rawMessages.length,
  549. rawMessageDiagnostics: rawMessages.map(summarizeWeixinRawMessage),
  550. messages: rawMessages
  551. .map((message) => buildInboundMessage(params.bot.id, message))
  552. .filter((message): message is BotInboundMessage => message !== null),
  553. buf: readNextBuf(payload) ?? params.buf,
  554. };
  555. }
  556. export function createWeixinBotProvider(deps: WeixinProviderDeps): BotProviderAdapter {
  557. return {
  558. async test(bot) {
  559. if (!bot.enabled) {
  560. return { ok: false, message: "Weixin bot is disabled." };
  561. }
  562. if (!bot.credentialRef) {
  563. return { ok: false, message: "Weixin iLink bot token is missing. Scan the Weixin login QR code first." };
  564. }
  565. await requestWeixinJson(bot, deps, "/getconfig");
  566. return {
  567. ok: true,
  568. message: "Weixin iLink API is reachable.",
  569. };
  570. },
  571. async send(bot, message) {
  572. // Bugfix: 微信 iLink 发送协议必须走 /ilink/bot/sendmessage,并把文本放进 msg.item_list。
  573. // 之前把 openclaw-weixin 当成本地 gateway 依赖,会导致 ZCode 不能独立完成微信接入。
  574. await requestWeixinJson(bot, deps, "/sendmessage", {
  575. msg: {
  576. from_user_id: bot.providerUserId ?? "",
  577. to_user_id: message.providerUserId,
  578. client_id: buildWeixinClientId(),
  579. message_type: WEIXIN_MESSAGE_TYPE_BOT,
  580. message_state: WEIXIN_MESSAGE_STATE_FINISH,
  581. ...(message.providerContextToken ? { context_token: message.providerContextToken } : {}),
  582. item_list: [
  583. {
  584. type: 1,
  585. text_item: { text: buildWeixinText(message) },
  586. },
  587. ],
  588. },
  589. });
  590. },
  591. async sendTyping(bot, target: BotTypingTarget) {
  592. const config = (await requestWeixinJson(bot, deps, "/getconfig", {
  593. ilink_user_id: target.providerUserId,
  594. ...(target.providerContextToken ? { context_token: target.providerContextToken } : {}),
  595. })) as WeixinTestResponse;
  596. if (!config.typing_ticket) {
  597. return;
  598. }
  599. await requestWeixinJson(bot, deps, "/sendtyping", {
  600. ilink_user_id: target.providerUserId,
  601. typing_ticket: config.typing_ticket,
  602. status: 1,
  603. });
  604. },
  605. async downloadAttachment(_bot, attachment) {
  606. const aesKey = attachment.providerMetadata?.weixinAesKey;
  607. if (!attachment.downloadUrl || !aesKey) {
  608. return null;
  609. }
  610. const response = await fetch(attachment.downloadUrl);
  611. if (!response.ok) {
  612. throw new Error(`Weixin attachment download failed: HTTP ${response.status}`);
  613. }
  614. return {
  615. attachment,
  616. data: decryptWeixinCdnMedia(new Uint8Array(await response.arrayBuffer()), aesKey),
  617. };
  618. },
  619. parseCallback(payload): BotInboundMessage[] {
  620. if (!isRecord(payload)) {
  621. return [];
  622. }
  623. const botId = readString(payload, "botId");
  624. if (!botId) {
  625. return [];
  626. }
  627. return readWeixinMessages(payload)
  628. .map((message) => buildInboundMessage(botId, message))
  629. .filter((message): message is BotInboundMessage => message !== null);
  630. },
  631. };
  632. }