Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Add the Feishu and WeChat adapters and the QR login endpoints

Fei24119179e728ef22
diff --git a/ds-bot/src/host/im/index.js b/ds-bot/src/host/im/index.js
index ee0bde86..51abd7ce 100644
--- a/ds-bot/src/host/im/index.js
+++ b/ds-bot/src/host/im/index.js
@@ -797,11 +797,49 @@ export function install(rt) {
await sync()
return true
},
- async 'im-login-start'() {
- throw new Error('This platform is not available yet')
+ async 'im-login-start'(body) {
+ const platform = imPlatform(String(body.platform ?? ''))
+ const adapter = platform === undefined ? undefined : adapters[platform.id]
+ if (platform === undefined || typeof adapter?.loginStart !== 'function') throw new Error('This platform has no QR login')
+ const bot = rt.botOf(String(body.botId ?? ''))
+ if (bot === undefined) throw new Error('Choose a Bot first')
+ const env = await envFor({ id: 'im_login', platform: platform.id, settings: {}, secrets: {} }, { get: () => ({}), set: () => {} })
+ const login = await adapter.loginStart(env)
+ return { loginId: login.loginId, qr: login.qr, expiresAt: login.expiresAt, botId: bot.id }
},
- async 'im-login-wait'() {
- throw new Error('This platform is not available yet')
+ async 'im-login-wait'(body) {
+ const platform = imPlatform(String(body.platform ?? 'weixin'))
+ const adapter = platform === undefined ? undefined : adapters[platform.id]
+ if (platform === undefined || typeof adapter?.loginWait !== 'function') throw new Error('This platform has no QR login')
+ const bot = rt.botOf(String(body.botId ?? ''))
+ if (bot === undefined) throw new Error('Choose a Bot first')
+ const env = await envFor({ id: 'im_login', platform: platform.id, settings: {}, secrets: {} }, { get: () => ({}), set: () => {} })
+ const login = await adapter.loginWait(String(body.loginId ?? ''), env)
+ if (login.status !== 'done') return { status: login.status }
+ // Confirmed: create the connection with the platform credentials the
+ // login returned, paired with the scanning owner — no review needed.
+ const conn = {
+ id: `im_${randomBytes(4).toString('hex')}`,
+ platform: platform.id,
+ account: login.connection.account,
+ botId: bot.id,
+ settings: login.connection.settings ?? {},
+ secrets: {},
+ enabled: true,
+ paired: login.owner === undefined ? [] : [{ id: login.owner.id, name: login.owner.name, at: Date.now() }],
+ requests: [],
+ chats: login.owner === undefined ? {} : { [login.owner.id]: { kind: 'direct', title: login.owner.name, at: Date.now() } },
+ createdAt: Date.now(),
+ }
+ for (const [key, value] of Object.entries(login.connection.secrets ?? {})) {
+ const name = secretName(conn, key)
+ await rt.secretEndpoint('secret-set', { name, value, purpose: `${platform.name} IM bot`, scope: [] })
+ conn.secrets[key] = name
+ }
+ connections()[conn.id] = conn
+ await rt.save()
+ await sync()
+ return { status: 'done', id: conn.id }
},
}
diff --git a/ds-bot/src/host/im/platforms/feishu.js b/ds-bot/src/host/im/platforms/feishu.js
new file mode 100644
index 00000000..3f40cfb7
--- /dev/null
+++ b/ds-bot/src/host/im/platforms/feishu.js
@@ -0,0 +1,352 @@
+// Feishu / Lark: the long connection speaks protobuf pbbp2 frames — control
+// pings answered with pong, data frames ACKed by sending the frame back with a
+// {"code":200} payload and a biz_rt header; split payloads reassemble by
+// sum/seq. p2p messages are direct; a group message counts when the bot's
+// open_id is in its mentions. Sends go through the OpenAPI with a tenant
+// access token: interactive cards with a markdown element and buttons, edited
+// by PATCH. The tiny protobuf codec below implements only this frame shape.
+// Protocol ported from @larksuiteoapi/node-sdk (MIT, see NOTICE).
+import { chunkMarkdown } from '../format.js'
+
+const TEXT_LIMIT = 4000
+
+const apiBase = (env, fields) => String(env.config?.api ?? (fields.domain === 'lark' ? 'https://open.larksuite.com' : 'https://open.feishu.cn')).replace(/\/+$/, '')
+
+// ---- pbbp2.Frame codec (protobuf wire format, only this message) ----------
+// Frame: SeqID u64=1, LogID u64=2, service i32=3, method i32=4,
+// headers repeated Header=5, payload_encoding string=6, payload_type
+// string=7, payload bytes=8, LogIDNew string=9. Header: key string=1, value
+// string=2. Wire types: 0 varint, 2 length-delimited.
+const uvarint = (value) => {
+ let v = BigInt(value)
+ const bytes = []
+ while (v > 127n) { bytes.push(Number(v & 127n) | 128); v >>= 7n }
+ bytes.push(Number(v))
+ return bytes
+}
+const field = (number, wire, bytes) => {
+ const tag = uvarint((number << 3) | wire)
+ if (wire === 0) return [...tag, ...uvarint(bytes)]
+ const body = typeof bytes === 'string' ? [...Buffer.from(bytes, 'utf8')] : [...bytes]
+ return [...tag, ...uvarint(body.length), ...body]
+}
+const encodeHeader = ({ key, value }) => [...field(1, 2, key), ...field(2, 2, value)]
+export const encodeFrame = (frame) => {
+ const out = []
+ if (frame.SeqID !== undefined) out.push(...field(1, 0, frame.SeqID))
+ if (frame.LogID !== undefined) out.push(...field(2, 0, frame.LogID))
+ if (frame.service !== undefined) out.push(...field(3, 0, frame.service))
+ if (frame.method !== undefined) out.push(...field(4, 0, frame.method))
+ for (const header of frame.headers ?? []) out.push(...field(5, 2, encodeHeader(header)))
+ if (frame.payloadEncoding !== undefined) out.push(...field(6, 2, frame.payloadEncoding))
+ if (frame.payloadType !== undefined) out.push(...field(7, 2, frame.payloadType))
+ if (frame.payload !== undefined) out.push(...field(8, 2, frame.payload))
+ if (frame.LogIDNew !== undefined) out.push(...field(9, 2, frame.LogIDNew))
+ return Buffer.from(out)
+}
+export const decodeFrame = (buffer) => {
+ const frame = { headers: [] }
+ let at = 0
+ const varint = () => {
+ let value = 0n
+ let shift = 0n
+ while (at < buffer.length) {
+ const byte = buffer[at]
+ at += 1
+ value |= BigInt(byte & 127) << shift
+ if ((byte & 128) === 0) break
+ shift += 7n
+ }
+ return value
+ }
+ const bytes = () => {
+ const length = Number(varint())
+ const part = buffer.subarray(at, at + length)
+ at += length
+ return part
+ }
+ const header = (buf) => {
+ let index = 0
+ const out = {}
+ const v = () => {
+ let value = 0n
+ let shift = 0n
+ while (index < buf.length) {
+ const byte = buf[index]
+ index += 1
+ value |= BigInt(byte & 127) << shift
+ if ((byte & 128) === 0) break
+ shift += 7n
+ }
+ return value
+ }
+ const b = () => {
+ const length = Number(v())
+ const part = buf.subarray(index, index + length)
+ index += length
+ return part
+ }
+ while (index < buf.length) {
+ const tag = Number(v())
+ if (tag >> 3 === 1) out.key = b().toString('utf8')
+ else if (tag >> 3 === 2) out.value = b().toString('utf8')
+ else if ((tag & 7) === 2) b()
+ else if ((tag & 7) === 0) v()
+ }
+ return out
+ }
+ while (at < buffer.length) {
+ const tag = Number(varint())
+ const number = tag >> 3
+ const wire = tag & 7
+ if (wire === 0) {
+ const value = varint()
+ if (number === 1) frame.SeqID = Number(value)
+ else if (number === 2) frame.LogID = Number(value)
+ else if (number === 3) frame.service = Number(value)
+ else if (number === 4) frame.method = Number(value)
+ } else if (wire === 2) {
+ const value = bytes()
+ if (number === 5) frame.headers.push(header(value))
+ else if (number === 6) frame.payloadEncoding = value.toString('utf8')
+ else if (number === 7) frame.payloadType = value.toString('utf8')
+ else if (number === 8) frame.payload = Buffer.from(value)
+ else if (number === 9) frame.LogIDNew = value.toString('utf8')
+ }
+ }
+ return frame
+}
+// ---------------------------------------------------------------------------
+
+export default {
+ id: 'feishu',
+
+ async check(fields, env) {
+ const token = await tenantToken(fields, env)
+ const me = await api(env, apiBase(env, fields), token, '/open-apis/bot/v3/info', { method: 'GET' })
+ const bot = me?.bot ?? me
+ return { account: { id: String(bot?.open_id ?? bot?.app_id ?? fields.appId), name: bot?.app_name ?? String(fields.appId) } }
+ },
+
+ connect(fields, env, handlers) {
+ const appId = String(fields.appId ?? '').trim()
+ const appSecret = String(fields.appSecret ?? '').trim()
+ let stopped = false
+ let socket
+ let generation = 0
+ let reconnectTimer
+ let token
+ let tokenExpiresAt = 0
+ let botOpenId = ''
+ // Split data frames reassemble by (sum, seq) until all parts arrive.
+ const parts = new Map()
+
+ const rest = async (path, { method = 'POST', body } = {}) => {
+ if (token === undefined || Date.now() > tokenExpiresAt - 30_000) {
+ const got = await tenantToken({ appId, appSecret }, env)
+ token = got.token
+ tokenExpiresAt = got.expiresAt
+ }
+ return api(env, apiBase(env, fields), token, path, { method, body })
+ }
+
+ const sendFrame = (buffer) => { if (socket?.readyState === 1) socket.send(buffer) }
+ const pong = (frame) => sendFrame(encodeFrame({ ...frame, headers: frame.headers.map(h => h.key === 'type' ? { key: 'type', value: 'pong' } : h), payload: Buffer.from('pong') }))
+ const ack = (frame, ms) => sendFrame(encodeFrame({
+ ...frame,
+ headers: [...frame.headers.filter(h => h.key !== 'biz_rt'), { key: 'biz_rt', value: String(ms) }],
+ payload: Buffer.from(JSON.stringify({ code: 200, headers: {}, data: '' })),
+ payloadType: 'json',
+ }))
+
+ const dispatch = async (type, body) => {
+ const payload = JSON.parse(body.toString('utf8'))
+ if (type === 'event' && payload.header?.event_type === 'im.message.receive_v1') {
+ const event = payload.event ?? {}
+ const message = event.message ?? {}
+ const direct = message.chat_type === 'p2p'
+ const mentioned = !direct && (message.mentions ?? []).some(m => m.id?.open_id === botOpenId || m.key === `@_user_${1}`)
+ const content = safeJson(message.content)
+ const text = String(content.text ?? '').replace(/@_user_\d+/g, '').trim()
+ const images = []
+ if (message.message_type === 'image' && content.image_key !== undefined) {
+ const bytes = await resource(env, apiBase(env, fields), token, message.message_id, content.image_key, 'image').catch(() => undefined)
+ if (bytes !== undefined) images.push({ mediaType: 'image/png', data: Buffer.from(bytes).toString('base64') })
+ }
+ const sender = event.sender?.sender_id?.open_id ?? event.sender?.user_id ?? ''
+ await handlers.onMessage({
+ chat: { key: String(message.chat_id ?? ''), kind: direct ? 'direct' : 'group', title: String(message.chat_id ?? '') },
+ sender: { id: String(sender), name: String(sender) },
+ text, images, files: [],
+ mentioned, messageId: String(message.message_id ?? ''),
+ })
+ }
+ if (type === 'card' || payload.header?.event_type === 'card.action.trigger') {
+ const event = payload.event ?? {}
+ const action = event.action ?? event.actions?.[0] ?? {}
+ const data = action.value ?? action.action_data?.value ?? action.action_data ?? {}
+ await handlers.onAction({
+ chat: { key: String(event.context?.open_chat_id ?? event.message?.chat_id ?? ''), kind: 'direct', title: '' },
+ sender: { id: String(event.operator?.open_id ?? event.user_id ?? ''), name: '' },
+ data: String(typeof data === 'object' ? (data.v ?? JSON.stringify(data)) : data),
+ messageId: String(event.message_id ?? event.context?.open_message_id ?? ''),
+ })
+ }
+ }
+
+ const open = async () => {
+ const gen = generation
+ let url
+ try {
+ const answer = await env.fetch(`${apiBase(env, fields)}/open-apis/bot/v2/endpoint`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ appId, appSecret }),
+ })
+ const body = await answer.json().catch(() => ({}))
+ url = body.data?.URL
+ if (url === undefined) throw new Error(body.msg ?? 'Feishu refused the connection')
+ } catch (error) {
+ handlers.onStatus({ state: 'error', error: error.message })
+ return
+ }
+ try {
+ socket = new env.WebSocket(url)
+ socket.binaryType = 'arraybuffer'
+ } catch (error) {
+ handlers.onStatus({ state: 'error', error: `Feishu could not open a socket: ${error?.message ?? error}` })
+ return
+ }
+ socket.addEventListener('message', (event) => {
+ if (stopped || generation !== gen) return
+ let frame
+ try { frame = decodeFrame(Buffer.from(event.data)) } catch { return }
+ const type = frame.headers.find(h => h.key === 'type')?.value
+ if (frame.method === 0 && type === 'ping') { pong(frame); return }
+ if (frame.method === 1 && type === 'reconnect') { socket.close(4000, 'Reconnect requested'); return }
+ if (frame.method !== 1 || (type !== 'event' && type !== 'card')) return
+ const messageId = frame.headers.find(h => h.key === 'message_id')?.value ?? ''
+ const sum = Number(frame.headers.find(h => h.key === 'sum')?.value ?? 1)
+ const seq = Number(frame.headers.find(h => h.key === 'seq')?.value ?? 1)
+ ack(frame, 0)
+ if (sum > 1) {
+ const held = parts.get(messageId) ?? { received: new Map(), sum }
+ held.received.set(seq, frame.payload)
+ parts.set(messageId, held)
+ if (held.received.size !== sum) return
+ frame.payload = Buffer.concat([...held.received.keys()].sort((a, b) => a - b).map(s => held.received.get(s)))
+ parts.delete(messageId)
+ }
+ void dispatch(type, frame.payload).catch(error => env.log?.warn?.('ds-bot im: feishu event failed: %s', error?.message ?? error))
+ })
+ socket.addEventListener('open', () => handlers.onStatus({ state: 'ready' }))
+ socket.addEventListener('close', () => {
+ if (stopped || generation !== gen) return
+ handlers.onStatus({ state: 'connecting' })
+ reconnectTimer = setTimeout(() => { if (!stopped) void open() }, 2000)
+ reconnectTimer.unref?.()
+ })
+ socket.addEventListener('error', () => {})
+ }
+
+ handlers.onStatus({ state: 'connecting' })
+ void (async () => {
+ try {
+ const got = await tenantToken({ appId, appSecret }, env)
+ token = got.token
+ tokenExpiresAt = got.expiresAt
+ const me = await api(env, apiBase(env, fields), token, '/open-apis/bot/v3/info', { method: 'GET' }).catch(() => ({}))
+ botOpenId = String(me?.bot?.open_id ?? me?.open_id ?? '')
+ } catch (error) {
+ handlers.onStatus({ state: 'error', error: error.message })
+ return
+ }
+ if (!stopped) await open()
+ })()
+
+ const card = (text, buttons) => JSON.stringify({
+ schema: '2.0',
+ body: {
+ elements: [
+ { tag: 'markdown', content: text },
+ ...(buttons?.length > 0 ? [{
+ tag: 'action',
+ actions: buttons.slice(0, 5).map(button => ({
+ tag: 'button', type: 'primary',
+ text: { tag: 'plain_text', content: button.label.slice(0, 20) },
+ value: { v: button.data },
+ })),
+ }] : []),
+ ],
+ },
+ })
+
+ return {
+ send: async (chat, { text, buttons }) => {
+ const chunks = chunkMarkdown(String(text ?? ''), TEXT_LIMIT)
+ let messageId
+ for (const [index, chunk] of chunks.entries()) {
+ const interactive = buttons !== undefined && index === chunks.length - 1
+ const sent = await rest('/open-apis/im/v1/messages?receive_id_type=chat_id', {
+ body: {
+ receive_id: chat.key,
+ msg_type: interactive ? 'interactive' : 'text',
+ content: interactive ? card(chunk, buttons) : JSON.stringify({ text: chunk }),
+ },
+ })
+ messageId = String(sent?.data?.message_id ?? messageId ?? '')
+ }
+ return { messageId }
+ },
+ edit: async (chat, messageId, { text, buttons }) => {
+ await rest(`/open-apis/im/v1/messages/${messageId}`, {
+ method: 'PATCH',
+ body: { msg_type: 'interactive', content: card(toMarkdown(text).slice(0, TEXT_LIMIT), buttons) },
+ })
+ },
+ stop: () => {
+ stopped = true
+ generation += 1
+ clearTimeout(reconnectTimer)
+ try { socket?.close(1000, 'stop') } catch { /* not open */ }
+ },
+ }
+ },
+}
+
+const safeJson = (text) => { try { return JSON.parse(text ?? '{}') } catch { return {} } }
+const toMarkdown = text => String(text ?? '')
+
+async function tenantToken(fields, env) {
+ const response = await env.fetch(`${apiBase(env, fields)}/open-apis/auth/v3/tenant_access_token/internal`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ app_id: String(fields.appId ?? '').trim(), app_secret: String(fields.appSecret ?? '').trim() }),
+ })
+ const body = await response.json().catch(() => ({}))
+ if (body.tenant_access_token === undefined) throw new Error(body.msg ?? 'Feishu refused these credentials')
+ return { token: body.tenant_access_token, expiresAt: Date.now() + Math.max(60, Number(body.expire ?? 7200) - 300) * 1000 }
+}
+
+async function api(env, base, token, path, { method = 'GET', body } = {}) {
+ const response = await env.fetch(`${base}${path}`, {
+ method,
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ })
+ const json = await response.json().catch(() => ({}))
+ if (!response.ok || (json.code !== undefined && json.code !== 0)) {
+ const error = new Error(String(json.msg ?? `Feishu answered ${response.status}`))
+ error.permanent = response.status >= 400 && response.status < 500 && response.status !== 429
+ throw error
+ }
+ return json
+}
+
+async function resource(env, base, token, messageId, key, type) {
+ const response = await env.fetch(`${base}/open-apis/im/v1/messages/${messageId}/resources/${key}?type=${type}`, {
+ headers: { authorization: `Bearer ${token}` },
+ })
+ if (!response.ok) return undefined
+ return new Uint8Array(await response.arrayBuffer())
+}
diff --git a/ds-bot/src/host/im/platforms/index.js b/ds-bot/src/host/im/platforms/index.js
index d91b044b..b914c230 100644
--- a/ds-bot/src/host/im/platforms/index.js
+++ b/ds-bot/src/host/im/platforms/index.js
@@ -1,10 +1,12 @@
import dingtalk from './dingtalk.js'
import discord from './discord.js'
+import feishu from './feishu.js'
import qq from './qq.js'
import slack from './slack.js'
import telegram from './telegram.js'
import wecom from './wecom.js'
+import weixin from './weixin.js'
// Every platform with an adapter. The rest of IM_PLATFORMS still show in settings as
// coming soon — a connection can only be added for a platform listed here.
-export const adapters = { telegram, discord, slack, qq, dingtalk, wecom }
+export const adapters = { telegram, discord, slack, qq, dingtalk, wecom, feishu, weixin }
diff --git a/ds-bot/src/host/im/platforms/wecom.js b/ds-bot/src/host/im/platforms/wecom.js
index 36c9700e..8a0e66c4 100644
--- a/ds-bot/src/host/im/platforms/wecom.js
+++ b/ds-bot/src/host/im/platforms/wecom.js
@@ -19,7 +19,35 @@ export default {
// The subscription itself is the credential check: a bad bot id or secret
// fails the aibot_subscribe response.
async check(fields, env) {
- return { account: { id: String(fields.botId ?? '').trim(), name: String(fields.botId ?? '').trim() } }
+ const botId = String(fields.botId ?? '').trim()
+ const secret = String(fields.secret ?? '').trim()
+ if (env.WebSocket === undefined) throw new Error('This dsh runs on a Node without WebSocket')
+ return await new Promise((resolve, reject) => {
+ let socket
+ const finish = (error, account) => {
+ clearTimeout(timer)
+ try { socket?.close(1000, 'check') } catch { /* not open */ }
+ if (error === undefined) resolve({ account })
+ else reject(error)
+ }
+ const timer = setTimeout(() => finish(new Error('WeCom did not answer the subscription')), 10_000)
+ try { socket = new env.WebSocket(`${wsBase(env)}/wss`) } catch (error) {
+ finish(new Error(`WeCom could not open a socket: ${error?.message ?? error}`))
+ return
+ }
+ socket.addEventListener('open', () => {
+ socket.send(JSON.stringify({ cmd: 'aibot_subscribe', headers: { req_id: 'check-1' }, body: { secret, bot_id: botId } }))
+ })
+ socket.addEventListener('message', (event) => {
+ let packet
+ try { packet = JSON.parse(String(event.data)) } catch { return }
+ if (packet.errcode === undefined) return
+ if (packet.errcode === 0) finish(undefined, { id: botId, name: botId })
+ else finish(new Error(String(packet.errmsg ?? `WeCom answered ${packet.errcode}`)))
+ })
+ socket.addEventListener('error', () => finish(new Error('WeCom refused the socket')))
+ socket.addEventListener('close', () => {})
+ })
},
connect(fields, env, handlers) {
diff --git a/ds-bot/src/host/im/platforms/weixin.js b/ds-bot/src/host/im/platforms/weixin.js
new file mode 100644
index 00000000..c12c1be4
--- /dev/null
+++ b/ds-bot/src/host/im/platforms/weixin.js
@@ -0,0 +1,256 @@
+// WeChat iLink: a QR login creates the connection — get_bot_qrcode, then a
+// get_qrcode_status long poll until the owner confirms on their phone; the
+// reply carries bot_token, ilink_bot_id, ilink_user_id and the base URL.
+// From then a getupdates long poll delivers messages (the get_updates_buf
+// cursor and the latest context_token per user live in the connection
+// runtime so they survive restarts); sends go out through sendmessage with
+// that user's context_token, ~1800-char text chunks. Typing uses the
+// getconfig ticket. Voice items arrive with a transcript; images download
+// from the CDN and decrypt with their AES key. A refused send is permanent
+// with the platform's reason. Protocol ported from dsh-im (MIT, see NOTICE).
+import { createDecipheriv, randomBytes } from 'node:crypto'
+
+const QR_BASE = 'https://ilinkai.weixin.qq.com/'
+const BOT_TYPE = '3'
+const TEXT_LIMIT = 1800
+const POLL_TIMEOUT_MS = 35_000
+
+const qrBase = env => String(env.config?.qr ?? env.config?.api ?? QR_BASE).replace(/\/+$/, '/')
+const base = (env, fields) => String(fields.baseUrl || env.config?.api || QR_BASE).replace(/\/+$/, '/')
+const baseInfo = () => ({ channel_version: 'ds-bot' })
+
+const logins = new Map() // loginId → { qrcode, baseUrl, expiresAt, result }
+
+const fail = (reason, opts = {}) => Object.assign(new Error(String(reason)), opts)
+
+export default {
+ id: 'weixin',
+
+ // ---- QR login (im-login-start / im-login-wait drive these) --------------
+ async loginStart(env) {
+ const response = await env.fetch(`${qrBase(env)}ilink/bot/get_bot_qrcode?bot_type=${BOT_TYPE}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ local_token_list: [] }),
+ })
+ const body = await response.json().catch(() => ({}))
+ if (body.qrcode === undefined) throw fail(body.errmsg ?? 'WeChat did not return a code', { permanent: false })
+ const loginId = `wx_${randomBytes(8).toString('hex')}`
+ const expiresAt = Date.now() + 5 * 60_000
+ logins.set(loginId, { qrcode: String(body.qrcode), expiresAt })
+ for (const [id, held] of logins) if (held.expiresAt < Date.now()) logins.delete(id)
+ return { loginId, qr: String(body.qrcode_img_content ?? body.qrcode), expiresAt }
+ },
+
+ async loginWait(loginId, env) {
+ const held = logins.get(String(loginId))
+ if (held === undefined) return { status: 'expired' }
+ if (held.expiresAt < Date.now()) { logins.delete(String(loginId)); return { status: 'expired' } }
+ const response = await env.fetch(`${qrBase(env)}ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(held.qrcode)}`, {
+ signal: AbortSignal.timeout?.(POLL_TIMEOUT_MS) ?? undefined,
+ }).catch(() => undefined)
+ const body = await response?.json().catch(() => ({})) ?? {}
+ const status = String(body.status ?? 'wait')
+ if (status === 'expired' || status === 'invalid') { logins.delete(String(loginId)); return { status: 'expired' } }
+ if (status === 'scaned' || status === 'scaned_but_redirect' || status === 'binded_redirect') return { status: 'scanned' }
+ if (status !== 'confirmed') return { status: 'waiting' }
+ logins.delete(String(loginId))
+ return {
+ status: 'done',
+ connection: {
+ settings: { baseUrl: String(body.baseurl ?? QR_BASE) },
+ secrets: { token: String(body.bot_token ?? '') },
+ account: { id: String(body.ilink_bot_id ?? ''), name: '微信' },
+ },
+ owner: { id: String(body.ilink_user_id ?? ''), name: String(body.ilink_user_id ?? '') },
+ }
+ },
+
+ // The token is proven by a short getupdates poll: ret 0 is a valid bot.
+ async check(fields, env) {
+ const answer = await request(env, base(env, fields), fields.token, 'getupdates', { get_updates_buf: '', timeout_ms: 0 }, 8_000)
+ if (Number(answer.ret) !== 0) throw fail(`WeChat answered ${answer.ret}`, { permanent: true })
+ return { account: { id: String(fields.ilinkBotId ?? ''), name: '微信' } }
+ },
+
+ // -------------------------------------------------------------------------
+ connect(fields, env, handlers) {
+ let stopped = false
+ let running = false
+ let generation = 0
+
+ const runtime = () => env.runtime.get()
+ const setRuntime = patch => env.runtime.set(patch)
+ const contextTokens = () => runtime().contextTokens ?? {}
+ const remember = (userId, token) => {
+ if (token === undefined || token === '') return
+ const next = { ...contextTokens(), [userId]: token }
+ setRuntime({ contextTokens: next })
+ }
+
+ const deliver = async (msg) => {
+ const userId = String(msg.from_user_id ?? '')
+ if (userId === '') return
+ remember(userId, msg.context_token)
+ const images = []
+ const files = []
+ const texts = []
+ for (const item of msg.item_list ?? []) {
+ if (item.type === 1 && item.text_item?.text !== undefined) texts.push(String(item.text_item.text))
+ // Voice items carry their transcript in voice_item.text.
+ else if (item.type === 3 && item.voice_item?.text !== undefined) texts.push(String(item.voice_item.text))
+ else if (item.type === 2 && item.image_item?.media !== undefined) {
+ const bytes = await image(item.image_item.media, env).catch(() => undefined)
+ if (bytes !== undefined) images.push({ mediaType: 'image/jpeg', data: bytes.toString('base64') })
+ }
+ else if (item.type === 4 && item.file_item !== undefined) files.push({ name: String(item.file_item.file_name ?? 'file'), data: undefined })
+ }
+ await handlers.onMessage({
+ chat: { key: userId, kind: 'direct', title: '' },
+ sender: { id: userId, name: userId },
+ text: texts.join('\n').trim(), images, files,
+ mentioned: false, messageId: String(msg.client_id ?? msg.message_id ?? ''),
+ })
+ }
+
+ const poll = async () => {
+ if (running || stopped) return
+ running = true
+ const gen = generation
+ try {
+ while (!stopped && generation === gen) {
+ let answer
+ try {
+ answer = await request(env, base(env, fields), fields.token, 'getupdates', { get_updates_buf: runtime().cursor ?? '' }, POLL_TIMEOUT_MS + 15_000)
+ } catch (error) {
+ if (stopped || generation !== gen) return
+ if (error?.timeout) { continue }
+ env.log?.warn?.('ds-bot im: weixin poll failed: %s', error?.message ?? error)
+ handlers.onStatus({ state: error.permanent ? 'error' : 'connecting', ...(error.permanent ? { error: error.message } : {}) })
+ if (error.permanent) return
+ await sleep(3000)
+ continue
+ }
+ if (Number(answer.ret) !== 0) {
+ env.log?.warn?.('ds-bot im: weixin getupdates answered %s', answer.ret)
+ if (Number(answer.ret) === 401 || Number(answer.ret) === 403) {
+ handlers.onStatus({ state: 'error', error: `WeChat answered ${answer.ret}` })
+ return
+ }
+ await sleep(3000)
+ continue
+ }
+ handlers.onStatus({ state: 'ready' })
+ if (answer.get_updates_buf !== undefined && answer.get_updates_buf !== runtime().cursor) {
+ setRuntime({ cursor: String(answer.get_updates_buf) })
+ }
+ for (const msg of answer.msgs ?? []) {
+ await deliver(msg).catch(error => env.log?.warn?.('ds-bot im: weixin message failed: %s', error?.message ?? error))
+ }
+ }
+ } finally {
+ running = false
+ }
+ }
+
+ handlers.onStatus({ state: 'connecting' })
+ void poll()
+
+ return {
+ send: async (chat, { text }) => {
+ const chunks = chunk(String(text ?? ''), TEXT_LIMIT)
+ const contextToken = contextTokens()[chat.key]
+ let messageId
+ for (const chunkText of chunks) {
+ const clientId = `ds-bot-${randomBytes(8).toString('hex')}`
+ const answer = await request(env, base(env, fields), fields.token, 'sendmessage', {
+ msg: {
+ from_user_id: '', to_user_id: chat.key, client_id: clientId,
+ message_type: 2, message_state: 2,
+ item_list: [{ type: 1, text_item: { text: chunkText } }],
+ ...(contextToken ? { context_token: contextToken } : {}),
+ },
+ })
+ if (Number(answer.ret) !== 0 && answer.ret !== undefined) {
+ throw fail(`WeChat refused the reply (${answer.errmsg ?? answer.ret})`, { permanent: true })
+ }
+ messageId = clientId
+ }
+ return { messageId }
+ },
+ typing: async (chat) => {
+ const answer = await request(env, base(env, fields), fields.token, 'getconfig', { ilink_user_id: chat.key }, 8_000).catch(() => undefined)
+ const ticket = String(answer?.typing_ticket ?? '')
+ if (ticket === '') return
+ await request(env, base(env, fields), fields.token, 'sendtyping', { ilink_user_id: chat.key, typing_ticket: ticket, status: 1 }, 8_000).catch(() => {})
+ },
+ stop: () => {
+ stopped = true
+ generation += 1
+ },
+ }
+ },
+}
+
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
+
+// Text chunks: paragraphs/lines first, a hard cut at the limit otherwise.
+const chunk = (text, limit) => {
+ const chunks = []
+ let rest = String(text)
+ while (rest !== '') {
+ if (rest.length <= limit) { chunks.push(rest); break }
+ let at = limit
+ const newline = rest.lastIndexOf('\n', at)
+ if (newline > limit / 2) at = newline
+ else {
+ const space = rest.lastIndexOf(' ', at)
+ if (space > limit / 2) at = space
+ }
+ chunks.push(rest.slice(0, at))
+ rest = rest.slice(at).replace(/^\s+/, '')
+ }
+ return chunks
+}
+
+async function request(env, baseUrl, token, endpoint, body, timeoutMs = POLL_TIMEOUT_MS) {
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs)
+ timer.unref?.()
+ let response
+ try {
+ response = await env.fetch(`${baseUrl}ilink/bot/${endpoint}`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ ...(token ? { authorization: `Bearer ${token}`, AuthorizationType: 'ilink_bot_token' } : {}),
+ },
+ body: JSON.stringify({ ...body, base_info: baseInfo() }),
+ signal: controller.signal,
+ })
+ } catch (error) {
+ const timedOut = error?.name === 'AbortError' || /timeout|aborted/i.test(String(error?.message))
+ throw Object.assign(new Error(timedOut ? 'timeout' : String(error?.message ?? error)), { timeout: timedOut })
+ } finally {
+ clearTimeout(timer)
+ }
+ const json = await response.json().catch(() => ({}))
+ if (response.status === 429 || json.ret === 429) throw fail('WeChat rate limited the request', { retryAfter: Number(response.headers.get('retry-after')) })
+ if (response.status === 401 || response.status === 403) throw fail('WeChat refused the token', { permanent: true })
+ if (!response.ok) throw fail(`WeChat answered ${response.status}`)
+ return json
+}
+
+// Inbound images: the CDN URL plus a base64 AES-128 key (ECB, PKCS7).
+async function image(media, env) {
+ const url = String(media.full_url ?? media.url ?? '')
+ if (url === '') return undefined
+ const response = await env.fetch(url)
+ if (!response.ok) return undefined
+ const encrypted = Buffer.from(await response.arrayBuffer())
+ const hex = Buffer.from(String(media.aes_key ?? ''), 'base64').toString('utf8')
+ const key = /^[0-9a-f]{32}$/i.test(hex) ? Buffer.from(hex, 'hex') : undefined
+ if (key === undefined) return encrypted
+ const decipher = createDecipheriv('aes-128-ecb', key, null)
+ return Buffer.concat([decipher.update(encrypted), decipher.final()])
+}
diff --git a/ds-bot/test/fake-ws.js b/ds-bot/test/fake-ws.js
index 37009232..551f33b5 100644
--- a/ds-bot/test/fake-ws.js
+++ b/ds-bot/test/fake-ws.js
@@ -34,7 +34,7 @@ export function fakeWsServer({ onSocket, onRequest } = {}) {
const accept = createHash('sha1').update(key + GUID).digest('base64')
socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`)
const ws = {
- send: text => socket.write(encode(text)),
+ send: data => socket.write(encode(data, Buffer.isBuffer(data) ? 0x82 : 0x81)),
close: (code = 1000) => {
try { socket.write(encode('', 0x88)) } catch { /* down */ }
try { socket.destroy() } catch { /* down */ }
@@ -74,9 +74,10 @@ export function fakeWsServer({ onSocket, onRequest } = {}) {
if (opcode === 9) { socket.write(encode('', 0x8a)); continue }
pieces.push(payload)
if (!fin) continue
- const text = Buffer.concat(pieces).toString('utf8')
+ const joined = Buffer.concat(pieces)
pieces.length = 0
- for (const fn of ws.listeners.message) fn(text)
+ const body = opcode === 2 ? joined : joined.toString('utf8')
+ for (const fn of ws.listeners.message) fn(body)
}
})
socket.on('close', () => { for (const fn of ws.listeners.close) fn() })
diff --git a/ds-bot/test/im-feishu.test.js b/ds-bot/test/im-feishu.test.js
new file mode 100644
index 00000000..7f4f5421
--- /dev/null
+++ b/ds-bot/test/im-feishu.test.js
@@ -0,0 +1,156 @@
+import assert from 'node:assert/strict'
+import { createServer } from 'node:http'
+import { test } from 'node:test'
+import feishu, { decodeFrame, encodeFrame } from '../src/host/im/platforms/feishu.js'
+import { fakeWsServer } from './fake-ws.js'
+
+// A fake Feishu: OpenAPI answers the tenant token, bot info and message calls;
+// the endpoint hands back the fake socket and the test pushes protobuf frames.
+async function fakeFeishu() {
+ const calls = []
+ const frames = []
+ const replies = {}
+ const http = createServer((req, res) => {
+ let body = ''
+ req.on('data', chunk => { body += chunk })
+ req.on('end', () => {
+ const params = JSON.parse(body || '{}')
+ calls.push({ method: req.method, path: req.url, params, auth: req.headers.authorization })
+ let answer = replies[req.url]
+ if (answer === undefined && req.url === '/open-apis/auth/v3/tenant_access_token/internal') answer = { result: { tenant_access_token: 'fs-tok', expire: 7200 } }
+ if (answer === undefined && req.url === '/open-apis/bot/v3/info') answer = { result: { code: 0, bot: { open_id: 'ou_bot', app_name: 'fakebot' } } }
+ if (answer === undefined && req.url === '/open-apis/bot/v2/endpoint') answer = { result: { code: 0, data: { URL: wss.url } } }
+ if (typeof answer === 'function') answer = answer(params)
+ if (answer === undefined) answer = { result: { code: 0, data: { message_id: 'om_x' } } }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify(answer.result))
+ })
+ })
+ const wss = await fakeWsServer({
+ onSocket(ws) {
+ ws.on('message', (raw) => {
+ const frame = decodeFrame(Buffer.isBuffer(raw) ? raw : Buffer.from(String(raw), 'utf8'))
+ frames.push({ ws, frame })
+ })
+ ws.send(encodeFrame({ SeqID: 1, LogID: 2, service: 100, method: 0, headers: [{ key: 'type', value: 'ping' }], payload: Buffer.from('ping') }))
+ },
+ })
+ await new Promise(resolve => http.listen(0, '127.0.0.1', resolve))
+ return {
+ api: `http://127.0.0.1:${http.address().port}`,
+ calls, replies, frames,
+ sockets: wss.sockets,
+ push: (ws, frame) => ws.send(encodeFrame(frame)),
+ dataFrame: (type, payload, extra = {}) => ({
+ SeqID: 9, LogID: 9, service: 100, method: 1,
+ headers: [{ key: 'type', value: type }, { key: 'message_id', value: extra.messageId ?? 'fm1' }, ...(extra.headers ?? [])],
+ payload: Buffer.from(JSON.stringify(payload)),
+ }),
+ close: () => { wss.close(); http.closeAllConnections?.(); http.close() },
+ }
+}
+
+const env = (fake) => ({
+ fetch: globalThis.fetch,
+ WebSocket: globalThis.WebSocket,
+ config: { api: fake.api },
+ runtime: { get: () => ({}), set: () => {} },
+ log: { warn: (...args) => console.error('[im-feishu]', ...args) },
+})
+const FIELDS = { appId: 'cli_a1', appSecret: 'sec' }
+
+const until = async (fn, tries = 80) => {
+ for (let at = 0; at < tries; at += 1) {
+ const value = await fn()
+ if (value !== undefined && value !== false) return value
+ await new Promise(done => setTimeout(done, 50))
+ }
+ return undefined
+}
+
+const message = (body) => ({
+ header: { event_type: 'im.message.receive_v1' },
+ event: {
+ sender: { sender_id: { open_id: 'ou_u1' } },
+ message: body,
+ },
+})
+
+test('check asks for a tenant token and names the bot', async () => {
+ const fake = await fakeFeishu()
+ const { account } = await feishu.check(FIELDS, env(fake))
+ assert.equal(account.id, 'ou_bot')
+ assert.equal(account.name, 'fakebot')
+ const token = fake.calls.find(call => call.path === '/open-apis/auth/v3/tenant_access_token/internal')
+ assert.equal(token.params.app_id, 'cli_a1')
+ await fake.close()
+})
+
+test('a ping gets a pong, a p2p is direct, a group counts only with a mention, data frames are ACKed', async (t) => {
+ const fake = await fakeFeishu()
+ const messages = []
+ const handle = feishu.connect(FIELDS, env(fake), { onMessage: async msg => { messages.push(msg) }, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ await until(() => fake.calls.some(call => call.path === '/open-apis/bot/v2/endpoint'))
+ // The ping sent on connect gets a pong back.
+ await until(() => fake.frames.some(({ frame }) => frame.method === 0 && frame.headers.some(h => h.key === 'type' && h.value === 'pong')))
+ fake.push(ws, fake.dataFrame('event', message({ chat_type: 'p2p', chat_id: 'oc_1', message_id: 'om_1', message_type: 'text', content: JSON.stringify({ text: 'hello' }) }), { messageId: 'fm1' }))
+ fake.push(ws, fake.dataFrame('event', message({ chat_type: 'group', chat_id: 'oc_2', message_id: 'om_2', message_type: 'text', content: JSON.stringify({ text: '@_user_1 ping' }), mentions: [{ key: '@_user_1', id: { open_id: 'ou_bot' } }] }), { messageId: 'fm2' }))
+ fake.push(ws, fake.dataFrame('event', message({ chat_type: 'group', chat_id: 'oc_2', message_id: 'om_3', message_type: 'text', content: JSON.stringify({ text: 'noise' }), mentions: [] }), { messageId: 'fm3' }))
+ await until(() => messages.length === 3)
+ assert.equal(messages[0].chat.kind, 'direct')
+ assert.equal(messages[1].chat.kind, 'group')
+ assert.equal(messages[1].mentioned, true)
+ assert.equal(messages[1].text, 'ping')
+ assert.equal(messages[2].mentioned, false)
+ // Each data frame was ACKed back with the {"code":200} payload.
+ await until(() => fake.frames.filter(({ frame }) => frame.method === 1 && frame.headers.some(h => h.key === 'biz_rt')).length === 3)
+})
+
+test('a card action reports the button data', async (t) => {
+ const fake = await fakeFeishu()
+ const actions = []
+ const handle = feishu.connect(FIELDS, env(fake), { onMessage: () => {}, onAction: async action => { actions.push(action) }, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ await until(() => fake.sockets.length === 1)
+ fake.push(ws, fake.dataFrame('card', {
+ header: { event_type: 'card.action.trigger' },
+ event: { action: { value: { v: 'q:q1:0' } }, operator: { open_id: 'ou_u1' }, context: { open_chat_id: 'oc_1' }, message_id: 'om_9' },
+ }, { messageId: 'fm9' }))
+ await until(() => actions.length === 1)
+ assert.equal(actions[0].data, 'q:q1:0')
+ assert.equal(actions[0].messageId, 'om_9')
+})
+
+test('send posts text and an interactive card, edit patches the message', async (t) => {
+ const fake = await fakeFeishu()
+ const handle = feishu.connect(FIELDS, env(fake), { onMessage: () => {}, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ await until(() => fake.sockets[0])
+ await until(() => fake.calls.some(call => call.path === '/open-apis/bot/v3/info'))
+ const { messageId } = await handle.send({ key: 'oc_1', kind: 'direct' }, { text: 'hello', buttons: [{ data: 'q:q1:0', label: 'yes' }] })
+ const post = fake.calls.find(call => call.path.startsWith('/open-apis/im/v1/messages?'))
+ assert.ok(post, 'messages POST called')
+ assert.equal(post.params.receive_id, 'oc_1')
+ assert.equal(post.params.msg_type, 'interactive')
+ const card = JSON.parse(post.params.content)
+ const action = card.body.elements.at(-1)
+ assert.equal(action.tag, 'action')
+ assert.equal(action.actions[0].value.v, 'q:q1:0')
+ assert.equal(messageId, 'om_x')
+ await handle.edit({ key: 'oc_1', kind: 'direct' }, 'om_9', { text: 'done', buttons: [] })
+ const patch = fake.calls.find(call => call.method === 'PATCH' && call.path === '/open-apis/im/v1/messages/om_9')
+ assert.ok(patch, 'message PATCH called')
+})
+
+test('a dropped socket reconnects through a fresh endpoint', async (t) => {
+ const fake = await fakeFeishu()
+ const handle = feishu.connect(FIELDS, env(fake), { onMessage: () => {}, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ ws.close()
+ await until(() => fake.sockets.length === 2)
+ assert.ok(fake.calls.filter(call => call.path === '/open-apis/bot/v2/endpoint').length >= 2)
+})
diff --git a/ds-bot/test/im-wecom.test.js b/ds-bot/test/im-wecom.test.js
index c865800e..4146a30c 100644
--- a/ds-bot/test/im-wecom.test.js
+++ b/ds-bot/test/im-wecom.test.js
@@ -48,6 +48,32 @@ const until = async (fn, tries = 80) => {
return undefined
}
+test('check subscribes over a throwaway socket: success returns the account, failure throws the reason', async () => {
+ const fake = await fakeWecom()
+ const { account } = await wecom.check(FIELDS, env(fake))
+ assert.deepEqual(account, { id: 'bot-1', name: 'bot-1' })
+ assert.ok(fake.packets.some(packet => packet.cmd === 'aibot_subscribe' && packet.body.secret === 'sec-1'))
+ await fake.close()
+ const refused = await fakeWsServer({
+ onSocket(ws) {
+ ws.on('message', (raw) => {
+ const packet = JSON.parse(raw)
+ if (packet.cmd === 'aibot_subscribe') {
+ ws.send(JSON.stringify({ headers: { req_id: packet.headers.req_id }, errcode: 60111, errmsg: 'invalid bot' }))
+ }
+ })
+ },
+ })
+ await assert.rejects(
+ () => wecom.check(FIELDS, {
+ fetch: globalThis.fetch, WebSocket: globalThis.WebSocket,
+ config: { gateway: refused.url.replace('/wss', '') }, runtime: { get: () => ({}), set: () => {} },
+ }),
+ /invalid bot/,
+ )
+ refused.close()
+})
+
test('the socket subscribes with the bot id and secret and goes ready', async (t) => {
const fake = await fakeWecom()
const statuses = []
diff --git a/ds-bot/test/im-weixin.test.js b/ds-bot/test/im-weixin.test.js
new file mode 100644
index 00000000..92e6a88d
--- /dev/null
+++ b/ds-bot/test/im-weixin.test.js
@@ -0,0 +1,137 @@
+import assert from 'node:assert/strict'
+import { createServer } from 'node:http'
+import { test } from 'node:test'
+import weixin from '../src/host/im/platforms/weixin.js'
+
+// A fake iLink: the QR endpoints drive the login states the test wants, the
+// getupdates long poll answers from a queued script, and sends are recorded.
+async function fakeIlink() {
+ const calls = []
+ const replies = {}
+ let updates = []
+ const http = createServer((req, res) => {
+ let body = ''
+ req.on('data', chunk => { body += chunk })
+ req.on('end', () => {
+ const params = JSON.parse(body || '{}')
+ calls.push({ method: req.method, path: req.url, params, auth: req.headers.authorization })
+ if (req.url.startsWith('/ilink/bot/get_bot_qrcode')) {
+ const answer = replies.qrcode ?? { qrcode: 'qr-tok-1', qrcode_img_content: 'weixin://qr/abc' }
+ res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(answer))
+ return
+ }
+ if (req.url.startsWith('/ilink/bot/get_qrcode_status')) {
+ const status = (replies.statuses ?? ['wait']).shift() ?? replies.lastStatus ?? 'wait'
+ res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(typeof status === 'object' ? status : { status }))
+ return
+ }
+ if (req.url === '/ilink/bot/getupdates') {
+ const answer = replies.updatesShift ?? updates.shift() ?? replies.updates ?? { ret: 0, msgs: [], get_updates_buf: 'c1' }
+ if (typeof answer === 'function') { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(answer(params))); return }
+ res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(answer))
+ return
+ }
+ const answer = replies[req.url] ?? { ret: 0 }
+ res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(answer))
+ })
+ })
+ await new Promise(resolve => http.listen(0, '127.0.0.1', resolve))
+ return {
+ base: `http://127.0.0.1:${http.address().port}/`,
+ calls, replies,
+ queue: items => { updates = items },
+ close: () => { http.closeAllConnections?.(); http.close() },
+ }
+}
+
+const env = (fake, runtime = {}) => ({
+ fetch: globalThis.fetch,
+ WebSocket: globalThis.WebSocket,
+ config: { api: fake.base, qr: fake.base },
+ runtime: { get: () => runtime, set: patch => Object.assign(runtime, patch) },
+ log: { warn: (...args) => console.error('[im-weixin]', ...args) },
+})
+const FIELDS = { token: 'wx-tok', baseUrl: '' }
+
+const until = async (fn, tries = 80) => {
+ for (let at = 0; at < tries; at += 1) {
+ const value = await fn()
+ if (value !== undefined && value !== false) return value
+ await new Promise(done => setTimeout(done, 50))
+ }
+ return undefined
+}
+
+test('login start returns a code, wait reports waiting then scanned then done with the owner', async () => {
+ const fake = await fakeIlink()
+ fake.replies.statuses = [
+ 'wait',
+ 'scaned',
+ { status: 'confirmed', bot_token: 'wx-tok', baseurl: fake.base, ilink_bot_id: 'bot-9', ilink_user_id: 'owner-1' },
+ ]
+ const { loginId, qr, expiresAt } = await weixin.loginStart(env(fake))
+ assert.equal(qr, 'weixin://qr/abc')
+ assert.ok(expiresAt > Date.now())
+ assert.equal((await weixin.loginWait(loginId, env(fake))).status, 'waiting')
+ assert.equal((await weixin.loginWait(loginId, env(fake))).status, 'scanned')
+ const done = await weixin.loginWait(loginId, env(fake))
+ assert.equal(done.status, 'done')
+ assert.deepEqual(done.owner, { id: 'owner-1', name: 'owner-1' })
+ assert.equal(done.connection.secrets.token, 'wx-tok')
+ assert.equal(done.connection.account.id, 'bot-9')
+ assert.equal(done.connection.settings.baseUrl, fake.base)
+ await fake.close()
+})
+
+test('getupdates keeps the cursor and context_token in runtime and delivers text and voice', async (t) => {
+ const fake = await fakeIlink()
+ const runtime = {}
+ const messages = []
+ fake.replies.updates = (params) => {
+ if (params.get_updates_buf === 'c1') return { ret: 0, msgs: [], get_updates_buf: 'c1' }
+ return {
+ ret: 0, get_updates_buf: 'c1',
+ msgs: [
+ { from_user_id: 'u1', client_id: 'm1', context_token: 'tok-u1', item_list: [{ type: 1, text_item: { text: 'hello' } }] },
+ { from_user_id: 'u1', client_id: 'm2', context_token: 'tok-u1', item_list: [{ type: 3, voice_item: { text: 'a voice transcript' } }] },
+ ],
+ }
+ }
+ const handle = weixin.connect(FIELDS, env(fake, runtime), { onMessage: async msg => { messages.push(msg) }, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ await until(() => messages.length === 2)
+ assert.equal(runtime.cursor, 'c1')
+ assert.deepEqual(runtime.contextTokens, { u1: 'tok-u1' })
+ assert.equal(messages[0].chat.kind, 'direct')
+ assert.equal(messages[0].text, 'hello')
+ assert.equal(messages[1].text, 'a voice transcript')
+})
+
+test('send goes through sendmessage with the stored context_token, chunked at the limit', async (t) => {
+ const fake = await fakeIlink()
+ const runtime = { cursor: 'c1', contextTokens: { u1: 'tok-u1' } }
+ fake.replies.updates = { ret: 0, msgs: [], get_updates_buf: 'c1' }
+ const handle = weixin.connect(FIELDS, env(fake, runtime), { onMessage: () => {}, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ await until(() => fake.calls.some(call => call.path === '/ilink/bot/getupdates'))
+ const { messageId } = await handle.send({ key: 'u1', kind: 'direct' }, { text: 'x'.repeat(4000) })
+ const sends = fake.calls.filter(call => call.path === '/ilink/bot/sendmessage')
+ assert.ok(sends.length >= 2, 'chunked at the limit')
+ assert.equal(sends[0].params.msg.to_user_id, 'u1')
+ assert.equal(sends[0].params.msg.context_token, 'tok-u1')
+ assert.equal(sends[0].params.msg.item_list[0].type, 1)
+ assert.ok(messageId.startsWith('ds-bot-'))
+})
+
+test('a refused send is permanent, and the auth header carries the token', async (t) => {
+ const fake = await fakeIlink()
+ const runtime = { cursor: 'c1' }
+ fake.replies.updates = { ret: 0, msgs: [] }
+ const handle = weixin.connect(FIELDS, env(fake, runtime), { onMessage: () => {}, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ await until(() => fake.calls.some(call => call.path === '/ilink/bot/getupdates'))
+ fake.replies['/ilink/bot/sendmessage'] = { ret: -2, errmsg: 'msg out of window' }
+ await assert.rejects(() => handle.send({ key: 'u1', kind: 'direct' }, { text: 'late' }),
+ error => error.permanent === true && /window/.test(error.message))
+ assert.equal(fake.calls[0].auth, 'Bearer wx-tok')
+})
diff --git a/ds-bot/test/im.test.js b/ds-bot/test/im.test.js
index 58a48f9f..8f1fb7d1 100644
--- a/ds-bot/test/im.test.js
+++ b/ds-bot/test/im.test.js
@@ -488,3 +488,35 @@ test('a permanent send error shows in the status and is not retried; a network e
await delay(20)
await s.rt.imEndpoint('im-retry', { id: conn.id })
})
+
+test('a weixin QR login creates the connection paired with the scanning owner', async (t) => {
+ const s = await start({ platform: 'weixin', adapter: {
+ ...fakeAdapter(),
+ id: 'weixin',
+ async loginStart(env) { return { loginId: 'l1', qr: 'weixin://qr/abc', expiresAt: Date.now() + 60_000 } },
+ async loginWait(loginId, env) {
+ this.waits = (this.waits ?? 0) + 1
+ if (this.waits < 2) return { status: 'waiting' }
+ return {
+ status: 'done',
+ connection: { settings: { baseUrl: 'http://ilink/' }, secrets: { token: 'wx-tok' }, account: { id: 'bot-9', name: 'wxbot' } },
+ owner: { id: 'owner-1', name: 'Fei' },
+ }
+ },
+ } })
+ t.after(s.stop)
+ const login = await s.rt.imEndpoint('im-login-start', { platform: 'weixin', botId: 'a' })
+ assert.equal(login.qr, 'weixin://qr/abc')
+ const waiting = await s.rt.imEndpoint('im-login-wait', { platform: 'weixin', botId: 'a', loginId: 'l1' })
+ assert.deepEqual(waiting, { status: 'waiting' })
+ const done = await s.rt.imEndpoint('im-login-wait', { platform: 'weixin', botId: 'a', loginId: 'l1' })
+ assert.equal(done.status, 'done')
+ const conn = s.rt.state.im.connections[done.id]
+ assert.ok(conn, 'connection created on confirm')
+ assert.equal(conn.platform, 'weixin')
+ assert.deepEqual(conn.paired, [{ id: 'owner-1', name: 'Fei', at: conn.paired[0].at }])
+ assert.equal(conn.chats['owner-1'].kind, 'direct')
+ assert.equal(conn.secrets.token, `IM_WEIXIN_${conn.id.slice(3, 9).toUpperCase()}_TOKEN`, 'the token is stored as a secret')
+ assert.equal(s.rt.secretValue(conn.secrets.token), 'wx-tok')
+ assert.equal(conn.settings.baseUrl, 'http://ilink/')
+})