Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(im): add Yunzhijia integration

jacentsao150c07368b84
diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts
index d02a21991..4c950707e 100644
--- a/frontend/src/api/agent/index.ts
+++ b/frontend/src/api/agent/index.ts
@@ -296,7 +296,7 @@ export interface IMChannel {
tenant_id?: number;
agent_id: string;
// 'lark' is Feishu's international edition; it shares Feishu's credentials and modes.
- platform: 'wecom' | 'feishu' | 'lark' | 'slack' | 'telegram' | 'dingtalk' | 'mattermost' | 'wechat' | 'qqbot';
+ platform: 'wecom' | 'feishu' | 'lark' | 'slack' | 'telegram' | 'dingtalk' | 'mattermost' | 'wechat' | 'qqbot' | 'yunzhijia';
name: string;
enabled: boolean;
mode: 'webhook' | 'websocket' | 'longpoll';
diff --git a/frontend/src/assets/img/im/yunzhijia.svg b/frontend/src/assets/img/im/yunzhijia.svg
new file mode 100644
index 000000000..6805ba784
--- /dev/null
+++ b/frontend/src/assets/img/im/yunzhijia.svg
@@ -0,0 +1,3 @@
+<svg width="1em" height="1em" viewBox="-5 -5 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <image width="90" height="90" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAABaCAYAAAA4qEECAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAOdEVYdFNvZnR3YXJlAEZpZ21hnrGWYwAAHmNJREFUeAHlXWuMnkd1fub91utbkl07NZdE4HXSEKCA7VYRlIpmHbUVFFpwUekvRPyjlUiRSKhEC5Uam0pt/1S5tPCzCf1RCSg1bYWQqlZ2qCoqQsimSYhQm7BJsAmBxGvn4svu956emTnnzJn53nV8TaJ2km/f21yfOfOcy7zf54BXWbppP+0Y9djBp9spYIaAnXw+y8eZQNgU8/B94v9CCFji4xICFomPHfAAXy/0Iyx+YXdYwKsoBbz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0i4H+iy7NaymoRxMzl+zyhUppi3xqwxZJQaa3tbk85GNQRshBq5cn9XOJ671y3DrfvOU8uXi1dNKA1CeC38umHuLXZZvDkgGxpwuCRpW6WChyQBcMCPuA42nmwfW3hxHqP8tntU1O442IBDGvuZUoC+DxC+gfM5uS2NwUTZo5mVl3yDmybLpmIauddy9kfGKXEr5PcyQDffrEB1vSyAe3TVx6k+fQb1SHt3mw9DaD1dcvXQBVlQ30/Jk8hEdy/5UDQ1373uv/D/7jvaukrj9A8K6B5RuR6sVbq36zO2cyCcHRhUkwD8RD+LHEMYIGp4x6u/+Ce6/4f/nPVp0tf5qBVN8YcjbCdqSYGsGa5l3OI/zaXey9QJuCI8OwSHxfiOd9fiN/LiV8Zwaso/S8d0bIPYqlYogAAAABJRU5ErkJggg==" preserveAspectRatio="xMidYMid meet"/>
+</svg>
diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vue
index f27a9751b..b9f3d346f 100644
--- a/frontend/src/components/IMChannelPanel.vue
+++ b/frontend/src/components/IMChannelPanel.vue
@@ -154,7 +154,8 @@
<div class="option-chips">
<button type="button" class="option-chip"
:class="{ 'option-chip--active': formData.mode === 'websocket' }"
- :disabled="formData.platform === 'mattermost'" @click="formData.mode = 'websocket'">
+ :disabled="formData.platform === 'mattermost'"
+ @click="formData.mode = 'websocket'">
WebSocket
</button>
<button type="button" class="option-chip" :class="{ 'option-chip--active': formData.mode === 'webhook' }"
@@ -164,7 +165,8 @@
</div>
<p class="form-desc">
{{ formData.platform === 'mattermost' ? $t('agentEditor.im.mattermostModeHint') :
- $t('agentEditor.im.modeHint') }}
+ formData.platform === 'yunzhijia' ? $t('agentEditor.im.yunzhijiaModeHint') :
+ $t('agentEditor.im.modeHint') }}
</p>
</div>
@@ -472,6 +474,40 @@
</div>
</div>
</template>
+
+ <!-- Yunzhijia credentials -->
+ <template v-if="formData.platform === 'yunzhijia'">
+ <div class="platform-link-hint">
+ <a href="https://open.yunzhijia.com/" target="_blank" rel="noopener noreferrer" class="doc-link">
+ {{ $t('agentEditor.im.yunzhijiaConsole') }}
+ <t-icon name="link" class="link-icon" />
+ </a>
+ <span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
+ </div>
+ <div class="form-item">
+ <label class="form-label required">{{ $t('agentEditor.im.yunzhijiaSendMsgUrl') }}</label>
+ <t-input v-model="formData.credentials.send_msg_url"
+ placeholder="https://www.yunzhijia.com/gateway/robot/webhook/send?yzjtype=0&yzjtoken=..." />
+ </div>
+ <div class="form-item">
+ <label class="form-label">{{ $t('agentEditor.im.yunzhijiaSecret') }}</label>
+ <t-input v-model="formData.credentials.secret" type="password"
+ :placeholder="$t('agentEditor.im.yunzhijiaSecretPlaceholder')" />
+ <p class="form-desc">{{ $t('agentEditor.im.yunzhijiaSecretHint') }}</p>
+ </div>
+ <div class="form-item">
+ <label class="form-label">{{ $t('agentEditor.im.yunzhijiaTimeout') }}</label>
+ <t-input-number v-model="formData.credentials.timeout_seconds" placeholder="10" :min="1" :max="60"
+ style="width: 100%;" />
+ <p class="form-desc">{{ $t('agentEditor.im.yunzhijiaTimeoutHint') }}</p>
+ </div>
+ <div class="form-item">
+ <label class="form-label required">{{ $t('agentEditor.im.yunzhijiaAllowedHostSuffix') }}</label>
+ <t-input v-model="formData.credentials.allowed_webhook_host_suffix" placeholder="yunzhijia.com" />
+ <p class="form-desc">{{ $t('agentEditor.im.yunzhijiaAllowedHostSuffixHint') }}</p>
+ </div>
+ </template>
+
<!-- WeChat credentials (QR code binding) -->
<template v-if="formData.platform === 'wechat'">
<p class="form-desc">{{ $t('agentEditor.im.wechatHint') }}</p>
@@ -545,6 +581,7 @@ import dingtalkLogo from '@/assets/img/im/dingtalk.svg';
import mattermostLogo from '@/assets/img/im/mattermost.svg';
import wechatLogo from '@/assets/img/im/wechat.svg';
import qqbotLogo from '@/assets/img/im/qqbot.png';
+import yunzhijiaLogo from '@/assets/img/im/yunzhijia.svg';
type IMPlatform = IMChannel['platform'];
@@ -558,6 +595,7 @@ const PLATFORM_LOGO: Record<string, string> = {
mattermost: mattermostLogo,
wechat: wechatLogo,
qqbot: qqbotLogo,
+ yunzhijia: yunzhijiaLogo,
};
const platformLogo = (platform: string): string => (platform ? PLATFORM_LOGO[platform] || '' : '');
@@ -609,6 +647,7 @@ const platformOptions = computed(() => ([
{ value: 'mattermost' as IMPlatform, label: t('agentEditor.im.mattermost'), logo: mattermostLogo },
{ value: 'wechat' as IMPlatform, label: t('agentEditor.im.wechat'), logo: wechatLogo },
{ value: 'qqbot' as IMPlatform, label: t('agentEditor.im.qqbot'), logo: qqbotLogo },
+ { value: 'yunzhijia' as IMPlatform, label: t('agentEditor.im.yunzhijia'), logo: yunzhijiaLogo },
]));
// Feishu and Lark are the same product on separate clouds, so each has its own
@@ -756,6 +795,15 @@ function onPlatformChange(val: string | number | boolean) {
if (val === 'wechat') {
formData.value.mode = 'longpoll';
formData.value.output_mode = 'full';
+ } else if (val === 'mattermost' || val === 'yunzhijia') {
+ formData.value.mode = 'webhook';
+ formData.value.output_mode = 'stream';
+ if (val === 'yunzhijia') {
+ formData.value.credentials = {
+ timeout_seconds: 10,
+ allowed_webhook_host_suffix: 'yunzhijia.com',
+ };
+ }
} else {
formData.value.mode = 'websocket';
formData.value.output_mode = 'stream';
@@ -957,6 +1005,12 @@ async function handleSave() {
MessagePlugin.warning(t('agentEditor.im.wechatScanBind'));
return;
}
+ if (formData.value.platform === 'yunzhijia' &&
+ (!String(formData.value.credentials.send_msg_url || '').trim() ||
+ !String(formData.value.credentials.allowed_webhook_host_suffix || '').trim())) {
+ MessagePlugin.warning(t('agentEditor.im.yunzhijiaRequiredCredentials'));
+ return;
+ }
if (editingChannel.value) {
await updateIMChannel(editingChannel.value.id, {
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 0c39a4d85..a4d5f7611 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -5883,7 +5883,7 @@ export default {
},
im: {
title: 'IM Integration',
- description: 'Connect agent to instant messaging platforms like WeCom, Feishu, Lark, Slack, Telegram, DingTalk, Mattermost, WeChat and QQBot',
+ description: 'Connect agent to instant messaging platforms like WeCom, Feishu, Lark, Slack, Telegram, DingTalk, Mattermost, WeChat, QQBot and Yunzhijia',
feishu: 'Feishu',
lark: 'Lark',
slack: 'Slack',
@@ -5893,6 +5893,7 @@ export default {
wecom: 'WeCom',
wechat: 'WeChat',
qqbot: 'QQBot',
+ yunzhijia: 'Yunzhijia',
addChannel: 'Add Channel',
channelsTitle: 'IM Channels',
disabled: 'Disabled',
@@ -5922,6 +5923,17 @@ export default {
qqbotConsole: 'QQ Open Platform',
qqbotAPIBaseURLHint: 'Optional. Leave empty to use the default production API endpoint.',
qqbotGatewayURLHint: 'Optional. Leave empty to fetch the common WebSocket gateway automatically.',
+ yunzhijiaConsole: 'Yunzhijia Robot Console',
+ yunzhijiaModeHint: 'Supports Webhook and WebSocket; WebSocket mode does not require a public callback URL.',
+ yunzhijiaSendMsgUrl: 'Send Message URL',
+ yunzhijiaSecret: 'Signature Secret (optional)',
+ yunzhijiaSecretPlaceholder: 'HmacSHA1 signature secret from Yunzhijia robot settings',
+ yunzhijiaSecretHint: 'If configured, incoming callbacks will be verified using HmacSHA1 signature',
+ yunzhijiaTimeout: 'HTTP Timeout (seconds)',
+ yunzhijiaTimeoutHint: 'Timeout for sending replies via Send Message URL, default 10 seconds',
+ yunzhijiaAllowedHostSuffix: 'Allowed Host Suffix',
+ yunzhijiaAllowedHostSuffixHint: 'Restrict Send Message URL host to this suffix for security (e.g. yunzhijia.com)',
+ yunzhijiaRequiredCredentials: 'Enter the Send Message URL and allowed host suffix',
mattermostModeHint: 'Mattermost only supports Webhook mode (outgoing webhook + bot token).',
mattermostPostToMain: 'Post replies in channel timeline',
mattermostPostToMainHint:
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index ca61fed2f..7cdb5aeaf 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -5817,7 +5817,7 @@ export default {
},
im: {
title: "IM 통합",
- description: "에이전트를 Feishu, Slack, Telegram, DingTalk, Mattermost, QQBot 등 인스턴트 메시징 플랫폼에 연결",
+ description: "에이전트를 Feishu, Slack, Telegram, DingTalk, Mattermost, QQBot, Yunzhijia 등 인스턴트 메시징 플랫폼에 연결",
wecom: "WeCom",
feishu: "Feishu",
lark: "Lark",
@@ -5827,6 +5827,7 @@ export default {
mattermost: "Mattermost",
wechat: "WeChat",
qqbot: "QQBot",
+ yunzhijia: "Yunzhijia",
addChannel: "채널 추가",
channelsTitle: "IM 채널",
disabled: "비활성",
@@ -5856,6 +5857,17 @@ export default {
qqbotConsole: "QQ Open Platform",
qqbotAPIBaseURLHint: "선택 사항. 비워두면 기본 프로덕션 API 엔드포인트를 사용합니다.",
qqbotGatewayURLHint: "선택 사항. 비워두면 공용 WebSocket gateway를 자동으로 가져옵니다.",
+ yunzhijiaConsole: "Yunzhijia 로봇 콘솔",
+ yunzhijiaModeHint: "Webhook과 WebSocket을 지원하며 WebSocket 모드에는 공개 콜백 URL이 필요하지 않습니다.",
+ yunzhijiaSendMsgUrl: "메시지 전송 URL",
+ yunzhijiaSecret: "서명 시크릿 (선택 사항)",
+ yunzhijiaSecretPlaceholder: "Yunzhijia 로봇 설정의 HmacSHA1 서명 시크릿",
+ yunzhijiaSecretHint: "설정하면 들어오는 콜백 요청이 HmacSHA1 서명으로 검증됩니다",
+ yunzhijiaTimeout: "HTTP 타임아웃 (초)",
+ yunzhijiaTimeoutHint: "메시지 전송 URL을 통한 응답 전송 타임아웃, 기본 10초",
+ yunzhijiaAllowedHostSuffix: "허용 호스트 접미사",
+ yunzhijiaAllowedHostSuffixHint: "보안을 위해 메시지 전송 URL 호스트를 이 접미사로 제한 (예: yunzhijia.com)",
+ yunzhijiaRequiredCredentials: "메시지 전송 URL과 허용 호스트 접미사를 입력하세요",
mattermostModeHint: "Mattermost는 Webhook(아웃고잉 웹훅 + 봇 토큰)만 지원합니다.",
mattermostPostToMain: "답변을 채널 메인 타임라인에 표시",
mattermostPostToMainHint:
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 30bfb3faf..562d09f5f 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -5387,7 +5387,7 @@ export default {
},
im: {
title: 'Интеграция IM',
- description: 'Подключите агента к платформам мгновенных сообщений, таким как Feishu, Slack, Telegram, DingTalk, Mattermost и QQBot',
+ description: 'Подключите агента к платформам мгновенных сообщений, таким как Feishu, Slack, Telegram, DingTalk, Mattermost, QQBot и Yunzhijia',
wecom: 'WeCom',
feishu: 'Feishu',
lark: 'Lark',
@@ -5397,6 +5397,7 @@ export default {
mattermost: 'Mattermost',
wechat: 'WeChat',
qqbot: 'QQBot',
+ yunzhijia: 'Yunzhijia',
addChannel: 'Добавить канал',
channelsTitle: 'IM-каналы',
disabled: 'Отключено',
@@ -5426,6 +5427,17 @@ export default {
qqbotConsole: 'QQ Open Platform',
qqbotAPIBaseURLHint: 'Необязательно. Оставьте пустым, чтобы использовать стандартный production API endpoint.',
qqbotGatewayURLHint: 'Необязательно. Оставьте пустым, чтобы автоматически получить общий WebSocket gateway.',
+ yunzhijiaConsole: 'Консоль роботов Yunzhijia',
+ yunzhijiaModeHint: 'Поддерживаются Webhook и WebSocket; для режима WebSocket не требуется публичный URL обратного вызова.',
+ yunzhijiaSendMsgUrl: 'URL отправки сообщений',
+ yunzhijiaSecret: 'Секрет подписи (необязательно)',
+ yunzhijiaSecretPlaceholder: 'Секрет подписи HmacSHA1 из настроек робота Yunzhijia',
+ yunzhijiaSecretHint: 'Если указано, входящие обратные вызовы будут проверяться с помощью подписи HmacSHA1',
+ yunzhijiaTimeout: 'Таймаут HTTP (секунды)',
+ yunzhijiaTimeoutHint: 'Таймаут отправки ответов через URL отправки сообщений, по умолчанию 10 секунд',
+ yunzhijiaAllowedHostSuffix: 'Допустимый суффикс хоста',
+ yunzhijiaAllowedHostSuffixHint: 'Ограничить хост URL отправки сообщений этим суффиксом для безопасности (напр. yunzhijia.com)',
+ yunzhijiaRequiredCredentials: 'Укажите URL отправки сообщений и допустимый суффикс хоста',
mattermostModeHint: 'Mattermost поддерживает только режим Webhook (исходящий вебхук + токен бота).',
mattermostPostToMain: 'Ответы в основной ленте канала',
mattermostPostToMainHint:
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 7567cc1ec..2544faf63 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -5838,7 +5838,7 @@ export default {
},
im: {
title: "IM 集成",
- description: "将智能体接入即时通讯平台,支持企业微信、飞书、Slack、Telegram、钉钉、Mattermost、微信和 QQBot",
+ description: "将智能体接入即时通讯平台,支持企业微信、飞书、Slack、Telegram、钉钉、Mattermost、微信、QQBot 和云之家",
wecom: "企业微信",
feishu: "飞书",
lark: "Lark(飞书国际版)",
@@ -5848,6 +5848,7 @@ export default {
mattermost: "Mattermost",
wechat: "微信",
qqbot: "QQBot",
+ yunzhijia: "云之家",
addChannel: "添加渠道",
channelsTitle: "IM 渠道",
disabled: "已停用",
@@ -5877,6 +5878,17 @@ export default {
qqbotConsole: "QQ 开放平台",
qqbotAPIBaseURLHint: "可选,留空则使用默认正式环境 API 地址。",
qqbotGatewayURLHint: "可选,留空则自动获取通用 WebSocket 接入点。",
+ yunzhijiaConsole: "云之家机器人后台",
+ yunzhijiaModeHint: "支持 Webhook 和 WebSocket;WebSocket 模式无需配置公网回调地址。",
+ yunzhijiaSendMsgUrl: "发送消息地址",
+ yunzhijiaSecret: "签名密钥(可选)",
+ yunzhijiaSecretPlaceholder: "云之家机器人设置中的 HmacSHA1 签名密钥",
+ yunzhijiaSecretHint: "配置后,将对传入的回调请求进行 HmacSHA1 签名验证",
+ yunzhijiaTimeout: "HTTP 超时时间(秒)",
+ yunzhijiaTimeoutHint: "通过发送消息地址回复的超时时间,默认 10 秒",
+ yunzhijiaAllowedHostSuffix: "允许的主机后缀",
+ yunzhijiaAllowedHostSuffixHint: "限制发送消息地址的目标域名后缀,提升安全性(如 yunzhijia.com)",
+ yunzhijiaRequiredCredentials: "请填写发送消息地址和允许的主机后缀",
mattermostModeHint: "Mattermost 仅支持 Webhook(出站 Webhook + Bot Token)。",
mattermostPostToMain: "回复显示在频道主时间线",
mattermostPostToMainHint:
diff --git a/internal/container/container.go b/internal/container/container.go
index a30362bec..6a847379f 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -70,6 +70,7 @@ import (
"github.com/Tencent/WeKnora/internal/im/telegram"
"github.com/Tencent/WeKnora/internal/im/wechat"
"github.com/Tencent/WeKnora/internal/im/wecom"
+ "github.com/Tencent/WeKnora/internal/im/yunzhijia"
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
"github.com/Tencent/WeKnora/internal/logger"
@@ -1555,6 +1556,7 @@ func registerIMAdapterFactories(imService *imPkg.Service) {
imService.RegisterAdapterFactory("mattermost", mattermost.NewFactory())
imService.RegisterAdapterFactory("wechat", wechat.NewFactory())
imService.RegisterAdapterFactory("qqbot", qqbot.NewFactory())
+ imService.RegisterAdapterFactory("yunzhijia", yunzhijia.NewFactory())
// Load and start all enabled channels from database
if err := imService.LoadAndStartChannels(); err != nil {
diff --git a/internal/handler/im.go b/internal/handler/im.go
index 3bf793fcc..21917e444 100644
--- a/internal/handler/im.go
+++ b/internal/handler/im.go
@@ -15,7 +15,7 @@ import (
// validIMPlatforms is the set of supported IM platforms.
var validIMPlatforms = map[string]bool{
"wecom": true, "feishu": true, "lark": true, "slack": true, "telegram": true, "dingtalk": true,
- "mattermost": true, "wechat": true, "qqbot": true,
+ "mattermost": true, "wechat": true, "qqbot": true, "yunzhijia": true,
}
// invalidIMPlatformError is the 400 message listing the accepted platforms. It
@@ -97,7 +97,7 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
channel.OutputMode = "full"
} else {
if channel.Mode == "" {
- if channel.Platform == "mattermost" {
+ if channel.Platform == "mattermost" || channel.Platform == "yunzhijia" {
channel.Mode = "webhook"
} else {
channel.Mode = "websocket"
@@ -328,6 +328,21 @@ func (h *IMHandler) ToggleIMChannel(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"data": channel})
}
+func writeIMCallbackACK(c *gin.Context, platform string) {
+ if platform == "yunzhijia" {
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": gin.H{
+ "type": 2,
+ "content": "",
+ },
+ })
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
+
// ── Callback handlers ──
// IMCallback handles IM platform callback requests for a specific channel.
@@ -404,12 +419,12 @@ func (h *IMHandler) IMCallback(c *gin.Context) {
} else {
logger.Infof(ctx, "[IM] Callback parsed no message to process platform=%s path_channel_id=%s", channel.Platform, channelID)
}
- c.JSON(http.StatusOK, gin.H{"success": true})
+ writeIMCallbackACK(c, channel.Platform)
return
}
// Respond immediately to avoid platform timeout
- c.JSON(http.StatusOK, gin.H{"success": true})
+ writeIMCallbackACK(c, channel.Platform)
// Detach from gin request context
asyncCtx := context.WithoutCancel(ctx)
diff --git a/internal/im/adapter.go b/internal/im/adapter.go
index 034a28729..943be0a5e 100644
--- a/internal/im/adapter.go
+++ b/internal/im/adapter.go
@@ -22,6 +22,7 @@ const (
PlatformMattermost Platform = "mattermost"
PlatformWeChat Platform = "wechat"
PlatformQQBot Platform = "qqbot"
+ PlatformYunzhijia Platform = "yunzhijia"
)
// SessionMode determines how IM sessions are resolved.
diff --git a/internal/im/types.go b/internal/im/types.go
index 17f79ad65..c5ce994cf 100644
--- a/internal/im/types.go
+++ b/internal/im/types.go
@@ -1,8 +1,10 @@
package im
import (
+ "crypto/sha256"
"encoding/json"
"fmt"
+ "net/url"
"strings"
"time"
@@ -94,7 +96,7 @@ func (ch *IMChannel) BeforeCreate(tx *gorm.DB) error {
ch.ID = uuid.New().String()
}
if ch.Mode == "" {
- if ch.Platform == "mattermost" {
+ if ch.Platform == "mattermost" || ch.Platform == "yunzhijia" {
ch.Mode = "webhook"
} else {
ch.Mode = "websocket"
@@ -200,6 +202,16 @@ func (ch *IMChannel) computeBotIdentity() string {
if appID := str("app_id"); appID != "" {
return "qqbot:" + appID
}
+ case "yunzhijia":
+ if sendMsgURL := str("send_msg_url"); sendMsgURL != "" {
+ parsed, err := url.Parse(sendMsgURL)
+ if err != nil {
+ return ""
+ }
+ if token := strings.TrimSpace(parsed.Query().Get("yzjtoken")); token != "" {
+ return fmt.Sprintf("yunzhijia:%x", sha256.Sum256([]byte(token)))
+ }
+ }
}
return ""
}
diff --git a/internal/im/types_test.go b/internal/im/types_test.go
index b3301a196..0752a0eae 100644
--- a/internal/im/types_test.go
+++ b/internal/im/types_test.go
@@ -1,6 +1,8 @@
package im
import (
+ "crypto/sha256"
+ "fmt"
"testing"
"gorm.io/gorm"
@@ -160,6 +162,44 @@ func TestComputeBotIdentity_LarkWithoutAppID(t *testing.T) {
}
}
+func TestIMChannelComputeBotIdentity_YunzhijiaUsesYZJToken(t *testing.T) {
+ makeChannel := func(sendMsgURL string) *IMChannel {
+ return &IMChannel{
+ Platform: "yunzhijia",
+ Credentials: []byte(fmt.Sprintf(
+ `{"send_msg_url":%q}`,
+ sendMsgURL,
+ )),
+ }
+ }
+
+ first := makeChannel("https://open.yunzhijia.com/gateway/robot/webhook/send?yzjtoken=token-a&foo=1")
+ second := makeChannel("https://open.yunzhijia.com/gateway/robot/webhook/send?yzjtoken=token-b&foo=1")
+ firstWant := fmt.Sprintf("yunzhijia:%x", sha256.Sum256([]byte("token-a")))
+ secondWant := fmt.Sprintf("yunzhijia:%x", sha256.Sum256([]byte("token-b")))
+ if first.computeBotIdentity() != firstWant {
+ t.Errorf("first identity = %q, want %q", first.computeBotIdentity(), firstWant)
+ }
+ if second.computeBotIdentity() != secondWant {
+ t.Errorf("second identity = %q, want %q", second.computeBotIdentity(), secondWant)
+ }
+ if first.computeBotIdentity() == second.computeBotIdentity() {
+ t.Error("different yzjtoken values must produce different Yunzhijia bot identities")
+ }
+
+ sameTokenDifferentQuery := makeChannel(
+ "https://open.yunzhijia.com/gateway/robot/webhook/send?foo=2&yzjtoken=token-a",
+ )
+ if sameTokenDifferentQuery.computeBotIdentity() != first.computeBotIdentity() {
+ t.Error("same yzjtoken must produce the same Yunzhijia bot identity")
+ }
+
+ missingToken := makeChannel("https://open.yunzhijia.com/gateway/robot/webhook/send?foo=1")
+ if missingToken.computeBotIdentity() != "" {
+ t.Errorf("missing yzjtoken identity = %q, want empty", missingToken.computeBotIdentity())
+ }
+}
+
func TestChannelSessionThreadIDField(t *testing.T) {
cs := ChannelSession{
Platform: "slack",
diff --git a/internal/im/yunzhijia/adapter.go b/internal/im/yunzhijia/adapter.go
new file mode 100644
index 000000000..0a1a55cb2
--- /dev/null
+++ b/internal/im/yunzhijia/adapter.go
@@ -0,0 +1,256 @@
+package yunzhijia
+
+import (
+ "bytes"
+ "context"
+ "crypto/hmac"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/Tencent/WeKnora/internal/im"
+ "github.com/Tencent/WeKnora/internal/logger"
+)
+
+// textMessageType is the Yunzhijia message type value for plain text messages.
+const textMessageType = 2
+
+// Compile-time check.
+var _ im.Adapter = (*Adapter)(nil)
+
+// Adapter implements im.Adapter for Yunzhijia (云之家).
+type Adapter struct {
+ sendMsgURL string
+ secret string
+ httpClient *http.Client
+ allowedWebhookHostSuffix string
+}
+
+// NewAdapter creates a Yunzhijia adapter.
+func NewAdapter(sendMsgURL, secret string, timeoutSeconds int, allowedHostSuffix string) *Adapter {
+ if timeoutSeconds <= 0 {
+ timeoutSeconds = 10
+ }
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.Proxy = nil
+ transport.DialContext = safeDialContext
+ return &Adapter{
+ sendMsgURL: strings.TrimSpace(sendMsgURL),
+ secret: secret,
+ allowedWebhookHostSuffix: strings.TrimSpace(allowedHostSuffix),
+ httpClient: &http.Client{
+ Timeout: time.Duration(timeoutSeconds) * time.Second,
+ Transport: transport,
+ CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
+ return http.ErrUseLastResponse
+ },
+ },
+ }
+}
+
+func (a *Adapter) Platform() im.Platform {
+ return im.PlatformYunzhijia
+}
+
+func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
+ return false
+}
+
+// VerifyCallback verifies the Yunzhijia callback signature (HmacSHA1).
+// If secret is not configured, verification is skipped.
+func (a *Adapter) VerifyCallback(c *gin.Context) error {
+ if a.secret == "" {
+ return nil
+ }
+
+ bodyBytes, err := io.ReadAll(c.Request.Body)
+ if err != nil {
+ return fmt.Errorf("read body: %w", err)
+ }
+ c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
+
+ var msg callbackMessage
+ if err := json.Unmarshal(bodyBytes, &msg); err != nil {
+ return fmt.Errorf("parse callback for verification: %w", err)
+ }
+
+ // Read the sign header (case-insensitive via gin's GetHeader).
+ sign := c.GetHeader("sign")
+ if sign == "" {
+ sign = c.GetHeader("Sign")
+ }
+ if sign == "" {
+ sign = c.GetHeader("SIGN")
+ }
+ if sign == "" {
+ return fmt.Errorf("missing sign header")
+ }
+
+ expected := computeSignature(a.secret, &msg)
+ if !hmac.Equal([]byte(sign), []byte(expected)) {
+ return fmt.Errorf("invalid signature")
+ }
+
+ return nil
+}
+
+// ParseCallback parses a Yunzhijia webhook callback into an IncomingMessage.
+// Returns nil for non-text messages or empty content.
+func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
+ bodyBytes, err := io.ReadAll(c.Request.Body)
+ if err != nil {
+ return nil, fmt.Errorf("read body: %w", err)
+ }
+ c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
+
+ var msg callbackMessage
+ if err := json.Unmarshal(bodyBytes, &msg); err != nil {
+ return nil, fmt.Errorf("parse callback: %w", err)
+ }
+
+ return toIncomingMessage(c.Request.Context(), &msg), nil
+}
+
+func toIncomingMessage(ctx context.Context, msg *callbackMessage) *im.IncomingMessage {
+ if msg.Type != textMessageType {
+ logger.Infof(ctx,
+ "[Yunzhijia] Skip non-text message: type=%d msgId=%s", msg.Type, msg.MsgID)
+ return nil
+ }
+
+ content := strings.TrimSpace(msg.Content)
+ if content == "" {
+ logger.Infof(ctx,
+ "[Yunzhijia] Skip empty content: msgId=%s", msg.MsgID)
+ return nil
+ }
+
+ // Conversation bots should only receive messages explicitly addressed to them.
+ var mentioned bool
+ content, mentioned = cleanAtMention(content, msg.RobotName)
+ if !mentioned {
+ logger.Infof(ctx, "[Yunzhijia] Skip message without robot mention: msgId=%s", msg.MsgID)
+ return nil
+ }
+
+ if content == "" {
+ logger.Infof(ctx,
+ "[Yunzhijia] Skip after cleaning @mention: msgId=%s", msg.MsgID)
+ return nil
+ }
+
+ chatType := im.ChatTypeGroup
+ chatID := msg.RobotID
+
+ return &im.IncomingMessage{
+ Platform: im.PlatformYunzhijia,
+ MessageType: im.MessageTypeText,
+ UserID: msg.OperatorOpenid,
+ UserName: msg.OperatorName,
+ ChatID: chatID,
+ ChatType: chatType,
+ Content: content,
+ MessageID: msg.MsgID,
+ Extra: map[string]string{
+ "robot_id": msg.RobotID,
+ "robot_name": msg.RobotName,
+ "group_type": fmt.Sprintf("%d", msg.GroupType),
+ "operator_name": msg.OperatorName,
+ "time": fmt.Sprintf("%d", msg.Time),
+ },
+ }
+}
+
+// cleanAtMention removes @RobotName from the beginning of user content.
+func cleanAtMention(content, robotName string) (string, bool) {
+ if robotName == "" {
+ return content, false
+ }
+ prefix := "@" + robotName
+ trimmed := strings.TrimLeft(content, " \t")
+ if !strings.HasPrefix(trimmed, prefix) {
+ return content, false
+ }
+ rest := trimmed[len(prefix):]
+ if rest == "" {
+ return "", true
+ }
+ separator, _ := utf8.DecodeRuneInString(rest)
+ if !unicode.IsSpace(separator) && !strings.ContainsRune("::,,", separator) {
+ return content, false
+ }
+ return strings.TrimLeftFunc(rest, func(r rune) bool {
+ return unicode.IsSpace(r) || strings.ContainsRune("::,,", r)
+ }), true
+}
+
+// SendReply sends a reply to Yunzhijia via the configured sendMsgUrl.
+func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
+ if a.sendMsgURL == "" {
+ return fmt.Errorf("yunzhijia send_msg_url is not configured")
+ }
+
+ // Validate the send URL to prevent SSRF.
+ if err := a.validateSendURL(); err != nil {
+ return err
+ }
+
+ payload := sendMessagePayload{
+ MsgType: textMessageType,
+ Content: reply.Content,
+ }
+
+ // When groupType == 3, don't set notifyParams (per reference implementation).
+ groupType := ""
+ if incoming.Extra != nil {
+ groupType = incoming.Extra["group_type"]
+ }
+ if groupType != "3" && incoming.UserID != "" {
+ payload.NotifyParams = []notifyParam{
+ {
+ Type: "openIds",
+ Values: []string{incoming.UserID},
+ },
+ }
+ }
+
+ jsonBody, err := json.Marshal(payload)
+ if err != nil {
+ return fmt.Errorf("marshal reply: %w", err)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.sendMsgURL, bytes.NewReader(jsonBody))
+ if err != nil {
+ return fmt.Errorf("create request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := a.httpClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("send reply: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
+ respBody, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("yunzhijia sendMsgUrl returned %d: %s", resp.StatusCode, string(respBody))
+ }
+
+ return nil
+}
+
+// validateSendURL checks that sendMsgUrl is safe to call (HTTPS, no internal IPs, allowed host).
+func (a *Adapter) validateSendURL() error {
+ _, err := validateEndpointURL(a.sendMsgURL, "https", a.allowedWebhookHostSuffix)
+ if err != nil {
+ return fmt.Errorf("invalid send_msg_url: %w", err)
+ }
+ return nil
+}
diff --git a/internal/im/yunzhijia/adapter_test.go b/internal/im/yunzhijia/adapter_test.go
new file mode 100644
index 000000000..437df0dfb
--- /dev/null
+++ b/internal/im/yunzhijia/adapter_test.go
@@ -0,0 +1,95 @@
+package yunzhijia
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/Tencent/WeKnora/internal/im"
+)
+
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+ return f(req)
+}
+
+func TestVerifyCallbackSignature(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ msg := callbackMessage{
+ Type: 2, RobotID: "robot", RobotName: "WeKnora", OperatorOpenid: "user",
+ OperatorName: "User", Time: 123, MsgID: "message", Content: "@WeKnora hello",
+ }
+ body, err := json.Marshal(msg)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/callback", bytes.NewReader(body))
+ req.Header.Set("Sign", computeSignature("secret", &msg))
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = req
+
+ adapter := NewAdapter("https://www.yunzhijia.com/send", "secret", 10, "yunzhijia.com")
+ if err := adapter.VerifyCallback(c); err != nil {
+ t.Fatalf("VerifyCallback() error = %v", err)
+ }
+ parsed, err := adapter.ParseCallback(c)
+ if err != nil {
+ t.Fatalf("ParseCallback() error = %v", err)
+ }
+ if parsed == nil || parsed.Content != "hello" {
+ t.Fatalf("parsed message = %#v, want content hello", parsed)
+ }
+}
+
+func TestToIncomingMessageRequiresRobotMention(t *testing.T) {
+ msg := &callbackMessage{
+ Type: 2, RobotID: "robot", RobotName: "WeKnora", OperatorOpenid: "user",
+ OperatorName: "User", Time: 123, MsgID: "message", Content: "hello",
+ }
+ if got := toIncomingMessage(t.Context(), msg); got != nil {
+ t.Fatalf("toIncomingMessage() = %#v, want nil without robot mention", got)
+ }
+}
+
+func TestCleanAtMentionRequiresNameBoundary(t *testing.T) {
+ if _, mentioned := cleanAtMention("@WeKnoraPlus hello", "WeKnora"); mentioned {
+ t.Fatal("longer user name must not be treated as a robot mention")
+ }
+ if got, mentioned := cleanAtMention("@WeKnora:你好", "WeKnora"); !mentioned || got != "你好" {
+ t.Fatalf("cleanAtMention() = %q, %v; want 你好, true", got, mentioned)
+ }
+}
+
+func TestSendReplyAcceptsAny2xxAndBuildsPayload(t *testing.T) {
+ adapter := NewAdapter("https://www.yunzhijia.com/send", "", 10, "yunzhijia.com")
+ var payload sendMessagePayload
+ adapter.httpClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode payload: %v", err)
+ }
+ return &http.Response{
+ StatusCode: http.StatusNoContent,
+ Body: io.NopCloser(bytes.NewReader(nil)),
+ Header: make(http.Header),
+ }, nil
+ })}
+
+ incoming := &im.IncomingMessage{UserID: "user", Extra: map[string]string{"group_type": "1"}}
+ if err := adapter.SendReply(context.Background(), incoming, &im.ReplyMessage{Content: "answer"}); err != nil {
+ t.Fatalf("SendReply() error = %v", err)
+ }
+ if payload.MsgType != textMessageType || payload.Content != "answer" {
+ t.Fatalf("payload = %#v", payload)
+ }
+ if len(payload.NotifyParams) != 1 || len(payload.NotifyParams[0].Values) != 1 || payload.NotifyParams[0].Values[0] != "user" {
+ t.Fatalf("notify params = %#v", payload.NotifyParams)
+ }
+}
diff --git a/internal/im/yunzhijia/factory.go b/internal/im/yunzhijia/factory.go
new file mode 100644
index 000000000..205907172
--- /dev/null
+++ b/internal/im/yunzhijia/factory.go
@@ -0,0 +1,75 @@
+package yunzhijia
+
+import (
+ "context"
+ "fmt"
+ "strconv"
+
+ "github.com/Tencent/WeKnora/internal/im"
+ "github.com/Tencent/WeKnora/internal/logger"
+)
+
+// NewFactory returns an im.AdapterFactory for Yunzhijia channels.
+// Webhook remains the default; WebSocket uses yzjtoken from send_msg_url.
+func NewFactory() im.AdapterFactory {
+ return func(factoryCtx context.Context, channel *im.IMChannel, msgHandler func(context.Context, *im.IncomingMessage) error) (im.Adapter, context.CancelFunc, error) {
+ creds, err := im.ParseCredentials(channel.Credentials)
+ if err != nil {
+ return nil, nil, fmt.Errorf("parse yunzhijia credentials: %w", err)
+ }
+
+ sendMsgURL := im.GetString(creds, "send_msg_url")
+ if sendMsgURL == "" {
+ return nil, nil, fmt.Errorf("yunzhijia send_msg_url is required")
+ }
+
+ secret := im.GetString(creds, "secret")
+ allowedHostSuffix := im.GetString(creds, "allowed_webhook_host_suffix")
+
+ timeoutSeconds := positiveIntCredential(creds, "timeout_seconds", 10)
+
+ adapter := NewAdapter(sendMsgURL, secret, timeoutSeconds, allowedHostSuffix)
+ if err := adapter.validateSendURL(); err != nil {
+ return nil, nil, err
+ }
+
+ mode := im.ResolveMode(channel, "webhook")
+ switch mode {
+ case "webhook":
+ return adapter, nil, nil
+ case "websocket":
+ webSocketURL, err := deriveWebSocketURL(sendMsgURL, allowedHostSuffix)
+ if err != nil {
+ return nil, nil, err
+ }
+ client := NewLongConnClient(webSocketURL, msgHandler)
+ wsCtx, wsCancel := context.WithCancel(context.Background())
+ go func() {
+ if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
+ logger.Errorf(context.Background(), "[IM] Yunzhijia WebSocket stopped for channel %s: %v", channel.ID, err)
+ }
+ }()
+ stop := func() {
+ client.Stop()
+ wsCancel()
+ }
+ return adapter, stop, nil
+ default:
+ return nil, nil, fmt.Errorf("unsupported yunzhijia mode: %s", mode)
+ }
+ }
+}
+
+func positiveIntCredential(creds map[string]any, key string, fallback int) int {
+ switch value := creds[key].(type) {
+ case float64:
+ if value > 0 {
+ return int(value)
+ }
+ case string:
+ if parsed, err := strconv.Atoi(value); err == nil && parsed > 0 {
+ return parsed
+ }
+ }
+ return fallback
+}
diff --git a/internal/im/yunzhijia/sign.go b/internal/im/yunzhijia/sign.go
new file mode 100644
index 000000000..6aee40bd5
--- /dev/null
+++ b/internal/im/yunzhijia/sign.go
@@ -0,0 +1,32 @@
+package yunzhijia
+
+import (
+ "crypto/hmac"
+ "crypto/sha1"
+ "encoding/base64"
+ "fmt"
+ "strings"
+)
+
+// computeSignature builds the signature string from the callback fields
+// and returns the Base64(HMAC_SHA1(secret, signatureString)).
+//
+// The signature string is formed by joining the following fields in order
+// with commas: robotId, robotName, operatorOpenid, operatorName, time, msgId, content.
+func computeSignature(secret string, msg *callbackMessage) string {
+ // Build signature string: field1,field2,...,field7
+ parts := []string{
+ msg.RobotID,
+ msg.RobotName,
+ msg.OperatorOpenid,
+ msg.OperatorName,
+ fmt.Sprintf("%d", msg.Time),
+ msg.MsgID,
+ msg.Content,
+ }
+ signatureString := strings.Join(parts, ",")
+
+ mac := hmac.New(sha1.New, []byte(secret))
+ mac.Write([]byte(signatureString))
+ return base64.StdEncoding.EncodeToString(mac.Sum(nil))
+}
diff --git a/internal/im/yunzhijia/types.go b/internal/im/yunzhijia/types.go
new file mode 100644
index 000000000..8aefd0e47
--- /dev/null
+++ b/internal/im/yunzhijia/types.go
@@ -0,0 +1,27 @@
+package yunzhijia
+
+// callbackMessage is the JSON structure that Yunzhijia posts to the webhook.
+type callbackMessage struct {
+ Type int `json:"type"`
+ RobotID string `json:"robotId"`
+ RobotName string `json:"robotName"`
+ OperatorOpenid string `json:"operatorOpenid"`
+ OperatorName string `json:"operatorName"`
+ Time int64 `json:"time"`
+ MsgID string `json:"msgId"`
+ Content string `json:"content"`
+ GroupType int `json:"groupType"`
+}
+
+// sendMessagePayload is the JSON body POSTed to sendMsgUrl to reply.
+type sendMessagePayload struct {
+ MsgType int `json:"msgtype"`
+ Content string `json:"content"`
+ NotifyParams []notifyParam `json:"notifyParams,omitempty"`
+}
+
+// notifyParam specifies recipients in a Yunzhijia send message request.
+type notifyParam struct {
+ Type string `json:"type"`
+ Values []string `json:"values"`
+}
diff --git a/internal/im/yunzhijia/url.go b/internal/im/yunzhijia/url.go
new file mode 100644
index 000000000..de1a75cc3
--- /dev/null
+++ b/internal/im/yunzhijia/url.go
@@ -0,0 +1,97 @@
+package yunzhijia
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "net/url"
+ "strings"
+)
+
+func deriveWebSocketURL(sendMsgURL, allowedHostSuffix string) (string, error) {
+ u, err := validateEndpointURL(sendMsgURL, "https", allowedHostSuffix)
+ if err != nil {
+ return "", fmt.Errorf("invalid send_msg_url for websocket: %w", err)
+ }
+
+ token := strings.TrimSpace(u.Query().Get("yzjtoken"))
+ if token == "" {
+ return "", fmt.Errorf("send_msg_url is missing yzjtoken")
+ }
+
+ wsURL := &url.URL{
+ Scheme: "wss",
+ Host: u.Host,
+ Path: "/xuntong/websocket",
+ }
+ query := url.Values{}
+ query.Set("yzjtoken", token)
+ wsURL.RawQuery = query.Encode()
+ return wsURL.String(), nil
+}
+
+func validateEndpointURL(rawURL, requiredScheme, allowedHostSuffix string) (*url.URL, error) {
+ u, err := url.Parse(strings.TrimSpace(rawURL))
+ if err != nil {
+ return nil, err
+ }
+ if !strings.EqualFold(u.Scheme, requiredScheme) {
+ return nil, fmt.Errorf("URL must use %s", requiredScheme)
+ }
+ if u.User != nil {
+ return nil, fmt.Errorf("URL must not contain user information")
+ }
+
+ host := strings.ToLower(strings.TrimSuffix(u.Hostname(), "."))
+ if host == "" {
+ return nil, fmt.Errorf("URL has empty host")
+ }
+ if host == "localhost" || strings.HasSuffix(host, ".localhost") || net.ParseIP(host) != nil {
+ return nil, fmt.Errorf("URL host must be a DNS name")
+ }
+
+ suffix := strings.ToLower(strings.Trim(strings.TrimSpace(allowedHostSuffix), "."))
+ if suffix == "" {
+ return nil, fmt.Errorf("allowed host suffix is required")
+ }
+ if host != suffix && !strings.HasSuffix(host, "."+suffix) {
+ return nil, fmt.Errorf("URL host %q does not match allowed suffix %q", host, suffix)
+ }
+
+ return u, nil
+}
+
+func safeDialContext(ctx context.Context, network, address string) (net.Conn, error) {
+ host, port, err := net.SplitHostPort(address)
+ if err != nil {
+ return nil, fmt.Errorf("split dial address: %w", err)
+ }
+ addresses, err := net.DefaultResolver.LookupIPAddr(ctx, host)
+ if err != nil {
+ return nil, fmt.Errorf("resolve endpoint host %q: %w", host, err)
+ }
+ if len(addresses) == 0 {
+ return nil, fmt.Errorf("endpoint host %q resolved to no addresses", host)
+ }
+ for _, address := range addresses {
+ if !isPublicIP(address.IP) {
+ return nil, fmt.Errorf("endpoint host %q resolves to a non-public address", host)
+ }
+ }
+
+ dialer := &net.Dialer{}
+ var lastErr error
+ for _, address := range addresses {
+ conn, dialErr := dialer.DialContext(ctx, network, net.JoinHostPort(address.IP.String(), port))
+ if dialErr == nil {
+ return conn, nil
+ }
+ lastErr = dialErr
+ }
+ return nil, fmt.Errorf("dial endpoint host %q: %w", host, lastErr)
+}
+
+func isPublicIP(ip net.IP) bool {
+ return ip != nil && !ip.IsPrivate() && !ip.IsLoopback() && !ip.IsLinkLocalUnicast() &&
+ !ip.IsLinkLocalMulticast() && !ip.IsUnspecified() && !ip.IsMulticast()
+}
diff --git a/internal/im/yunzhijia/url_test.go b/internal/im/yunzhijia/url_test.go
new file mode 100644
index 000000000..a6df7c6d5
--- /dev/null
+++ b/internal/im/yunzhijia/url_test.go
@@ -0,0 +1,80 @@
+package yunzhijia
+
+import (
+ "net"
+ "testing"
+)
+
+func TestDeriveWebSocketURL(t *testing.T) {
+ got, err := deriveWebSocketURL(
+ "https://dev.kdweibo.cn:8443/gateway/robot/webhook/send?yzjtype=12&yzjtoken=token%20value",
+ "kdweibo.cn",
+ )
+ if err != nil {
+ t.Fatalf("deriveWebSocketURL() error = %v", err)
+ }
+ want := "wss://dev.kdweibo.cn:8443/xuntong/websocket?yzjtoken=token+value"
+ if got != want {
+ t.Fatalf("deriveWebSocketURL() = %q, want %q", got, want)
+ }
+}
+
+func TestDeriveWebSocketURLRejectsMissingToken(t *testing.T) {
+ _, err := deriveWebSocketURL("https://www.yunzhijia.com/gateway/robot/webhook/send", "yunzhijia.com")
+ if err == nil {
+ t.Fatal("deriveWebSocketURL() expected missing-token error")
+ }
+}
+
+func TestValidateEndpointURLHostSuffixBoundary(t *testing.T) {
+ valid := []string{
+ "https://yunzhijia.com/path",
+ "https://www.yunzhijia.com/path",
+ }
+ for _, rawURL := range valid {
+ if _, err := validateEndpointURL(rawURL, "https", "yunzhijia.com"); err != nil {
+ t.Errorf("validateEndpointURL(%q) unexpected error: %v", rawURL, err)
+ }
+ }
+
+ invalid := []string{
+ "http://www.yunzhijia.com/path",
+ "https://evilyunzhijia.com/path",
+ "https://127.0.0.1/path",
+ "https://localhost/path",
+ }
+ for _, rawURL := range invalid {
+ if _, err := validateEndpointURL(rawURL, "https", "yunzhijia.com"); err == nil {
+ t.Errorf("validateEndpointURL(%q) expected error", rawURL)
+ }
+ }
+}
+
+func TestValidateEndpointURLRequiresHostSuffix(t *testing.T) {
+ if _, err := validateEndpointURL("https://www.yunzhijia.com/path", "https", ""); err == nil {
+ t.Fatal("validateEndpointURL() expected missing host suffix error")
+ }
+}
+
+func TestIsPublicIP(t *testing.T) {
+ for _, rawIP := range []string{"127.0.0.1", "10.0.0.1", "169.254.169.254", "::1", "fc00::1"} {
+ if isPublicIP(net.ParseIP(rawIP)) {
+ t.Errorf("isPublicIP(%q) = true, want false", rawIP)
+ }
+ }
+ if !isPublicIP(net.ParseIP("8.8.8.8")) {
+ t.Error("isPublicIP(8.8.8.8) = false, want true")
+ }
+}
+
+func TestPositiveIntCredential(t *testing.T) {
+ if got := positiveIntCredential(map[string]any{"timeout": float64(25)}, "timeout", 10); got != 25 {
+ t.Fatalf("numeric timeout = %d, want 25", got)
+ }
+ if got := positiveIntCredential(map[string]any{"timeout": "30"}, "timeout", 10); got != 30 {
+ t.Fatalf("string timeout = %d, want 30", got)
+ }
+ if got := positiveIntCredential(map[string]any{"timeout": float64(0)}, "timeout", 10); got != 10 {
+ t.Fatalf("invalid timeout = %d, want fallback 10", got)
+ }
+}
diff --git a/internal/im/yunzhijia/websocket.go b/internal/im/yunzhijia/websocket.go
new file mode 100644
index 000000000..f43213d05
--- /dev/null
+++ b/internal/im/yunzhijia/websocket.go
@@ -0,0 +1,337 @@
+package yunzhijia
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/im"
+ "github.com/Tencent/WeKnora/internal/logger"
+ ws "github.com/gorilla/websocket"
+)
+
+const (
+ webSocketHeartbeatInterval = 15 * time.Second
+ webSocketReadTimeout = 45 * time.Second
+ webSocketHandshakeTimeout = 10 * time.Second
+ webSocketMaxMessageSize = 1 << 20
+ webSocketMaxInvalidFrames = 3
+ webSocketMessageQueueSize = 64
+)
+
+var webSocketReconnectDelays = [...]time.Duration{
+ 1 * time.Second,
+ 2 * time.Second,
+ 5 * time.Second,
+ 10 * time.Second,
+ 30 * time.Second,
+ 60 * time.Second,
+}
+
+type webSocketFrame struct {
+ message *callbackMessage
+ ack []byte
+ control string
+}
+
+type LongConnClient struct {
+ url string
+ handler func(context.Context, *im.IncomingMessage) error
+ dialer *ws.Dialer
+ messages chan *im.IncomingMessage
+
+ mu sync.Mutex
+ conn *ws.Conn
+ closed atomic.Bool
+}
+
+func NewLongConnClient(webSocketURL string, handler func(context.Context, *im.IncomingMessage) error) *LongConnClient {
+ dialer := *ws.DefaultDialer
+ dialer.HandshakeTimeout = webSocketHandshakeTimeout
+ dialer.Proxy = nil
+ dialer.NetDialContext = safeDialContext
+ return &LongConnClient{
+ url: webSocketURL,
+ handler: handler,
+ dialer: &dialer,
+ messages: make(chan *im.IncomingMessage, webSocketMessageQueueSize),
+ }
+}
+
+func (c *LongConnClient) Start(ctx context.Context) error {
+ logger.Infof(ctx, "[IM] Yunzhijia WebSocket connecting")
+ go c.handleMessages(ctx)
+ attempt := 0
+ for {
+ if ctx.Err() != nil || c.closed.Load() {
+ return nil
+ }
+
+ connectedAt := time.Now()
+ err := c.connectAndRun(ctx)
+ if ctx.Err() != nil || c.closed.Load() {
+ return nil
+ }
+ if time.Since(connectedAt) >= webSocketReconnectDelays[len(webSocketReconnectDelays)-1] {
+ attempt = 0
+ }
+
+ delay := webSocketReconnectDelay(attempt)
+ attempt++
+ logger.Warnf(ctx, "[Yunzhijia] WebSocket connection lost: %v; reconnecting in %v", err, delay)
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-time.After(delay):
+ }
+ }
+}
+
+func (c *LongConnClient) Stop() {
+ c.closed.Store(true)
+ c.closeConn()
+}
+
+func (c *LongConnClient) connectAndRun(ctx context.Context) error {
+ conn, _, err := c.dialer.DialContext(ctx, c.url, nil)
+ if err != nil {
+ return fmt.Errorf("dial websocket: %w", err)
+ }
+
+ c.mu.Lock()
+ c.conn = conn
+ c.mu.Unlock()
+ defer func() {
+ c.mu.Lock()
+ if c.conn == conn {
+ c.conn = nil
+ }
+ c.mu.Unlock()
+ _ = conn.Close()
+ }()
+
+ conn.SetReadLimit(webSocketMaxMessageSize)
+ _ = conn.SetReadDeadline(time.Now().Add(webSocketReadTimeout))
+ conn.SetPongHandler(func(string) error {
+ return conn.SetReadDeadline(time.Now().Add(webSocketReadTimeout))
+ })
+
+ heartbeatCtx, cancelHeartbeat := context.WithCancel(ctx)
+ defer cancelHeartbeat()
+ go c.heartbeatLoop(heartbeatCtx, conn)
+
+ logger.Infof(ctx, "[IM] Yunzhijia WebSocket connected")
+ invalidFrames := 0
+ for {
+ messageType, data, err := conn.ReadMessage()
+ if err != nil {
+ return fmt.Errorf("read websocket message: %w", err)
+ }
+ _ = conn.SetReadDeadline(time.Now().Add(webSocketReadTimeout))
+
+ if messageType != ws.TextMessage {
+ invalidFrames++
+ if invalidFrames >= webSocketMaxInvalidFrames {
+ return fmt.Errorf("too many non-text websocket frames")
+ }
+ continue
+ }
+
+ frame, err := parseWebSocketFrame(data)
+ if err != nil {
+ invalidFrames++
+ logger.Warnf(ctx, "[Yunzhijia] Invalid WebSocket frame: %v", err)
+ if invalidFrames >= webSocketMaxInvalidFrames {
+ return fmt.Errorf("too many invalid websocket frames")
+ }
+ continue
+ }
+ invalidFrames = 0
+
+ if len(frame.ack) > 0 {
+ if err := c.writeText(conn, frame.ack); err != nil {
+ return fmt.Errorf("send websocket ack: %w", err)
+ }
+ }
+ if frame.message == nil {
+ continue
+ }
+
+ incoming := toIncomingMessage(ctx, frame.message)
+ if incoming == nil {
+ continue
+ }
+ select {
+ case c.messages <- incoming:
+ case <-ctx.Done():
+ return nil
+ }
+ }
+}
+
+func (c *LongConnClient) handleMessages(ctx context.Context) {
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case msg := <-c.messages:
+ if err := c.handler(ctx, msg); err != nil {
+ logger.Errorf(ctx, "[Yunzhijia] Handle WebSocket message failed: %v", err)
+ }
+ }
+ }
+}
+
+func (c *LongConnClient) heartbeatLoop(ctx context.Context, conn *ws.Conn) {
+ ticker := time.NewTicker(webSocketHeartbeatInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ if err := conn.WriteControl(ws.PingMessage, nil, time.Now().Add(5*time.Second)); err != nil {
+ logger.Warnf(ctx, "[Yunzhijia] WebSocket heartbeat failed: %v", err)
+ _ = conn.Close()
+ return
+ }
+ }
+ }
+}
+
+func (c *LongConnClient) writeText(conn *ws.Conn, data []byte) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.conn != conn {
+ return fmt.Errorf("websocket connection changed")
+ }
+ return conn.WriteMessage(ws.TextMessage, data)
+}
+
+func (c *LongConnClient) closeConn() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.conn != nil {
+ _ = c.conn.Close()
+ c.conn = nil
+ }
+}
+
+func webSocketReconnectDelay(attempt int) time.Duration {
+ if attempt < 0 {
+ attempt = 0
+ }
+ if attempt >= len(webSocketReconnectDelays) {
+ return webSocketReconnectDelays[len(webSocketReconnectDelays)-1]
+ }
+ return webSocketReconnectDelays[attempt]
+}
+
+func parseWebSocketFrame(data []byte) (*webSocketFrame, error) {
+ trimmed := bytes.TrimSpace(data)
+ if len(trimmed) == 0 {
+ return nil, fmt.Errorf("empty frame")
+ }
+
+ plain := strings.ToLower(string(trimmed))
+ if plain == "ping" || plain == "pong" {
+ return &webSocketFrame{control: plain}, nil
+ }
+
+ var stringPayload string
+ if err := json.Unmarshal(trimmed, &stringPayload); err == nil {
+ control := strings.ToLower(strings.TrimSpace(stringPayload))
+ if control == "ping" || control == "pong" {
+ return &webSocketFrame{control: control}, nil
+ }
+ return nil, fmt.Errorf("unknown string frame")
+ }
+
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(trimmed, &fields); err != nil {
+ return nil, fmt.Errorf("decode frame: %w", err)
+ }
+
+ if msg := decodeBusinessMessage(trimmed); msg != nil {
+ return &webSocketFrame{message: msg}, nil
+ }
+
+ typeName := rawString(fields["type"])
+ if strings.EqualFold(typeName, "robotMessage") {
+ if msg := decodeBusinessMessage(fields["msg"]); msg != nil {
+ return &webSocketFrame{message: msg}, nil
+ }
+ return nil, fmt.Errorf("robotMessage envelope has invalid msg")
+ }
+
+ cmd := strings.ToLower(strings.TrimSpace(rawString(fields["cmd"])))
+ typeName = strings.ToLower(strings.TrimSpace(typeName))
+ event := strings.ToLower(strings.TrimSpace(rawString(fields["event"])))
+ control := cmd
+ if control == "" {
+ control = typeName
+ }
+ if control == "" {
+ control = event
+ }
+
+ frame := &webSocketFrame{control: control}
+ if cmd == "directpush" || typeName == "msgchg" {
+ var needAck bool
+ _ = json.Unmarshal(fields["needAck"], &needAck)
+ var seq int64
+ if needAck && json.Unmarshal(fields["seq"], &seq) == nil {
+ frame.ack, _ = json.Marshal(struct {
+ Cmd string `json:"cmd"`
+ Seq int64 `json:"seq"`
+ }{Cmd: "ack", Seq: seq})
+ }
+ return frame, nil
+ }
+ if control != "" {
+ return frame, nil
+ }
+ return nil, fmt.Errorf("frame has no business message or control type")
+}
+
+func decodeBusinessMessage(data []byte) *callbackMessage {
+ if len(data) == 0 {
+ return nil
+ }
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(data, &fields); err != nil {
+ return nil
+ }
+ for _, key := range []string{"robotId", "robotName", "operatorOpenid", "operatorName", "msgId", "content"} {
+ var value string
+ if json.Unmarshal(fields[key], &value) != nil {
+ return nil
+ }
+ }
+ var messageType int
+ if json.Unmarshal(fields["type"], &messageType) != nil {
+ return nil
+ }
+ var messageTime int64
+ if json.Unmarshal(fields["time"], &messageTime) != nil {
+ return nil
+ }
+ var msg callbackMessage
+ if err := json.Unmarshal(data, &msg); err != nil {
+ return nil
+ }
+ return &msg
+}
+
+func rawString(raw json.RawMessage) string {
+ var value string
+ if len(raw) > 0 && json.Unmarshal(raw, &value) == nil {
+ return value
+ }
+ return ""
+}
diff --git a/internal/im/yunzhijia/websocket_test.go b/internal/im/yunzhijia/websocket_test.go
new file mode 100644
index 000000000..5b9b23273
--- /dev/null
+++ b/internal/im/yunzhijia/websocket_test.go
@@ -0,0 +1,191 @@
+package yunzhijia
+
+import (
+ "context"
+ "encoding/json"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/im"
+ ws "github.com/gorilla/websocket"
+)
+
+const testBusinessMessage = `{
+ "type": 2,
+ "robotId": "bot-1",
+ "robotName": "WeKnora",
+ "operatorOpenid": "user-1",
+ "operatorName": "User",
+ "time": 1719648000000,
+ "msgId": "msg-1",
+ "content": "@WeKnora hello",
+ "groupType": 1
+}`
+
+func TestParseWebSocketFrameDirectMessage(t *testing.T) {
+ frame, err := parseWebSocketFrame([]byte(testBusinessMessage))
+ if err != nil {
+ t.Fatalf("parseWebSocketFrame() error = %v", err)
+ }
+ if frame.message == nil || frame.message.MsgID != "msg-1" {
+ t.Fatalf("message = %#v, want msg-1", frame.message)
+ }
+}
+
+func TestParseWebSocketFrameRobotMessageEnvelope(t *testing.T) {
+ frame, err := parseWebSocketFrame([]byte(`{"type":"robotMessage","msg":` + testBusinessMessage + `}`))
+ if err != nil {
+ t.Fatalf("parseWebSocketFrame() error = %v", err)
+ }
+ if frame.message == nil || frame.message.OperatorOpenid != "user-1" {
+ t.Fatalf("message = %#v, want user-1", frame.message)
+ }
+}
+
+func TestParseWebSocketFrameBuildsDirectPushACK(t *testing.T) {
+ frame, err := parseWebSocketFrame([]byte(`{"cmd":"directPush","needAck":true,"seq":42}`))
+ if err != nil {
+ t.Fatalf("parseWebSocketFrame() error = %v", err)
+ }
+ var ack struct {
+ Cmd string `json:"cmd"`
+ Seq int64 `json:"seq"`
+ }
+ if err := json.Unmarshal(frame.ack, &ack); err != nil {
+ t.Fatalf("unmarshal ack: %v", err)
+ }
+ if ack.Cmd != "ack" || ack.Seq != 42 {
+ t.Fatalf("ack = %#v, want cmd=ack seq=42", ack)
+ }
+}
+
+func TestParseWebSocketFrameControlAndInvalid(t *testing.T) {
+ frame, err := parseWebSocketFrame([]byte(`{"event":"pong"}`))
+ if err != nil || frame.control != "pong" {
+ t.Fatalf("control frame = %#v, err=%v", frame, err)
+ }
+ if _, err := parseWebSocketFrame([]byte(`{"unknown":true}`)); err == nil {
+ t.Fatal("expected invalid frame error")
+ }
+}
+
+func TestToIncomingMessageSharedByWebhookAndWebSocket(t *testing.T) {
+ var msg callbackMessage
+ if err := json.Unmarshal([]byte(testBusinessMessage), &msg); err != nil {
+ t.Fatal(err)
+ }
+ incoming := toIncomingMessage(t.Context(), &msg)
+ if incoming == nil {
+ t.Fatal("toIncomingMessage() returned nil")
+ }
+ if incoming.Content != "hello" {
+ t.Fatalf("content = %q, want hello", incoming.Content)
+ }
+ if incoming.MessageID != "msg-1" || incoming.UserID != "user-1" {
+ t.Fatalf("incoming = %#v", incoming)
+ }
+}
+
+func TestWebSocketReconnectDelayCaps(t *testing.T) {
+ if got := webSocketReconnectDelay(-1); got != webSocketReconnectDelays[0] {
+ t.Fatalf("negative attempt delay = %v", got)
+ }
+ last := webSocketReconnectDelays[len(webSocketReconnectDelays)-1]
+ if got := webSocketReconnectDelay(100); got != last {
+ t.Fatalf("capped delay = %v, want %v", got, last)
+ }
+}
+
+func TestLongConnClientProcessesMessagesInOrder(t *testing.T) {
+ started := make(chan string, 2)
+ releaseFirst := make(chan struct{})
+ client := NewLongConnClient("wss://example.com/ws", func(_ context.Context, msg *im.IncomingMessage) error {
+ started <- msg.MessageID
+ if msg.MessageID == "first" {
+ <-releaseFirst
+ }
+ return nil
+ })
+
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ go client.handleMessages(ctx)
+ client.messages <- &im.IncomingMessage{MessageID: "first"}
+ client.messages <- &im.IncomingMessage{MessageID: "second"}
+
+ select {
+ case got := <-started:
+ if got != "first" {
+ t.Fatalf("first handled message = %q, want first", got)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("first message was not handled")
+ }
+ select {
+ case got := <-started:
+ t.Fatalf("second message started before first completed: %q", got)
+ case <-time.After(25 * time.Millisecond):
+ }
+
+ close(releaseFirst)
+ select {
+ case got := <-started:
+ if got != "second" {
+ t.Fatalf("second handled message = %q, want second", got)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("second message was not handled")
+ }
+}
+
+func TestLongConnClientAcknowledgesFrameAndStops(t *testing.T) {
+ ackReceived := make(chan struct{})
+ var ackOnce sync.Once
+ upgrader := ws.Upgrader{}
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ conn, err := upgrader.Upgrade(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+ if err := conn.WriteMessage(ws.TextMessage, []byte(`{"cmd":"directPush","needAck":true,"seq":42}`)); err != nil {
+ return
+ }
+ _, data, err := conn.ReadMessage()
+ if err == nil && string(data) == `{"cmd":"ack","seq":42}` {
+ ackOnce.Do(func() { close(ackReceived) })
+ }
+ }))
+ defer server.Close()
+
+ client := NewLongConnClient("ws"+strings.TrimPrefix(server.URL, "http"), func(context.Context, *im.IncomingMessage) error {
+ return nil
+ })
+ dialer := &net.Dialer{}
+ client.dialer.NetDialContext = dialer.DialContext
+
+ ctx, cancel := context.WithCancel(t.Context())
+ done := make(chan error, 1)
+ go func() { done <- client.Start(ctx) }()
+
+ select {
+ case <-ackReceived:
+ case <-time.After(time.Second):
+ t.Fatal("websocket ACK was not received")
+ }
+ cancel()
+ client.Stop()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("Start() error after stop = %v", err)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("websocket client did not stop promptly")
+ }
+}