diff --git a/plugins/dingtalk/README.md b/plugins/dingtalk/README.md new file mode 100644 index 0000000..3d90aae --- /dev/null +++ b/plugins/dingtalk/README.md @@ -0,0 +1,74 @@ +# 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. +- 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. + +## 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 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. + +## 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/assets/icon.png b/plugins/dingtalk/assets/icon.png new file mode 100644 index 0000000..b164f7f Binary files /dev/null and b/plugins/dingtalk/assets/icon.png differ diff --git a/plugins/dingtalk/locales/en.json b/plugins/dingtalk/locales/en.json new file mode 100644 index 0000000..3174b53 --- /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. 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}}", + "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..05e8f3d --- /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. 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}}", + "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..8ab9709 --- /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": "私は主人の仕事アシスタントです。現在はリクエストを処理できません。まだ権限が付与されていません(あなたの 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}}", + "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..0027851 --- /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": "저는 주인님의 업무 비서입니다. 현재 요청을 처리할 수 없습니다. 아직 권한이 부여되지 않았습니다(내 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}}", + "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..41f9029 --- /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": "我是主人的工作助理,暂时不能为您处理请求。您尚未获得授权(您的 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}}", + "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..26782a8 --- /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": "我是主人的工作助理,暫時無法為您處理請求。您尚未獲得授權(您的 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}}", + "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..c5aa661 --- /dev/null +++ b/plugins/dingtalk/package.json @@ -0,0 +1,51 @@ +{ + "name": "cola-plugin-dingtalk", + "version": "0.2.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://raw.githubusercontent.com/marswaveai/cola-plugins/main/plugins/dingtalk/assets/icon.png", + "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..862e507 --- /dev/null +++ b/plugins/dingtalk/src/api/client.ts @@ -0,0 +1,428 @@ +import { AccessTokenManager, type FetchLike } from "./token.js"; +import type { DingTalkAccountConfig } from "./types.js"; + +const API_BASE = "https://api.dingtalk.com"; +/** 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 = { + 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 }), + }; +} + +/** + * 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 + .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, + }); + } + + /** + * 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; + 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; +}; + +/** + * Sanitize an inbound file name for safe use as a temp download path: strip + * 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, "_"); + // 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 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(); + +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..dc228dd --- /dev/null +++ b/plugins/dingtalk/src/gateway/event-handler.ts @@ -0,0 +1,201 @@ +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"; +import { downloadRobotMessageMedia } from "./media-download.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 = "[所有者]"; + +/** + * 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; + 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. + 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. + 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; + } + + // 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] + : ["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, + ...(attachment ? { attachments: [attachment] } : {}), + }); +} + +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/media-download.ts b/plugins/dingtalk/src/gateway/media-download.ts new file mode 100644 index 0000000..e6dbaf7 --- /dev/null +++ b/plugins/dingtalk/src/gateway/media-download.ts @@ -0,0 +1,77 @@ +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"; + +/** 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 ?? mediaFallbackName(downloadCode, 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; + } +} + +/** + * 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 ".jpg"; + case "audio": + return ".amr"; + case "video": + return ".mp4"; + default: + return ""; + } +} diff --git a/plugins/dingtalk/src/gateway/message.ts b/plugins/dingtalk/src/gateway/message.ts new file mode 100644 index 0000000..98a5d23 --- /dev/null +++ b/plugins/dingtalk/src/gateway/message.ts @@ -0,0 +1,276 @@ +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; + /** + * 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 = "@机器人"; + +/** + * 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 ?? "") + : payload.msgtype === "richText" + ? summarizeRichText(payload) + : 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, + 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 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") return undefined; + if (payload.msgtype === "richText") return extractRichTextMedia(payload); + + const content = (payload.content ?? {}) as { + downloadCode?: string; + fileName?: string; + }; + + const downloadCode = content.downloadCode ?? (payload as { downloadCode?: string }).downloadCode; + // 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) }; +} + +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 + * 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": + return summarizeRichText(payload); + 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"}]`; + } +} + +/** + * 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 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; + // 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 }; +} + +/** + * 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..fa82d30 --- /dev/null +++ b/plugins/dingtalk/src/gateway/monitor.ts @@ -0,0 +1,321 @@ +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. + */ +/** + * 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"; + 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; + + // 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(); + + // 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); + + // 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, + 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`); + } + startWatchdog(); + return; + } catch (err) { + recordError(err); + const delayMs = Math.min(60_000, 1000 * 2 ** attempt); + attempt += 1; + await sleep(delayMs); + } + } + }; + + 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) { + 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..e3e0801 --- /dev/null +++ b/plugins/dingtalk/src/index.ts @@ -0,0 +1,286 @@ +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, sendMedia } 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) { + // 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. 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. 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 }, + ); + }, + + 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 + // 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: { + 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) { + ctx.logger.error("sendText: no active DingTalk account"); + return; + } + await sendText( + handle.restClient, + ctx.deliveryContext.to, + ctx.text, + handle.getRobotCode(), + 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 new file mode 100644 index 0000000..f00f212 --- /dev/null +++ b/plugins/dingtalk/src/outbound/send.ts @@ -0,0 +1,127 @@ +import type { PluginLogger } from "@marswave/cola-plugin-sdk"; +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. + * + * 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; + } +} + +/** + * 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/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..f68e47c --- /dev/null +++ b/plugins/dingtalk/tests/gateway-status.test.ts @@ -0,0 +1,502 @@ +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, + 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"; + +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"); + }); + + // 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/media.test.ts b/plugins/dingtalk/tests/media.test.ts new file mode 100644 index 0000000..77af343 --- /dev/null +++ b/plugins/dingtalk/tests/media.test.ts @@ -0,0 +1,292 @@ +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"); + }); + + 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", () => { + 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/); + }); + + 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 new file mode 100644 index 0000000..3f7c815 --- /dev/null +++ b/plugins/dingtalk/tests/message.test.ts @@ -0,0 +1,414 @@ +import { describe, expect, it, vi } from "vitest"; +import { + buildSessionTarget, + parseRobotMessage, + stripMentionPrefix, + summarizeMediaMessage, + summarizeRichText, + extractMedia, + richTextContent, +} 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; + +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 picture-richText messages via the media summary marker", () => { + expect( + summarizeMediaMessage({ + ...base, + msgtype: "richText", + content: { + richText: [ + { text: "rich " }, + { text: "body" }, + { type: "picture", downloadCode: "dc-pic" }, + ], + }, + }), + ).toBe("[图文] rich body"); + expect(summarizeMediaMessage({ ...base, msgtype: "richText" })).toBe(""); // no picture, no text + }); + + it("falls back to the raw msgtype for unknown types", () => { + expect(summarizeMediaMessage({ ...base, msgtype: "hologram" })).toBe("[hologram]"); + }); +}); + +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: undefined, + }); + }); + + 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({ + 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).toBeUndefined(); + }); + + 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 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: undefined }); + }); + + 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(); + }); +}); + +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("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: longCode }, + } as never; + + await downloadRobotMessageMedia(client as never, parsed, { + info: vi.fn(), + warn: vi.fn(), + } as never); + + 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 () => { + 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(); + 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/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"); + }); +}); 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); + }); +}); 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: