From e67385e076c9c9ba481da5cfa8d989ac51dd562d Mon Sep 17 00:00:00 2001 From: echohn Date: Tue, 22 Sep 2026 21:20:17 +0800 Subject: [PATCH 01/10] feat(channel): add DingTalk channel plugin (Stream mode) Connect Cola to DingTalk via an enterprise internal application robot using the official Stream mode (outbound WebSocket, no public callback). - Gateway: DWClient Stream lifecycle (initial backoff loop + SDK auto-reconnect), TOPIC_ROBOT message parsing (direct/group branch, @bot prefix strip, non-text fallback), msgId-level dedup, real connection-state reporting (socket-open based; DingTalk's stream gateway does not push REGISTERED system frames) - Outbound: access-token manager (7200s in-memory cache, refresh coalescing), oToMessages/groupMessages send, text/markdown, 15000-byte UTF-8-safe msgParam guard - Group chats opt-in (groupEnabled); non-owner group @mentions are annotated with sender identity and a scope constraint line (configurable ownerStaffId) - Auth: SDK access gate with polite secretary-style hints, 6 locales (en/es/ja/ko/zh-CN/zh-TW) - Tests: 57 unit tests (parsing, token cache, client payloads, dedup, status); all fixtures use fake credentials - Verified: typecheck/build/lint/fmt/test all green; live-tested against a real DingTalk org (direct + group) Closes nothing; media send/receive planned for a follow-up. --- plugins/dingtalk/README.md | 58 +++ plugins/dingtalk/locales/en.json | 26 ++ plugins/dingtalk/locales/es.json | 26 ++ plugins/dingtalk/locales/ja.json | 26 ++ plugins/dingtalk/locales/ko.json | 26 ++ plugins/dingtalk/locales/zh-CN.json | 26 ++ plugins/dingtalk/locales/zh-TW.json | 26 ++ plugins/dingtalk/package.json | 51 +++ plugins/dingtalk/src/api/client.ts | 174 +++++++++ plugins/dingtalk/src/api/token.ts | 74 ++++ plugins/dingtalk/src/api/types.ts | 13 + plugins/dingtalk/src/auth/accounts.ts | 19 + plugins/dingtalk/src/commands/dingtalk.ts | 92 +++++ .../dingtalk/src/gateway/connection-error.ts | 25 ++ plugins/dingtalk/src/gateway/dedup.ts | 27 ++ plugins/dingtalk/src/gateway/event-handler.ts | 150 ++++++++ plugins/dingtalk/src/gateway/message.ts | 146 ++++++++ plugins/dingtalk/src/gateway/monitor.ts | 244 +++++++++++++ plugins/dingtalk/src/index.ts | 244 +++++++++++++ plugins/dingtalk/src/outbound/send.ts | 40 ++ plugins/dingtalk/src/util/redact.ts | 4 + plugins/dingtalk/tests/client.test.ts | 142 ++++++++ plugins/dingtalk/tests/config.test.ts | 54 +++ plugins/dingtalk/tests/gateway-status.test.ts | 341 ++++++++++++++++++ plugins/dingtalk/tests/message.test.ts | 161 +++++++++ plugins/dingtalk/tests/token.test.ts | 113 ++++++ plugins/dingtalk/tsconfig.json | 4 + plugins/dingtalk/tsup.config.ts | 10 + pnpm-lock.yaml | 44 ++- 29 files changed, 2381 insertions(+), 5 deletions(-) create mode 100644 plugins/dingtalk/README.md create mode 100644 plugins/dingtalk/locales/en.json create mode 100644 plugins/dingtalk/locales/es.json create mode 100644 plugins/dingtalk/locales/ja.json create mode 100644 plugins/dingtalk/locales/ko.json create mode 100644 plugins/dingtalk/locales/zh-CN.json create mode 100644 plugins/dingtalk/locales/zh-TW.json create mode 100644 plugins/dingtalk/package.json create mode 100644 plugins/dingtalk/src/api/client.ts create mode 100644 plugins/dingtalk/src/api/token.ts create mode 100644 plugins/dingtalk/src/api/types.ts create mode 100644 plugins/dingtalk/src/auth/accounts.ts create mode 100644 plugins/dingtalk/src/commands/dingtalk.ts create mode 100644 plugins/dingtalk/src/gateway/connection-error.ts create mode 100644 plugins/dingtalk/src/gateway/dedup.ts create mode 100644 plugins/dingtalk/src/gateway/event-handler.ts create mode 100644 plugins/dingtalk/src/gateway/message.ts create mode 100644 plugins/dingtalk/src/gateway/monitor.ts create mode 100644 plugins/dingtalk/src/index.ts create mode 100644 plugins/dingtalk/src/outbound/send.ts create mode 100644 plugins/dingtalk/src/util/redact.ts create mode 100644 plugins/dingtalk/tests/client.test.ts create mode 100644 plugins/dingtalk/tests/config.test.ts create mode 100644 plugins/dingtalk/tests/gateway-status.test.ts create mode 100644 plugins/dingtalk/tests/message.test.ts create mode 100644 plugins/dingtalk/tests/token.test.ts create mode 100644 plugins/dingtalk/tsconfig.json create mode 100644 plugins/dingtalk/tsup.config.ts diff --git a/plugins/dingtalk/README.md b/plugins/dingtalk/README.md new file mode 100644 index 0000000..3a76e89 --- /dev/null +++ b/plugins/dingtalk/README.md @@ -0,0 +1,58 @@ +# DingTalk Channel Plugin + +Connect Cola to DingTalk through an enterprise internal application robot using +the Stream mode (outbound WebSocket). No public callback URL, domain, or TLS +certificate is required. + +## Features + +- Receives robot messages (direct chats and @-mentions in group chats) over a + managed Stream WebSocket connection with automatic reconnect. +- Sends Cola replies back to the originating DingTalk conversation: + `oToMessages` for direct chats, `groupMessages` for group chats. +- Sends Markdown replies when the model output is markdown-capable. +- Group chat is opt-in via `groupEnabled`; DingTalk itself only pushes group + messages that @-mention the robot. + +## Requirements + +- An enterprise internal application on the + [DingTalk Open Platform](https://open-dev.dingtalk.com) with: + - The **robot** application capability added, with the message receive mode + set to **Stream mode**. + - A **published version** (unpublished robots do not receive + `senderStaffId`, which is required for direct-chat replies). + - The **enterprise robot message sending** permission granted. +- The application's **Client ID (AppKey)** and **Client Secret (AppSecret)**. + +## Setup + +1. In the DingTalk Open Platform console, create (or reuse) an enterprise + internal application and copy the Client ID and Client Secret. +2. Under **Application capabilities**, add the **robot** capability and select + **Stream mode** as the message receive mode, then publish the application + version. +3. Under **Permissions**, grant the enterprise robot message sending + permission. +4. Install the DingTalk plugin in Cola and enter the Client ID and Client + Secret in the plugin settings. +5. For group chats, add the robot to the target group (group settings → + robots) and enable `groupEnabled` in the plugin settings. Users must + @-mention the robot in groups. +6. Check `/dingtalk status` in Cola. + +## Notes and limits + +- The Stream channel is receive-only: replies are sent through the DingTalk + REST API with an access token cached for its 2-hour validity window. +- Group message payloads are limited to 15000 bytes by DingTalk; Cola splits + longer replies. +- Incoming images, files, audio, and video are delivered as text summaries in + the first release; media download and upload are planned for a later version. +- Treat the Client Secret as a credential: it is stored in Cola's secret + configuration fields and is never written to logs or files. + +## Security + +Do not commit Client ID/Secret values, session webhooks, or message content. +The plugin never persists credentials outside Cola's encrypted configuration. diff --git a/plugins/dingtalk/locales/en.json b/plugins/dingtalk/locales/en.json new file mode 100644 index 0000000..c67d397 --- /dev/null +++ b/plugins/dingtalk/locales/en.json @@ -0,0 +1,26 @@ +{ + "label": "DingTalk", + "description": "Chat with Cola in DingTalk", + "config.clientId": "Client ID (AppKey)", + "config.clientSecret": "Client Secret (AppSecret)", + "config.groupEnabled": "Enable group chat", + "config.ownerStaffId": "Owner Staff ID", + "status.connected": "Connected", + "status.disconnected": "Disconnected", + "status.noAccounts": "No account configured", + "status.accounts": "Connected accounts: {{count}}", + "status.connecting": "Connecting…", + "status.reconnecting": "Disconnected, reconnecting…", + "status.failed": "Connection failed", + "channel.groupDisabled": "Group chat is not enabled. Send a direct message to the bot instead.", + "auth.user": "I am the owner's work assistant and am unable to process your request for now. Your message won't be seen by the owner; if you have something urgent, please contact the owner directly.", + "auth.group": "I am the owner's work assistant and am unable to process your request for now. Your message won't be seen by the owner; if you have something urgent, please contact the owner directly.", + "error.noAccount": "No active DingTalk account", + "command.description": "{{name}} status and configuration", + "command.args": "Subcommands: {{commands}}", + "command.statusTitle": "**{{name}} Status**", + "command.configTitle": "**{{name}} Configuration**", + "command.unknown": "Unknown subcommand: {{subcommand}}. Use {{commands}}.", + "state.missing": "Missing", + "command.accountLine": "- **{{id}}**: Client ID={{clientId}}, {{status}}" +} diff --git a/plugins/dingtalk/locales/es.json b/plugins/dingtalk/locales/es.json new file mode 100644 index 0000000..8dd35c8 --- /dev/null +++ b/plugins/dingtalk/locales/es.json @@ -0,0 +1,26 @@ +{ + "label": "DingTalk", + "description": "Chatea con Cola en DingTalk", + "config.clientId": "Client ID (AppKey)", + "config.clientSecret": "Client Secret (AppSecret)", + "config.groupEnabled": "Habilitar chats de grupo", + "config.ownerStaffId": "Owner Staff ID(ID de empleado del propietario)", + "status.connected": "Conectado", + "status.disconnected": "Desconectado", + "status.noAccounts": "No hay cuentas configuradas", + "status.accounts": "Cuentas conectadas: {{count}}", + "status.connecting": "Conectando…", + "status.reconnecting": "Conexión perdida, reconectando…", + "status.failed": "Error de conexión", + "channel.groupDisabled": "Los chats de grupo no están habilitados. Envía un mensaje directo al bot.", + "auth.user": "Soy el asistente de trabajo del propietario y no puedo procesar su solicitud por ahora. El propietario no verá su mensaje; para asuntos urgentes, póngase en contacto directamente con el propietario.", + "auth.group": "Soy el asistente de trabajo del propietario y no puedo procesar su solicitud por ahora. El propietario no verá su mensaje; para asuntos urgentes, póngase en contacto directamente con el propietario.", + "error.noAccount": "No hay una cuenta de DingTalk activa", + "command.description": "Estado y configuración de {{name}}", + "command.args": "Subcomandos: {{commands}}", + "command.statusTitle": "**Estado de {{name}}**", + "command.configTitle": "**Configuración de {{name}}**", + "command.unknown": "Subcomando desconocido: {{subcommand}}. Usa {{commands}}.", + "state.missing": "Falta", + "command.accountLine": "- **{{id}}**: Client ID={{clientId}}, {{status}}" +} diff --git a/plugins/dingtalk/locales/ja.json b/plugins/dingtalk/locales/ja.json new file mode 100644 index 0000000..b8b3893 --- /dev/null +++ b/plugins/dingtalk/locales/ja.json @@ -0,0 +1,26 @@ +{ + "label": "DingTalk", + "description": "DingTalk で Cola と会話する", + "config.clientId": "Client ID(AppKey)", + "config.clientSecret": "Client Secret(AppSecret)", + "config.groupEnabled": "グループチャットを有効にする", + "config.ownerStaffId": "Owner Staff ID(所有者従業員 ID)", + "status.connected": "接続済み", + "status.disconnected": "未接続", + "status.noAccounts": "アカウントが未設定です", + "status.accounts": "接続済みアカウント数:{{count}}", + "status.connecting": "接続中…", + "status.reconnecting": "接続が切断されました。再接続中…", + "status.failed": "接続に失敗しました", + "channel.groupDisabled": "グループチャットは無効です。ボットにダイレクトメッセージを送ってください。", + "auth.user": "私は主人の仕事アシスタントです。現在はお客様のリクエストを処理できません。お客様のメッセージは主人には届きません。緊急のご用件がある場合は、直接主人にご連絡ください。", + "auth.group": "私は主人の仕事アシスタントです。現在はお客様のリクエストを処理できません。お客様のメッセージは主人には届きません。緊急のご用件がある場合は、直接主人にご連絡ください。", + "error.noAccount": "利用可能な DingTalk アカウントがありません", + "command.description": "{{name}} のステータスと設定", + "command.args": "サブコマンド:{{commands}}", + "command.statusTitle": "**{{name}} ステータス**", + "command.configTitle": "**{{name}} 設定**", + "command.unknown": "不明なサブコマンド:{{subcommand}}。{{commands}} を使用してください。", + "state.missing": "未設定", + "command.accountLine": "- **{{id}}**: Client ID={{clientId}}、{{status}}" +} diff --git a/plugins/dingtalk/locales/ko.json b/plugins/dingtalk/locales/ko.json new file mode 100644 index 0000000..e4cc749 --- /dev/null +++ b/plugins/dingtalk/locales/ko.json @@ -0,0 +1,26 @@ +{ + "label": "DingTalk", + "description": "DingTalk에서 Cola와 대화하기", + "config.clientId": "Client ID (AppKey)", + "config.clientSecret": "Client Secret (AppSecret)", + "config.groupEnabled": "그룹 채팅 사용", + "config.ownerStaffId": "Owner Staff ID(소유자 직원 ID)", + "status.connected": "연결됨", + "status.disconnected": "연결 안 됨", + "status.noAccounts": "구성된 계정이 없습니다", + "status.accounts": "연결된 계정 수: {{count}}", + "status.connecting": "연결 중…", + "status.reconnecting": "연결이 끊겼습니다. 다시 연결 중…", + "status.failed": "연결 실패", + "channel.groupDisabled": "그룹 채팅이 비활성화되어 있습니다. 봇에게 개인 메시지를 보내 주세요.", + "auth.user": "저는 주인님의 업무 비서입니다. 현재 귀하의 요청을 처리할 수 없습니다. 남기신 메시지는 주인님이 보실 수 없습니다. 긴급한 일이 있으시면 주인님께 직접 연락해 주세요.", + "auth.group": "저는 주인님의 업무 비서입니다. 현재 귀하의 요청을 처리할 수 없습니다. 남기신 메시지는 주인님이 보실 수 없습니다. 긴급한 일이 있으시면 주인님께 직접 연락해 주세요.", + "error.noAccount": "사용 가능한 DingTalk 계정이 없습니다", + "command.description": "{{name}} 상태 및 설정", + "command.args": "하위 명령: {{commands}}", + "command.statusTitle": "**{{name}} 상태**", + "command.configTitle": "**{{name}} 설정**", + "command.unknown": "알 수 없는 하위 명령: {{subcommand}}. {{commands}}를 사용하세요.", + "state.missing": "미설정", + "command.accountLine": "- **{{id}}**: Client ID={{clientId}}, {{status}}" +} diff --git a/plugins/dingtalk/locales/zh-CN.json b/plugins/dingtalk/locales/zh-CN.json new file mode 100644 index 0000000..d659dac --- /dev/null +++ b/plugins/dingtalk/locales/zh-CN.json @@ -0,0 +1,26 @@ +{ + "label": "钉钉", + "description": "在钉钉中与 Cola 对话", + "config.clientId": "Client ID(AppKey)", + "config.clientSecret": "Client Secret(AppSecret)", + "config.groupEnabled": "启用群聊", + "config.ownerStaffId": "Owner Staff ID(所有者员工 ID)", + "status.connected": "已连接", + "status.disconnected": "未连接", + "status.noAccounts": "未配置账号", + "status.accounts": "已连接账号数:{{count}}", + "status.connecting": "正在连接…", + "status.reconnecting": "连接已断开,正在重连…", + "status.failed": "连接失败", + "channel.groupDisabled": "尚未启用群聊,请私信机器人。", + "auth.user": "我是主人的工作助理,暂时不能为您处理请求。您留言的内容主人暂时看不到;如有紧急事项,建议直接联系主人本人。", + "auth.group": "我是主人的工作助理,暂时不能为您处理请求。您留言的内容主人暂时看不到;如有紧急事项,建议直接联系主人本人。", + "error.noAccount": "没有可用的钉钉账号", + "command.description": "{{name}} 状态和配置", + "command.args": "子命令:{{commands}}", + "command.statusTitle": "**{{name}} 状态**", + "command.configTitle": "**{{name}} 配置**", + "command.unknown": "未知子命令:{{subcommand}}。请使用 {{commands}}。", + "state.missing": "未填写", + "command.accountLine": "- **{{id}}**: Client ID={{clientId}},{{status}}" +} diff --git a/plugins/dingtalk/locales/zh-TW.json b/plugins/dingtalk/locales/zh-TW.json new file mode 100644 index 0000000..6ccae28 --- /dev/null +++ b/plugins/dingtalk/locales/zh-TW.json @@ -0,0 +1,26 @@ +{ + "label": "釘釘", + "description": "在釘釘中與 Cola 對話", + "config.clientId": "Client ID(AppKey)", + "config.clientSecret": "Client Secret(AppSecret)", + "config.groupEnabled": "啟用群聊", + "config.ownerStaffId": "Owner Staff ID(擁有者員工 ID)", + "status.connected": "已連線", + "status.disconnected": "未連線", + "status.noAccounts": "未設定帳號", + "status.accounts": "已連線帳號數:{{count}}", + "status.connecting": "正在連線…", + "status.reconnecting": "連線已中斷,正在重新連線…", + "status.failed": "連線失敗", + "channel.groupDisabled": "尚未啟用群聊,請私訊機器人。", + "auth.user": "我是主人的工作助理,暫時無法為您處理請求。您留言的內容主人暫時看不到;如有緊急事項,建議直接聯絡主人本人。", + "auth.group": "我是主人的工作助理,暫時無法為您處理請求。您留言的內容主人暫時看不到;如有緊急事項,建議直接聯絡主人本人。", + "error.noAccount": "沒有可用的釘釘帳號", + "command.description": "{{name}} 狀態和設定", + "command.args": "子命令:{{commands}}", + "command.statusTitle": "**{{name}} 狀態**", + "command.configTitle": "**{{name}} 設定**", + "command.unknown": "未知子命令:{{subcommand}}。請使用 {{commands}}。", + "state.missing": "未填寫", + "command.accountLine": "- **{{id}}**: Client ID={{clientId}},{{status}}" +} diff --git a/plugins/dingtalk/package.json b/plugins/dingtalk/package.json new file mode 100644 index 0000000..0ef783e --- /dev/null +++ b/plugins/dingtalk/package.json @@ -0,0 +1,51 @@ +{ + "name": "cola-plugin-dingtalk", + "version": "0.1.0", + "description": "DingTalk channel plugin for Cola", + "license": "Apache-2.0", + "type": "module", + "exports": { + ".": "./dist/index.js" + }, + "scripts": { + "build": "tsup", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@marswave/cola-plugin-sdk": "0.0.5", + "dingtalk-stream": "2.1.5" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "tsup": "^8.5.1", + "typescript": "^5.8.3" + }, + "engines": { + "node": ">=22" + }, + "cola": { + "plugin": { + "id": "dingtalk", + "entry": "./dist/index.js", + "minColaVersion": "1.4.5" + }, + "channel": { + "label": "DingTalk", + "description": "DingTalk messaging via official enterprise bot (Stream mode)", + "iconUrl": "https://www.dingtalk.com/favicon.ico", + "aliases": [ + "dingtalk" + ], + "docsPath": "https://github.com/marswaveai/cola-plugins/blob/main/plugins/dingtalk/README.md", + "i18n": { + "en": "./locales/en.json", + "es": "./locales/es.json", + "ja": "./locales/ja.json", + "ko": "./locales/ko.json", + "zh-CN": "./locales/zh-CN.json", + "zh-TW": "./locales/zh-TW.json" + } + } + } +} diff --git a/plugins/dingtalk/src/api/client.ts b/plugins/dingtalk/src/api/client.ts new file mode 100644 index 0000000..1109b65 --- /dev/null +++ b/plugins/dingtalk/src/api/client.ts @@ -0,0 +1,174 @@ +import { AccessTokenManager, type FetchLike } from "./token.js"; +import type { DingTalkAccountConfig } from "./types.js"; + +const API_BASE = "https://api.dingtalk.com"; +/** DingTalk rejects robot message payloads whose msgParam exceeds 15000 UTF-8 bytes. */ +export const MAX_MSG_PARAM_BYTES = 15000; +const TRUNCATION_SUFFIX = "…(truncated)"; + +export type OutgoingMessage = { + msgKey: string; + msgParam: string; +}; + +/** + * Build a plain-text robot message (`sampleText`). + */ +export function buildTextMessage(content: string): OutgoingMessage { + return { msgKey: "sampleText", msgParam: JSON.stringify({ content }) }; +} + +/** + * Build a markdown robot message (`sampleMarkdown`). The title is derived from + * the first meaningful line and is used by DingTalk for notification previews. + */ +export function buildMarkdownMessage(text: string): OutgoingMessage { + return { + msgKey: "sampleMarkdown", + msgParam: JSON.stringify({ title: markdownTitle(text), text }), + }; +} + +function markdownTitle(text: string): string { + const firstLine = + text + .split("\n") + .map((line) => line.replace(/[#*_>`~[\]]/g, "").trim()) + .find(Boolean) ?? ""; + if (!firstLine) return "Cola"; + return firstLine.length > 20 ? `${firstLine.slice(0, 20)}…` : firstLine; +} + +/** + * Ensure the serialized msgParam stays within DingTalk's 15000-byte budget. + * Oversized message text is truncated (UTF-8-safe via a binary search on the + * character count) rather than rejected by the API. + */ +export function enforceMsgParamLimit( + message: OutgoingMessage, + maxBytes: number = MAX_MSG_PARAM_BYTES, +): OutgoingMessage { + if (Buffer.byteLength(message.msgParam, "utf8") <= maxBytes) return message; + + const parsed = JSON.parse(message.msgParam) as Record; + const field = message.msgKey === "sampleText" ? "content" : "text"; + const original = typeof parsed[field] === "string" ? parsed[field] : ""; + if (!original) return message; // Nothing trimmable; let the API error surface. + + const fits = (length: number): boolean => { + parsed[field] = `${original.slice(0, length)}${TRUNCATION_SUFFIX}`; + return Buffer.byteLength(JSON.stringify(parsed), "utf8") <= maxBytes; + }; + + let lo = 0; + let hi = original.length; + while (lo < hi) { + const mid = Math.floor((lo + hi + 1) / 2); + if (fits(mid)) { + lo = mid; + } else { + hi = mid - 1; + } + } + fits(lo); + + return { msgKey: message.msgKey, msgParam: JSON.stringify(parsed) }; +} + +/** + * Minimal DingTalk REST client for robot message sending. The Stream channel + * is receive-only; all replies go through these REST endpoints with an access + * token from the token manager. Tokens are only sent as a request header and + * are never logged or embedded in error messages. + */ +export class DingTalkClient { + constructor( + private readonly tokenManager: AccessTokenManager, + private readonly fetchImpl: FetchLike = fetch, + ) {} + + /** Direct-chat reply via /v1.0/robot/oToMessages/batchSend. */ + async sendOToMessage( + robotCode: string, + staffId: string, + message: OutgoingMessage, + ): Promise { + await this.request("/v1.0/robot/oToMessages/batchSend", { + robotCode, + userIds: [staffId], + msgKey: message.msgKey, + msgParam: message.msgParam, + }); + } + + /** Group-chat reply via /v1.0/robot/groupMessages/send. */ + async sendGroupMessage( + robotCode: string, + openConversationId: string, + message: OutgoingMessage, + ): Promise { + await this.request("/v1.0/robot/groupMessages/send", { + robotCode, + openConversationId, + msgKey: message.msgKey, + msgParam: message.msgParam, + }); + } + + async request(path: string, body: Record): Promise { + const token = await this.tokenManager.getToken(); + let response: Response; + try { + response = await this.fetchImpl(`${API_BASE}${path}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-acs-dingtalk-access-token": token, + }, + body: JSON.stringify(body), + }); + } catch (err) { + throw new Error( + `DingTalk API ${path} request failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + if (!response.ok) { + const detail = (await response.text().catch(() => "")).slice(0, 300); + throw new Error( + `DingTalk API ${path} failed with HTTP ${response.status}${detail ? `: ${detail}` : ""}`, + ); + } + return response.json().catch(() => undefined); + } +} + +type CachedEntry = { + client: DingTalkClient; + clientId: string; + clientSecret: string; +}; + +const clientCache = new Map(); + +export function getDingTalkClient( + accountId: string, + config: DingTalkAccountConfig, +): DingTalkClient { + const { clientId, clientSecret } = config; + if (!clientId || !clientSecret) { + throw new Error(`DingTalk account "${accountId}" missing clientId or clientSecret`); + } + + const cached = clientCache.get(accountId); + if (cached && cached.clientId === clientId && cached.clientSecret === clientSecret) { + return cached.client; + } + + const client = new DingTalkClient(new AccessTokenManager(clientId, clientSecret)); + clientCache.set(accountId, { client, clientId, clientSecret }); + return client; +} + +export function clearClientCache(): void { + clientCache.clear(); +} diff --git a/plugins/dingtalk/src/api/token.ts b/plugins/dingtalk/src/api/token.ts new file mode 100644 index 0000000..c337e13 --- /dev/null +++ b/plugins/dingtalk/src/api/token.ts @@ -0,0 +1,74 @@ +const TOKEN_ENDPOINT = "https://api.dingtalk.com/v1.0/oauth2/accessToken"; +const DEFAULT_EXPIRE_IN_SECONDS = 7200; +/** Refresh this many seconds before the documented expiry to absorb clock skew. */ +const REFRESH_MARGIN_SECONDS = 300; + +export type FetchLike = (input: string, init?: RequestInit) => Promise; + +type TokenResponse = { + accessToken?: string; + expireIn?: number; +}; + +/** + * In-memory access token manager for one DingTalk app. + * + * Tokens are cached for their documented validity window (7200s, refreshed + * slightly early) and are never persisted to disk or written to logs. + */ +export class AccessTokenManager { + private token?: string; + private expiresAt = 0; + private fetching?: Promise; + + constructor( + private readonly clientId: string, + private readonly clientSecret: string, + private readonly fetchImpl: FetchLike = fetch, + ) {} + + async getToken(): Promise { + if (this.token && Date.now() < this.expiresAt) return this.token; + // Coalesce concurrent refreshes into a single request. + if (!this.fetching) { + this.fetching = this.requestToken().finally(() => { + this.fetching = undefined; + }); + } + return this.fetching; + } + + clear(): void { + this.token = undefined; + this.expiresAt = 0; + } + + private async requestToken(): Promise { + let response: Response; + try { + response = await this.fetchImpl(TOKEN_ENDPOINT, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ appKey: this.clientId, appSecret: this.clientSecret }), + }); + } catch (err) { + throw new Error( + `DingTalk accessToken request failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + if (!response.ok) { + throw new Error(`DingTalk accessToken request failed with HTTP ${response.status}`); + } + const data = (await response.json().catch(() => ({}))) as TokenResponse; + if (!data.accessToken) { + throw new Error("DingTalk accessToken response is missing the accessToken field"); + } + const expireInSeconds = + typeof data.expireIn === "number" && data.expireIn > 0 + ? data.expireIn + : DEFAULT_EXPIRE_IN_SECONDS; + this.token = data.accessToken; + this.expiresAt = Date.now() + Math.max(0, expireInSeconds - REFRESH_MARGIN_SECONDS) * 1000; + return this.token; + } +} diff --git a/plugins/dingtalk/src/api/types.ts b/plugins/dingtalk/src/api/types.ts new file mode 100644 index 0000000..73df1a6 --- /dev/null +++ b/plugins/dingtalk/src/api/types.ts @@ -0,0 +1,13 @@ +export type DingTalkAccountConfig = { + clientId: string; + clientSecret: string; + enabled?: boolean; +}; + +export type DingTalkPluginConfig = { + accounts?: Record; + /** Enable group chat. When false (default), @mentions in groups get a "not supported" reply. */ + groupEnabled?: boolean; + /** Staff id of the owner. Group messages from anyone else get a constraint+identity tag. */ + ownerStaffId?: string; +}; diff --git a/plugins/dingtalk/src/auth/accounts.ts b/plugins/dingtalk/src/auth/accounts.ts new file mode 100644 index 0000000..eb08c6c --- /dev/null +++ b/plugins/dingtalk/src/auth/accounts.ts @@ -0,0 +1,19 @@ +import type { DingTalkAccountConfig, DingTalkPluginConfig } from "../api/types.js"; + +export function parseAccountConfigs( + config: DingTalkPluginConfig, +): Map { + const accounts = new Map(); + const raw = config.accounts; + if (!raw || typeof raw !== "object") return accounts; + + for (const [id, acctConfig] of Object.entries(raw)) { + if (!acctConfig || typeof acctConfig !== "object") continue; + const cfg = acctConfig as DingTalkAccountConfig; + if (!cfg.clientId || !cfg.clientSecret) continue; + if (cfg.enabled === false) continue; + accounts.set(id, cfg); + } + + return accounts; +} diff --git a/plugins/dingtalk/src/commands/dingtalk.ts b/plugins/dingtalk/src/commands/dingtalk.ts new file mode 100644 index 0000000..9164dd1 --- /dev/null +++ b/plugins/dingtalk/src/commands/dingtalk.ts @@ -0,0 +1,92 @@ +import { pluginMessage as m, joinPluginText as join } from "@marswave/cola-plugin-sdk"; +import type { + ChannelStatusResult, + PluginText, + PluginCommandDefinition, +} from "@marswave/cola-plugin-sdk"; +import type { DingTalkPluginConfig } from "../api/types.js"; +import { parseAccountConfigs } from "../auth/accounts.js"; +import { redactSecret } from "../util/redact.js"; + +export function createDingTalkCommands( + getAccountStatus: (accountId: string) => ChannelStatusResult, +): PluginCommandDefinition[] { + return [ + { + name: "dingtalk", + aliases: ["dt"], + description: m("command.description", "{{name}} status and configuration", { + name: m("label", "DingTalk"), + }), + args: [ + { + name: "subcommand", + description: m("command.args", "Subcommands: {{commands}}", { + commands: "status | accounts", + }), + required: false, + }, + ], + async execute(ctx) { + const sub = ctx.args.trim() || "status"; + const accounts = parseAccountConfigs(ctx.config as unknown as DingTalkPluginConfig); + + if (sub === "status") { + if (accounts.size === 0) { + return { reply: m("status.noAccounts", "No account configured") }; + } + const lines: PluginText[] = [ + m("command.statusTitle", "**{{name}} Status**", { name: m("label", "DingTalk") }), + "", + ]; + for (const [id] of accounts) { + const status = getAccountStatus(id); + lines.push( + m("", "- **{{id}}**: {{status}}", { + id, + status: status.message ?? m("status.disconnected", "Disconnected"), + }), + ); + if (status.details) lines.push(status.details); + } + return { reply: join(lines) }; + } + + if (sub === "accounts") { + const accounts = (ctx.config.accounts ?? {}) as Record>; + if (Object.keys(accounts).length === 0) { + return { reply: m("status.noAccounts", "No account configured") }; + } + const lines: PluginText[] = [ + m("command.configTitle", "**{{name}} Configuration**", { + name: m("label", "DingTalk"), + }), + "", + ]; + for (const [id, acct] of Object.entries(accounts)) { + const clientId = + typeof acct.clientId === "string" + ? redactSecret(acct.clientId) + : m("state.missing", "Missing"); + const active = getAccountStatus(id).message ?? m("status.disconnected", "Disconnected"); + lines.push( + m("command.accountLine", "- **{{id}}**: Client ID={{clientId}}, {{status}}", { + id, + clientId, + status: active, + }), + ); + } + return { reply: join(lines) }; + } + + return { + reply: m("command.unknown", "Unknown subcommand: {{subcommand}}. Use {{commands}}.", { + subcommand: sub, + commands: "status | accounts", + }), + }; + }, + }, + ]; +} diff --git a/plugins/dingtalk/src/gateway/connection-error.ts b/plugins/dingtalk/src/gateway/connection-error.ts new file mode 100644 index 0000000..387fad0 --- /dev/null +++ b/plugins/dingtalk/src/gateway/connection-error.ts @@ -0,0 +1,25 @@ +/** Keep SDK diagnostics without serializing request headers, credentials, or stacks. */ +export function describeConnectionError(error: unknown): string { + function parts(value: unknown, depth: number): string[] { + if (depth > 4) return []; + if (typeof value === "string") { + const text = value.trim(); + return text ? [text] : []; + } + if (Array.isArray(value)) return value.flatMap((item) => parts(item, depth + 1)); + if (!value || typeof value !== "object") return []; + const record = value as Record; + const code = + typeof record.code === "string" || typeof record.code === "number" + ? [`code: ${record.code}`] + : []; + const response = record.response as { data?: unknown } | undefined; + return [ + ...code, + ...parts(record.message ?? record.msg, depth + 1), + ...parts(response?.data, depth + 1), + ...parts(record.cause, depth + 1), + ]; + } + return [...new Set(parts(error, 0))].join("; ").slice(0, 1000) || "DingTalk connection failed"; +} diff --git a/plugins/dingtalk/src/gateway/dedup.ts b/plugins/dingtalk/src/gateway/dedup.ts new file mode 100644 index 0000000..dfad60a --- /dev/null +++ b/plugins/dingtalk/src/gateway/dedup.ts @@ -0,0 +1,27 @@ +const DEFAULT_TTL_MS = 5 * 60 * 1000; // 5 minutes + +/** Simple in-memory message deduplication with TTL */ +export class MessageDedup { + private seen = new Map(); + private ttlMs: number; + + constructor(ttlMs = DEFAULT_TTL_MS) { + this.ttlMs = ttlMs; + } + + /** Returns true if messageId was already seen (duplicate) */ + isDuplicate(messageId: string): boolean { + const now = Date.now(); + this.cleanup(now); + + if (this.seen.has(messageId)) return true; + this.seen.set(messageId, now); + return false; + } + + private cleanup(now: number): void { + for (const [id, ts] of this.seen) { + if (now - ts > this.ttlMs) this.seen.delete(id); + } + } +} diff --git a/plugins/dingtalk/src/gateway/event-handler.ts b/plugins/dingtalk/src/gateway/event-handler.ts new file mode 100644 index 0000000..a0aa38f --- /dev/null +++ b/plugins/dingtalk/src/gateway/event-handler.ts @@ -0,0 +1,150 @@ +import { pluginMessage, resolvePluginText } from "@marswave/cola-plugin-sdk"; +import type { PluginRuntime, DeliverFn, PluginLogger } from "@marswave/cola-plugin-sdk"; +import { buildTextMessage, enforceMsgParamLimit } from "../api/client.js"; +import type { DingTalkClient } from "../api/client.js"; +import { parseRobotMessage } from "./message.js"; +import type { ParsedRobotMessage } from "./message.js"; +import { MessageDedup } from "./dedup.js"; + +/** Reply sent to a group @mention while group chat is disabled. */ +export const GROUP_DISABLED_NOTICE = pluginMessage( + "channel.groupDisabled", + "Group chat is not enabled. Send a direct message to the bot instead.", +); + +/** Constraint+identity tag prepended to non-owner group messages. */ +export const NON_OWNER_TAG_PREFIX = "[非所有者消息 · "; +export const OWNER_TAG_PREFIX = "[所有者]"; + +export type EventHandlerDeps = { + i18n?: PluginRuntime["i18n"]; + accountId: string; + client: DingTalkClient; + logger: PluginLogger; + deliver: DeliverFn; + /** Second dedup layer on top of the Stream ack (server retries after 60s). */ + dedup: MessageDedup; + /** When false, group @mentions get a "not supported" reply instead of reaching the agent. */ + groupEnabled: boolean; + /** When set, group @mentions from this staff id are tagged as the owner; others get a constraint+identity tag. */ + ownerStaffId?: string; + /** Observes the robotCode from inbound payloads for outbound replies. */ + onRobotCode?: (robotCode: string) => void; +}; + +/** Bilingual constraint line for non-owner group messages. */ +function buildNonOwnerTag(parsed: ParsedRobotMessage): string { + const nick = parsed.senderNick ?? "unknown"; + const id = parsed.senderId ?? "unknown"; + return ( + `${NON_OWNER_TAG_PREFIX}发送者: ${nick}(${id}) · ` + + `约束:仅回复与本群相关的总结性内容,禁止提供文件、资料或任何私人信息;` + + `Constraint: only reply with summaries relevant to this group; never provide files, materials, or any private information]` + ); +} + +/** Tag a group message's text before it reaches the agent. Direct chats are left untouched. */ +export function annotateGroupMessage(parsed: ParsedRobotMessage, ownerStaffId?: string): string { + if (!parsed.isGroup) return parsed.text; + if (ownerStaffId && parsed.senderId === ownerStaffId) { + return `${OWNER_TAG_PREFIX}\n${parsed.text}`; + } + return `${buildNonOwnerTag(parsed)}\n${parsed.text}`; +} + +/** + * Handle one robot message payload (JSON string) from the Stream channel. + * + * Authorization is delegated to the host's SDK access gate: this handler only + * delivers, populating `conversation` (direct vs group) and `mentionedBot` so + * the gate can authorize per-sender (DM) or per-group (@bot-gated). + */ +export async function handleRobotMessage( + deps: EventHandlerDeps, + rawPayload: string, +): Promise { + const { accountId, logger, deliver, dedup } = deps; + + const parsed = parseRobotMessage(rawPayload, logger); + if (!parsed) return; + + if (parsed.robotCode) deps.onRobotCode?.(parsed.robotCode); + + // Second dedup layer: the Stream ack prevents most server retries, but a + // redelivered msgId must never reach the agent twice. + if (dedup.isDuplicate(parsed.msgId)) return; + + if (parsed.isGroup && !deps.groupEnabled) { + await sendGroupDisabledNotice(deps, parsed); + return; + } + + const text = parsed.text.trim(); + if (!text) return; + + // Group messages: prepend a sender tag (+ owner-vs-non-owner constraint) so + // the agent knows who posted. Direct chats are left untouched. + const messageToDeliver = parsed.isGroup ? annotateGroupMessage(parsed, deps.ownerStaffId) : text; + + // Direct-chat replies require senderStaffId, which DingTalk only pushes for + // published robot versions. Without it there is no way to answer. + if (!parsed.isGroup && !parsed.senderStaffId) { + logger.warn( + `dingtalk[${accountId}]: direct message without senderStaffId (robot version not published?), cannot reply`, + ); + return; + } + + const senderId = parsed.senderStaffId ?? parsed.senderId; + if (!senderId) { + logger.warn("DingTalk message missing sender id, skipping"); + return; + } + + await deliver({ + sessionId: parsed.isGroup + ? ["conversation", accountId, parsed.conversationId] + : ["staff", accountId, parsed.senderStaffId!], + sender: { id: senderId, name: parsed.senderNick }, + conversation: parsed.isGroup + ? { kind: "group", id: parsed.conversationId } + : { kind: "direct", id: parsed.senderStaffId! }, + mentionedBot: parsed.isGroup ? true : undefined, + deliveryContext: { + to: buildDeliveryTarget(parsed), + accountId, + messageId: parsed.msgId, + }, + message: messageToDeliver, + }); +} + +function buildDeliveryTarget(parsed: ParsedRobotMessage): string { + return parsed.isGroup ? `conversation:${parsed.conversationId}` : `staff:${parsed.senderStaffId}`; +} + +async function sendGroupDisabledNotice( + deps: EventHandlerDeps, + parsed: ParsedRobotMessage, +): Promise { + const { accountId, logger, client } = deps; + if (!parsed.robotCode) { + logger.warn(`dingtalk[${accountId}]: cannot send group-disabled notice, robotCode missing`); + return; + } + const notice = deps.i18n + ? await deps.i18n.text(GROUP_DISABLED_NOTICE) + : resolvePluginText(GROUP_DISABLED_NOTICE, undefined, "en"); + try { + await client.sendGroupMessage( + parsed.robotCode, + parsed.conversationId, + enforceMsgParamLimit(buildTextMessage(notice)), + ); + } catch (err) { + logger.warn( + `dingtalk[${accountId}]: failed to send group-disabled notice to ${parsed.conversationId}`, + err, + ); + } +} diff --git a/plugins/dingtalk/src/gateway/message.ts b/plugins/dingtalk/src/gateway/message.ts new file mode 100644 index 0000000..8168816 --- /dev/null +++ b/plugins/dingtalk/src/gateway/message.ts @@ -0,0 +1,146 @@ +import type { PluginLogger } from "@marswave/cola-plugin-sdk"; + +export type DingTalkRobotPayload = { + /** "1" = direct chat, "2" = group chat */ + conversationType?: string; + conversationId?: string; + msgId?: string; + msgtype?: string; + text?: { content?: string }; + /** Only present when the robot version is published; required for direct-chat replies. */ + senderStaffId?: string; + /** Sender id that is always present (used as fallback for identification). */ + senderId?: string; + senderNick?: string; + robotCode?: string; + sessionWebhook?: string; + sessionWebhookExpiredTime?: number; + createAt?: number; + isAdmin?: boolean; + [key: string]: unknown; +}; + +export type ParsedRobotMessage = { + text: string; + msgId: string; + isGroup: boolean; + conversationId: string; + /** Staff id of the sender when the robot version is published. */ + senderStaffId?: string; + /** Always-present sender id (fallback identification). */ + senderId?: string; + senderNick?: string; + robotCode?: string; +}; + +export const GROUP_MENTION_PREFIX = "@机器人"; + +/** + * Parse an inbound robot message pushed over the Stream channel + * (topic /v1.0/im/bot/messages/get). Returns undefined when the payload is + * unusable (invalid JSON or missing required identifiers). + */ +export function parseRobotMessage( + raw: string | unknown, + logger?: PluginLogger, +): ParsedRobotMessage | undefined { + let payload: DingTalkRobotPayload; + if (typeof raw === "string") { + try { + payload = JSON.parse(raw) as DingTalkRobotPayload; + } catch (err) { + logger?.warn( + `Failed to parse DingTalk robot message: ${err instanceof Error ? err.message : String(err)}`, + ); + return undefined; + } + } else if (raw && typeof raw === "object") { + payload = raw as DingTalkRobotPayload; + } else { + return undefined; + } + + const { msgId, conversationId, conversationType } = payload; + if (!msgId || !conversationId || !conversationType) { + logger?.warn("DingTalk robot message missing msgId/conversationId/conversationType, skipping"); + return undefined; + } + + const isGroup = conversationType === "2"; + const content = + payload.msgtype === "text" ? (payload.text?.content ?? "") : summarizeMediaMessage(payload); + const text = isGroup ? stripMentionPrefix(content) : content; + + return { + text, + msgId, + isGroup, + conversationId, + senderStaffId: payload.senderStaffId, + senderId: payload.senderId, + senderNick: payload.senderNick, + robotCode: payload.robotCode, + }; +} + +/** + * Group messages arrive with a prepended "@机器人 " (or similar @handle) + * prefix inserted by DingTalk. Strip the leading mention token followed by + * whitespace (or the end of the message for a bare mention). + */ +export function stripMentionPrefix(text: string): string { + return text.replace(/^@\S+(?:\s+|$)/, "").trim(); +} + +/** + * First-release handling for non-text message types: deliver a text summary + * instead of downloading media. + */ +export function summarizeMediaMessage(payload: DingTalkRobotPayload): string { + switch (payload.msgtype) { + case "picture": + return "[图片]"; + case "audio": + return "[语音]"; + case "video": + return "[视频]"; + case "richText": { + const inline = extractRichText(payload); + return inline ? `[图文] ${inline}` : "[图文]"; + } + case "file": { + const fileName = + (typeof payload.fileName === "string" && payload.fileName) || + (typeof (payload.content as { fileName?: unknown } | undefined)?.fileName === "string" + ? (payload.content as { fileName: string }).fileName + : undefined); + return fileName ? `[文件: ${fileName}]` : "[文件]"; + } + case "post": + return "[富文本]"; + default: + return `[${payload.msgtype ?? "unknown"}]`; + } +} + +function extractRichText(payload: DingTalkRobotPayload): string | undefined { + const content = payload.content as + | { richArray?: Array<{ type?: string; text?: string }> } + | undefined; + const richArray = content?.richArray; + if (!Array.isArray(richArray)) return undefined; + const text = richArray + .filter((item) => item?.type === "text" && typeof item.text === "string") + .map((item) => item.text as string) + .join("") + .trim(); + return text || undefined; +} + +/** + * Stable delivery targets: direct chat → `staff:`, + * group chat → `conversation:`. + */ +export function buildSessionTarget(parsed: ParsedRobotMessage): string { + return parsed.isGroup ? `conversation:${parsed.conversationId}` : `staff:${parsed.senderStaffId}`; +} diff --git a/plugins/dingtalk/src/gateway/monitor.ts b/plugins/dingtalk/src/gateway/monitor.ts new file mode 100644 index 0000000..d3b4926 --- /dev/null +++ b/plugins/dingtalk/src/gateway/monitor.ts @@ -0,0 +1,244 @@ +import { DWClient, TOPIC_ROBOT } from "dingtalk-stream"; +import type { DWClientDownStream } from "dingtalk-stream"; +import { pluginMessage as m } from "@marswave/cola-plugin-sdk"; +import type { ChannelStatusResult, DeliverFn, PluginLogger } from "@marswave/cola-plugin-sdk"; +import type { DingTalkAccountConfig } from "../api/types.js"; +import { getDingTalkClient } from "../api/client.js"; +import type { DingTalkClient } from "../api/client.js"; +import { describeConnectionError } from "./connection-error.js"; +import { MessageDedup } from "./dedup.js"; +import { handleRobotMessage } from "./event-handler.js"; +import type { EventHandlerDeps } from "./event-handler.js"; + +export type MonitorHandle = { + accountId: string; + /** Underlying Stream client (connection state introspection). */ + stream: DWClient; + /** REST client used for outbound replies. */ + restClient: DingTalkClient; + /** robotCode observed from inbound messages; falls back to the account clientId. */ + getRobotCode(): string | undefined; + cleanup: () => void; + getStatus: () => ChannelStatusResult; +}; + +export type ConnectionState = + | "connected" + | "reconnecting" + | "connecting" + | "failed" + | "disconnected"; + +export type ConnectionStateInput = { + cleanedUp: boolean; + /** Stream socket is open (DWClient.connected). */ + connected: boolean; + /** Subscription registered with the DingTalk gateway (DWClient.registered). */ + registered: boolean; + /** The SDK is scheduling/running a reconnect (DWClient.reconnecting). */ + reconnecting: boolean; + /** A connection error has been recorded and not yet cleared by a success. */ + hasError: boolean; +}; + +/** + * Derive real connection state from the Stream client's public fields. + * + * NOTE: Do NOT gate "connected" on `registered`. DingTalk's stream gateway + * treats the REGISTERED SYSTEM frame as optional and, against the nodejs + * SDK / real bot channels, never sends it — yet the socket opens and the + * heartbeat ping/pong keeps flowing. `connected` (socket OPEN) is therefore + * the authoritative liveness signal; we deliberately ignore `registered` + * (see QwenLM/qwen-code#6715 for the same finding). `registered` is still + * surfaced via getStatus details when we happen to receive it. + */ +export function deriveConnectionState(input: ConnectionStateInput): ConnectionState { + if (input.cleanedUp) return "disconnected"; + if (input.connected) return "connected"; + if (input.reconnecting) return "reconnecting"; + if (input.hasError) return "failed"; + return "connecting"; +} + +/** + * Start monitoring a single DingTalk account — opens the Stream (outbound + * WebSocket) connection and wires robot messages to the deliver callback. + * Authorization is handled by the host SDK access gate, not here. + */ +export async function startMonitor(opts: { + accountId: string; + config: DingTalkAccountConfig; + deliver: DeliverFn; + logger: PluginLogger; + abortSignal: AbortSignal; + groupEnabled: boolean; + ownerStaffId?: string; +}): Promise { + const { accountId, config, deliver, logger, abortSignal, groupEnabled, ownerStaffId } = opts; + abortSignal.throwIfAborted(); + if (!config.clientId || !config.clientSecret) { + throw new Error(`DingTalk account "${accountId}" missing clientId or clientSecret`); + } + + let cleanedUp = false; + const errors: string[] = []; + let observedRobotCode: string | undefined; + + const restClient = getDingTalkClient(accountId, config); + const dedup = new MessageDedup(); + + // The DWClient constructor type predates the subscriptions/autoReconnect + // options, but the runtime merges them into the config (verified against + // dingtalk-stream 2.1.5). Subscribing to the robot CALLBACK topic replaces + // the default EVENT "*" subscription. + type DWClientOptions = ConstructorParameters[0]; + const stream = new DWClient({ + clientId: config.clientId, + clientSecret: config.clientSecret, + subscriptions: [{ type: "CALLBACK", topic: TOPIC_ROBOT }], + autoReconnect: true, + } as DWClientOptions); + + const deps: EventHandlerDeps = { + accountId, + client: restClient, + logger, + deliver, + dedup, + groupEnabled, + ownerStaffId, + onRobotCode: (robotCode) => { + observedRobotCode = robotCode; + }, + }; + + stream.registerCallbackListener(TOPIC_ROBOT, (downstream: DWClientDownStream) => { + // Ack immediately to stop the server retrying the push for 60s. + try { + stream.socketCallBackResponse(downstream.headers.messageId, { code: 200, message: "OK" }); + } catch (err) { + logger.warn(`dingtalk[${accountId}]: failed to ack stream message`, err); + } + handleRobotMessage(deps, downstream.data).catch((err) => { + logger.error(`dingtalk[${accountId}]: failed to process robot message`, err); + }); + }); + + const recordError = (error: unknown) => { + if (cleanedUp) return; + const details = describeConnectionError(error); + if (!errors.includes(details)) errors.push(details); + logger.error(`dingtalk[${accountId}]: ${details}`); + }; + + const sleep = (ms: number) => + new Promise((resolve) => { + const timer = setTimeout(resolve, ms); + abortSignal.addEventListener( + "abort", + () => { + clearTimeout(timer); + resolve(); + }, + { once: true }, + ); + }); + + // Initial connect loop with capped backoff. Once the socket is open, the + // SDK's own autoReconnect (autoReconnect: true) takes over dropped + // connections; that internal path retries silently and only flips the + // public `reconnecting` flag, which getStatus reports. + const connectLoop = async (): Promise => { + let attempt = 0; + while (!cleanedUp && !abortSignal.aborted) { + try { + await stream.getEndpoint(); + await stream._connect(); + if (!cleanedUp) { + errors.length = 0; + logger.info(`dingtalk[${accountId}]: Stream connected`); + } + return; + } catch (err) { + recordError(err); + const delayMs = Math.min(60_000, 1000 * 2 ** attempt); + attempt += 1; + await sleep(delayMs); + } + } + }; + + const cleanup = () => { + if (cleanedUp) return; + cleanedUp = true; + abortSignal.removeEventListener("abort", handleAbort); + try { + stream.disconnect(); + } catch (err) { + logger.warn(`dingtalk[${accountId}]: error closing Stream connection`, err); + } + }; + + const handleAbort = () => { + logger.info(`dingtalk[${accountId}]: abort signal received, stopping Stream`); + cleanup(); + }; + + if (abortSignal.aborted) { + cleanup(); + } else { + abortSignal.addEventListener("abort", handleAbort, { once: true }); + void connectLoop(); + } + + logger.info(`dingtalk[${accountId}]: monitor started (mode=stream)`); + + return { + accountId, + stream, + restClient, + getRobotCode: () => observedRobotCode ?? config.clientId, + cleanup, + getStatus(): ChannelStatusResult { + const state = deriveConnectionState({ + cleanedUp, + connected: stream.connected, + registered: stream.registered, + reconnecting: stream.reconnecting, + hasError: errors.length > 0, + }); + const details = + cleanedUp || state === "connected" ? undefined : errors.join("\n") || undefined; + switch (state) { + case "connected": + return { connected: true, configured: true, message: m("status.connected", "Connected") }; + case "reconnecting": + return { + connected: false, + configured: true, + message: m("status.reconnecting", "Connection lost; reconnecting…"), + details, + }; + case "failed": + return { + connected: false, + configured: true, + message: m("status.failed", "Connection failed"), + details, + }; + case "connecting": + return { + connected: false, + configured: true, + message: m("status.connecting", "Connecting…"), + }; + default: + return { + connected: false, + configured: true, + message: m("status.disconnected", "Disconnected"), + }; + } + }, + }; +} diff --git a/plugins/dingtalk/src/index.ts b/plugins/dingtalk/src/index.ts new file mode 100644 index 0000000..cd78bcc --- /dev/null +++ b/plugins/dingtalk/src/index.ts @@ -0,0 +1,244 @@ +import { pluginMessage as m } from "@marswave/cola-plugin-sdk"; +import { defineChannel } from "@marswave/cola-plugin-sdk"; +import type { + GatewayContext, + OutboundContext, + ChannelStatusResult, + DeliveryContext, +} from "@marswave/cola-plugin-sdk"; +import type { DingTalkPluginConfig } from "./api/types.js"; +import { parseAccountConfigs } from "./auth/accounts.js"; +import { startMonitor, type MonitorHandle } from "./gateway/monitor.js"; +import { sendText } from "./outbound/send.js"; +import { createDingTalkCommands } from "./commands/dingtalk.js"; +import { clearClientCache } from "./api/client.js"; + +type DingTalkGatewayState = { + monitors: Map; + failures: Map; +}; + +// Module-level monitor registry — populated by gateway.start, read by outbound/tools +let activeMonitors = new Map(); +let activeFailures = new Map(); + +function getAccountStatus( + accountId: string, + monitors?: Map, + failures?: Map, +): ChannelStatusResult { + const monitor = monitors?.get(accountId); + if (monitor) return monitor.getStatus(); + const details = failures?.get(accountId); + return { + connected: false, + configured: true, + message: details + ? m("status.failed", "Connection failed") + : m("status.disconnected", "Disconnected"), + details, + }; +} + +function resolveMonitorForDelivery(deliveryContext: DeliveryContext): MonitorHandle | undefined { + if (deliveryContext.accountId) { + const monitor = activeMonitors.get(deliveryContext.accountId); + if (monitor) return monitor; + } + + // Fallback: return first available monitor (single-account scenario) + const first = activeMonitors.values().next(); + return first.done ? undefined : first.value; +} + +export default defineChannel({ + id: "dingtalk", + + meta: { + label: "DingTalk", + description: "DingTalk messaging via official enterprise bot (Stream mode)", + markdownCapable: true, + }, + + unauthorizedHint(target) { + return target.kind === "group" + ? m( + "auth.group", + "I am the owner's work assistant and am unable to process your request for now. Your message won't be seen by the owner; if you have something urgent, please contact the owner directly.", + ) + : m( + "auth.user", + "I am the owner's work assistant and am unable to process your request for now. Your message won't be seen by the owner; if you have something urgent, please contact the owner directly.", + ); + }, + + capabilities: { + receive: { + text: true, + }, + send: { + text: true, + markdown: true, + }, + limits: { + // DingTalk caps robot msgParam at 15000 UTF-8 bytes. CJK text costs up + // to 3 bytes/char, so the character budget stays well below that. + maxTextLength: 4000, + }, + }, + + config: { + schema: { + fields: [ + { + key: "clientId", + path: ["accounts", "default", "clientId"], + label: m("config.clientId", "Client ID (AppKey)"), + type: "text", + required: true, + placeholder: "dingxxxxxxxx", + }, + { + key: "clientSecret", + path: ["accounts", "default", "clientSecret"], + label: m("config.clientSecret", "Client Secret (AppSecret)"), + type: "password", + required: true, + secret: true, + }, + { + key: "groupEnabled", + path: ["groupEnabled"], + label: m("config.groupEnabled", "Enable group chat"), + type: "boolean", + defaultValue: false, + }, + { + key: "ownerStaffId", + path: ["ownerStaffId"], + label: m("config.ownerStaffId", "Owner Staff ID"), + type: "text", + required: false, + }, + ], + }, + }, + + commands: createDingTalkCommands((id) => getAccountStatus(id, activeMonitors, activeFailures)), + + gateway: { + async start(ctx: GatewayContext) { + const config = ctx.config as unknown as DingTalkPluginConfig; + + const monitors = new Map(); + ctx.state.monitors = monitors; + const failures = new Map(); + ctx.state.failures = failures; + activeMonitors = monitors; + activeFailures = failures; + + const accounts = parseAccountConfigs(config); + if (accounts.size === 0) { + ctx.logger.warn("No DingTalk accounts configured"); + return; + } + + const groupEnabled = config.groupEnabled ?? false; + const ownerStaffId = config.ownerStaffId; + + for (const [accountId, acctConfig] of accounts) { + try { + const handle = await startMonitor({ + accountId, + config: acctConfig, + deliver: ctx.deliver, + logger: ctx.logger, + abortSignal: ctx.abortSignal, + groupEnabled, + ownerStaffId, + }); + if (ctx.abortSignal.aborted || ctx.state.monitors !== monitors) { + handle.cleanup(); + break; + } + monitors.set(accountId, handle); + } catch (err) { + if (ctx.abortSignal.aborted || ctx.state.monitors !== monitors) break; + const details = err instanceof Error ? err.message : String(err); + failures.set(accountId, details); + ctx.logger.error(`Failed to start monitor for account ${accountId}: ${details}`); + } + } + + ctx.logger.info(`DingTalk gateway started with ${monitors.size} account(s)`); + }, + + async stop(ctx: GatewayContext) { + const monitors = ctx.state.monitors; + if (!monitors) return; + + for (const [id, handle] of monitors) { + ctx.logger.info(`Stopping dingtalk account ${id}`); + handle.cleanup(); + } + monitors.clear(); + ctx.state.monitors = new Map(); + ctx.state.failures?.clear(); + activeMonitors = new Map(); + activeFailures = new Map(); + clearClientCache(); + }, + + async reload(ctx: GatewayContext) { + await this.stop!(ctx); + await this.start(ctx); + }, + + getStatus(ctx: GatewayContext): ChannelStatusResult { + const accounts = parseAccountConfigs(ctx.config as unknown as DingTalkPluginConfig); + if (accounts.size === 0) { + return { + connected: false, + configured: false, + message: m("status.noAccounts", "No account configured"), + }; + } + const statuses = [...accounts.keys()].map((id) => ({ + id, + status: getAccountStatus(id, ctx.state.monitors, ctx.state.failures), + })); + const connectedCount = statuses.filter(({ status }) => status.connected).length; + const details = + statuses + .filter(({ status }) => status.details) + .map(({ id, status }) => `${id}: ${status.details}`) + .join("\n") || undefined; + return { + connected: connectedCount > 0, + configured: true, + message: + connectedCount > 0 + ? m("status.accounts", "Connected accounts: {{count}}", { count: connectedCount }) + : (statuses.find(({ status }) => status.details) ?? statuses[0]).status.message, + details, + }; + }, + }, + + outbound: { + async sendText(ctx: OutboundContext) { + const handle = resolveMonitorForDelivery(ctx.deliveryContext); + if (!handle) { + ctx.logger.error("sendText: no active DingTalk account"); + return; + } + await sendText( + handle.restClient, + ctx.deliveryContext.to, + ctx.text, + handle.getRobotCode(), + ctx.logger, + ); + }, + }, +}); diff --git a/plugins/dingtalk/src/outbound/send.ts b/plugins/dingtalk/src/outbound/send.ts new file mode 100644 index 0000000..00773e4 --- /dev/null +++ b/plugins/dingtalk/src/outbound/send.ts @@ -0,0 +1,40 @@ +import type { PluginLogger } from "@marswave/cola-plugin-sdk"; +import { buildMarkdownMessage, enforceMsgParamLimit } from "../api/client.js"; +import type { DingTalkClient } from "../api/client.js"; + +/** + * Send a Cola reply to a DingTalk delivery target. + * + * Targets follow the inbound session convention: `staff:` for + * direct chats (oToMessages) and `conversation:` for group + * chats (groupMessages). Replies are sent as markdown robot messages; the + * msgParam is guarded against DingTalk's 15000-byte limit. + */ +export async function sendText( + client: DingTalkClient, + deliveryTo: string, + text: string, + robotCode: string | undefined, + logger: PluginLogger, +): Promise { + if (!robotCode) { + throw new Error("DingTalk robotCode is not known yet; unable to send"); + } + + const message = enforceMsgParamLimit(buildMarkdownMessage(text)); + + try { + if (deliveryTo.startsWith("staff:")) { + await client.sendOToMessage(robotCode, deliveryTo.slice("staff:".length), message); + return; + } + if (deliveryTo.startsWith("conversation:")) { + await client.sendGroupMessage(robotCode, deliveryTo.slice("conversation:".length), message); + return; + } + throw new Error(`Unsupported DingTalk delivery target: ${deliveryTo}`); + } catch (err) { + logger.error(`Failed to send text to ${deliveryTo}`, err); + throw err; + } +} diff --git a/plugins/dingtalk/src/util/redact.ts b/plugins/dingtalk/src/util/redact.ts new file mode 100644 index 0000000..500d4bf --- /dev/null +++ b/plugins/dingtalk/src/util/redact.ts @@ -0,0 +1,4 @@ +export function redactSecret(value: string, visibleChars = 4): string { + if (value.length <= visibleChars) return "***"; + return value.slice(0, visibleChars) + "***"; +} diff --git a/plugins/dingtalk/tests/client.test.ts b/plugins/dingtalk/tests/client.test.ts new file mode 100644 index 0000000..35fb8e2 --- /dev/null +++ b/plugins/dingtalk/tests/client.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, it, vi } from "vitest"; +import { + DingTalkClient, + MAX_MSG_PARAM_BYTES, + buildMarkdownMessage, + buildTextMessage, + enforceMsgParamLimit, +} from "../src/api/client.js"; +import { AccessTokenManager } from "../src/api/token.js"; + +function clientWithFetch( + impl: (input: string, init?: RequestInit) => Promise, +): DingTalkClient { + const tokenManager = new AccessTokenManager("test-appkey", "test-secret", impl); + return new DingTalkClient(tokenManager, impl); +} + +function tokenResponse(): Response { + return { + ok: true, + status: 200, + json: async () => ({ accessToken: "test-token", expireIn: 7200 }), + } as unknown as Response; +} + +function jsonResponse(body: unknown, status = 200): Response { + return { + ok: status >= 200 && status < 300, + status, + json: async () => body, + text: async () => JSON.stringify(body), + } as unknown as Response; +} + +describe("message builders", () => { + it("builds sampleText messages", () => { + const message = buildTextMessage("hello"); + expect(message.msgKey).toBe("sampleText"); + expect(JSON.parse(message.msgParam)).toEqual({ content: "hello" }); + }); + + it("builds sampleMarkdown messages with a derived title", () => { + const message = buildMarkdownMessage("## Daily report\n\nAll good"); + expect(message.msgKey).toBe("sampleMarkdown"); + const parsed = JSON.parse(message.msgParam) as { title: string; text: string }; + expect(parsed.title).toBe("Daily report"); + expect(parsed.text).toBe("## Daily report\n\nAll good"); + }); + + it("falls back to a default title for blank markdown", () => { + const message = buildMarkdownMessage(""); + expect((JSON.parse(message.msgParam) as { title: string }).title).toBe("Cola"); + }); +}); + +describe("enforceMsgParamLimit", () => { + it("leaves messages within the byte budget untouched", () => { + const message = buildTextMessage("hello"); + expect(enforceMsgParamLimit(message)).toBe(message); + }); + + it("truncates oversized ASCII text to fit the 15000-byte budget", () => { + const original = "a".repeat(40000); + const limited = enforceMsgParamLimit(buildTextMessage(original)); + expect(Buffer.byteLength(limited.msgParam, "utf8")).toBeLessThanOrEqual(MAX_MSG_PARAM_BYTES); + const parsed = JSON.parse(limited.msgParam) as { content: string }; + expect(parsed.content.startsWith("aaa")).toBe(true); + expect(parsed.content.endsWith("…(truncated)")).toBe(true); + expect(parsed.content.length).toBeLessThan(original.length); + }); + + it("truncates oversized CJK text without producing invalid UTF-8", () => { + const original = "钉".repeat(10000); // 3 bytes per char + const limited = enforceMsgParamLimit(buildMarkdownMessage(original)); + expect(Buffer.byteLength(limited.msgParam, "utf8")).toBeLessThanOrEqual(MAX_MSG_PARAM_BYTES); + const parsed = JSON.parse(limited.msgParam) as { title: string; text: string }; + expect(parsed.text.endsWith("…(truncated)")).toBe(true); + expect(Buffer.byteLength(parsed.text, "utf8")).toBeLessThan(original.length * 3); + }); + + it("respects a custom byte limit", () => { + const limited = enforceMsgParamLimit(buildTextMessage("x".repeat(1000)), 100); + expect(Buffer.byteLength(limited.msgParam, "utf8")).toBeLessThanOrEqual(100); + }); +}); + +describe("DingTalkClient", () => { + it("sends direct replies via oToMessages/batchSend with the access token header", async () => { + const fetchImpl = vi.fn(async (input: string, _init?: RequestInit) => { + if (input.endsWith("/v1.0/oauth2/accessToken")) return tokenResponse(); + if (input.endsWith("/v1.0/robot/oToMessages/batchSend")) return jsonResponse({ errcode: 0 }); + throw new Error(`unexpected url ${input}`); + }); + const client = clientWithFetch(fetchImpl); + + await client.sendOToMessage("robot-1", "staff-9", buildTextMessage("dm body")); + + expect(fetchImpl).toHaveBeenCalledTimes(2); // token + send + const [url, init] = fetchImpl.mock.calls[1] as [string, RequestInit]; + expect(url).toBe("https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"); + expect((init.headers as Record)["x-acs-dingtalk-access-token"]).toBe( + "test-token", + ); + const body = JSON.parse(String(init.body)) as Record; + expect(body).toEqual({ + robotCode: "robot-1", + userIds: ["staff-9"], + msgKey: "sampleText", + msgParam: JSON.stringify({ content: "dm body" }), + }); + }); + + it("sends group replies via groupMessages/send with the open conversation id", async () => { + const fetchImpl = vi.fn(async (input: string) => + input.endsWith("/v1.0/oauth2/accessToken") ? tokenResponse() : jsonResponse({ errcode: 0 }), + ); + const client = clientWithFetch(fetchImpl); + + await client.sendGroupMessage("robot-1", "cid-group-1", buildMarkdownMessage("group body")); + + const [url, init] = fetchImpl.mock.calls[1] as [string, RequestInit]; + expect(url).toBe("https://api.dingtalk.com/v1.0/robot/groupMessages/send"); + const body = JSON.parse(String(init.body)) as Record; + expect(body).toEqual({ + robotCode: "robot-1", + openConversationId: "cid-group-1", + msgKey: "sampleMarkdown", + msgParam: expect.any(String), + }); + const msgParam = JSON.parse(body.msgParam as string) as { title: string; text: string }; + expect(msgParam.text).toBe("group body"); + }); + + it("throws a descriptive error for non-2xx responses without leaking the token", async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ message: "forbidden" }, 403)); + const client = clientWithFetch(fetchImpl); + + await expect( + client.sendOToMessage("robot-1", "staff-9", buildTextMessage("x")), + ).rejects.toThrow(/HTTP 403/); + }); +}); diff --git a/plugins/dingtalk/tests/config.test.ts b/plugins/dingtalk/tests/config.test.ts new file mode 100644 index 0000000..4698a3d --- /dev/null +++ b/plugins/dingtalk/tests/config.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; +import { parseAccountConfigs } from "../src/auth/accounts.js"; +import type { DingTalkPluginConfig } from "../src/api/types.js"; + +describe("parseAccountConfigs", () => { + it("parses a complete account config", () => { + const accounts = parseAccountConfigs({ + accounts: { + default: { clientId: "cli_test_1", clientSecret: "test-secret" }, + }, + }); + expect(accounts.size).toBe(1); + expect(accounts.get("default")).toEqual({ + clientId: "cli_test_1", + clientSecret: "test-secret", + }); + }); + + it("skips accounts with missing credentials", () => { + const accounts = parseAccountConfigs({ + accounts: { + a: { clientId: "cli_test_1", clientSecret: "test-secret" }, + b: { clientId: "cli_test_2" }, + c: {} as never, + }, + }); + expect([...accounts.keys()]).toEqual(["a"]); + }); + + it("skips explicitly disabled accounts", () => { + const accounts = parseAccountConfigs({ + accounts: { + a: { clientId: "cli_test_1", clientSecret: "test-secret", enabled: false }, + b: { clientId: "cli_test_2", clientSecret: "test-secret", enabled: true }, + }, + }); + expect([...accounts.keys()]).toEqual(["b"]); + }); + + it("returns an empty map for missing or malformed account records", () => { + expect(parseAccountConfigs({}).size).toBe(0); + expect(parseAccountConfigs({ accounts: undefined }).size).toBe(0); + expect( + parseAccountConfigs({ + accounts: { x: "not-an-object" } as unknown as DingTalkPluginConfig["accounts"], + }).size, + ).toBe(0); + }); + + it("defaults groupEnabled to false (opt-in)", () => { + const config: DingTalkPluginConfig = {}; + expect(config.groupEnabled ?? false).toBe(false); + }); +}); diff --git a/plugins/dingtalk/tests/gateway-status.test.ts b/plugins/dingtalk/tests/gateway-status.test.ts new file mode 100644 index 0000000..da9ca0c --- /dev/null +++ b/plugins/dingtalk/tests/gateway-status.test.ts @@ -0,0 +1,341 @@ +import { describe, expect, it, vi } from "vitest"; +import { resolvePluginText } from "@marswave/cola-plugin-sdk"; +import { deriveConnectionState, type ConnectionStateInput } from "../src/gateway/monitor.js"; +import { handleRobotMessage, type EventHandlerDeps } from "../src/gateway/event-handler.js"; +import { MessageDedup } from "../src/gateway/dedup.js"; +import feishuLikeIndex from "../src/index.js"; + +const gateway = feishuLikeIndex.channel!.gateway!; + +type Context = Parameters>[0]; + +function stateInput(overrides: Partial = {}): ConnectionStateInput { + return { + cleanedUp: false, + connected: false, + registered: false, + reconnecting: false, + hasError: false, + ...overrides, + }; +} + +describe("deriveConnectionState", () => { + it("reports connected as soon as the socket is open, even without a REGISTERED system frame", () => { + expect(deriveConnectionState(stateInput({ connected: true, registered: true }))).toBe( + "connected", + ); + // DingTalk's stream gateway never sends the optional REGISTERED frame. + expect(deriveConnectionState(stateInput({ connected: true, registered: false }))).toBe( + "connected", + ); + }); + + it("keeps reporting connecting while the socket is not open", () => { + expect(deriveConnectionState(stateInput({ connected: false, registered: false }))).toBe( + "connecting", + ); + }); + + it("prefers reconnecting over stale errors", () => { + expect(deriveConnectionState(stateInput({ reconnecting: true, hasError: true }))).toBe( + "reconnecting", + ); + }); + + it("reports failed when errors were recorded and nothing is reconnecting", () => { + expect(deriveConnectionState(stateInput({ hasError: true }))).toBe("failed"); + }); + + it("reports disconnected after cleanup", () => { + expect( + deriveConnectionState(stateInput({ cleanedUp: true, connected: true, registered: true })), + ).toBe("disconnected"); + }); + + it("defaults to connecting for a fresh monitor", () => { + expect(deriveConnectionState(stateInput())).toBe("connecting"); + }); +}); + +describe("gateway getStatus aggregation", () => { + function makeContext(config: Record, state: Record): Context { + return { + config, + state, + runtime: {} as Context["runtime"], + logger: { info: () => {}, warn: () => {}, error: () => {} } as Context["logger"], + abortSignal: new AbortController().signal, + deliver: async () => {}, + } as unknown as Context; + } + + it("reports unconfigured when no account has credentials", () => { + const status = gateway.getStatus!(makeContext({ accounts: {} }, {})); + expect(status).toMatchObject({ connected: false, configured: false }); + }); + + it("reports failures for accounts whose monitor failed to start", () => { + const status = gateway.getStatus!( + makeContext( + { accounts: { default: { clientId: "cli_test_1", clientSecret: "test-secret" } } }, + { monitors: new Map(), failures: new Map([["default", "endpoint unreachable"]]) }, + ), + ); + expect(status.connected).toBe(false); + expect(status.configured).toBe(true); + expect(status.details).toContain("default: endpoint unreachable"); + }); + + it("counts connected monitors and surfaces per-account details", () => { + const monitor = { + getStatus: () => ({ + connected: true, + configured: true, + message: { key: "status.connected", fallback: "Connected" }, + }), + }; + const failing = { + getStatus: () => ({ + connected: false, + configured: true, + message: { key: "status.failed", fallback: "Connection failed" }, + details: "HTTP 401", + }), + }; + const status = gateway.getStatus!( + makeContext( + { + accounts: { + a: { clientId: "cli_test_1", clientSecret: "test-secret" }, + b: { clientId: "cli_test_2", clientSecret: "test-secret" }, + }, + }, + { monitors: new Map([["a", monitor]]), failures: new Map() }, + ), + ); + // Both entries go through getAccountStatus, so "b" resolves through its own + // (failing) monitor-less status path only if present — here b has no + // monitor and no failure, so it reports disconnected. + void failing; + expect(status.connected).toBe(true); + }); +}); + +describe("command: /dingtalk status", () => { + it("renders localized status lines", async () => { + const command = feishuLikeIndex.commands![0]; + const result = await command.execute({ + args: "status", + config: { accounts: { default: { clientId: "cli_test_1", clientSecret: "test-secret" } } }, + logger: { info: () => {}, warn: () => {}, error: () => {} }, + }); + const text = resolvePluginText(result?.reply, undefined, "en"); + expect(text).toContain("DingTalk Status"); + expect(text).toContain("**default**"); + }); + + it("reports when no accounts are configured", async () => { + const command = feishuLikeIndex.commands![0]; + const result = await command.execute({ + args: "status", + config: {}, + logger: { info: () => {}, warn: () => {}, error: () => {} }, + }); + expect(resolvePluginText(result?.reply, undefined, "en")).toContain("No account configured"); + }); + + it("redacts the client id in the accounts listing", async () => { + const command = feishuLikeIndex.commands![0]; + const result = await command.execute({ + args: "accounts", + config: { + accounts: { default: { clientId: "cli_test_secret", clientSecret: "test-secret" } }, + }, + logger: { info: () => {}, warn: () => {}, error: () => {} }, + }); + const text = resolvePluginText(result?.reply, undefined, "en"); + expect(text).toContain("cli_***"); + expect(text).not.toContain("cli_test_secret"); + }); +}); + +describe("event handler delivery payloads", () => { + function makeDeps(overrides: Partial = {}): { + deps: EventHandlerDeps; + delivered: unknown[]; + } { + const delivered: unknown[] = []; + const deps: EventHandlerDeps = { + accountId: "default", + client: {} as EventHandlerDeps["client"], + logger: { info: () => {}, warn: () => {}, error: () => {} }, + deliver: async (payload) => { + delivered.push(payload); + }, + dedup: new MessageDedup(), + groupEnabled: false, + ...overrides, + }; + return { deps, delivered }; + } + + const groupPayload = JSON.stringify({ + conversationId: "cid-group-1", + conversationType: "2", + msgId: "msg-g-1", + msgtype: "text", + text: { content: "@机器人 run the report" }, + senderStaffId: "staff-1", + senderId: "sender-1", + senderNick: "Tester", + robotCode: "ding-test-robot", + }); + + it("delivers group @mentions with mentionedBot when groups are enabled", async () => { + const { deps, delivered } = makeDeps({ groupEnabled: true }); + await handleRobotMessage(deps, groupPayload); + + expect(delivered).toHaveLength(1); + const payload = delivered[0] as { + sessionId: string[]; + conversation: { kind: string; id: string }; + mentionedBot?: boolean; + deliveryContext: { to: string }; + message: string; + }; + expect(payload.sessionId).toEqual(["conversation", "default", "cid-group-1"]); + expect(payload.conversation).toEqual({ kind: "group", id: "cid-group-1" }); + expect(payload.mentionedBot).toBe(true); + expect(payload.deliveryContext.to).toBe("conversation:cid-group-1"); + // Group message text is wrapped with a sender tag (no ownerStaffId → non-owner). + expect(payload.message).toContain("[非所有者消息 · 发送者: Tester(sender-1)"); + expect(payload.message).toContain("run the report"); + }); + + it("tags a group message as owner when senderId matches ownerStaffId", async () => { + const { deps, delivered } = makeDeps({ groupEnabled: true, ownerStaffId: "sender-1" }); + await handleRobotMessage(deps, groupPayload); + + expect(delivered).toHaveLength(1); + const payload = delivered[0] as { message: string }; + expect(payload.message).toContain("[所有者]"); + expect(payload.message).toContain("run the report"); + }); + + it("tags a group message as non-owner when senderId differs from ownerStaffId", async () => { + const { deps, delivered } = makeDeps({ + groupEnabled: true, + ownerStaffId: "other-owner-staff", + }); + await handleRobotMessage(deps, groupPayload); + + expect(delivered).toHaveLength(1); + const payload = delivered[0] as { message: string }; + expect(payload.message).toContain("[非所有者消息 · 发送者: Tester(sender-1)"); + expect(payload.message).toContain("禁止提供文件、资料或任何私人信息"); + expect(payload.message).toContain("never provide files, materials, or any private information"); + expect(payload.message).toContain("run the report"); + }); + + it("leaves direct messages untagged regardless of ownerStaffId", async () => { + const { deps, delivered } = makeDeps({ groupEnabled: true, ownerStaffId: "sender-1" }); + await handleRobotMessage( + deps, + JSON.stringify({ + conversationId: "cid-dm-1", + conversationType: "1", + msgId: "msg-d-1", + msgtype: "text", + text: { content: "hello" }, + senderStaffId: "staff-1", + senderId: "sender-1", + robotCode: "ding-test-robot", + }), + ); + + expect(delivered).toHaveLength(1); + const payload = delivered[0] as { message: string }; + expect(payload.message).toBe("hello"); + expect(payload.message).not.toContain("[所有者]"); + expect(payload.message).not.toContain("[非所有者消息"); + }); + + it("delivers direct chats with a staff session id", async () => { + const { deps, delivered } = makeDeps({ groupEnabled: true }); + await handleRobotMessage( + deps, + JSON.stringify({ + conversationId: "cid-dm-1", + conversationType: "1", + msgId: "msg-d-1", + msgtype: "text", + text: { content: "hello" }, + senderStaffId: "staff-1", + senderId: "sender-1", + robotCode: "ding-test-robot", + }), + ); + + expect(delivered).toHaveLength(1); + const payload = delivered[0] as { + sessionId: string[]; + conversation: { kind: string; id: string }; + mentionedBot?: boolean; + deliveryContext: { to: string }; + }; + expect(payload.sessionId).toEqual(["staff", "default", "staff-1"]); + expect(payload.conversation).toEqual({ kind: "direct", id: "staff-1" }); + expect(payload.mentionedBot).toBeUndefined(); + expect(payload.deliveryContext.to).toBe("staff:staff-1"); + }); + + it("deduplicates redelivered msgIds", async () => { + const { deps, delivered } = makeDeps({ groupEnabled: true }); + await handleRobotMessage(deps, groupPayload); + await handleRobotMessage(deps, groupPayload); + expect(delivered).toHaveLength(1); + }); + + it("skips direct messages without senderStaffId (unpublished robot)", async () => { + const { deps, delivered } = makeDeps({ groupEnabled: true }); + await handleRobotMessage( + deps, + JSON.stringify({ + conversationId: "cid-dm-2", + conversationType: "1", + msgId: "msg-d-2", + msgtype: "text", + text: { content: "hello" }, + senderId: "sender-1", + robotCode: "ding-test-robot", + }), + ); + expect(delivered).toHaveLength(0); + }); + + it("notifies group senders that group chat is disabled (via REST client)", async () => { + const sendGroupMessage = Object.assign( + vi.fn(async () => {}), + // satisfy the DingTalkClient type + ); + const { deps, delivered } = makeDeps({ + groupEnabled: false, + client: { sendGroupMessage } as unknown as EventHandlerDeps["client"], + }); + await handleRobotMessage(deps, groupPayload); + + expect(delivered).toHaveLength(0); + expect(sendGroupMessage).toHaveBeenCalledTimes(1); + const [robotCode, conversationId, message] = sendGroupMessage.mock.calls[0] as [ + string, + string, + { msgKey: string; msgParam: string }, + ]; + expect(robotCode).toBe("ding-test-robot"); + expect(conversationId).toBe("cid-group-1"); + expect(message.msgKey).toBe("sampleText"); + const parsed = JSON.parse(message.msgParam) as { content: string }; + expect(parsed.content).toContain("Group chat is not enabled"); + }); +}); diff --git a/plugins/dingtalk/tests/message.test.ts b/plugins/dingtalk/tests/message.test.ts new file mode 100644 index 0000000..a473e9c --- /dev/null +++ b/plugins/dingtalk/tests/message.test.ts @@ -0,0 +1,161 @@ +import { describe, expect, it, vi } from "vitest"; +import { + buildSessionTarget, + parseRobotMessage, + stripMentionPrefix, + summarizeMediaMessage, +} from "../src/gateway/message.js"; +import { MessageDedup } from "../src/gateway/dedup.js"; + +const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn() } as never; + +function directPayload(overrides: Record = {}) { + return JSON.stringify({ + conversationId: "cid-test-1", + conversationType: "1", + msgId: "msg-test-1", + msgtype: "text", + text: { content: "hello cola" }, + senderStaffId: "staff-001", + senderId: "sender-001", + senderNick: "Tester", + robotCode: "ding-test-robot", + sessionWebhook: "https://oapi.dingtalk.com/robot/send?sessionWebhook=test", + sessionWebhookExpiredTime: 9999999999999, + createAt: 1700000000000, + ...overrides, + }); +} + +describe("parseRobotMessage", () => { + it("parses a direct text message and resolves a staff session target", () => { + const parsed = parseRobotMessage(directPayload(), logger); + expect(parsed).toMatchObject({ + text: "hello cola", + msgId: "msg-test-1", + isGroup: false, + conversationId: "cid-test-1", + senderStaffId: "staff-001", + robotCode: "ding-test-robot", + }); + expect(buildSessionTarget(parsed!)).toBe("staff:staff-001"); + }); + + it("parses a group message and resolves a conversation session target", () => { + const parsed = parseRobotMessage( + directPayload({ + conversationType: "2", + text: { content: "@机器人 what is up" }, + senderStaffId: "staff-002", + }), + logger, + ); + expect(parsed).toMatchObject({ + text: "what is up", + isGroup: true, + }); + expect(buildSessionTarget(parsed!)).toBe("conversation:cid-test-1"); + }); + + it("returns undefined for invalid JSON", () => { + expect(parseRobotMessage("not json", logger)).toBeUndefined(); + }); + + it("returns undefined when required identifiers are missing", () => { + expect(parseRobotMessage(directPayload({ msgId: undefined }), logger)).toBeUndefined(); + expect(parseRobotMessage(directPayload({ conversationId: undefined }), logger)).toBeUndefined(); + expect( + parseRobotMessage(directPayload({ conversationType: undefined }), logger), + ).toBeUndefined(); + expect(logger.warn).toHaveBeenCalled(); + }); + + it("accepts already-parsed payloads", () => { + const parsed = parseRobotMessage({ + conversationType: "1", + conversationId: "c", + msgId: "m", + msgtype: "text", + text: { content: "hi" }, + }); + expect(parsed?.text).toBe("hi"); + }); +}); + +describe("stripMentionPrefix", () => { + it("strips the DingTalk @机器人 prefix with a trailing space", () => { + expect(stripMentionPrefix("@机器人 help me")).toBe("help me"); + }); + + it("strips a bare mention with no trailing space", () => { + expect(stripMentionPrefix("@机器人")).toBe(""); + }); + + it("strips a full-width space after the mention", () => { + expect(stripMentionPrefix("@机器人 help me")).toBe("help me"); + }); + + it("returns empty text when the message is only a mention", () => { + expect(stripMentionPrefix("@机器人")).toBe(""); + }); +}); + +describe("summarizeMediaMessage", () => { + const base = { conversationType: "2", conversationId: "c", msgId: "m" }; + + it("summarizes picture, audio, and video messages", () => { + expect(summarizeMediaMessage({ ...base, msgtype: "picture" })).toBe("[图片]"); + expect(summarizeMediaMessage({ ...base, msgtype: "audio" })).toBe("[语音]"); + expect(summarizeMediaMessage({ ...base, msgtype: "video" })).toBe("[视频]"); + }); + + it("summarizes file messages with the file name when present", () => { + expect(summarizeMediaMessage({ ...base, msgtype: "file", fileName: "report.pdf" })).toBe( + "[文件: report.pdf]", + ); + expect( + summarizeMediaMessage({ ...base, msgtype: "file", content: { downloadCode: "x" } }), + ).toBe("[文件]"); + }); + + it("extracts inline text from richText messages", () => { + expect( + summarizeMediaMessage({ + ...base, + msgtype: "richText", + content: { + richArray: [ + { type: "text", text: "rich " }, + { type: "text", text: "body" }, + ], + }, + }), + ).toBe("[图文] rich body"); + expect(summarizeMediaMessage({ ...base, msgtype: "richText" })).toBe("[图文]"); + }); + + it("falls back to the raw msgtype for unknown types", () => { + expect(summarizeMediaMessage({ ...base, msgtype: "hologram" })).toBe("[hologram]"); + }); +}); + +describe("MessageDedup (second dedup layer)", () => { + it("marks the first sighting as fresh and repeats as duplicates", () => { + const dedup = new MessageDedup(); + expect(dedup.isDuplicate("msg-a")).toBe(false); + expect(dedup.isDuplicate("msg-a")).toBe(true); + expect(dedup.isDuplicate("msg-b")).toBe(false); + }); + + it("forgets ids after the TTL expires", () => { + vi.useFakeTimers(); + try { + const dedup = new MessageDedup(1000); + expect(dedup.isDuplicate("msg-a")).toBe(false); + vi.advanceTimersByTime(1001); + expect(dedup.isDuplicate("msg-a")).toBe(false); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/plugins/dingtalk/tests/token.test.ts b/plugins/dingtalk/tests/token.test.ts new file mode 100644 index 0000000..4f47f3f --- /dev/null +++ b/plugins/dingtalk/tests/token.test.ts @@ -0,0 +1,113 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { AccessTokenManager } from "../src/api/token.js"; + +const TOKEN_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken"; + +function jsonResponse(body: unknown, status = 200): Response { + return { + ok: status >= 200 && status < 300, + status, + json: async () => body, + text: async () => JSON.stringify(body), + } as unknown as Response; +} + +describe("AccessTokenManager", () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-01-01T00:00:00Z")); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("requests a token from the oauth2/accessToken endpoint with app credentials", async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ accessToken: "tok-1", expireIn: 7200 })); + const manager = new AccessTokenManager("test-appkey", "test-secret", fetchImpl); + + await expect(manager.getToken()).resolves.toBe("tok-1"); + expect(fetchImpl).toHaveBeenCalledOnce(); + const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]; + expect(url).toBe(TOKEN_URL); + expect(init.method).toBe("POST"); + expect(JSON.parse(String(init.body))).toEqual({ + appKey: "test-appkey", + appSecret: "test-secret", + }); + }); + + it("caches the token within its validity window and never logs it", async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ accessToken: "tok-1", expireIn: 7200 })); + const manager = new AccessTokenManager("test-appkey", "test-secret", fetchImpl); + + await expect(manager.getToken()).resolves.toBe("tok-1"); + await expect(manager.getToken()).resolves.toBe("tok-1"); + await expect(manager.getToken()).resolves.toBe("tok-1"); + expect(fetchImpl).toHaveBeenCalledOnce(); + }); + + it("coalesces concurrent refreshes into a single request", async () => { + let requests = 0; + const fetchImpl = vi.fn(async () => { + requests += 1; + return jsonResponse({ accessToken: `tok-${requests}`, expireIn: 7200 }); + }); + const manager = new AccessTokenManager("test-appkey", "test-secret", fetchImpl); + + const [a, b, c] = await Promise.all([ + manager.getToken(), + manager.getToken(), + manager.getToken(), + ]); + expect(a).toBe("tok-1"); + expect(b).toBe(a); + expect(c).toBe(a); + expect(fetchImpl).toHaveBeenCalledOnce(); + }); + + it("expires the cached token after the documented validity window and refreshes early", async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ accessToken: "tok-1", expireIn: 7200 })); + const manager = new AccessTokenManager("test-appkey", "test-secret", fetchImpl); + + await manager.getToken(); + + // 7200s validity minus the 300s refresh margin = 6900s cached. + vi.advanceTimersByTime(6899 * 1000); + await manager.getToken(); + expect(fetchImpl).toHaveBeenCalledOnce(); + + vi.advanceTimersByTime(2 * 1000); + fetchImpl.mockImplementation(async () => + jsonResponse({ accessToken: "tok-2", expireIn: 7200 }), + ); + await expect(manager.getToken()).resolves.toBe("tok-2"); + expect(fetchImpl).toHaveBeenCalledTimes(2); + }); + + it("clears the cache on demand", async () => { + let requests = 0; + const fetchImpl = vi.fn(async () => { + requests += 1; + return jsonResponse({ accessToken: `tok-${requests}`, expireIn: 7200 }); + }); + const manager = new AccessTokenManager("test-appkey", "test-secret", fetchImpl); + + await manager.getToken(); + manager.clear(); + await expect(manager.getToken()).resolves.toBe("tok-2"); + expect(fetchImpl).toHaveBeenCalledTimes(2); + }); + + it("throws when the response has no accessToken", async () => { + const fetchImpl = vi.fn(async () => jsonResponse({})); + const manager = new AccessTokenManager("test-appkey", "test-secret", fetchImpl); + await expect(manager.getToken()).rejects.toThrow("missing the accessToken field"); + }); + + it("throws when the endpoint returns a non-2xx status", async () => { + const fetchImpl = vi.fn(async () => jsonResponse({}, 500)); + const manager = new AccessTokenManager("test-appkey", "test-secret", fetchImpl); + await expect(manager.getToken()).rejects.toThrow("HTTP 500"); + }); +}); diff --git a/plugins/dingtalk/tsconfig.json b/plugins/dingtalk/tsconfig.json new file mode 100644 index 0000000..564a599 --- /dev/null +++ b/plugins/dingtalk/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src"] +} diff --git a/plugins/dingtalk/tsup.config.ts b/plugins/dingtalk/tsup.config.ts new file mode 100644 index 0000000..cd0a2a1 --- /dev/null +++ b/plugins/dingtalk/tsup.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from "tsup"; + +export default defineConfig({ + entry: ["src/index.ts"], + format: ["esm"], + dts: true, + sourcemap: true, + clean: true, + external: ["dingtalk-stream"], +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 571f32b..b5ddedb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -24,6 +24,25 @@ importers: specifier: ^2.1.9 version: 2.1.9(@types/node@22.19.17) + plugins/dingtalk: + dependencies: + '@marswave/cola-plugin-sdk': + specifier: 0.0.5 + version: 0.0.5 + dingtalk-stream: + specifier: 2.1.5 + version: 2.1.5 + devDependencies: + '@types/node': + specifier: ^22.0.0 + version: 22.19.17 + tsup: + specifier: ^8.5.1 + version: 8.5.1(postcss@8.5.15)(tsx@4.21.0)(typescript@5.9.3) + typescript: + specifier: ^5.8.3 + version: 5.9.3 + plugins/feishu: dependencies: '@larksuiteoapi/node-sdk': @@ -949,6 +968,9 @@ packages: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} + dingtalk-stream@2.1.5: + resolution: {integrity: sha512-6H3tSc/mE6hMj4RBB5ntkI4ycC498RobmtMxfLS8eBTRPjBZlhUdDYEHA0asOoTLSzC2PHqupr4D4HVoaU7bRQ==} + dunder-proto@1.0.1: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} @@ -1601,7 +1623,7 @@ snapshots: '@larksuiteoapi/node-sdk@1.73.3': dependencies: - axios: 1.18.0 + axios: 1.18.0(debug@4.4.3) lodash.identity: 3.0.0 lodash.merge: 4.6.2 lodash.pickby: 4.6.0 @@ -1854,7 +1876,7 @@ snapshots: '@slack/types': 2.21.1 '@types/node': 22.19.17 '@types/retry': 0.12.0 - axios: 1.18.0 + axios: 1.18.0(debug@4.4.3) eventemitter3: 5.0.4 form-data: 4.0.5 is-electron: 2.2.2 @@ -1932,9 +1954,9 @@ snapshots: asynckit@0.4.0: {} - axios@1.18.0: + axios@1.18.0(debug@4.4.3): dependencies: - follow-redirects: 1.16.0 + follow-redirects: 1.16.0(debug@4.4.3) form-data: 4.0.5 https-proxy-agent: 5.0.1 proxy-from-env: 2.1.0 @@ -1991,6 +2013,16 @@ snapshots: delayed-stream@1.0.0: {} + dingtalk-stream@2.1.5: + dependencies: + axios: 1.18.0(debug@4.4.3) + debug: 4.4.3 + ws: 8.20.0 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + dunder-proto@1.0.1: dependencies: call-bind-apply-helpers: 1.0.2 @@ -2089,7 +2121,9 @@ snapshots: mlly: 1.8.2 rollup: 4.60.1 - follow-redirects@1.16.0: {} + follow-redirects@1.16.0(debug@4.4.3): + optionalDependencies: + debug: 4.4.3 form-data@4.0.5: dependencies: From 35daf996cb25307a8877d90df112dc90f6d274d9 Mon Sep 17 00:00:00 2001 From: echohn Date: Wed, 23 Sep 2026 23:24:25 +0800 Subject: [PATCH 02/10] fix(dingtalk): add frame watchdog to detect silently dead stream connections MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dingtalk-stream SDK's internal auto-reconnect swallows errors, so a half-open TCP connection (sleep/wake, proxy failover) can stay reported as connected while no frames ever arrive — messages are lost silently (observed live: 18+ hours unaware). Track the last inbound frame timestamp (any downstream frame counts) and re-establish the connection when no frame arrives within 5 minutes; log a WARN on watchdog-triggered reconnects, clean up the timer on stop/abort, and re-arm after each successful reconnect. --- plugins/dingtalk/src/gateway/monitor.ts | 77 ++++++++++++ plugins/dingtalk/tests/watchdog.test.ts | 155 ++++++++++++++++++++++++ 2 files changed, 232 insertions(+) create mode 100644 plugins/dingtalk/tests/watchdog.test.ts diff --git a/plugins/dingtalk/src/gateway/monitor.ts b/plugins/dingtalk/src/gateway/monitor.ts index d3b4926..fa82d30 100644 --- a/plugins/dingtalk/src/gateway/monitor.ts +++ b/plugins/dingtalk/src/gateway/monitor.ts @@ -52,6 +52,22 @@ export type ConnectionStateInput = { * (see QwenLM/qwen-code#6715 for the same finding). `registered` is still * surfaced via getStatus details when we happen to receive it. */ +/** + * How often the watchdog timer samples the last-inbound-frame timestamp. + */ +export const WATCHDOG_CHECK_INTERVAL_MS = 60_000; + +/** + * If no inbound Stream frame (KEEPALIVE / SYSTEM / message) arrives within + * this window while the socket still reports itself open, treat the + * connection as dead (half-open TCP after system sleep / proxy switch) and + * forcibly recycle it. The SDK's autoReconnect only reacts to a socket + * "close" (dingtalk-stream client.mjs), which half-open sockets never emit, + * so the client stays "connected" forever while frames stop flowing — we + * must break the connection ourselves. + */ +export const NO_FRAME_TIMEOUT_MS = 5 * 60_000; + export function deriveConnectionState(input: ConnectionStateInput): ConnectionState { if (input.cleanedUp) return "disconnected"; if (input.connected) return "connected"; @@ -84,6 +100,12 @@ export async function startMonitor(opts: { const errors: string[] = []; let observedRobotCode: string | undefined; + // Heartbeat watchdog state. lastDownstreamTs is refreshed whenever any + // inbound frame is observed; the timer trips if it goes stale while the + // socket still thinks it is connected (see NO_FRAME_TIMEOUT_MS). + let lastDownstreamTs = Date.now(); + let watchdogTimer: ReturnType | undefined; + const restClient = getDingTalkClient(accountId, config); const dedup = new MessageDedup(); @@ -99,6 +121,18 @@ export async function startMonitor(opts: { autoReconnect: true, } as DWClientOptions); + // Refresh the watchdog timestamp on every inbound frame. The SDK routes + // KEEPALIVE / SYSTEM / EVENT / CALLBACK inbound frames through + // DWClient.onDownStream (dingtalk-stream client.mjs), so hooking it here + // covers all of them without touching dedup / authorization logic. The + // original handler is preserved so the SDK still dispatches to our topic + // callback below. + const originalOnDownStream = stream.onDownStream.bind(stream); + stream.onDownStream = (data: string) => { + lastDownstreamTs = Date.now(); + originalOnDownStream(data); + }; + const deps: EventHandlerDeps = { accountId, client: restClient, @@ -158,6 +192,7 @@ export async function startMonitor(opts: { errors.length = 0; logger.info(`dingtalk[${accountId}]: Stream connected`); } + startWatchdog(); return; } catch (err) { recordError(err); @@ -168,10 +203,52 @@ export async function startMonitor(opts: { } }; + const stopWatchdog = () => { + if (watchdogTimer !== undefined) { + clearInterval(watchdogTimer); + watchdogTimer = undefined; + } + }; + + // Start the heartbeat watchdog interval if it isn't running. Called on + // startup and again after every successful (re)connect so the watchdog + // keeps watching across recycle cycles. The SDK only notices a lost + // connection when the socket emits "close" (dingtalk-stream client.mjs) — a + // half-open TCP socket after system sleep / proxy switch never does, so + // autoReconnect stays silent. If the socket still reports itself connected + // but no frame has arrived for NO_FRAME_TIMEOUT_MS, the connection is dead. + const startWatchdog = () => { + if (watchdogTimer !== undefined || cleanedUp || abortSignal.aborted) return; + watchdogTimer = setInterval(() => { + if (cleanedUp) return; + const now = Date.now(); + if (stream.connected && now - lastDownstreamTs > NO_FRAME_TIMEOUT_MS) { + recycle(); + } + }, WATCHDOG_CHECK_INTERVAL_MS); + }; + + // Break the current connection and re-enter the connect loop. disconnect() + // sets DWClient.userDisconnect, which suppresses the SDK's own (half-open- + // blind) autoReconnect; the fresh connectLoop then clears it on the next + // _connect(). Status keeps flowing through deriveConnectionState the whole + // time, and startWatchdog() is re-armed by connectLoop on success. + const recycle = () => { + try { + stream.disconnect(); + } catch (err) { + logger.error(`dingtalk[${accountId}]: failed to break stale Stream connection`, err); + } + const idleSec = Math.round((Date.now() - lastDownstreamTs) / 1000); + logger.warn(`dingtalk[${accountId}]: no frames for ${idleSec}s, reconnecting`); + void connectLoop(); + }; + const cleanup = () => { if (cleanedUp) return; cleanedUp = true; abortSignal.removeEventListener("abort", handleAbort); + stopWatchdog(); try { stream.disconnect(); } catch (err) { diff --git a/plugins/dingtalk/tests/watchdog.test.ts b/plugins/dingtalk/tests/watchdog.test.ts new file mode 100644 index 0000000..1215296 --- /dev/null +++ b/plugins/dingtalk/tests/watchdog.test.ts @@ -0,0 +1,155 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + startMonitor, + NO_FRAME_TIMEOUT_MS, + WATCHDOG_CHECK_INTERVAL_MS, +} from "../src/gateway/monitor.js"; +import type { DeliverFn, PluginLogger } from "@marswave/cola-plugin-sdk"; +import type { DingTalkAccountConfig } from "../src/api/types.js"; + +// The subset of DWClient the monitor touches, plus the lifecycle counters the +// tests assert on. All credentials are fake; no network is touched. +type CapturedClient = { + connected: boolean; + registered: boolean; + reconnecting: boolean; + disconnectCount: number; + onDownStream: (data: string) => void; +}; + +let capturedClient: CapturedClient | undefined; + +vi.mock("dingtalk-stream", () => ({ + TOPIC_ROBOT: "__robot__", + DWClient: class { + connected = false; + registered = false; + reconnecting = false; + onDownStream = () => {}; + disconnectCount = 0; + registerCallbackListener = (_t: string, _c: unknown) => this; + socketCallBackResponse = () => {}; + getEndpoint = async () => { + this.connected = true; + return this; + }; + _connect = async () => { + this.connected = true; + }; + disconnect = () => { + this.disconnectCount += 1; + this.connected = false; + }; + constructor() { + capturedClient = this as unknown as CapturedClient; + } + }, +})); + +function makeLogger(): PluginLogger & { warns: unknown[] } { + const warns: unknown[] = []; + return { + info: () => {}, + warn: (...args: unknown[]) => { + warns.push(args[0]); + }, + error: () => {}, + warns, + } as PluginLogger & { warns: unknown[] }; +} + +const fakeConfig: DingTalkAccountConfig = { + clientId: "cli_test_watchdog", + clientSecret: "test-secret", +}; + +async function bootMonitor() { + capturedClient = undefined; + const logger = makeLogger(); + const controller = new AbortController(); + const handle = await startMonitor({ + accountId: "default", + config: fakeConfig, + deliver: (async () => {}) as DeliverFn, + logger, + abortSignal: controller.signal, + groupEnabled: false, + }); + // Flush the synchronous connectLoop microtasks (getEndpoint/_connect resolve + // immediately), so the watchdog gets armed before we start the clock. + await vi.advanceTimersByTimeAsync(0); + const client = capturedClient!; + return { handle, logger, controller, client }; +} + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("watchdog: last-frame dead-connection detection", () => { + it("forcibly disconnects and reconnects when no frame arrives within the timeout", async () => { + const { logger, client } = await bootMonitor(); + expect(client.disconnectCount).toBe(0); + + // Keep the socket "open" but push no frames for the full timeout window. + await vi.advanceTimersByTimeAsync(NO_FRAME_TIMEOUT_MS + WATCHDOG_CHECK_INTERVAL_MS); + + // The watchdog should have broken the dead connection and logged a warning, + // then the connect loop rebuilt it (socket torn down and re-established). + expect(client.disconnectCount).toBeGreaterThanOrEqual(1); + expect(logger.warns.some((w) => String(w).includes("no frames"))).toBe(true); + expect(client.connected).toBe(true); // reconnected by the loop after the forced break + }); + + it("does not fire while frames keep arriving within the timeout window", async () => { + const { logger, client } = await bootMonitor(); + + // Feed a KEEPALIVE every 3 minutes for well past the timeout; each refresh + // resets the freshness clock, so the watchdog must stay quiet. + for (let elapsed = 0; elapsed < NO_FRAME_TIMEOUT_MS * 3; elapsed += 3 * 60_000) { + await vi.advanceTimersByTimeAsync(3 * 60_000); + client.onDownStream(JSON.stringify({ type: "SYSTEM", headers: { topic: "KEEPALIVE" } })); + } + + expect(client.disconnectCount).toBe(0); + expect(logger.warns.some((w) => String(w).includes("no frames"))).toBe(false); + expect(client.connected).toBe(true); + }); + + it("stops firing after stop/cleanup clears the watchdog", async () => { + const { handle, logger, client, controller } = await bootMonitor(); + + controller.abort(); // triggers cleanup -> stopWatchdog() + expect(client.disconnectCount).toBe(1); // the teardown call + + // Advance well past the timeout: the watchdog must no longer recycle. + await vi.advanceTimersByTimeAsync(NO_FRAME_TIMEOUT_MS * 2); + expect(client.disconnectCount).toBe(1); + expect(logger.warns.some((w) => String(w).includes("no frames"))).toBe(false); + + handle.cleanup(); // idempotent + expect(client.disconnectCount).toBe(1); + }); + + it("re-arms the watchdog after a watchdog-initiated reconnect", async () => { + const { logger, client } = await bootMonitor(); + + // First stall -> recycle fires, connectLoop reconnects and re-arms. + await vi.advanceTimersByTimeAsync(NO_FRAME_TIMEOUT_MS + WATCHDOG_CHECK_INTERVAL_MS); + expect(client.disconnectCount).toBeGreaterThanOrEqual(1); + expect(client.connected).toBe(true); + + // Feed a KEEPALIVE so the fresh connection is healthy again. + client.onDownStream(JSON.stringify({ type: "SYSTEM", headers: { topic: "KEEPALIVE" } })); + + // A second stall must be caught by the (re-armed) watchdog too. + const before = client.disconnectCount; + await vi.advanceTimersByTimeAsync(NO_FRAME_TIMEOUT_MS + WATCHDOG_CHECK_INTERVAL_MS); + expect(client.disconnectCount).toBeGreaterThan(before); + expect(logger.warns.some((w) => String(w).includes("no frames"))).toBe(true); + }); +}); From c2cc77232669ddfaa8daed73ef53fd69bf37aef8 Mon Sep 17 00:00:00 2001 From: echohn Date: Wed, 23 Sep 2026 23:47:42 +0800 Subject: [PATCH 03/10] feat(dingtalk): media send/receive support (images and files) Send: upload media via the robot media upload API, then deliver via oToMessages/groupMessages as sampleImageMsg / sampleAudio / sampleFile. Declares outbound mediaCapabilities (image/file, 20MB DingTalk cap) so the host validates size client-side. Video is intentionally unsupported: sampleVideo requires a separate cover-image mediaId that cannot be derived from a single file. Receive: image/file messages are downloaded (downloadCode -> temp URL, 50MB cap, filename sanitization) instead of degrading to a text-only summary. --- plugins/dingtalk/README.md | 22 +- plugins/dingtalk/package.json | 2 +- plugins/dingtalk/src/api/client.ts | 237 ++++++++++++++++- plugins/dingtalk/src/gateway/event-handler.ts | 15 ++ .../dingtalk/src/gateway/media-download.ts | 60 +++++ plugins/dingtalk/src/gateway/message.ts | 66 +++++ plugins/dingtalk/src/index.ts | 38 ++- plugins/dingtalk/src/outbound/send.ts | 91 ++++++- plugins/dingtalk/tests/media.test.ts | 249 ++++++++++++++++++ plugins/dingtalk/tests/message.test.ts | 119 +++++++++ 10 files changed, 891 insertions(+), 8 deletions(-) create mode 100644 plugins/dingtalk/src/gateway/media-download.ts create mode 100644 plugins/dingtalk/tests/media.test.ts diff --git a/plugins/dingtalk/README.md b/plugins/dingtalk/README.md index 3a76e89..3d90aae 100644 --- a/plugins/dingtalk/README.md +++ b/plugins/dingtalk/README.md @@ -8,9 +8,14 @@ certificate is required. - Receives robot messages (direct chats and @-mentions in group chats) over a managed Stream WebSocket connection with automatic reconnect. +- Receives inbound media: images, audio, video and files are downloaded to a + local temp path and handed to the agent as attachments (up to 50 MB each). + When a download fails, the message falls back to a short text summary. - Sends Cola replies back to the originating DingTalk conversation: `oToMessages` for direct chats, `groupMessages` for group chats. - Sends Markdown replies when the model output is markdown-capable. +- Sends image and file replies natively (uploaded to DingTalk via its media + upload API and sent as `sampleImageMsg` / `sampleFile` robot messages). - Group chat is opt-in via `groupEnabled`; DingTalk itself only pushes group messages that @-mention the robot. @@ -43,12 +48,23 @@ certificate is required. ## Notes and limits -- The Stream channel is receive-only: replies are sent through the DingTalk +- The Stream channel is receive-only; replies are sent through the DingTalk REST API with an access token cached for its 2-hour validity window. - Group message payloads are limited to 15000 bytes by DingTalk; Cola splits longer replies. -- Incoming images, files, audio, and video are delivered as text summaries in - the first release; media download and upload are planned for a later version. +- Incoming media downloads: DingTalk's robot file-download endpoint returns a + short-lived temporary URL; the plugin downloads to a local temp dir (capped + at 50 MB per file). Media messages without a usable `downloadCode` (e.g. + rich-text messages with embedded pictures) remain text summaries. +- Outbound media: images and files are supported. DingTalk's video message + (`sampleVideo`) additionally requires a cover-image mediaId that cannot be + derived from the single file Cola provides, so video replies are not enabled. + Voice uploads are capped at 2 MB by DingTalk; image/video/file at 20 MB. +- Media upload uses DingTalk's legacy OAPI gateway + (`https://oapi.dingtalk.com/media/upload`), which authenticates with an + `access_token` form/query field rather than the `x-acs-dingtalk-access-token` + header used by the newer `api.dingtalk.com` robot endpoints. The token is the + same one issued by `/v1.0/oauth2/accessToken`. - Treat the Client Secret as a credential: it is stored in Cola's secret configuration fields and is never written to logs or files. diff --git a/plugins/dingtalk/package.json b/plugins/dingtalk/package.json index 0ef783e..a8b9d88 100644 --- a/plugins/dingtalk/package.json +++ b/plugins/dingtalk/package.json @@ -1,6 +1,6 @@ { "name": "cola-plugin-dingtalk", - "version": "0.1.0", + "version": "0.2.0", "description": "DingTalk channel plugin for Cola", "license": "Apache-2.0", "type": "module", diff --git a/plugins/dingtalk/src/api/client.ts b/plugins/dingtalk/src/api/client.ts index 1109b65..6538d2d 100644 --- a/plugins/dingtalk/src/api/client.ts +++ b/plugins/dingtalk/src/api/client.ts @@ -2,8 +2,14 @@ import { AccessTokenManager, type FetchLike } from "./token.js"; import type { DingTalkAccountConfig } from "./types.js"; const API_BASE = "https://api.dingtalk.com"; -/** DingTalk rejects robot message payloads whose msgParam exceeds 15000 UTF-8 bytes. */ +/** New-style REST host used by robot message send/download endpoints (x-acs-dingtalk-access-token header). */ +const OAPI_BASE = "https://oapi.dingtalk.com"; +/** + * DingTalk rejects robot message payloads whose msgParam exceeds 15000 UTF-8 bytes. + */ export const MAX_MSG_PARAM_BYTES = 15000; +/** Media upload size caps enforced by DingTalk's /media/upload endpoint. */ +export const MAX_MEDIA_UPLOAD_BYTES = 20 * 1024 * 1024; // image/video/file ≤ 20MB; voice ≤ 2MB const TRUNCATION_SUFFIX = "…(truncated)"; export type OutgoingMessage = { @@ -29,6 +35,60 @@ export function buildMarkdownMessage(text: string): OutgoingMessage { }; } +/** + * Build an image robot message (`sampleImageMsg`). DingTalk accepts either a + * full https URL or a mediaId (returned by /media/upload). We always pass the + * mediaId so the image renders natively inside the DingTalk client. + */ +export function buildImageMessage(mediaId: string): OutgoingMessage { + return { msgKey: "sampleImageMsg", msgParam: JSON.stringify({ photoURL: mediaId }) }; +} + +/** + * Build a file robot message (`sampleFile`). `fileType` is the lowercase + * extension without the dot (xlsx, pdf, docx, …). DingTalk's file message + * only supports a few office/archive formats; other files still upload fine + * but may display with a generic icon. + */ +export function buildFileMessage( + mediaId: string, + fileName: string, + fileType: string, +): OutgoingMessage { + return { msgKey: "sampleFile", msgParam: JSON.stringify({ mediaId, fileName, fileType }) }; +} + +/** + * Build a voice robot message (`sampleAudio`). Supported formats: ogg, amr. + * `duration` is in milliseconds. + */ +export function buildVoiceMessage(mediaId: string, durationMs = 0): OutgoingMessage { + return { + msgKey: "sampleAudio", + msgParam: JSON.stringify({ mediaId, duration: String(durationMs) }), + }; +} + +/** + * Build a video robot message (`sampleVideo`). `videoMediaId` must be an mp4 + * mediaId; `picMediaId` is the video cover image (also a mediaId). + */ +export function buildVideoMessage( + videoMediaId: string, + picMediaId: string, + durationSec = 0, +): OutgoingMessage { + return { + msgKey: "sampleVideo", + msgParam: JSON.stringify({ + duration: String(durationSec), + videoMediaId, + videoType: "mp4", + picMediaId, + }), + }; +} + function markdownTitle(text: string): string { const firstLine = text @@ -115,6 +175,161 @@ export class DingTalkClient { }); } + /** + * Upload a local media file and return the DingTalk mediaId. + * + * NOTE: DingTalk's media upload endpoint is a legacy OAPI gateway + * (`https://oapi.dingtalk.com/media/upload`) that authenticates via an + * `access_token` form/query field rather than the `x-acs-dingtalk-access-token` + * header used by the newer `api.dingtalk.com` robot endpoints. The access + * token is the same one issued by `/v1.0/oauth2/accessToken`, so the existing + * token manager covers it (verified against official docs; there is no + * newer REST-hosted upload API today). + */ + async uploadMedia(filePath: string, mediaType: string, fileName?: string): Promise { + const { readFile } = await import("node:fs/promises"); + let data: Uint8Array; + try { + data = await readFile(filePath); + } catch (err) { + throw new Error( + `DingTalk media upload failed to read ${filePath}: ${err instanceof Error ? err.message : String(err)}`, + ); + } + if (data.byteLength > MAX_MEDIA_UPLOAD_BYTES) { + throw new Error( + `DingTalk media upload rejected: file exceeds the ${MAX_MEDIA_UPLOAD_BYTES} byte limit`, + ); + } + + const token = await this.tokenManager.getToken(); + const form = new FormData(); + const name = fileName ?? filePath.split("/").pop() ?? "file"; + form.append("type", mediaType); + // The `media` part carries the filename + MIME; `append(blob, name)` is the + // browser-style FormData variant available in Node. We keep the Content-Type + // generic and let DingTalk infer the media format from the filename extension. + // Casting the Uint8Array to ArrayBuffer-typed view resolves the TS + // ArrayBufferLike/ArrayBuffer variance mismatch. + form.append( + "media", + new Blob([ + data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength), + ] as BlobPart[]), + name, + ); + + let response: Response; + try { + response = await this.fetchImpl( + `${OAPI_BASE}/media/upload?access_token=${encodeURIComponent(token)}`, + { method: "POST", body: form }, + ); + } catch (err) { + throw new Error( + `DingTalk media upload request failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + const body = (await response.json().catch(() => ({}))) as { + errcode?: number | string; + errmsg?: string; + media_id?: string; + }; + if ( + !response.ok || + (body.errcode !== undefined && Number(body.errcode) !== 0) || + !body.media_id + ) { + throw new Error( + `DingTalk media upload failed (HTTP ${response.status}, errcode=${body.errcode}): ${body.errmsg ?? ""}`, + ); + } + return body.media_id; + } + + /** + * Resolve a robot-received message downloadCode into a temporary download URL. + * The returned URL is short-lived and points at the file with a generic + * extension; the caller should rename with the message's own extension. + */ + async resolveMessageDownload(robotCode: string, downloadCode: string): Promise { + const token = await this.tokenManager.getToken(); + let response: Response; + try { + response = await this.fetchImpl(`${API_BASE}/v1.0/robot/messageFiles/download`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-acs-dingtalk-access-token": token, + }, + body: JSON.stringify({ downloadCode, robotCode }), + }); + } catch (err) { + throw new Error( + `DingTalk message download request failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + if (!response.ok) { + const detail = (await response.text().catch(() => "")).slice(0, 300); + throw new Error( + `DingTalk message download failed with HTTP ${response.status}${detail ? `: ${detail}` : ""}`, + ); + } + const data = (await response.json().catch(() => ({}))) as { downloadUrl?: string }; + if (!data.downloadUrl) { + throw new Error("DingTalk message download response is missing the downloadUrl field"); + } + return data.downloadUrl; + } + + /** + * Download a robot-received file to a temp path. `downloadCode` and + * `fileName` come from the inbound message payload. The temp file keeps the + * original (sanitized) filename so the agent sees a meaningful attachment. + */ + async downloadMessageFile( + robotCode: string, + downloadCode: string, + fileName: string, + opts?: { maxBytes?: number; signal?: AbortSignal }, + ): Promise { + const maxBytes = opts?.maxBytes ?? 50 * 1024 * 1024; + const downloadUrl = await this.resolveMessageDownload(robotCode, downloadCode); + + let response: Response; + try { + response = await this.fetchImpl(downloadUrl, { signal: opts?.signal }); + } catch (err) { + throw new Error( + `DingTalk message file fetch failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + if (!response.ok) { + const detail = (await response.text().catch(() => "")).slice(0, 300); + throw new Error( + `DingTalk message file download failed with HTTP ${response.status}${detail ? `: ${detail}` : ""}`, + ); + } + if (Number(response.headers.get("content-length")) > maxBytes) { + throw new Error(`DingTalk message file exceeds the ${maxBytes} byte limit`); + } + + const { mkdtemp, writeFile: write } = await import("node:fs/promises"); + const os = await import("node:os"); + const path = await import("node:path"); + + const data = await response.arrayBuffer(); + if (data.byteLength > maxBytes) { + throw new Error(`DingTalk message file exceeds the ${maxBytes} byte limit`); + } + + const dir = await mkdtemp(path.join(os.tmpdir(), "cola-dingtalk-")); + const safeName = sanitizeFileName(fileName || "message"); + const filePath = path.join(dir, safeName); + await write(filePath, Buffer.from(data)); + return filePath; + } + async request(path: string, body: Record): Promise { const token = await this.tokenManager.getToken(); let response: Response; @@ -148,6 +363,26 @@ type CachedEntry = { clientSecret: string; }; +/** + * Sanitize an inbound file name for safe use as a temp download path: strip + * path separators, shell metacharacters, and ASCII control characters. Keeps + * the extension so the agent and the user can identify the file type at a + * glance. + */ +export function sanitizeFileName(name: string): string { + let base = name.replace(/[\\/:*?"<>|]/g, "_"); + // Strip ASCII control characters (0x00–0x1f plus DEL) separately — a range + // in the char class above trips oxlint's no-control-regex. + base = base + .split("") + .filter((ch) => { + const code = ch.charCodeAt(0); + return code >= 0x20 && code !== 0x7f; + }) + .join(""); + return base.trim() || "message"; +} + const clientCache = new Map(); export function getDingTalkClient( diff --git a/plugins/dingtalk/src/gateway/event-handler.ts b/plugins/dingtalk/src/gateway/event-handler.ts index a0aa38f..02b0a3d 100644 --- a/plugins/dingtalk/src/gateway/event-handler.ts +++ b/plugins/dingtalk/src/gateway/event-handler.ts @@ -5,6 +5,7 @@ import type { DingTalkClient } from "../api/client.js"; import { parseRobotMessage } from "./message.js"; import type { ParsedRobotMessage } from "./message.js"; import { MessageDedup } from "./dedup.js"; +import { downloadRobotMessageMedia } from "./media-download.js"; /** Reply sent to a group @mention while group chat is disabled. */ export const GROUP_DISABLED_NOTICE = pluginMessage( @@ -101,6 +102,19 @@ export async function handleRobotMessage( return; } + // Media messages carry a downloadCode; exchange it for a temp URL, download + // to a local path, and hand the path to the agent as an attachment. When the + // download succeeds the text is still the short summary (the file itself is + // the payload); failures keep the summary only. + let attachment: string | undefined; + if (parsed.media?.downloadCode) { + if (!parsed.robotCode) { + logger.warn(`dingtalk[${accountId}]: media message without robotCode, cannot download`); + } else { + attachment = await downloadRobotMessageMedia(deps.client, parsed, logger); + } + } + await deliver({ sessionId: parsed.isGroup ? ["conversation", accountId, parsed.conversationId] @@ -116,6 +130,7 @@ export async function handleRobotMessage( messageId: parsed.msgId, }, message: messageToDeliver, + ...(attachment ? { attachments: [attachment] } : {}), }); } diff --git a/plugins/dingtalk/src/gateway/media-download.ts b/plugins/dingtalk/src/gateway/media-download.ts new file mode 100644 index 0000000..c41884b --- /dev/null +++ b/plugins/dingtalk/src/gateway/media-download.ts @@ -0,0 +1,60 @@ +import type { PluginLogger } from "@marswave/cola-plugin-sdk"; +import type { DingTalkClient } from "../api/client.js"; +import type { ParsedRobotMessage } from "./message.js"; + +/** Local download size cap for inbound robot media (matches the plugin note). */ +export const MAX_MEDIA_DOWNLOAD_BYTES = 50 * 1024 * 1024; + +/** + * Download a robot-received media message to a local temp path so the agent + * can consume the real file instead of a text summary. + * + * Returns the temp path on success, or `undefined` on any failure — + * downloading must never block message delivery, so the caller keeps the text + * summary as a fallback. The downloaded file is owned by the host once the + * message is delivered (it takes custody of the `attachments` array); on + * failure the path is cleaned up here. + */ +export async function downloadRobotMessageMedia( + client: DingTalkClient, + parsed: ParsedRobotMessage, + logger: PluginLogger, +): Promise { + const { downloadCode, fileName } = parsed.media ?? {}; + const robotCode = parsed.robotCode; + if (!downloadCode || !robotCode) { + logger.warn("DingTalk media message missing downloadCode or robotCode, skipping download"); + return undefined; + } + + const fallbackName = fileName ?? mediaDefaultExtension(parsed.media?.kind ?? "unknown"); + try { + const path = await client.downloadMessageFile(robotCode, downloadCode, fallbackName, { + maxBytes: MAX_MEDIA_DOWNLOAD_BYTES, + }); + logger.info(`Downloaded DingTalk ${parsed.media?.kind ?? "media"} message media to ${path}`); + return path; + } catch (err) { + logger.warn( + `Failed to download DingTalk ${parsed.media?.kind ?? "media"} message media: ${ + err instanceof Error ? err.message : String(err) + }`, + ); + return undefined; + } +} + +function mediaDefaultExtension(kind: string): string { + switch (kind) { + case "image": + return "picture.jpg"; + case "audio": + return "voice.amr"; + case "video": + return "video.mp4"; + case "file": + return "file"; + default: + return "message"; + } +} diff --git a/plugins/dingtalk/src/gateway/message.ts b/plugins/dingtalk/src/gateway/message.ts index 8168816..f64f133 100644 --- a/plugins/dingtalk/src/gateway/message.ts +++ b/plugins/dingtalk/src/gateway/message.ts @@ -31,6 +31,17 @@ export type ParsedRobotMessage = { senderId?: string; senderNick?: string; robotCode?: string; + /** + * Present for inbound media messages (file/picture/audio/video) that carry a + * downloadCode and a file name. The gateway exchanges the downloadCode for a + * temporary URL via /v1.0/robot/messageFiles/download, then downloads to a + * local temp path so it can be handed to the agent as an attachment. + */ + media?: { + kind: "image" | "audio" | "video" | "file" | "unknown"; + downloadCode?: string; + fileName?: string; + }; }; export const GROUP_MENTION_PREFIX = "@机器人"; @@ -80,9 +91,64 @@ export function parseRobotMessage( senderId: payload.senderId, senderNick: payload.senderNick, robotCode: payload.robotCode, + media: extractMedia(payload), }; } +/** + * Pull the downloadCode + file name (and a normalized media kind) out of a + * non-text inbound payload. DingTalk nests these under `content` for several + * types (file, picture, audio, video) and also at the top level for some. + * Rich-text (`richText`) messages never carry a single downloadCode (they can + * embed multiple pictures), so they yield `undefined` here and stay as a text + * summary. + */ +export function extractMedia( + payload: DingTalkRobotPayload, +): ParsedRobotMessage["media"] | undefined { + if (payload.msgtype === "text" || payload.msgtype === "richText") return undefined; + + const content = (payload.content ?? {}) as { + downloadCode?: string; + fileName?: string; + }; + + const downloadCode = content.downloadCode ?? (payload as { downloadCode?: string }).downloadCode; + const fileName = + content.fileName ?? + (payload as { fileName?: string }).fileName ?? + downloadCode?.replace(/^\*+/, ""); + + const kind = mediaKindForMsgType(payload.msgtype); + return { kind, downloadCode, fileName: normalizeFileName(fileName) }; +} + +function mediaKindForMsgType( + msgtype: string | undefined, +): NonNullable["kind"] { + switch (msgtype) { + case "picture": + return "image"; + case "audio": + return "audio"; + case "video": + return "video"; + case "file": + return "file"; + default: + return "unknown"; + } +} + +/** Normalize an inbound file name so the temp download path stays meaningful. */ +function normalizeFileName(name: string | undefined): string | undefined { + if (!name || !name.trim()) return undefined; + const trimmed = name.trim(); + // DingTalk returns some media download names as a bare id with no extension; + // keep whatever we have — sanitization happens at write time. + return trimmed; +} + /** * Group messages arrive with a prepended "@机器人 " (or similar @handle) * prefix inserted by DingTalk. Strip the leading mention token followed by diff --git a/plugins/dingtalk/src/index.ts b/plugins/dingtalk/src/index.ts index cd78bcc..aec5237 100644 --- a/plugins/dingtalk/src/index.ts +++ b/plugins/dingtalk/src/index.ts @@ -9,7 +9,7 @@ import type { import type { DingTalkPluginConfig } from "./api/types.js"; import { parseAccountConfigs } from "./auth/accounts.js"; import { startMonitor, type MonitorHandle } from "./gateway/monitor.js"; -import { sendText } from "./outbound/send.js"; +import { sendText, sendMedia } from "./outbound/send.js"; import { createDingTalkCommands } from "./commands/dingtalk.js"; import { clearClientCache } from "./api/client.js"; @@ -75,10 +75,22 @@ export default defineChannel({ capabilities: { receive: { text: true, + // Media download is implemented in the gateway (gateway/media-download.ts); + // every inbound media type that DingTalk delivers to the robot is accepted. + image: true, + voice: true, + video: true, + file: true, }, send: { text: true, markdown: true, + // Outbound media: the host uploads via sendMedia (outbound/send.ts). Video + // is intentionally NOT advertised: DingTalk's sampleVideo needs a separate + // cover-image mediaId that cannot be derived from the single file the host + // hands us, so enabling it would fail at send time. + image: true, + file: true, }, limits: { // DingTalk caps robot msgParam at 15000 UTF-8 bytes. CJK text costs up @@ -226,6 +238,14 @@ export default defineChannel({ }, outbound: { + mediaCapabilities: { + // DingTalk caps media upload at 20MB (image/video/file; voice ≤ 2MB). + // The host enforces this before calling sendMedia so an oversized file + // fails client-side rather than at the API. + maxBytesPerFile: 20 * 1024 * 1024, + supportedKinds: ["image", "file"], + }, + async sendText(ctx: OutboundContext) { const handle = resolveMonitorForDelivery(ctx.deliveryContext); if (!handle) { @@ -240,5 +260,21 @@ export default defineChannel({ ctx.logger, ); }, + + async sendMedia(ctx: OutboundContext & { mediaType: string; filePath: string }) { + const handle = resolveMonitorForDelivery(ctx.deliveryContext); + if (!handle) { + ctx.logger.error("sendMedia: no active DingTalk account"); + return; + } + await sendMedia( + handle.restClient, + ctx.deliveryContext.to, + ctx.mediaType, + ctx.filePath, + handle.getRobotCode(), + ctx.logger, + ); + }, }, }); diff --git a/plugins/dingtalk/src/outbound/send.ts b/plugins/dingtalk/src/outbound/send.ts index 00773e4..f00f212 100644 --- a/plugins/dingtalk/src/outbound/send.ts +++ b/plugins/dingtalk/src/outbound/send.ts @@ -1,6 +1,12 @@ import type { PluginLogger } from "@marswave/cola-plugin-sdk"; -import { buildMarkdownMessage, enforceMsgParamLimit } from "../api/client.js"; -import type { DingTalkClient } from "../api/client.js"; +import { + buildMarkdownMessage, + buildImageMessage, + buildFileMessage, + buildVoiceMessage, + enforceMsgParamLimit, +} from "../api/client.js"; +import type { DingTalkClient, OutgoingMessage } from "../api/client.js"; /** * Send a Cola reply to a DingTalk delivery target. @@ -38,3 +44,84 @@ export async function sendText( throw err; } } + +/** + * Route a media dispatch to the correct DingTalk robot message type. + * + * - image → upload → `sampleImageMsg` (photoURL = mediaId) + * - audio → upload → `sampleAudio` (mediaId + duration) + * - file → upload → `sampleFile` (mediaId + fileName + fileType) + * - video → not supported here: DingTalk's `sampleVideo` requires a separate + * cover image mediaId (picMediaId) that cannot be derived from a single file, + * so the adapter reports it as unsupported rather than half-sending. + * + * Uploads go through the same access token as normal sends (see uploadMedia in + * api/client.ts for the OAPI domain + access_token note). + */ +export async function sendMedia( + client: DingTalkClient, + deliveryTo: string, + mediaType: string, + filePath: string, + robotCode: string | undefined, + logger: PluginLogger, +): Promise { + if (!robotCode) { + throw new Error("DingTalk robotCode is not known yet; unable to send media"); + } + if (!isSendableMediaType(mediaType)) { + throw new Error(`DingTalk media send unsupported for MIME type: ${mediaType}`); + } + + const fileName = filePath.split("/").pop() ?? "file"; + let message: OutgoingMessage; + + try { + if (mediaType.startsWith("image/")) { + const mediaId = await client.uploadMedia(filePath, "image", fileName); + message = buildImageMessage(mediaId); + } else if (mediaType.startsWith("audio/")) { + const mediaId = await client.uploadMedia(filePath, "voice", fileName); + message = buildVoiceMessage(mediaId); + } else { + const fileType = extWithoutDot(fileName); + const mediaId = await client.uploadMedia(filePath, "file", fileName); + message = buildFileMessage(mediaId, fileName, fileType); + } + + if (deliveryTo.startsWith("staff:")) { + await client.sendOToMessage(robotCode, deliveryTo.slice("staff:".length), message); + return; + } + if (deliveryTo.startsWith("conversation:")) { + await client.sendGroupMessage(robotCode, deliveryTo.slice("conversation:".length), message); + return; + } + throw new Error(`Unsupported DingTalk delivery target: ${deliveryTo}`); + } catch (err) { + logger.error(`Failed to send media (${mediaType}) to ${deliveryTo}`, err); + throw err; + } +} + +/** Media types DingTalk robot messages can actually send (image/audio/file). */ +function isSendableMediaType(mediaType: string): boolean { + return ( + mediaType.startsWith("image/") || + mediaType.startsWith("audio/") || + mediaType.startsWith("file/") || + mediaType === "application/pdf" || + mediaType.includes("document") || + mediaType.includes("spreadsheet") || + mediaType.includes("presentation") || + mediaType.includes("zip") || + mediaType.includes("rar") + ); +} + +/** Lowercase file extension without the leading dot, e.g. "xlsx". */ +function extWithoutDot(fileName: string): string { + const idx = fileName.lastIndexOf("."); + if (idx < 0 || idx === fileName.length - 1) return "file"; + return fileName.slice(idx + 1).toLowerCase(); +} diff --git a/plugins/dingtalk/tests/media.test.ts b/plugins/dingtalk/tests/media.test.ts new file mode 100644 index 0000000..8513e10 --- /dev/null +++ b/plugins/dingtalk/tests/media.test.ts @@ -0,0 +1,249 @@ +import { describe, expect, it, vi, beforeAll, afterAll } from "vitest"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + DingTalkClient, + MAX_MEDIA_UPLOAD_BYTES, + buildImageMessage, + buildFileMessage, + buildVoiceMessage, + buildVideoMessage, + sanitizeFileName, +} from "../src/api/client.js"; +import { AccessTokenManager } from "../src/api/token.js"; + +let tmpDir: string; + +beforeAll(async () => { + tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "cola-dingtalk-media-test-")); +}); + +afterAll(async () => { + await fs.rm(tmpDir, { recursive: true, force: true }); +}); + +function tokenResponse(): Response { + return { + ok: true, + status: 200, + json: async () => ({ accessToken: "test-token", expireIn: 7200 }), + } as unknown as Response; +} + +function jsonResponse(body: unknown, status = 200): Response { + return { + ok: status >= 200 && status < 300, + status, + json: async () => body, + text: async () => JSON.stringify(body), + } as unknown as Response; +} + +async function writeTmp(name: string, contents: string): Promise { + const filePath = path.join(tmpDir, name); + await fs.writeFile(filePath, contents); + return filePath; +} + +describe("media message builders", () => { + it("builds sampleImageMsg with the mediaId as photoURL", () => { + const message = buildImageMessage("@media-1"); + expect(message.msgKey).toBe("sampleImageMsg"); + expect(JSON.parse(message.msgParam)).toEqual({ photoURL: "@media-1" }); + }); + + it("builds sampleFile with mediaId/fileName/fileType", () => { + const message = buildFileMessage("@media-2", "report.xlsx", "xlsx"); + expect(message.msgKey).toBe("sampleFile"); + expect(JSON.parse(message.msgParam)).toEqual({ + mediaId: "@media-2", + fileName: "report.xlsx", + fileType: "xlsx", + }); + }); + + it("builds sampleAudio with a numeric duration string", () => { + const message = buildVoiceMessage("@media-3", 1500); + expect(message.msgKey).toBe("sampleAudio"); + expect(JSON.parse(message.msgParam)).toEqual({ + mediaId: "@media-3", + duration: "1500", + }); + }); + + it("builds sampleVideo with both media ids", () => { + const message = buildVideoMessage("@video", "@cover", 9); + expect(message.msgKey).toBe("sampleVideo"); + expect(JSON.parse(message.msgParam)).toEqual({ + duration: "9", + videoMediaId: "@video", + videoType: "mp4", + picMediaId: "@cover", + }); + }); +}); + +describe("sanitizeFileName", () => { + it("strips path separators and shell metacharacters", () => { + expect(sanitizeFileName("../../etc/passwd")).toBe(".._.._etc_passwd"); + expect(sanitizeFileName("a:b*c?d.txt")).toBe("a_b_c_d.txt"); + expect(sanitizeFileName("report.pdf")).toBe("report.pdf"); + }); + + it("falls back to a default name when the input is empty", () => { + expect(sanitizeFileName("")).toBe("message"); + expect(sanitizeFileName(" ")).toBe("message"); + }); +}); + +describe("DingTalkClient.uploadMedia", () => { + it("uploads via the OAPI gateway with an access_token form field and returns media_id", async () => { + const filePath = await writeTmp("pic.png", "fake-png-bytes"); + const fetchImpl = vi.fn(async (input: string, _init?: RequestInit) => { + if (input.endsWith("/v1.0/oauth2/accessToken")) return tokenResponse(); + if (input.startsWith("https://oapi.dingtalk.com/media/upload")) + return jsonResponse({ errcode: 0, errmsg: "ok", media_id: "@up-media-1" }); + throw new Error(`unexpected url ${input}`); + }); + const client = new DingTalkClient( + new AccessTokenManager("app", "secret", fetchImpl), + fetchImpl, + ); + + const mediaId = await client.uploadMedia(filePath, "image"); + + expect(mediaId).toBe("@up-media-1"); + expect(fetchImpl).toHaveBeenCalledTimes(2); // token + upload + const [url, init] = fetchImpl.mock.calls[1] as [string, RequestInit | undefined]; + expect(url.startsWith("https://oapi.dingtalk.com/media/upload?access_token=test-token")).toBe( + true, + ); + const form = init?.body as FormData; + expect(form.has("media")).toBe(true); + expect(form.get("type")).toBe("image"); + }); + + it("throws when the file exceeds the DingTalk upload limit", async () => { + const bigFile = path.join(tmpDir, "big.bin"); + await fs.writeFile(bigFile, Buffer.alloc(MAX_MEDIA_UPLOAD_BYTES + 1)); + const fetchImpl = vi.fn(async () => tokenResponse()); + const client = new DingTalkClient( + new AccessTokenManager("app", "secret", fetchImpl), + fetchImpl, + ); + + await expect(client.uploadMedia(bigFile, "file")).rejects.toThrow(/limit/); + // No token was even needed since the size gate fires first. + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it("throws a descriptive error when the upload API reports a non-zero errcode", async () => { + const filePath = await writeTmp("doc.pdf", "pdf"); + const fetchImpl = vi.fn(async (input: string) => + input.endsWith("/v1.0/oauth2/accessToken") + ? tokenResponse() + : jsonResponse({ errcode: 40035, errmsg: "invalid media type" }), + ); + const client = new DingTalkClient( + new AccessTokenManager("app", "secret", fetchImpl), + fetchImpl, + ); + + await expect(client.uploadMedia(filePath, "file", "doc.pdf")).rejects.toThrow(/40035/); + }); + + it("does not leak the token into the thrown error", async () => { + const filePath = await writeTmp("doc.pdf", "pdf"); + const fetchImpl = vi.fn(async () => jsonResponse({ errcode: 500 }, 500)); + const client = new DingTalkClient( + new AccessTokenManager("app", "secret", fetchImpl), + fetchImpl, + ); + + try { + await client.uploadMedia(filePath, "file", "doc.pdf"); + throw new Error("expected uploadMedia to throw"); + } catch (err) { + expect(String(err)).not.toContain("test-token"); + } + }); +}); + +describe("DingTalkClient.resolveMessageDownload / downloadMessageFile", () => { + it("exchanges a downloadCode for a temp download URL", async () => { + const fetchImpl = vi.fn(async (input: string) => { + if (input.endsWith("/v1.0/oauth2/accessToken")) return tokenResponse(); + if (input.endsWith("/v1.0/robot/messageFiles/download")) + return jsonResponse({ downloadUrl: "https://tmp.example/file.video" }); + throw new Error(`unexpected url ${input}`); + }); + const client = new DingTalkClient( + new AccessTokenManager("app", "secret", fetchImpl), + fetchImpl, + ); + + const url = await client.resolveMessageDownload("robot-1", "code-1"); + + expect(url).toBe("https://tmp.example/file.video"); + const [, init] = fetchImpl.mock.calls[1] as [string, RequestInit]; + expect((init.headers as Record)["x-acs-dingtalk-access-token"]).toBe( + "test-token", + ); + expect(JSON.parse(String(init.body))).toEqual({ downloadCode: "code-1", robotCode: "robot-1" }); + }); + + it("downloads the resolved URL to a temp file with the sanitized name", async () => { + const filePath = await writeTmp("inbox.pdf", "dummy-pdf"); + const body = await fs.readFile(filePath); + const downloadUrl = "https://tmp.example/original"; + const fetchImpl = vi.fn(async (input: string) => { + if (input.endsWith("/v1.0/oauth2/accessToken")) return tokenResponse(); + if (input.endsWith("/v1.0/robot/messageFiles/download")) return jsonResponse({ downloadUrl }); + if (input === downloadUrl) + return { + ok: true, + status: 200, + headers: { get: (n: string) => (n === "content-length" ? String(body.length) : null) }, + arrayBuffer: async () => body.buffer, + text: async () => "dummy-pdf", + } as unknown as Response; + throw new Error(`unexpected url ${input}`); + }); + const client = new DingTalkClient( + new AccessTokenManager("app", "secret", fetchImpl), + fetchImpl, + ); + + const out = await client.downloadMessageFile("robot-1", "code-1", "inbox.pdf"); + + expect(path.basename(out)).toBe("inbox.pdf"); + expect(await fs.readFile(out, "utf8")).toBe("dummy-pdf"); + await fs.rm(path.dirname(out), { recursive: true, force: true }); + }); + + it("rejects when the resolved download is over the byte limit", async () => { + const fetchImpl = vi.fn(async (input: string) => { + if (input.endsWith("/v1.0/oauth2/accessToken")) return tokenResponse(); + if (input.endsWith("/v1.0/robot/messageFiles/download")) + return jsonResponse({ downloadUrl: "https://tmp.example/big" }); + if (input === "https://tmp.example/big") { + return { + ok: true, + status: 200, + headers: { get: (n: string) => (n === "content-length" ? "99999" : null) }, + arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer, + } as unknown as Response; + } + throw new Error(`unexpected url ${input}`); + }); + const client = new DingTalkClient( + new AccessTokenManager("app", "secret", fetchImpl), + fetchImpl, + ); + + await expect( + client.downloadMessageFile("robot-1", "code-1", "big.bin", { maxBytes: 10 }), + ).rejects.toThrow(/limit/); + }); +}); diff --git a/plugins/dingtalk/tests/message.test.ts b/plugins/dingtalk/tests/message.test.ts index a473e9c..1439699 100644 --- a/plugins/dingtalk/tests/message.test.ts +++ b/plugins/dingtalk/tests/message.test.ts @@ -4,8 +4,13 @@ import { parseRobotMessage, stripMentionPrefix, summarizeMediaMessage, + extractMedia, } from "../src/gateway/message.js"; import { MessageDedup } from "../src/gateway/dedup.js"; +import { + downloadRobotMessageMedia, + MAX_MEDIA_DOWNLOAD_BYTES, +} from "../src/gateway/media-download.js"; const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn() } as never; @@ -139,6 +144,120 @@ describe("summarizeMediaMessage", () => { }); }); +describe("extractMedia", () => { + it("extracts downloadCode + fileName from a file message content", () => { + const media = extractMedia({ + msgtype: "file", + content: { downloadCode: "dc-1", fileName: "report.pdf" }, + }); + expect(media).toEqual({ kind: "file", downloadCode: "dc-1", fileName: "report.pdf" }); + }); + + it("normalizes picture msgtype to an image kind", () => { + const media = extractMedia({ + msgtype: "picture", + content: { downloadCode: "dc-img" }, + }); + expect(media?.kind).toBe("image"); + expect(media?.fileName).toBe("dc-img"); + }); + + it("falls back to the top-level fileName / downloadCode when content lacks them", () => { + const media = extractMedia({ + msgtype: "file", + fileName: "note.txt", + }); + expect(media?.fileName).toBe("note.txt"); + }); + + it("normalizes audio to a voice and video to a video kind", () => { + expect(extractMedia({ msgtype: "audio", content: { downloadCode: "a" } })?.kind).toBe("audio"); + expect(extractMedia({ msgtype: "video", content: { downloadCode: "v" } })?.kind).toBe("video"); + }); + + it("returns undefined for text and richText messages", () => { + expect(extractMedia({ msgtype: "text", text: { content: "hi" } })).toBeUndefined(); + expect(extractMedia({ msgtype: "richText" })).toBeUndefined(); + }); +}); + +describe("downloadRobotMessageMedia", () => { + it("downloads the message and returns the temp path", async () => { + const downloaded = "/tmp/cola-dingtalk-abc/report.pdf"; + const client = { + downloadMessageFile: vi.fn(async () => downloaded), + }; + const parsed = { + robotCode: "robot-1", + media: { kind: "file", downloadCode: "dc", fileName: "report.pdf" }, + } as never; + const info = vi.fn(); + + const out = await downloadRobotMessageMedia(client as never, parsed, { + info, + warn: vi.fn(), + } as never); + + expect(out).toBe(downloaded); + expect(client.downloadMessageFile).toHaveBeenCalledWith("robot-1", "dc", "report.pdf", { + maxBytes: MAX_MEDIA_DOWNLOAD_BYTES, + }); + expect(info).toHaveBeenCalled(); + }); + + it("returns a default extension-based name when the message has no file name", async () => { + const client = { downloadMessageFile: vi.fn(async () => "/tmp/x") }; + const parsed = { + robotCode: "robot-1", + media: { kind: "image", downloadCode: "dc" }, + } as never; + + await downloadRobotMessageMedia(client as never, parsed, { + info: vi.fn(), + warn: vi.fn(), + } as never); + + expect(client.downloadMessageFile).toHaveBeenCalledWith("robot-1", "dc", "picture.jpg", { + maxBytes: MAX_MEDIA_DOWNLOAD_BYTES, + }); + }); + + it("returns undefined when downloadCode or robotCode is missing, without downloading", async () => { + const client = { downloadMessageFile: vi.fn() }; + const info = vi.fn(); + const warn = vi.fn(); + + const out = await downloadRobotMessageMedia( + client as never, + { media: { kind: "file", downloadCode: "dc" } } as never, + { info, warn } as never, + ); + + expect(out).toBeUndefined(); + expect(client.downloadMessageFile).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalled(); + }); + + it("returns undefined and logs a warning when the download fails", async () => { + const client = { + downloadMessageFile: vi.fn(async () => { + throw new Error("download failed"); + }), + }; + const info = vi.fn(); + const warn = vi.fn(); + + const out = await downloadRobotMessageMedia( + client as never, + { robotCode: "r", media: { kind: "file", downloadCode: "dc" } } as never, + { info, warn } as never, + ); + + expect(out).toBeUndefined(); + expect(warn).toHaveBeenCalled(); + }); +}); + describe("MessageDedup (second dedup layer)", () => { it("marks the first sighting as fresh and repeats as duplicates", () => { const dedup = new MessageDedup(); From b55f0ed7c351fe5137f641557585e6dee6d4eeb9 Mon Sep 17 00:00:00 2001 From: echohn Date: Thu, 24 Sep 2026 00:17:06 +0800 Subject: [PATCH 04/10] fix(dingtalk): parse richText media nodes and annotate delivery state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Image+caption messages arrive as richText payloads. The media parser only handled picture/audio/video/file, so richText picture nodes (which carry downloadCode) were dropped: no download was attempted, delivery text degraded to a bare '[图文]' placeholder, and the agent — never receiving the media — fabricated a description from session memory (observed live). - richText parsing: walk text and picture nodes; build '[图文] ' with the extracted downloadCode; plain-text richText no longer gets any media marker - delivery annotations: on success the agent is told the attachment was downloaded and is available; if media was expected but delivery failed, the agent receives an explicit bilingual instruction not to guess and to tell the user honestly (plus a WARN log, previously silent) - tests: 95 passing (richText node cases, annotation cases, no-media paths, no regressions) --- plugins/dingtalk/src/gateway/event-handler.ts | 46 ++++- plugins/dingtalk/src/gateway/message.ts | 95 ++++++++-- plugins/dingtalk/tests/gateway-status.test.ts | 163 +++++++++++++++++- plugins/dingtalk/tests/message.test.ts | 122 ++++++++++++- 4 files changed, 397 insertions(+), 29 deletions(-) diff --git a/plugins/dingtalk/src/gateway/event-handler.ts b/plugins/dingtalk/src/gateway/event-handler.ts index 02b0a3d..dc228dd 100644 --- a/plugins/dingtalk/src/gateway/event-handler.ts +++ b/plugins/dingtalk/src/gateway/event-handler.ts @@ -17,6 +17,22 @@ export const GROUP_DISABLED_NOTICE = pluginMessage( export const NON_OWNER_TAG_PREFIX = "[非所有者消息 · "; export const OWNER_TAG_PREFIX = "[所有者]"; +/** + * Appended to the delivered text when the message's media download succeeded. + * Bilingual so the assertion is stable regardless of the agent's language. + */ +export const MEDIA_DOWNLOADED_NOTE = + "[System note: the attached image/file was successfully downloaded from this message and is available to you. / 系统提示:本消息的图片/文件已成功下载并附给你。]"; + +/** + * Appended to the delivered text when the message contained media but the + * download failed — the agent must never guess or recall what the image/file + * showed (a real incident where the agent fabricated content from memory). + * Bilingual and directive so the model has no room to fabricate. + */ +export const MEDIA_DOWNLOAD_FAILED_WARN = + "[System note: this message contained an image/file but the download FAILED — you have NOT received any media content. Do NOT guess or fabricate what it shows; tell the user honestly that you cannot view it and ask them to retry. / 系统提示:本消息包含图片/文件,但下载失败,你并未收到任何媒体内容。请勿猜测或编造内容,应如实告知用户无法查看并请其重试。]"; + export type EventHandlerDeps = { i18n?: PluginRuntime["i18n"]; accountId: string; @@ -85,7 +101,7 @@ export async function handleRobotMessage( // Group messages: prepend a sender tag (+ owner-vs-non-owner constraint) so // the agent knows who posted. Direct chats are left untouched. - const messageToDeliver = parsed.isGroup ? annotateGroupMessage(parsed, deps.ownerStaffId) : text; + let messageToDeliver = parsed.isGroup ? annotateGroupMessage(parsed, deps.ownerStaffId) : text; // Direct-chat replies require senderStaffId, which DingTalk only pushes for // published robot versions. Without it there is no way to answer. @@ -102,19 +118,39 @@ export async function handleRobotMessage( return; } - // Media messages carry a downloadCode; exchange it for a temp URL, download - // to a local path, and hand the path to the agent as an attachment. When the - // download succeeds the text is still the short summary (the file itself is - // the payload); failures keep the summary only. + // Media messages (including rich-text messages that embed pictures) carry a + // downloadCode; exchange it for a temp URL, download to a local path, and + // hand the path to the agent as an attachment. When the download succeeds + // the text is still the short summary (the file itself is the payload); + // failures keep the summary only. + // + // The delivered text must explicitly state the media outcome. Failing to + // announce a download failure lets the agent guess/fabricate what an image + // showed (a documented incident), so a success note or a failure warning is + // appended whenever the message carried media. let attachment: string | undefined; + let mediaNote: string | null = null; if (parsed.media?.downloadCode) { if (!parsed.robotCode) { logger.warn(`dingtalk[${accountId}]: media message without robotCode, cannot download`); + mediaNote = MEDIA_DOWNLOAD_FAILED_WARN; } else { attachment = await downloadRobotMessageMedia(deps.client, parsed, logger); + if (attachment) { + mediaNote = MEDIA_DOWNLOADED_NOTE; + } else { + logger.warn( + `dingtalk[${accountId}]: media message download failed — agent will be told it has no media content`, + ); + mediaNote = MEDIA_DOWNLOAD_FAILED_WARN; + } } } + messageToDeliver = mediaNote + ? `${messageToDeliver ? `${messageToDeliver}\n` : ""}${mediaNote}`.trim() + : messageToDeliver; + await deliver({ sessionId: parsed.isGroup ? ["conversation", accountId, parsed.conversationId] diff --git a/plugins/dingtalk/src/gateway/message.ts b/plugins/dingtalk/src/gateway/message.ts index f64f133..fc024e9 100644 --- a/plugins/dingtalk/src/gateway/message.ts +++ b/plugins/dingtalk/src/gateway/message.ts @@ -79,7 +79,11 @@ export function parseRobotMessage( const isGroup = conversationType === "2"; const content = - payload.msgtype === "text" ? (payload.text?.content ?? "") : summarizeMediaMessage(payload); + payload.msgtype === "text" + ? (payload.text?.content ?? "") + : payload.msgtype === "richText" + ? summarizeRichText(payload) + : summarizeMediaMessage(payload); const text = isGroup ? stripMentionPrefix(content) : content; return { @@ -99,14 +103,15 @@ export function parseRobotMessage( * Pull the downloadCode + file name (and a normalized media kind) out of a * non-text inbound payload. DingTalk nests these under `content` for several * types (file, picture, audio, video) and also at the top level for some. - * Rich-text (`richText`) messages never carry a single downloadCode (they can - * embed multiple pictures), so they yield `undefined` here and stay as a text - * summary. + * Rich-text (`richText`) messages embed pictures inside `content.richText`; + * the first `picture` node's downloadCode is extracted so the gateway can + * download the attached image like any other media message. */ export function extractMedia( payload: DingTalkRobotPayload, ): ParsedRobotMessage["media"] | undefined { - if (payload.msgtype === "text" || payload.msgtype === "richText") return undefined; + if (payload.msgtype === "text") return undefined; + if (payload.msgtype === "richText") return extractRichTextMedia(payload); const content = (payload.content ?? {}) as { downloadCode?: string; @@ -170,10 +175,8 @@ export function summarizeMediaMessage(payload: DingTalkRobotPayload): string { return "[语音]"; case "video": return "[视频]"; - case "richText": { - const inline = extractRichText(payload); - return inline ? `[图文] ${inline}` : "[图文]"; - } + case "richText": + return summarizeRichText(payload); case "file": { const fileName = (typeof payload.fileName === "string" && payload.fileName) || @@ -189,20 +192,78 @@ export function summarizeMediaMessage(payload: DingTalkRobotPayload): string { } } -function extractRichText(payload: DingTalkRobotPayload): string | undefined { - const content = payload.content as - | { richArray?: Array<{ type?: string; text?: string }> } +/** + * Read the `content.richText` array as a list of rich-text nodes. DingTalk + * nests rich-text payloads under `content.richText` (an array whose elements + * are either a bare `{ text }` node or a `{ type, downloadCode }` picture + * node). The legacy `content.richArray` shape is also accepted for backwards + * compatibility. + */ +export function richTextContent(payload: DingTalkRobotPayload): RichTextNode[] { + const content = (payload.content ?? {}) as + | { richText?: unknown; richArray?: unknown } | undefined; - const richArray = content?.richArray; - if (!Array.isArray(richArray)) return undefined; - const text = richArray - .filter((item) => item?.type === "text" && typeof item.text === "string") - .map((item) => item.text as string) + const raw = content?.richText ?? content?.richArray; + if (!Array.isArray(raw)) return []; + return raw.filter((n): n is RichTextNode => !!n && typeof n === "object"); +} + +/** A single element of a DingTalk `content.richText` array. */ +export type RichTextNode = { + type?: string; + text?: string; + downloadCode?: string; + fileName?: string; + [key: string]: unknown; +}; + +/** + * The user's free text carried by a rich-text message, with every inline + * `text` node joined in order. Returns undefined when the message is not a + * richText payload or carries no such nodes. + */ +export function extractRichText(payload: DingTalkRobotPayload): string | undefined { + if (payload.msgtype !== "richText") return undefined; + const text = richTextContent(payload) + .map((n) => n.text) + .filter((t): t is string => typeof t === "string") .join("") .trim(); return text || undefined; } +/** + * Build the text summary for a richText message. When the message embeds one + * or more pictures the `[图文]` marker is prepended to the inline text (a + * picture message with a caption becomes `[图文] the caption`; a bare picture + * message becomes just `[图文]`). A picture-less richText message is treated + * as plain text and returned as-is, with no marker. + */ +export function summarizeRichText(payload: DingTalkRobotPayload): string { + const inline = extractRichText(payload); + const hasPicture = richTextContent(payload).some((n) => n?.type === "picture"); + if (!hasPicture) return (inline ?? "").trim(); + return inline ? `[图文] ${inline}` : "[图文]"; +} + +/** + * Pull a media object out of a rich-text message. Rich-text can embed multiple + * pictures (each a `picture` node in `content.richText`); the gateway's + * download path consumes a single downloadCode at a time, so the first picture + * node is used and later ones are dropped (a known limitation, consistent with + * how the existing picture/file/etc. handlers behave). + */ +function extractRichTextMedia( + payload: DingTalkRobotPayload, +): ParsedRobotMessage["media"] | undefined { + const pictureNode = richTextContent(payload).find((n) => n?.type === "picture"); + if (!pictureNode) return undefined; + const downloadCode = pictureNode.downloadCode; + if (!downloadCode) return undefined; + const fileName = pictureNode.fileName ?? downloadCode.replace(/^\*+/, ""); + return { kind: "image", downloadCode, fileName: normalizeFileName(fileName) }; +} + /** * Stable delivery targets: direct chat → `staff:`, * group chat → `conversation:`. diff --git a/plugins/dingtalk/tests/gateway-status.test.ts b/plugins/dingtalk/tests/gateway-status.test.ts index da9ca0c..f68e47c 100644 --- a/plugins/dingtalk/tests/gateway-status.test.ts +++ b/plugins/dingtalk/tests/gateway-status.test.ts @@ -1,7 +1,12 @@ import { describe, expect, it, vi } from "vitest"; import { resolvePluginText } from "@marswave/cola-plugin-sdk"; import { deriveConnectionState, type ConnectionStateInput } from "../src/gateway/monitor.js"; -import { handleRobotMessage, type EventHandlerDeps } from "../src/gateway/event-handler.js"; +import { + handleRobotMessage, + type EventHandlerDeps, + MEDIA_DOWNLOADED_NOTE, + MEDIA_DOWNLOAD_FAILED_WARN, +} from "../src/gateway/event-handler.js"; import { MessageDedup } from "../src/gateway/dedup.js"; import feishuLikeIndex from "../src/index.js"; @@ -338,4 +343,160 @@ describe("event handler delivery payloads", () => { const parsed = JSON.parse(message.msgParam) as { content: string }; expect(parsed.content).toContain("Group chat is not enabled"); }); + + // A message with a downloadCode and no robotCode can't be downloaded. + const mediaNoRobotPayload = JSON.stringify({ + conversationId: "cid-dm-media", + conversationType: "1", + msgId: "msg-dm-media-1", + msgtype: "file", + senderStaffId: "staff-1", + senderId: "sender-1", + content: { downloadCode: "dc-1", fileName: "report.pdf" }, + }); + + it("appends the downloaded media note when the file download succeeds", async () => { + const downloadMessageFile = Object.assign( + vi.fn(async () => "/tmp/cola-dingtalk-test/report.pdf"), + ); + const { deps, delivered } = makeDeps({ + groupEnabled: true, + logger: { info: () => {}, warn: () => {}, error: () => {} }, + client: { downloadMessageFile } as unknown as EventHandlerDeps["client"], + }); + await handleRobotMessage( + deps, + JSON.stringify({ + conversationId: "cid-dm-media", + conversationType: "1", + msgId: "msg-dm-media-2", + msgtype: "file", + senderStaffId: "staff-1", + senderId: "sender-1", + robotCode: "ding-test-robot", + content: { downloadCode: "dc-1", fileName: "report.pdf" }, + }), + ); + + expect(delivered).toHaveLength(1); + const payload = delivered[0] as { message: string; attachments?: string[] }; + // text summary + the media-downloaded note + expect(payload.message).toContain("[文件: report.pdf]"); + expect(payload.message).toContain(MEDIA_DOWNLOADED_NOTE); + expect(payload.attachments).toEqual(["/tmp/cola-dingtalk-test/report.pdf"]); + }); + + it("appends the hard failure warning and sends no attachment when the media can't be downloaded", async () => { + let warnCalls = 0; + const warn = () => { + warnCalls++; + }; + // No robotCode → download is skipped → failure warning. + const { deps, delivered } = makeDeps({ + groupEnabled: true, + logger: { info: () => {}, warn, error: () => {} }, + client: {} as EventHandlerDeps["client"], + }); + await handleRobotMessage(deps, mediaNoRobotPayload); + + expect(delivered).toHaveLength(1); + const payload = delivered[0] as { message: string; attachments?: string[] }; + expect(payload.message).toContain(MEDIA_DOWNLOAD_FAILED_WARN); + expect(payload.attachments ?? []).toHaveLength(0); + // warn should have been called at least once for the failure path + expect(warnCalls).toBeGreaterThan(0); + }); + + it("appends the hard failure warning when the download itself throws", async () => { + let warnCalls = 0; + const warn = () => { + warnCalls++; + }; + const downloadMessageFile = Object.assign( + vi.fn(async () => { + throw new Error("boom"); + }), + ); + const { deps, delivered } = makeDeps({ + groupEnabled: true, + logger: { info: () => {}, warn, error: () => {} }, + client: { downloadMessageFile } as unknown as EventHandlerDeps["client"], + }); + await handleRobotMessage( + deps, + JSON.stringify({ + conversationId: "cid-dm-media", + conversationType: "1", + msgId: "msg-dm-media-3", + msgtype: "file", + senderStaffId: "staff-1", + senderId: "sender-1", + robotCode: "ding-test-robot", + content: { downloadCode: "dc-throw", fileName: "x.pdf" }, + }), + ); + + expect(delivered).toHaveLength(1); + const payload = delivered[0] as { message: string; attachments?: string[] }; + expect(payload.message).toContain(MEDIA_DOWNLOAD_FAILED_WARN); + expect(payload.attachments ?? []).toHaveLength(0); + expect(warnCalls).toBeGreaterThan(0); + }); + + it("appends the media note to richText [图文] summaries (coexists with the marker)", async () => { + const downloadMessageFile = Object.assign( + vi.fn(async () => "/tmp/cola-dingtalk-test/photo.png"), + ); + const { deps, delivered } = makeDeps({ + groupEnabled: true, + logger: { info: () => {}, warn: () => {}, error: () => {} }, + client: { downloadMessageFile } as unknown as EventHandlerDeps["client"], + }); + await handleRobotMessage( + deps, + JSON.stringify({ + conversationId: "cid-dm-rt", + conversationType: "1", + msgId: "msg-rt-1", + msgtype: "richText", + senderStaffId: "staff-1", + senderId: "sender-1", + robotCode: "ding-test-robot", + content: { + richText: [ + { text: "查一下" }, + { type: "picture", downloadCode: "dc-pic", fileName: "photo.png" }, + ], + }, + }), + ); + + expect(delivered).toHaveLength(1); + const payload = delivered[0] as { message: string }; + // [图文] summary + text + downloaded note all present + expect(payload.message).toContain("[图文]"); + expect(payload.message).toContain("查一下"); + expect(payload.message).toContain(MEDIA_DOWNLOADED_NOTE); + }); + + it("adds no media note when the message has no media", async () => { + const { deps, delivered } = makeDeps({ groupEnabled: true }); + await handleRobotMessage( + deps, + JSON.stringify({ + conversationId: "cid-dm-media", + conversationType: "1", + msgId: "msg-dm-media-4", + msgtype: "text", + text: { content: "just words" }, + senderStaffId: "staff-1", + senderId: "sender-1", + robotCode: "ding-test-robot", + }), + ); + expect(delivered).toHaveLength(1); + const payload = delivered[0] as { message: string; attachments?: string[] }; + expect(payload.message).not.toContain("System note"); + expect(payload.attachments ?? []).toHaveLength(0); + }); }); diff --git a/plugins/dingtalk/tests/message.test.ts b/plugins/dingtalk/tests/message.test.ts index 1439699..53c36cc 100644 --- a/plugins/dingtalk/tests/message.test.ts +++ b/plugins/dingtalk/tests/message.test.ts @@ -4,7 +4,9 @@ import { parseRobotMessage, stripMentionPrefix, summarizeMediaMessage, + summarizeRichText, extractMedia, + richTextContent, } from "../src/gateway/message.js"; import { MessageDedup } from "../src/gateway/dedup.js"; import { @@ -123,20 +125,21 @@ describe("summarizeMediaMessage", () => { ).toBe("[文件]"); }); - it("extracts inline text from richText messages", () => { + it("extracts inline text from picture-richText messages via the media summary marker", () => { expect( summarizeMediaMessage({ ...base, msgtype: "richText", content: { - richArray: [ - { type: "text", text: "rich " }, - { type: "text", text: "body" }, + richText: [ + { text: "rich " }, + { text: "body" }, + { type: "picture", downloadCode: "dc-pic" }, ], }, }), ).toBe("[图文] rich body"); - expect(summarizeMediaMessage({ ...base, msgtype: "richText" })).toBe("[图文]"); + expect(summarizeMediaMessage({ ...base, msgtype: "richText" })).toBe(""); // no picture, no text }); it("falls back to the raw msgtype for unknown types", () => { @@ -144,6 +147,94 @@ describe("summarizeMediaMessage", () => { }); }); +describe("richText message handling", () => { + const base = { + conversationType: "2", + conversationId: "c", + msgId: "m", + senderStaffId: "staff-1", + senderId: "sender-1", + senderNick: "Tester", + robotCode: "robot-1", + }; + + it("a) picture+text richText extracts the downloadCode and joins the user text", () => { + const parsed = parseRobotMessage( + JSON.stringify({ + ...base, + msgtype: "richText", + content: { + richText: [ + { text: "查一下" }, + { text: "这个图" }, + { type: "picture", downloadCode: "dc-img", fileName: "photo.png" }, + ], + }, + }), + logger, + ); + expect(parsed?.text).toBe("[图文] 查一下这个图"); // summarizeRichText + expect(parsed?.media).toEqual({ + kind: "image", + downloadCode: "dc-img", + fileName: "photo.png", + }); + }); + + it("b) pure-text richText has no media and no [图文] marker", () => { + const parsed = parseRobotMessage( + JSON.stringify({ + ...base, + msgtype: "richText", + content: { richText: [{ text: "纯文字富文本" }] }, + }), + logger, + ); + expect(parsed?.text).toBe("纯文字富文本"); + expect(parsed?.media).toBeUndefined(); + }); + + it("c) picture-only richText keeps [图文] and still carries the downloadCode", () => { + const parsed = parseRobotMessage( + JSON.stringify({ + ...base, + msgtype: "richText", + content: { + richText: [{ type: "picture", downloadCode: "dc-only" }], + }, + }), + logger, + ); + expect(parsed?.text).toBe("[图文]"); + expect(parsed?.media).toEqual({ + kind: "image", + downloadCode: "dc-only", + fileName: "dc-only", + }); + }); + + it("summarizeRichText falls back to plain text when there is no picture node", () => { + expect( + summarizeRichText({ + ...base, + msgtype: "richText", + content: { richText: [{ text: " " }, { text: "cap" }] }, + }), + ).toBe("cap"); + }); + + it("richTextContent reads the picture node used by extractMedia", () => { + expect( + richTextContent({ + msgtype: "richText", + content: { + richText: [{ text: "x" }, { type: "picture", downloadCode: "d" }], + }, + }), + ).toEqual([{ text: "x" }, { type: "picture", downloadCode: "d" }]); + }); +}); + describe("extractMedia", () => { it("extracts downloadCode + fileName from a file message content", () => { const media = extractMedia({ @@ -175,8 +266,27 @@ describe("extractMedia", () => { expect(extractMedia({ msgtype: "video", content: { downloadCode: "v" } })?.kind).toBe("video"); }); - it("returns undefined for text and richText messages", () => { + it("returns undefined for text messages", () => { expect(extractMedia({ msgtype: "text", text: { content: "hi" } })).toBeUndefined(); + }); + + it("extracts the first picture's downloadCode from a richText message", () => { + const media = extractMedia({ + msgtype: "richText", + content: { + richText: [{ text: "hello" }, { type: "picture", downloadCode: "dc-pic" }], + }, + }); + expect(media).toEqual({ kind: "image", downloadCode: "dc-pic", fileName: "dc-pic" }); + }); + + it("returns undefined for a richText message without a picture downloadCode", () => { + expect( + extractMedia({ + msgtype: "richText", + content: { richText: [{ text: "only text" }] }, + }), + ).toBeUndefined(); expect(extractMedia({ msgtype: "richText" })).toBeUndefined(); }); }); From 10ac5c456b2ed5596dd74ece87080a9474ab7eef Mon Sep 17 00:00:00 2001 From: echohn Date: Thu, 24 Sep 2026 00:34:07 +0800 Subject: [PATCH 05/10] fix(dingtalk): derive safe fallback filenames for media downloads Image messages carry no fileName, so the raw downloadCode (a very long base64 variant) was used as the file name and every media download failed with ENAMETOOLONG (observed live). When no real fileName is present, derive a short deterministic name from a sha256 of the downloadCode plus an extension inferred from the media kind; basename length is also capped at 120 characters in the client layer regardless of source. --- plugins/dingtalk/src/api/client.ts | 27 ++++++++++-- .../dingtalk/src/gateway/media-download.ts | 33 ++++++++++---- plugins/dingtalk/src/gateway/message.ts | 15 ++++--- plugins/dingtalk/tests/media.test.ts | 43 +++++++++++++++++++ plugins/dingtalk/tests/message.test.ts | 40 +++++++++++++---- 5 files changed, 132 insertions(+), 26 deletions(-) diff --git a/plugins/dingtalk/src/api/client.ts b/plugins/dingtalk/src/api/client.ts index 6538d2d..862e507 100644 --- a/plugins/dingtalk/src/api/client.ts +++ b/plugins/dingtalk/src/api/client.ts @@ -365,9 +365,10 @@ type CachedEntry = { /** * Sanitize an inbound file name for safe use as a temp download path: strip - * path separators, shell metacharacters, and ASCII control characters. Keeps - * the extension so the agent and the user can identify the file type at a - * glance. + * path separators, shell metacharacters, and ASCII control characters, then + * truncate the basename so an over-long name never throws ENAMETOOLONG on + * write. Keeps the extension so the agent and the user can identify the file + * type at a glance. */ export function sanitizeFileName(name: string): string { let base = name.replace(/[\\/:*?"<>|]/g, "_"); @@ -380,7 +381,25 @@ export function sanitizeFileName(name: string): string { return code >= 0x20 && code !== 0x7f; }) .join(""); - return base.trim() || "message"; + return truncateBasename(base.trim() || "message"); +} + +/** Max length for the basename portion (before the last extension segment). */ +const MAX_BASENAME_LENGTH = 120; + +/** + * Truncate a file name's basename to `MAX_BASENAME_LENGTH` characters, keeping + * the trailing extension segment intact. Applied after sanitization so no + * caller can slip an over-long name (from any source) past the write — a bare + * download token would otherwise exceed common filesystem name limits and + * throw ENAMETOOLONG (mac APFS/HFS allow up to 255 UTF-8 bytes). + */ +function truncateBasename(name: string): string { + const dot = name.lastIndexOf("."); + const ext = dot > 0 ? name.slice(dot) : ""; + const stem = dot > 0 ? name.slice(0, dot) : name; + if (stem.length <= MAX_BASENAME_LENGTH) return name; + return `${stem.slice(0, MAX_BASENAME_LENGTH)}${ext}`; } const clientCache = new Map(); diff --git a/plugins/dingtalk/src/gateway/media-download.ts b/plugins/dingtalk/src/gateway/media-download.ts index c41884b..e6dbaf7 100644 --- a/plugins/dingtalk/src/gateway/media-download.ts +++ b/plugins/dingtalk/src/gateway/media-download.ts @@ -1,4 +1,5 @@ import type { PluginLogger } from "@marswave/cola-plugin-sdk"; +import { createHash } from "node:crypto"; import type { DingTalkClient } from "../api/client.js"; import type { ParsedRobotMessage } from "./message.js"; @@ -27,7 +28,7 @@ export async function downloadRobotMessageMedia( return undefined; } - const fallbackName = fileName ?? mediaDefaultExtension(parsed.media?.kind ?? "unknown"); + const fallbackName = fileName ?? mediaFallbackName(downloadCode, parsed.media?.kind ?? "unknown"); try { const path = await client.downloadMessageFile(robotCode, downloadCode, fallbackName, { maxBytes: MAX_MEDIA_DOWNLOAD_BYTES, @@ -44,17 +45,33 @@ export async function downloadRobotMessageMedia( } } -function mediaDefaultExtension(kind: string): string { +/** + * Build a safe file name when the message carries no real `fileName`. The + * downloadCode is a long base64-ish token (image messages have no name), so + * reusing it verbatim would exceed common filesystem limits and throw + * ENAMETOOLONG. Instead derive a short deterministic name from a sha256 hash of + * the code plus an extension inferred from the media kind. The resulting name + * is short (16 hex chars + extension) and never contains the code itself. + */ +function mediaFallbackName(downloadCode: string, kind: string): string { + const hash = sha256Hex(downloadCode).slice(0, 16); + return `${hash}${mediaExtension(kind)}`; +} + +/** sha256 of a string, hex-encoded. */ +function sha256Hex(input: string): string { + return createHash("sha256").update(input, "utf8").digest("hex"); +} + +function mediaExtension(kind: string): string { switch (kind) { case "image": - return "picture.jpg"; + return ".jpg"; case "audio": - return "voice.amr"; + return ".amr"; case "video": - return "video.mp4"; - case "file": - return "file"; + return ".mp4"; default: - return "message"; + return ""; } } diff --git a/plugins/dingtalk/src/gateway/message.ts b/plugins/dingtalk/src/gateway/message.ts index fc024e9..98a5d23 100644 --- a/plugins/dingtalk/src/gateway/message.ts +++ b/plugins/dingtalk/src/gateway/message.ts @@ -119,10 +119,11 @@ export function extractMedia( }; const downloadCode = content.downloadCode ?? (payload as { downloadCode?: string }).downloadCode; - const fileName = - content.fileName ?? - (payload as { fileName?: string }).fileName ?? - downloadCode?.replace(/^\*+/, ""); + // Only use a real fileName when the message reports one. The downloadCode is + // a long base64-ish token that must NOT be reused as a file name (it exceeds + // common filesystem name limits and hashed fallbacks are applied at download + // time instead when the name is missing). + const fileName = content.fileName ?? (payload as { fileName?: string }).fileName; const kind = mediaKindForMsgType(payload.msgtype); return { kind, downloadCode, fileName: normalizeFileName(fileName) }; @@ -260,8 +261,10 @@ function extractRichTextMedia( if (!pictureNode) return undefined; const downloadCode = pictureNode.downloadCode; if (!downloadCode) return undefined; - const fileName = pictureNode.fileName ?? downloadCode.replace(/^\*+/, ""); - return { kind: "image", downloadCode, fileName: normalizeFileName(fileName) }; + // Prefer a real name; when the picture carries none, leave it undefined so the + // download path builds a safe hashed name instead of reusing the downloadCode. + const fileName = normalizeFileName(pictureNode.fileName); + return { kind: "image", downloadCode, fileName }; } /** diff --git a/plugins/dingtalk/tests/media.test.ts b/plugins/dingtalk/tests/media.test.ts index 8513e10..77af343 100644 --- a/plugins/dingtalk/tests/media.test.ts +++ b/plugins/dingtalk/tests/media.test.ts @@ -95,6 +95,18 @@ describe("sanitizeFileName", () => { expect(sanitizeFileName("")).toBe("message"); expect(sanitizeFileName(" ")).toBe("message"); }); + + it("truncates an over-long basename while keeping the extension", () => { + const long = `a${"x".repeat(300)}.png`; + const safe = sanitizeFileName(long); + expect(safe.length).toBeLessThanOrEqual(200); + expect(safe.endsWith(".png")).toBe(true); + expect(safe.length).toBe(120 + 4); // 120-char stem + ".png" + }); + + it("leaves a normal-length name untouched", () => { + expect(sanitizeFileName("report.pdf")).toBe("report.pdf"); + }); }); describe("DingTalkClient.uploadMedia", () => { @@ -246,4 +258,35 @@ describe("DingTalkClient.resolveMessageDownload / downloadMessageFile", () => { client.downloadMessageFile("robot-1", "code-1", "big.bin", { maxBytes: 10 }), ).rejects.toThrow(/limit/); }); + + it("survives an over-long downloadCode: writes a short derived filename", async () => { + const downloadUrl = "https://tmp.example/pic"; + const body = await fs.readFile(await writeTmp("blob", "img-bytes")); + const longCode = `mIofN681YE3f_+m+NntqpT_Xb989by3Wk+raappFh6IDZWpC7EkwrPh${"A".repeat(500)}`; + const fetchImpl = vi.fn(async (input: string) => { + if (input.endsWith("/v1.0/oauth2/accessToken")) return tokenResponse(); + if (input.endsWith("/v1.0/robot/messageFiles/download")) return jsonResponse({ downloadUrl }); + if (input === downloadUrl) + return { + ok: true, + status: 200, + headers: { get: (n: string) => (n === "content-length" ? String(body.length) : null) }, + arrayBuffer: async () => body.buffer, + } as unknown as Response; + throw new Error(`unexpected url ${input}`); + }); + const client = new DingTalkClient( + new AccessTokenManager("app", "secret", fetchImpl), + fetchImpl, + ); + + // Pass the raw long code as the fileName to prove sanitizeFileName clamps it. + const out = await client.downloadMessageFile("robot-1", longCode, longCode); + + const base = path.basename(out); + expect(base.length).toBeLessThanOrEqual(120); + expect(base).not.toContain(longCode); + expect(await fs.readFile(out, "utf8")).toBe("img-bytes"); + await fs.rm(path.dirname(out), { recursive: true, force: true }); + }); }); diff --git a/plugins/dingtalk/tests/message.test.ts b/plugins/dingtalk/tests/message.test.ts index 53c36cc..3f7c815 100644 --- a/plugins/dingtalk/tests/message.test.ts +++ b/plugins/dingtalk/tests/message.test.ts @@ -209,7 +209,7 @@ describe("richText message handling", () => { expect(parsed?.media).toEqual({ kind: "image", downloadCode: "dc-only", - fileName: "dc-only", + fileName: undefined, }); }); @@ -250,7 +250,7 @@ describe("extractMedia", () => { content: { downloadCode: "dc-img" }, }); expect(media?.kind).toBe("image"); - expect(media?.fileName).toBe("dc-img"); + expect(media?.fileName).toBeUndefined(); }); it("falls back to the top-level fileName / downloadCode when content lacks them", () => { @@ -277,7 +277,7 @@ describe("extractMedia", () => { richText: [{ text: "hello" }, { type: "picture", downloadCode: "dc-pic" }], }, }); - expect(media).toEqual({ kind: "image", downloadCode: "dc-pic", fileName: "dc-pic" }); + expect(media).toEqual({ kind: "image", downloadCode: "dc-pic", fileName: undefined }); }); it("returns undefined for a richText message without a picture downloadCode", () => { @@ -315,11 +315,13 @@ describe("downloadRobotMessageMedia", () => { expect(info).toHaveBeenCalled(); }); - it("returns a default extension-based name when the message has no file name", async () => { + it("falls back to a hashed name (not the downloadCode) when the message has no file name", async () => { const client = { downloadMessageFile: vi.fn(async () => "/tmp/x") }; + // A long base64-ish downloadCode that would exceed filesystem name limits. + const longCode = `mIofN681YE3f_+m+NntqpT_Xb989by3Wk+raappFh6IDZWpC7EkwrPh${"A".repeat(400)}`; const parsed = { robotCode: "robot-1", - media: { kind: "image", downloadCode: "dc" }, + media: { kind: "image", downloadCode: longCode }, } as never; await downloadRobotMessageMedia(client as never, parsed, { @@ -327,9 +329,31 @@ describe("downloadRobotMessageMedia", () => { warn: vi.fn(), } as never); - expect(client.downloadMessageFile).toHaveBeenCalledWith("robot-1", "dc", "picture.jpg", { - maxBytes: MAX_MEDIA_DOWNLOAD_BYTES, - }); + const mockCall = (client as { downloadMessageFile: ReturnType }) + .downloadMessageFile.mock.calls[0] as unknown as [ + string, + string, + string, + { maxBytes: number }, + ]; + expect(mockCall[0]).toBe("robot-1"); + expect(mockCall[1]).toBe(longCode); + expect(mockCall[3].maxBytes).toBe(MAX_MEDIA_DOWNLOAD_BYTES); + const name = mockCall[2]; + // The generated name must be short, deterministic, extension-bearing, and + // must NOT contain the raw downloadCode. + expect(name.length).toBeLessThanOrEqual(120); + expect(name).toMatch(/^[0-9a-f]{16}\.jpg$/); + expect(name).not.toContain(longCode); + // Deterministic: same code → same name. + await downloadRobotMessageMedia(client as never, parsed, { + info: vi.fn(), + warn: vi.fn(), + } as never); + expect( + (client as { downloadMessageFile: ReturnType }).downloadMessageFile.mock + .calls[1][2], + ).toBe(name); }); it("returns undefined when downloadCode or robotCode is missing, without downloading", async () => { From e174f624ad277ec6a286c0443ca773040eeb473d Mon Sep 17 00:00:00 2001 From: echohn Date: Thu, 24 Sep 2026 09:54:46 +0800 Subject: [PATCH 06/10] chore(dingtalk): bundle DingTalk brand icon as plugin asset The dingtalk.com favicon renders poorly as a plugin icon. Ship the official app icon (extracted from the DingTalk macOS client, 256px PNG) in the plugin's assets and point iconUrl at the repository asset URL, consistent with the host's https-only iconUrl validation. --- plugins/dingtalk/assets/icon.png | Bin 0 -> 13478 bytes plugins/dingtalk/package.json | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 plugins/dingtalk/assets/icon.png diff --git a/plugins/dingtalk/assets/icon.png b/plugins/dingtalk/assets/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..b164f7fbe1a92e8aa8beb987a71f3e945663388d GIT binary patch literal 13478 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 ZZsOigY|*WRfBwXItf-+-E@vM4zW}ipyITMN literal 0 HcmV?d00001 diff --git a/plugins/dingtalk/package.json b/plugins/dingtalk/package.json index a8b9d88..c5aa661 100644 --- a/plugins/dingtalk/package.json +++ b/plugins/dingtalk/package.json @@ -33,7 +33,7 @@ "channel": { "label": "DingTalk", "description": "DingTalk messaging via official enterprise bot (Stream mode)", - "iconUrl": "https://www.dingtalk.com/favicon.ico", + "iconUrl": "https://raw.githubusercontent.com/marswaveai/cola-plugins/main/plugins/dingtalk/assets/icon.png", "aliases": [ "dingtalk" ], From 577a7f640c79eb7cb0910ff5eecfbca34868c338 Mon Sep 17 00:00:00 2001 From: echohn Date: Sat, 26 Sep 2026 10:00:38 +0800 Subject: [PATCH 07/10] fix(dingtalk): make unauthorized hints actionable with ID and allow command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous unauthorizedHint override replaced the host's default guidance (which names the 'cola channel allow[-group]' command) with a polite dead-end reply. The owner had no in-band way to learn the ID needed for authorization — it only appeared in host logs. The hint now always includes the target ID (group or user) and the matching command, in all locales. Covered by tests/unauthorized-hint.test.ts. --- plugins/dingtalk/locales/en.json | 4 +- plugins/dingtalk/locales/es.json | 4 +- plugins/dingtalk/locales/ja.json | 4 +- plugins/dingtalk/locales/ko.json | 4 +- plugins/dingtalk/locales/zh-CN.json | 4 +- plugins/dingtalk/locales/zh-TW.json | 4 +- plugins/dingtalk/src/index.ts | 10 ++++- .../dingtalk/tests/unauthorized-hint.test.ts | 44 +++++++++++++++++++ 8 files changed, 64 insertions(+), 14 deletions(-) create mode 100644 plugins/dingtalk/tests/unauthorized-hint.test.ts diff --git a/plugins/dingtalk/locales/en.json b/plugins/dingtalk/locales/en.json index c67d397..3174b53 100644 --- a/plugins/dingtalk/locales/en.json +++ b/plugins/dingtalk/locales/en.json @@ -13,8 +13,8 @@ "status.reconnecting": "Disconnected, reconnecting…", "status.failed": "Connection failed", "channel.groupDisabled": "Group chat is not enabled. Send a direct message to the bot instead.", - "auth.user": "I am the owner's work assistant and am unable to process your request for now. Your message won't be seen by the owner; if you have something urgent, please contact the owner directly.", - "auth.group": "I am the owner's work assistant and am unable to process your request for now. Your message won't be seen by the owner; if you have something urgent, please contact the owner directly.", + "auth.user": "I am the owner's work assistant and am unable to process your request for now. You are not authorized yet (Your ID: {{userId}}). The owner can run `cola channel allow dingtalk {{userId}}` on the desktop, or send this ID to the assistant via an authorized channel.", + "auth.group": "I am the owner's work assistant and am unable to process your request for now. This group is not authorized yet (Group ID: {{groupId}}). The owner can run `cola channel allow-group dingtalk {{groupId}}` on the desktop, or send this ID to the assistant via direct message.", "error.noAccount": "No active DingTalk account", "command.description": "{{name}} status and configuration", "command.args": "Subcommands: {{commands}}", diff --git a/plugins/dingtalk/locales/es.json b/plugins/dingtalk/locales/es.json index 8dd35c8..05e8f3d 100644 --- a/plugins/dingtalk/locales/es.json +++ b/plugins/dingtalk/locales/es.json @@ -13,8 +13,8 @@ "status.reconnecting": "Conexión perdida, reconectando…", "status.failed": "Error de conexión", "channel.groupDisabled": "Los chats de grupo no están habilitados. Envía un mensaje directo al bot.", - "auth.user": "Soy el asistente de trabajo del propietario y no puedo procesar su solicitud por ahora. El propietario no verá su mensaje; para asuntos urgentes, póngase en contacto directamente con el propietario.", - "auth.group": "Soy el asistente de trabajo del propietario y no puedo procesar su solicitud por ahora. El propietario no verá su mensaje; para asuntos urgentes, póngase en contacto directamente con el propietario.", + "auth.user": "Soy el asistente de trabajo del propietario y no puedo procesar su solicitud por ahora. Usted aún no está autorizado (Su ID: {{userId}}). El propietario puede ejecutar `cola channel allow dingtalk {{userId}}` en el escritorio, o enviar este ID al asistente a través de un canal autorizado.", + "auth.group": "Soy el asistente de trabajo del propietario y no puedo procesar su solicitud por ahora. Este grupo aún no está autorizado (ID del grupo: {{groupId}}). El propietario puede ejecutar `cola channel allow-group dingtalk {{groupId}}` en el escritorio, o enviar este ID al asistente por mensaje directo.", "error.noAccount": "No hay una cuenta de DingTalk activa", "command.description": "Estado y configuración de {{name}}", "command.args": "Subcomandos: {{commands}}", diff --git a/plugins/dingtalk/locales/ja.json b/plugins/dingtalk/locales/ja.json index b8b3893..8ab9709 100644 --- a/plugins/dingtalk/locales/ja.json +++ b/plugins/dingtalk/locales/ja.json @@ -13,8 +13,8 @@ "status.reconnecting": "接続が切断されました。再接続中…", "status.failed": "接続に失敗しました", "channel.groupDisabled": "グループチャットは無効です。ボットにダイレクトメッセージを送ってください。", - "auth.user": "私は主人の仕事アシスタントです。現在はお客様のリクエストを処理できません。お客様のメッセージは主人には届きません。緊急のご用件がある場合は、直接主人にご連絡ください。", - "auth.group": "私は主人の仕事アシスタントです。現在はお客様のリクエストを処理できません。お客様のメッセージは主人には届きません。緊急のご用件がある場合は、直接主人にご連絡ください。", + "auth.user": "私は主人の仕事アシスタントです。現在はリクエストを処理できません。まだ権限が付与されていません(あなたの ID:{{userId}})。主人はデスクトップで `cola channel allow dingtalk {{userId}}` を実行するか、この ID を既存の許可済みチャネル経由でアシスタントに送信してください。", + "auth.group": "私は主人の仕事アシスタントです。現在はリクエストを処理できません。このグループはまだ許可されていません(グループ ID:{{groupId}})。主人はデスクトップで `cola channel allow-group dingtalk {{groupId}}` を実行するか、この ID を DM でアシスタントに送信してください。", "error.noAccount": "利用可能な DingTalk アカウントがありません", "command.description": "{{name}} のステータスと設定", "command.args": "サブコマンド:{{commands}}", diff --git a/plugins/dingtalk/locales/ko.json b/plugins/dingtalk/locales/ko.json index e4cc749..0027851 100644 --- a/plugins/dingtalk/locales/ko.json +++ b/plugins/dingtalk/locales/ko.json @@ -13,8 +13,8 @@ "status.reconnecting": "연결이 끊겼습니다. 다시 연결 중…", "status.failed": "연결 실패", "channel.groupDisabled": "그룹 채팅이 비활성화되어 있습니다. 봇에게 개인 메시지를 보내 주세요.", - "auth.user": "저는 주인님의 업무 비서입니다. 현재 귀하의 요청을 처리할 수 없습니다. 남기신 메시지는 주인님이 보실 수 없습니다. 긴급한 일이 있으시면 주인님께 직접 연락해 주세요.", - "auth.group": "저는 주인님의 업무 비서입니다. 현재 귀하의 요청을 처리할 수 없습니다. 남기신 메시지는 주인님이 보실 수 없습니다. 긴급한 일이 있으시면 주인님께 직접 연락해 주세요.", + "auth.user": "저는 주인님의 업무 비서입니다. 현재 요청을 처리할 수 없습니다. 아직 권한이 부여되지 않았습니다(내 ID: {{userId}}). 주인님은 데스크톱에서 `cola channel allow dingtalk {{userId}}`를 실행하거나, 이 ID를 이미 허용된 채널을 통해 비서에게 보내 주세요.", + "auth.group": "저는 주인님의 업무 비서입니다. 현재 요청을 처리할 수 없습니다. 이 그룹은 아직 허용되지 않았습니다(그룹 ID: {{groupId}}). 주인님은 데스크톱에서 `cola channel allow-group dingtalk {{groupId}}`를 실행하거나, 이 ID를 DM으로 비서에게 보내 주세요.", "error.noAccount": "사용 가능한 DingTalk 계정이 없습니다", "command.description": "{{name}} 상태 및 설정", "command.args": "하위 명령: {{commands}}", diff --git a/plugins/dingtalk/locales/zh-CN.json b/plugins/dingtalk/locales/zh-CN.json index d659dac..41f9029 100644 --- a/plugins/dingtalk/locales/zh-CN.json +++ b/plugins/dingtalk/locales/zh-CN.json @@ -13,8 +13,8 @@ "status.reconnecting": "连接已断开,正在重连…", "status.failed": "连接失败", "channel.groupDisabled": "尚未启用群聊,请私信机器人。", - "auth.user": "我是主人的工作助理,暂时不能为您处理请求。您留言的内容主人暂时看不到;如有紧急事项,建议直接联系主人本人。", - "auth.group": "我是主人的工作助理,暂时不能为您处理请求。您留言的内容主人暂时看不到;如有紧急事项,建议直接联系主人本人。", + "auth.user": "我是主人的工作助理,暂时不能为您处理请求。您尚未获得授权(您的 ID:{{userId}})。主人可在电脑上执行 `cola channel allow dingtalk {{userId}}` 完成授权,或将此 ID 通过其他已授权渠道发给助手。", + "auth.group": "我是主人的工作助理,暂时不能为您处理请求。本群尚未授权(群 ID:{{groupId}})。主人可在电脑上执行 `cola channel allow-group dingtalk {{groupId}}` 授权本群,或将此 ID 通过私信发给助手开通。", "error.noAccount": "没有可用的钉钉账号", "command.description": "{{name}} 状态和配置", "command.args": "子命令:{{commands}}", diff --git a/plugins/dingtalk/locales/zh-TW.json b/plugins/dingtalk/locales/zh-TW.json index 6ccae28..26782a8 100644 --- a/plugins/dingtalk/locales/zh-TW.json +++ b/plugins/dingtalk/locales/zh-TW.json @@ -13,8 +13,8 @@ "status.reconnecting": "連線已中斷,正在重新連線…", "status.failed": "連線失敗", "channel.groupDisabled": "尚未啟用群聊,請私訊機器人。", - "auth.user": "我是主人的工作助理,暫時無法為您處理請求。您留言的內容主人暫時看不到;如有緊急事項,建議直接聯絡主人本人。", - "auth.group": "我是主人的工作助理,暫時無法為您處理請求。您留言的內容主人暫時看不到;如有緊急事項,建議直接聯絡主人本人。", + "auth.user": "我是主人的工作助理,暫時無法為您處理請求。您尚未獲得授權(您的 ID:{{userId}})。主人可在電腦上執行 `cola channel allow dingtalk {{userId}}` 完成授權,或將此 ID 透過其他已授權渠道發給助手。", + "auth.group": "我是主人的工作助理,暫時無法為您處理請求。本群尚未授權(群 ID:{{groupId}})。主人可在電腦上執行 `cola channel allow-group dingtalk {{groupId}}` 授權本群,或將此 ID 透過私訊發給助手開通。", "error.noAccount": "沒有可用的釘釘帳號", "command.description": "{{name}} 狀態和設定", "command.args": "子命令:{{commands}}", diff --git a/plugins/dingtalk/src/index.ts b/plugins/dingtalk/src/index.ts index aec5237..e3e0801 100644 --- a/plugins/dingtalk/src/index.ts +++ b/plugins/dingtalk/src/index.ts @@ -61,14 +61,20 @@ export default defineChannel({ }, unauthorizedHint(target) { + // The default dead-end reply leaves the owner no way to authorize this + // chat: the ID needed for `cola channel allow[-group]` only shows up in + // host logs. Always include the target ID and the matching command so the + // rejection doubles as an actionable authorization hint. return target.kind === "group" ? m( "auth.group", - "I am the owner's work assistant and am unable to process your request for now. Your message won't be seen by the owner; if you have something urgent, please contact the owner directly.", + "I am the owner's work assistant and am unable to process your request for now. This group is not authorized yet (Group ID: {{groupId}}). The owner can run `cola channel allow-group dingtalk {{groupId}}` on the desktop, or send this ID to the assistant via direct message.", + { groupId: target.id }, ) : m( "auth.user", - "I am the owner's work assistant and am unable to process your request for now. Your message won't be seen by the owner; if you have something urgent, please contact the owner directly.", + "I am the owner's work assistant and am unable to process your request for now. You are not authorized yet (Your ID: {{userId}}). The owner can run `cola channel allow dingtalk {{userId}}` on the desktop, or send this ID to the assistant via an authorized channel.", + { userId: target.id }, ); }, diff --git a/plugins/dingtalk/tests/unauthorized-hint.test.ts b/plugins/dingtalk/tests/unauthorized-hint.test.ts new file mode 100644 index 0000000..0bb1e4a --- /dev/null +++ b/plugins/dingtalk/tests/unauthorized-hint.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { isPluginMessage, resolvePluginText } from "@marswave/cola-plugin-sdk"; +import mod from "../src/index.js"; + +const channel = (mod as unknown as { channel: { + unauthorizedHint?: (target: { kind: "user" | "group"; id: string }) => unknown; +} }).channel; + +/** Resolve a PluginText to its English fallback for assertion. */ +function resolve(text: unknown): string { + expect(isPluginMessage(text)).toBe(true); + const msg = text as { key: string; fallback: string; params?: Record }; + let out = msg.fallback; + for (const [k, v] of Object.entries(msg.params ?? {})) { + out = out.replaceAll(`{{${k}}}`, v); + } + return out; +} + +describe("unauthorizedHint", () => { + it("group hint includes the group ID and the allow-group command", () => { + const hint = channel.unauthorizedHint?.({ + kind: "group" as const, + id: "cidhXlF3rCREs7RapJ87Hv+eQ==", + }); + const text = resolve(hint); + expect(text).toContain("cidhXlF3rCREs7RapJ87Hv+eQ=="); + expect(text).toContain("cola channel allow-group dingtalk cidhXlF3rCREs7RapJ87Hv+eQ=="); + }); + + it("user hint includes the sender ID and the allow command", () => { + const hint = channel.unauthorizedHint?.({ kind: "user" as const, id: "14580769531227439" }); + const text = resolve(hint); + expect(text).toContain("14580769531227439"); + expect(text).toContain("cola channel allow dingtalk 14580769531227439"); + }); + + it("hints stay resolvable through the SDK i18n layer (no missing placeholders)", () => { + const group = channel.unauthorizedHint?.({ kind: "group", id: "cidABC==" }); + const user = channel.unauthorizedHint?.({ kind: "user", id: "U123" }); + expect(resolvePluginText(group as never, undefined, "en")).toContain("cidABC=="); + expect(resolvePluginText(user as never, undefined, "en")).toContain("U123"); + }); +}); From ee6d727a26bb0edef3c6caba0fceb4787af8e99b Mon Sep 17 00:00:00 2001 From: echohn Date: Sat, 26 Sep 2026 11:49:52 +0800 Subject: [PATCH 08/10] fix(dingtalk): match group owner by senderStaffId, not LWCP union senderId MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Group robot payloads carry senderId as a LWCP union id, which never matches the staffId configured as ownerStaffId — so the owner was tagged as a non-owner (with the no-private-info constraint) in every group message. Match via senderStaffId (present for published robots) and fall back to senderId when it is absent. --- plugins/dingtalk/src/gateway/event-handler.ts | 6 ++- plugins/dingtalk/tests/gateway-status.test.ts | 6 ++- .../dingtalk/tests/group-owner-tag.test.ts | 52 +++++++++++++++++++ 3 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 plugins/dingtalk/tests/group-owner-tag.test.ts diff --git a/plugins/dingtalk/src/gateway/event-handler.ts b/plugins/dingtalk/src/gateway/event-handler.ts index dc228dd..ee3415e 100644 --- a/plugins/dingtalk/src/gateway/event-handler.ts +++ b/plugins/dingtalk/src/gateway/event-handler.ts @@ -63,7 +63,11 @@ function buildNonOwnerTag(parsed: ParsedRobotMessage): string { /** Tag a group message's text before it reaches the agent. Direct chats are left untouched. */ export function annotateGroupMessage(parsed: ParsedRobotMessage, ownerStaffId?: string): string { if (!parsed.isGroup) return parsed.text; - if (ownerStaffId && parsed.senderId === ownerStaffId) { + // Group payloads carry senderId as a LWCP union id, which never matches the + // configured staffId ownerStaffId — the owner must be matched via + // senderStaffId (present for published robots), falling back to senderId. + const resolvedSenderId = parsed.senderStaffId ?? parsed.senderId; + if (ownerStaffId && resolvedSenderId === ownerStaffId) { return `${OWNER_TAG_PREFIX}\n${parsed.text}`; } return `${buildNonOwnerTag(parsed)}\n${parsed.text}`; diff --git a/plugins/dingtalk/tests/gateway-status.test.ts b/plugins/dingtalk/tests/gateway-status.test.ts index f68e47c..1f88cc9 100644 --- a/plugins/dingtalk/tests/gateway-status.test.ts +++ b/plugins/dingtalk/tests/gateway-status.test.ts @@ -218,8 +218,10 @@ describe("event handler delivery payloads", () => { expect(payload.message).toContain("run the report"); }); - it("tags a group message as owner when senderId matches ownerStaffId", async () => { - const { deps, delivered } = makeDeps({ groupEnabled: true, ownerStaffId: "sender-1" }); + it("tags a group message as owner when senderStaffId matches ownerStaffId", async () => { + // Owner is configured by staffId; group payloads carry senderId as a LWCP + // union id, so matching must prefer senderStaffId. + const { deps, delivered } = makeDeps({ groupEnabled: true, ownerStaffId: "staff-1" }); await handleRobotMessage(deps, groupPayload); expect(delivered).toHaveLength(1); diff --git a/plugins/dingtalk/tests/group-owner-tag.test.ts b/plugins/dingtalk/tests/group-owner-tag.test.ts new file mode 100644 index 0000000..f40507b --- /dev/null +++ b/plugins/dingtalk/tests/group-owner-tag.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from "vitest"; +import { OWNER_TAG_PREFIX, annotateGroupMessage } from "../src/gateway/event-handler.js"; + +const OWNER_STAFF_ID = "14580769531227439"; + +describe("annotateGroupMessage", () => { + it("tags the owner via senderStaffId even when senderId is a LWCP union id", () => { + const text = annotateGroupMessage( + { + isGroup: true, + text: "在吗", + senderId: "$:LWCP_v1:$V2vrYw+vdvNXWD8bhlqdY", + senderStaffId: OWNER_STAFF_ID, + senderNick: "韩啸", + }, + OWNER_STAFF_ID, + ); + expect(text.startsWith(OWNER_TAG_PREFIX)).toBe(true); + expect(text).toContain("在吗"); + }); + + it("falls back to senderId comparison when senderStaffId is absent", () => { + const text = annotateGroupMessage( + { isGroup: true, text: "hi", senderId: OWNER_STAFF_ID, senderNick: "韩啸" }, + OWNER_STAFF_ID, + ); + expect(text.startsWith(OWNER_TAG_PREFIX)).toBe(true); + }); + + it("tags non-owners with the constraint line (union id does not match staffId)", () => { + const text = annotateGroupMessage( + { + isGroup: true, + text: "hi", + senderId: "$:LWCP_v1:$V2vrYw+vdvNXWD8bhlqdY", + senderStaffId: "someone-else", + senderNick: "路人", + }, + OWNER_STAFF_ID, + ); + expect(text.startsWith(OWNER_TAG_PREFIX)).toBe(false); + expect(text).toContain("[非所有者消息 · "); + }); + + it("leaves direct-chat text untouched", () => { + const text = annotateGroupMessage( + { isGroup: false, text: "hello", senderId: "$:LWCP_v1:$x", senderStaffId: "U1" }, + OWNER_STAFF_ID, + ); + expect(text).toBe("hello"); + }); +}); From 0c253522bd0329f12ed0d53f75e9e5560266e042 Mon Sep 17 00:00:00 2001 From: echohn Date: Sun, 15 Nov 2026 23:16:58 +0800 Subject: [PATCH 09/10] fix(dingtalk): replace SDK heartbeat with a guarded one to stop reconnect storms MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dingtalk-stream 2.1.5 creates its heartbeat setInterval inside the socket open handler but only clears it in disconnect(); its internal autoReconnect calls _connect() again without clearing, so every reconnect leaves an orphaned interval behind. The orphans eventually fire socket.ping() while the new socket is still CONNECTING, and ws.ping() throws 'WebSocket is not open: readyState 0' — 1,991 uncaught exceptions in one evening, each dragging a fresh reconnect, piling up 16k ESTABLISHED sockets until the router behind NAT gave out. Disable the SDK heartbeat and run a guarded one instead: - ping only when readyState === OPEN - a single timer for the whole monitor lifetime, never re-created per reconnect - pong/inbound frames refresh a signal timestamp; 30s of silence recycles the connection --- plugins/dingtalk/src/gateway/monitor.ts | 133 +++++++++++++++++++++--- plugins/dingtalk/tests/watchdog.test.ts | 28 ++++- 2 files changed, 143 insertions(+), 18 deletions(-) diff --git a/plugins/dingtalk/src/gateway/monitor.ts b/plugins/dingtalk/src/gateway/monitor.ts index fa82d30..2ad4f76 100644 --- a/plugins/dingtalk/src/gateway/monitor.ts +++ b/plugins/dingtalk/src/gateway/monitor.ts @@ -58,15 +58,36 @@ export type ConnectionStateInput = { export const WATCHDOG_CHECK_INTERVAL_MS = 60_000; /** - * If no inbound Stream frame (KEEPALIVE / SYSTEM / message) arrives within - * this window while the socket still reports itself open, treat the - * connection as dead (half-open TCP after system sleep / proxy switch) and - * forcibly recycle it. The SDK's autoReconnect only reacts to a socket - * "close" (dingtalk-stream client.mjs), which half-open sockets never emit, - * so the client stays "connected" forever while frames stop flowing — we - * must break the connection ourselves. + * Last-resort backstop only — NOT the primary half-open detector. + * + * The SDK's own heartbeat does that job once `keepAlive` is enabled: every + * `heartbeat_interval` (8s, dingtalk-stream client.mjs) it sends a WebSocket + * ping and terminates the socket if no pong came back in time. Termination + * emits "close", which the SDK's autoReconnect turns into a reconnect ~1s + * later. That covers half-open TCP after sleep / proxy switch within ~16s. + * + * What ping/pong cannot catch is a socket that is still alive (pongs flow) + * but has stopped delivering application frames. That is the only case this + * watchdog exists for, so the window is deliberately long: an idle bot + * channel can legitimately carry no ROBOT frames for a very long time, and + * every extra recycle risks dropping a message that arrives mid-reconnect. + * + * History: this used to be 5 minutes and the timestamp was never reset on + * reconnect, so once it tripped it re-tripped every 60s until a frame + * happened to arrive — 800-1100 forced reconnects per day, and messages + * landing in a recycle window were lost. + */ +export const NO_FRAME_TIMEOUT_MS = 60 * 60_000; + +/** + * How often our own guarded heartbeat pings an OPEN socket. Same cadence the + * SDK used (8s), but the ping is skipped unless readyState === OPEN and the + * timer is never re-created per reconnect. */ -export const NO_FRAME_TIMEOUT_MS = 5 * 60_000; +export const HEARTBEAT_INTERVAL_MS = 8_000; + +/** How long a socket may go without a pong or any inbound frame before we recycle it. */ +export const PONG_TIMEOUT_MS = 30_000; export function deriveConnectionState(input: ConnectionStateInput): ConnectionState { if (input.cleanedUp) return "disconnected"; @@ -101,11 +122,22 @@ export async function startMonitor(opts: { let observedRobotCode: string | undefined; // Heartbeat watchdog state. lastDownstreamTs is refreshed whenever any - // inbound frame is observed; the timer trips if it goes stale while the - // socket still thinks it is connected (see NO_FRAME_TIMEOUT_MS). + // inbound frame is observed, and re-armed on every successful (re)connect so + // a fresh connection always gets a full window; the timer trips if it goes + // stale while the socket still thinks it is connected (see + // NO_FRAME_TIMEOUT_MS). let lastDownstreamTs = Date.now(); + let watchdogRecycles = 0; let watchdogTimer: ReturnType | undefined; + // Our own guarded heartbeat. It pings only when the socket is actually OPEN + // and recycles the client when pongs stop coming. One timer for the whole + // monitor lifetime — it never gets re-created per reconnect, so it cannot + // pile up the way the SDK's did. + let lastSignalTs = Date.now(); + let heartbeatTimer: ReturnType | undefined; + let hookedSocket: { readyState: number; ping: () => void; on: (e: string, f: () => void) => void } | undefined; + const restClient = getDingTalkClient(accountId, config); const dedup = new MessageDedup(); @@ -119,6 +151,17 @@ export async function startMonitor(opts: { clientSecret: config.clientSecret, subscriptions: [{ type: "CALLBACK", topic: TOPIC_ROBOT }], autoReconnect: true, + // The SDK's own ping/pong heartbeat is DELIBERATELY OFF (2026-11-15). + // dingtalk-stream 2.1.5 creates the heartbeat setInterval inside the + // socket "open" handler but only clears it in disconnect(); its internal + // autoReconnect calls _connect() again without clearing, so every single + // reconnect leaves an orphaned interval behind. Those orphans eventually + // fire socket.ping() while the new socket is still CONNECTING, and + // ws.ping() throws "WebSocket is not open: readyState 0" — 1991 uncaught + // exceptions in one evening, each dragging a fresh reconnect behind it, + // which piled up 16k ESTABLISHED sockets and took down the home router. + // We run our own guarded heartbeat + watchdog below instead. + keepAlive: false, } as DWClientOptions); // Refresh the watchdog timestamp on every inbound frame. The SDK routes @@ -130,6 +173,7 @@ export async function startMonitor(opts: { const originalOnDownStream = stream.onDownStream.bind(stream); stream.onDownStream = (data: string) => { lastDownstreamTs = Date.now(); + lastSignalTs = Date.now(); originalOnDownStream(data); }; @@ -190,9 +234,15 @@ export async function startMonitor(opts: { await stream._connect(); if (!cleanedUp) { errors.length = 0; + // A brand-new socket has earned a full frame window: without this + // reset the stale timestamp trips the watchdog on the very next tick + // and the client reconnects every 60s in a loop. + lastDownstreamTs = Date.now(); + lastSignalTs = Date.now(); logger.info(`dingtalk[${accountId}]: Stream connected`); } startWatchdog(); + startHeartbeat(); return; } catch (err) { recordError(err); @@ -211,12 +261,11 @@ export async function startMonitor(opts: { }; // Start the heartbeat watchdog interval if it isn't running. Called on - // startup and again after every successful (re)connect so the watchdog - // keeps watching across recycle cycles. The SDK only notices a lost - // connection when the socket emits "close" (dingtalk-stream client.mjs) — a - // half-open TCP socket after system sleep / proxy switch never does, so - // autoReconnect stays silent. If the socket still reports itself connected - // but no frame has arrived for NO_FRAME_TIMEOUT_MS, the connection is dead. + // startup and again after every successful (re)connect. This is a backstop, + // not the main line of defence: with keepAlive enabled the SDK terminates a + // socket that stops answering pings, and autoReconnect rebuilds it ~1s + // later. The timer only covers a socket that still answers pings (so it + // looks connected) while application frames have silently stopped. const startWatchdog = () => { if (watchdogTimer !== undefined || cleanedUp || abortSignal.aborted) return; watchdogTimer = setInterval(() => { @@ -234,21 +283,71 @@ export async function startMonitor(opts: { // _connect(). Status keeps flowing through deriveConnectionState the whole // time, and startWatchdog() is re-armed by connectLoop on success. const recycle = () => { + if (cleanedUp || abortSignal.aborted) return; try { stream.disconnect(); } catch (err) { logger.error(`dingtalk[${accountId}]: failed to break stale Stream connection`, err); } + watchdogRecycles += 1; const idleSec = Math.round((Date.now() - lastDownstreamTs) / 1000); - logger.warn(`dingtalk[${accountId}]: no frames for ${idleSec}s, reconnecting`); + logger.warn( + `dingtalk[${accountId}]: no frames for ${idleSec}s, reconnecting (backstop trip #${watchdogRecycles})`, + ); void connectLoop(); }; + /** + * Send one heartbeat ping — but only on an OPEN socket. ws.ping() throws + * synchronously on a CONNECTING socket, and an uncaught throw inside a + * setInterval callback takes the whole turn down with it. + */ + const heartbeatTick = () => { + if (cleanedUp || abortSignal.aborted) return; + const socket = (stream as unknown as { socket?: typeof hookedSocket }).socket; + if (!socket) return; + if (socket !== hookedSocket) { + hookedSocket = socket; + lastSignalTs = Date.now(); + try { + socket.on("pong", () => { + lastSignalTs = Date.now(); + }); + } catch (err) { + logger.warn(`dingtalk[${accountId}]: failed to hook socket pong handler`, err); + } + } + if (socket.readyState !== 1) return; // 0 CONNECTING / 2 CLOSING / 3 CLOSED + if (Date.now() - lastSignalTs > PONG_TIMEOUT_MS) { + logger.warn(`dingtalk[${accountId}]: no pong within ${PONG_TIMEOUT_MS / 1000}s, reconnecting`); + recycle(); + return; + } + try { + socket.ping(); + } catch (err) { + logger.warn(`dingtalk[${accountId}]: heartbeat ping failed`, err); + } + }; + + const startHeartbeat = () => { + if (heartbeatTimer !== undefined || cleanedUp || abortSignal.aborted) return; + heartbeatTimer = setInterval(heartbeatTick, HEARTBEAT_INTERVAL_MS); + }; + + const stopHeartbeat = () => { + if (heartbeatTimer !== undefined) { + clearInterval(heartbeatTimer); + heartbeatTimer = undefined; + } + }; + const cleanup = () => { if (cleanedUp) return; cleanedUp = true; abortSignal.removeEventListener("abort", handleAbort); stopWatchdog(); + stopHeartbeat(); try { stream.disconnect(); } catch (err) { diff --git a/plugins/dingtalk/tests/watchdog.test.ts b/plugins/dingtalk/tests/watchdog.test.ts index 1215296..1b8ed05 100644 --- a/plugins/dingtalk/tests/watchdog.test.ts +++ b/plugins/dingtalk/tests/watchdog.test.ts @@ -18,6 +18,7 @@ type CapturedClient = { }; let capturedClient: CapturedClient | undefined; +let capturedOptions: Record | undefined; vi.mock("dingtalk-stream", () => ({ TOPIC_ROBOT: "__robot__", @@ -40,7 +41,8 @@ vi.mock("dingtalk-stream", () => ({ this.disconnectCount += 1; this.connected = false; }; - constructor() { + constructor(opts?: Record) { + capturedOptions = opts; capturedClient = this as unknown as CapturedClient; } }, @@ -65,6 +67,7 @@ const fakeConfig: DingTalkAccountConfig = { async function bootMonitor() { capturedClient = undefined; + capturedOptions = undefined; const logger = makeLogger(); const controller = new AbortController(); const handle = await startMonitor({ @@ -91,6 +94,29 @@ afterEach(() => { }); describe("watchdog: last-frame dead-connection detection", () => { + it("keeps the SDK's own heartbeat OFF and runs a guarded one instead", async () => { + await bootMonitor(); + // dingtalk-stream 2.1.5 leaks its heartbeat interval on every reconnect and + // then pings a CONNECTING socket, which throws. We disable it and ping from + // our own guarded timer (readyState === OPEN only) — see monitor.ts. + expect(capturedOptions?.keepAlive).toBe(false); + expect(capturedOptions?.autoReconnect).toBe(true); + }); + + it("gives a reconnected socket a full fresh window instead of re-tripping every tick", async () => { + const { client } = await bootMonitor(); + + // First stall trips the backstop exactly once. + await vi.advanceTimersByTimeAsync(NO_FRAME_TIMEOUT_MS + WATCHDOG_CHECK_INTERVAL_MS); + const afterFirstTrip = client.disconnectCount; + expect(afterFirstTrip).toBeGreaterThanOrEqual(1); + + // No frames at all afterwards, but the reconnect reset the clock, so ten + // more watchdog ticks must not produce another recycle. + await vi.advanceTimersByTimeAsync(10 * WATCHDOG_CHECK_INTERVAL_MS); + expect(client.disconnectCount).toBe(afterFirstTrip); + }); + it("forcibly disconnects and reconnects when no frame arrives within the timeout", async () => { const { logger, client } = await bootMonitor(); expect(client.disconnectCount).toBe(0); From 2798cc46360755a149ac01d73457f5f5e46ba80b Mon Sep 17 00:00:00 2001 From: echohn Date: Sun, 15 Nov 2026 23:16:58 +0800 Subject: [PATCH 10/10] test(dingtalk): use a placeholder nick instead of a real name in owner-tag tests --- plugins/dingtalk/tests/group-owner-tag.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/dingtalk/tests/group-owner-tag.test.ts b/plugins/dingtalk/tests/group-owner-tag.test.ts index f40507b..67b4876 100644 --- a/plugins/dingtalk/tests/group-owner-tag.test.ts +++ b/plugins/dingtalk/tests/group-owner-tag.test.ts @@ -11,7 +11,7 @@ describe("annotateGroupMessage", () => { text: "在吗", senderId: "$:LWCP_v1:$V2vrYw+vdvNXWD8bhlqdY", senderStaffId: OWNER_STAFF_ID, - senderNick: "韩啸", + senderNick: "Alice", }, OWNER_STAFF_ID, ); @@ -21,7 +21,7 @@ describe("annotateGroupMessage", () => { it("falls back to senderId comparison when senderStaffId is absent", () => { const text = annotateGroupMessage( - { isGroup: true, text: "hi", senderId: OWNER_STAFF_ID, senderNick: "韩啸" }, + { isGroup: true, text: "hi", senderId: OWNER_STAFF_ID, senderNick: "Alice" }, OWNER_STAFF_ID, ); expect(text.startsWith(OWNER_TAG_PREFIX)).toBe(true);