@wecom/wecom-openclaw-plugin 2026.3.30-beta.2 → 2026.3.31-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +251 -4
- package/dist/index.d.ts +2 -4
- package/dist/index.js +113 -0
- package/dist/src/accounts.d.ts +57 -0
- package/dist/src/accounts.js +222 -0
- package/dist/src/agent/api-client.d.ts +94 -0
- package/dist/src/agent/api-client.js +292 -0
- package/dist/src/agent/handler.d.ts +63 -0
- package/dist/src/agent/handler.js +532 -0
- package/dist/src/agent/index.d.ts +5 -0
- package/dist/src/agent/index.js +5 -0
- package/dist/src/agent/webhook.d.ts +23 -0
- package/dist/src/agent/webhook.js +226 -0
- package/dist/src/agent/xml.d.ts +21 -0
- package/dist/src/agent/xml.js +41 -0
- package/dist/src/channel.js +564 -0
- package/dist/src/chat-queue.d.ts +31 -0
- package/dist/src/chat-queue.js +45 -0
- package/dist/src/const.d.ts +46 -0
- package/dist/src/const.js +157 -0
- package/dist/src/dm-policy.js +84 -0
- package/dist/src/group-policy.js +126 -0
- package/dist/src/http.d.ts +26 -0
- package/dist/src/http.js +93 -0
- package/dist/src/interface.d.ts +0 -2
- package/dist/src/interface.js +4 -0
- package/dist/src/mcp/index.js +6 -0
- package/dist/src/mcp/interceptors/biz-error.js +64 -0
- package/dist/src/mcp/interceptors/index.js +66 -0
- package/dist/src/mcp/interceptors/msg-media.js +133 -0
- package/dist/src/mcp/interceptors/smartpage-create.js +132 -0
- package/dist/src/mcp/interceptors/smartpage-export.js +87 -0
- package/dist/src/mcp/interceptors/types.js +7 -0
- package/dist/src/mcp/schema.js +99 -0
- package/dist/src/mcp/tool.js +202 -0
- package/dist/src/mcp/transport.js +410 -0
- package/dist/src/media-handler.js +122 -0
- package/dist/src/media-uploader.js +333 -0
- package/dist/src/message-parser.js +129 -0
- package/dist/src/message-sender.d.ts +18 -0
- package/dist/src/message-sender.js +120 -0
- package/dist/src/monitor.js +832 -0
- package/dist/src/onboarding.js +175 -0
- package/dist/src/openclaw-compat.d.ts +49 -0
- package/dist/src/openclaw-compat.js +487 -0
- package/dist/src/reqid-store.js +83 -0
- package/dist/src/runtime.js +10 -0
- package/dist/src/shared/command-auth.d.ts +23 -0
- package/dist/src/shared/command-auth.js +73 -0
- package/dist/src/shared/xml-parser.d.ts +46 -0
- package/dist/src/shared/xml-parser.js +210 -0
- package/dist/src/state-manager.js +216 -0
- package/dist/src/target.d.ts +35 -0
- package/dist/src/target.js +67 -0
- package/dist/src/template-card-manager.d.ts +55 -0
- package/dist/src/template-card-manager.js +205 -0
- package/dist/src/template-card-parser.js +647 -0
- package/dist/src/timeout.js +36 -0
- package/dist/src/types/account.d.ts +29 -0
- package/dist/src/types/account.js +4 -0
- package/dist/src/types/config.d.ts +80 -0
- package/dist/src/types/config.js +7 -0
- package/dist/src/types/constants.d.ts +42 -0
- package/dist/src/types/constants.js +42 -0
- package/dist/src/types/index.d.ts +7 -0
- package/dist/src/types/index.js +5 -0
- package/dist/src/types/message.d.ts +238 -0
- package/dist/src/types/message.js +5 -0
- package/dist/src/utils.d.ts +39 -0
- package/dist/src/utils.js +70 -0
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +24 -0
- package/dist/src/webhook/command-auth.d.ts +47 -0
- package/dist/src/webhook/command-auth.js +96 -0
- package/dist/src/webhook/gateway.d.ts +36 -0
- package/dist/src/webhook/gateway.js +227 -0
- package/dist/src/webhook/handler.d.ts +18 -0
- package/dist/src/webhook/handler.js +420 -0
- package/dist/src/webhook/helpers.d.ts +156 -0
- package/dist/src/webhook/helpers.js +833 -0
- package/dist/src/webhook/http.d.ts +26 -0
- package/dist/src/webhook/http.js +94 -0
- package/dist/src/webhook/index.d.ts +11 -0
- package/dist/src/webhook/index.js +14 -0
- package/dist/src/webhook/media.d.ts +29 -0
- package/dist/src/webhook/media.js +88 -0
- package/dist/src/webhook/monitor.d.ts +59 -0
- package/dist/src/webhook/monitor.js +1147 -0
- package/dist/src/webhook/state.d.ts +220 -0
- package/dist/src/webhook/state.js +491 -0
- package/dist/src/webhook/target.d.ts +41 -0
- package/dist/src/webhook/target.js +132 -0
- package/dist/src/webhook/types.d.ts +347 -0
- package/dist/src/webhook/types.js +33 -0
- package/package.json +15 -7
- package/dist/index.cjs.js +0 -4953
- package/dist/index.cjs.js.map +0 -1
- package/dist/index.esm.js +0 -4926
- package/dist/index.esm.js.map +0 -1
package/dist/src/const.d.ts
CHANGED
|
@@ -70,5 +70,51 @@ export declare const EVENT_ENTER_CHECK_UPDATE = "event.enter_check_update";
|
|
|
70
70
|
export declare const CMD_ENTER_EVENT_REPLY = "ww_ai_robot_enter_event";
|
|
71
71
|
/** WSClient scene 参数:企微 OpenClaw 场景 */
|
|
72
72
|
export declare const SCENE_WECOM_OPENCLAW = 1;
|
|
73
|
+
/**
|
|
74
|
+
* WeCom 双模式常量定义
|
|
75
|
+
*/
|
|
76
|
+
/** 固定 Webhook 路径 */
|
|
77
|
+
export declare const WEBHOOK_PATHS: {
|
|
78
|
+
/** Bot 模式历史兼容路径(不再维护) */
|
|
79
|
+
readonly BOT: "/wecom";
|
|
80
|
+
/** Bot 模式历史备用兼容路径(不再维护) */
|
|
81
|
+
readonly BOT_ALT: "/wecom/bot";
|
|
82
|
+
/** Agent 模式历史兼容路径(不再维护) */
|
|
83
|
+
readonly AGENT: "/wecom/agent";
|
|
84
|
+
/** Bot 模式推荐路径前缀 */
|
|
85
|
+
readonly BOT_PLUGIN: "/plugins/wecom/bot";
|
|
86
|
+
/** Agent 模式推荐路径前缀 */
|
|
87
|
+
readonly AGENT_PLUGIN: "/plugins/wecom/agent";
|
|
88
|
+
};
|
|
89
|
+
/** 企业微信 API 端点 */
|
|
90
|
+
export declare const API_ENDPOINTS: {
|
|
91
|
+
readonly GET_TOKEN: "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
|
|
92
|
+
readonly SEND_MESSAGE: "https://qyapi.weixin.qq.com/cgi-bin/message/send";
|
|
93
|
+
readonly SEND_APPCHAT: "https://qyapi.weixin.qq.com/cgi-bin/appchat/send";
|
|
94
|
+
readonly UPLOAD_MEDIA: "https://qyapi.weixin.qq.com/cgi-bin/media/upload";
|
|
95
|
+
readonly DOWNLOAD_MEDIA: "https://qyapi.weixin.qq.com/cgi-bin/media/get";
|
|
96
|
+
};
|
|
97
|
+
/** 各类限制常量 */
|
|
98
|
+
export declare const LIMITS: {
|
|
99
|
+
/** 文本消息最大字节数 */
|
|
100
|
+
readonly TEXT_MAX_BYTES: 2048;
|
|
101
|
+
/** Token 刷新缓冲时间 (提前刷新) */
|
|
102
|
+
readonly TOKEN_REFRESH_BUFFER_MS: 60000;
|
|
103
|
+
/** HTTP 请求超时 */
|
|
104
|
+
readonly REQUEST_TIMEOUT_MS: 15000;
|
|
105
|
+
/** 最大请求体大小 */
|
|
106
|
+
readonly MAX_REQUEST_BODY_SIZE: number;
|
|
107
|
+
};
|
|
108
|
+
/** AES 加密常量 */
|
|
109
|
+
export declare const CRYPTO: {
|
|
110
|
+
/** PKCS#7 块大小 */
|
|
111
|
+
readonly PKCS7_BLOCK_SIZE: 32;
|
|
112
|
+
/** AES Key 长度 */
|
|
113
|
+
readonly AES_KEY_LENGTH: 32;
|
|
114
|
+
};
|
|
73
115
|
/** 合法的模板卡片 card_type 列表 */
|
|
74
116
|
export declare const VALID_CARD_TYPES: string[];
|
|
117
|
+
/** 模板卡片缓存条目 TTL(毫秒):24小时 */
|
|
118
|
+
export declare const TEMPLATE_CARD_CACHE_TTL_MS: number;
|
|
119
|
+
/** 模板卡片缓存最大条目数 */
|
|
120
|
+
export declare const TEMPLATE_CARD_CACHE_MAX_SIZE = 300;
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 企业微信渠道常量定义
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* 企业微信渠道 ID
|
|
6
|
+
*/
|
|
7
|
+
export const CHANNEL_ID = "wecom";
|
|
8
|
+
/**
|
|
9
|
+
* 企业微信 WebSocket 命令枚举
|
|
10
|
+
*/
|
|
11
|
+
export var WeComCommand;
|
|
12
|
+
(function (WeComCommand) {
|
|
13
|
+
/** 认证订阅 */
|
|
14
|
+
WeComCommand["SUBSCRIBE"] = "aibot_subscribe";
|
|
15
|
+
/** 心跳 */
|
|
16
|
+
WeComCommand["PING"] = "ping";
|
|
17
|
+
/** 企业微信推送消息 */
|
|
18
|
+
WeComCommand["AIBOT_CALLBACK"] = "aibot_callback";
|
|
19
|
+
/** clawdbot 响应消息 */
|
|
20
|
+
WeComCommand["AIBOT_RESPONSE"] = "aibot_response";
|
|
21
|
+
})(WeComCommand || (WeComCommand = {}));
|
|
22
|
+
// ============================================================================
|
|
23
|
+
// 超时和重试配置
|
|
24
|
+
// ============================================================================
|
|
25
|
+
/** 图片下载超时时间(毫秒) */
|
|
26
|
+
export const IMAGE_DOWNLOAD_TIMEOUT_MS = 30_000;
|
|
27
|
+
/** 文件下载超时时间(毫秒) */
|
|
28
|
+
export const FILE_DOWNLOAD_TIMEOUT_MS = 60_000;
|
|
29
|
+
/** 消息发送超时时间(毫秒) */
|
|
30
|
+
export const REPLY_SEND_TIMEOUT_MS = 15_000;
|
|
31
|
+
/** 消息处理总超时时间(毫秒) */
|
|
32
|
+
export const MESSAGE_PROCESS_TIMEOUT_MS = 6 * 60 * 1000;
|
|
33
|
+
/** WebSocket 心跳间隔(毫秒) */
|
|
34
|
+
export const WS_HEARTBEAT_INTERVAL_MS = 30_000;
|
|
35
|
+
/** WebSocket 连接断开时的最大重连次数 */
|
|
36
|
+
export const WS_MAX_RECONNECT_ATTEMPTS = 10;
|
|
37
|
+
/** WebSocket 认证失败时的最大重试次数 */
|
|
38
|
+
export const WS_MAX_AUTH_FAILURE_ATTEMPTS = 5;
|
|
39
|
+
// ============================================================================
|
|
40
|
+
// 消息状态管理配置
|
|
41
|
+
// ============================================================================
|
|
42
|
+
/** messageStates Map 条目的最大 TTL(毫秒),防止内存泄漏 */
|
|
43
|
+
export const MESSAGE_STATE_TTL_MS = 10 * 60 * 1000;
|
|
44
|
+
/** messageStates Map 清理间隔(毫秒) */
|
|
45
|
+
export const MESSAGE_STATE_CLEANUP_INTERVAL_MS = 60_000;
|
|
46
|
+
/** messageStates Map 最大条目数 */
|
|
47
|
+
export const MESSAGE_STATE_MAX_SIZE = 500;
|
|
48
|
+
// ============================================================================
|
|
49
|
+
// 消息模板
|
|
50
|
+
// ============================================================================
|
|
51
|
+
/** "思考中"流式消息占位内容 */
|
|
52
|
+
export const THINKING_MESSAGE = "<think></think>";
|
|
53
|
+
/** 仅包含图片时的消息占位符 */
|
|
54
|
+
export const MEDIA_IMAGE_PLACEHOLDER = "<media:image>";
|
|
55
|
+
/** 仅包含文件时的消息占位符 */
|
|
56
|
+
export const MEDIA_DOCUMENT_PLACEHOLDER = "<media:document>";
|
|
57
|
+
// ============================================================================
|
|
58
|
+
// 默认值
|
|
59
|
+
// ============================================================================
|
|
60
|
+
// ============================================================================
|
|
61
|
+
// MCP 配置
|
|
62
|
+
// ============================================================================
|
|
63
|
+
/** 获取 MCP 配置的 WebSocket 命令 */
|
|
64
|
+
export const MCP_GET_CONFIG_CMD = "aibot_get_mcp_config";
|
|
65
|
+
/** MCP 配置拉取超时时间(毫秒) */
|
|
66
|
+
export const MCP_CONFIG_FETCH_TIMEOUT_MS = 15_000;
|
|
67
|
+
// ============================================================================
|
|
68
|
+
// 默认值
|
|
69
|
+
// ============================================================================
|
|
70
|
+
/** 默认媒体大小上限(MB) */
|
|
71
|
+
export const DEFAULT_MEDIA_MAX_MB = 5;
|
|
72
|
+
/** 文本分块大小上限 */
|
|
73
|
+
export const TEXT_CHUNK_LIMIT = 4000;
|
|
74
|
+
// ============================================================================
|
|
75
|
+
// 媒体上传相关常量
|
|
76
|
+
// ============================================================================
|
|
77
|
+
/** 图片大小上限(字节):10MB */
|
|
78
|
+
export const IMAGE_MAX_BYTES = 10 * 1024 * 1024;
|
|
79
|
+
/** 视频大小上限(字节):10MB */
|
|
80
|
+
export const VIDEO_MAX_BYTES = 10 * 1024 * 1024;
|
|
81
|
+
/** 语音大小上限(字节):2MB */
|
|
82
|
+
export const VOICE_MAX_BYTES = 2 * 1024 * 1024;
|
|
83
|
+
/** 文件大小上限(字节):20MB */
|
|
84
|
+
export const FILE_MAX_BYTES = 20 * 1024 * 1024;
|
|
85
|
+
/** 文件绝对上限(字节):超过此值无法发送,等于 FILE_MAX_BYTES */
|
|
86
|
+
export const ABSOLUTE_MAX_BYTES = FILE_MAX_BYTES;
|
|
87
|
+
/** 上传分片大小(字节,Base64 编码前):512KB */
|
|
88
|
+
export const UPLOAD_CHUNK_SIZE = 512 * 1024;
|
|
89
|
+
// ============================================================================
|
|
90
|
+
// 事件/命令名称常量
|
|
91
|
+
// ============================================================================
|
|
92
|
+
/** 版本检查事件名称(SDK 事件监听用) */
|
|
93
|
+
export const EVENT_ENTER_CHECK_UPDATE = "event.enter_check_update";
|
|
94
|
+
/** 版本检查事件回复命令名称 */
|
|
95
|
+
export const CMD_ENTER_EVENT_REPLY = "ww_ai_robot_enter_event";
|
|
96
|
+
// ============================================================================
|
|
97
|
+
// SDK 连接配置
|
|
98
|
+
// ============================================================================
|
|
99
|
+
/** WSClient scene 参数:企微 OpenClaw 场景 */
|
|
100
|
+
export const SCENE_WECOM_OPENCLAW = 1;
|
|
101
|
+
/**
|
|
102
|
+
* WeCom 双模式常量定义
|
|
103
|
+
*/
|
|
104
|
+
/** 固定 Webhook 路径 */
|
|
105
|
+
export const WEBHOOK_PATHS = {
|
|
106
|
+
/** Bot 模式历史兼容路径(不再维护) */
|
|
107
|
+
BOT: "/wecom",
|
|
108
|
+
/** Bot 模式历史备用兼容路径(不再维护) */
|
|
109
|
+
BOT_ALT: "/wecom/bot",
|
|
110
|
+
/** Agent 模式历史兼容路径(不再维护) */
|
|
111
|
+
AGENT: "/wecom/agent",
|
|
112
|
+
/** Bot 模式推荐路径前缀 */
|
|
113
|
+
BOT_PLUGIN: "/plugins/wecom/bot",
|
|
114
|
+
/** Agent 模式推荐路径前缀 */
|
|
115
|
+
AGENT_PLUGIN: "/plugins/wecom/agent",
|
|
116
|
+
};
|
|
117
|
+
/** 企业微信 API 端点 */
|
|
118
|
+
export const API_ENDPOINTS = {
|
|
119
|
+
GET_TOKEN: "https://qyapi.weixin.qq.com/cgi-bin/gettoken",
|
|
120
|
+
SEND_MESSAGE: "https://qyapi.weixin.qq.com/cgi-bin/message/send",
|
|
121
|
+
SEND_APPCHAT: "https://qyapi.weixin.qq.com/cgi-bin/appchat/send",
|
|
122
|
+
UPLOAD_MEDIA: "https://qyapi.weixin.qq.com/cgi-bin/media/upload",
|
|
123
|
+
DOWNLOAD_MEDIA: "https://qyapi.weixin.qq.com/cgi-bin/media/get",
|
|
124
|
+
};
|
|
125
|
+
/** 各类限制常量 */
|
|
126
|
+
export const LIMITS = {
|
|
127
|
+
/** 文本消息最大字节数 */
|
|
128
|
+
TEXT_MAX_BYTES: 2048,
|
|
129
|
+
/** Token 刷新缓冲时间 (提前刷新) */
|
|
130
|
+
TOKEN_REFRESH_BUFFER_MS: 60_000,
|
|
131
|
+
/** HTTP 请求超时 */
|
|
132
|
+
REQUEST_TIMEOUT_MS: 15_000,
|
|
133
|
+
/** 最大请求体大小 */
|
|
134
|
+
MAX_REQUEST_BODY_SIZE: 1024 * 1024,
|
|
135
|
+
};
|
|
136
|
+
/** AES 加密常量 */
|
|
137
|
+
export const CRYPTO = {
|
|
138
|
+
/** PKCS#7 块大小 */
|
|
139
|
+
PKCS7_BLOCK_SIZE: 32,
|
|
140
|
+
/** AES Key 长度 */
|
|
141
|
+
AES_KEY_LENGTH: 32,
|
|
142
|
+
};
|
|
143
|
+
// ============================================================================
|
|
144
|
+
// 模板卡片配置
|
|
145
|
+
// ============================================================================
|
|
146
|
+
/** 合法的模板卡片 card_type 列表 */
|
|
147
|
+
export const VALID_CARD_TYPES = [
|
|
148
|
+
"text_notice",
|
|
149
|
+
"news_notice",
|
|
150
|
+
"button_interaction",
|
|
151
|
+
"vote_interaction",
|
|
152
|
+
"multiple_interaction",
|
|
153
|
+
];
|
|
154
|
+
/** 模板卡片缓存条目 TTL(毫秒):24小时 */
|
|
155
|
+
export const TEMPLATE_CARD_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
156
|
+
/** 模板卡片缓存最大条目数 */
|
|
157
|
+
export const TEMPLATE_CARD_CACHE_MAX_SIZE = 300;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 企业微信 DM(私聊)访问控制模块
|
|
3
|
+
*
|
|
4
|
+
* 负责私聊策略检查、配对流程
|
|
5
|
+
*/
|
|
6
|
+
import { getWeComRuntime } from "./runtime.js";
|
|
7
|
+
import { CHANNEL_ID } from "./const.js";
|
|
8
|
+
import { sendWeComReply } from "./message-sender.js";
|
|
9
|
+
import { isSenderAllowed } from "./group-policy.js";
|
|
10
|
+
// ============================================================================
|
|
11
|
+
// 公开 API
|
|
12
|
+
// ============================================================================
|
|
13
|
+
/**
|
|
14
|
+
* 检查 DM Policy 访问控制
|
|
15
|
+
* @returns 检查结果,包含是否允许继续处理
|
|
16
|
+
*/
|
|
17
|
+
export async function checkDmPolicy(params) {
|
|
18
|
+
const { senderId, isGroup, account, wsClient, frame, runtime } = params;
|
|
19
|
+
const core = getWeComRuntime();
|
|
20
|
+
// 群聊消息不检查 DM Policy
|
|
21
|
+
if (isGroup) {
|
|
22
|
+
return { allowed: true };
|
|
23
|
+
}
|
|
24
|
+
const dmPolicy = account.config.dmPolicy ?? "open";
|
|
25
|
+
const configAllowFrom = (account.config.allowFrom ?? []).map((v) => String(v));
|
|
26
|
+
// 如果 dmPolicy 是 disabled,直接拒绝
|
|
27
|
+
if (dmPolicy === "disabled") {
|
|
28
|
+
runtime.log?.(`[WeCom] Blocked DM from ${senderId} (dmPolicy=disabled)`);
|
|
29
|
+
return { allowed: false };
|
|
30
|
+
}
|
|
31
|
+
// 如果是 open 模式,允许所有人
|
|
32
|
+
if (dmPolicy === "open") {
|
|
33
|
+
return { allowed: true };
|
|
34
|
+
}
|
|
35
|
+
// OpenClaw <= 2026.2.19 signature: readAllowFromStore(channel, env?, accountId?)
|
|
36
|
+
// @ts-expect-error — 兼容旧版 SDK 的三参数签名,新版已改为单参数对象
|
|
37
|
+
const oldStoreAllowFrom = await core.channel.pairing.readAllowFromStore('wecom', undefined, account.accountId).catch(() => []);
|
|
38
|
+
// Compatibility fallback for newer OpenClaw implementations.
|
|
39
|
+
const newStoreAllowFrom = await core.channel.pairing
|
|
40
|
+
.readAllowFromStore({ channel: CHANNEL_ID, accountId: account.accountId })
|
|
41
|
+
.catch(() => []);
|
|
42
|
+
// 检查发送者是否在允许列表中
|
|
43
|
+
const storeAllowFrom = [...oldStoreAllowFrom, ...newStoreAllowFrom];
|
|
44
|
+
const effectiveAllowFrom = [...configAllowFrom, ...storeAllowFrom];
|
|
45
|
+
const senderAllowedResult = isSenderAllowed(senderId, effectiveAllowFrom);
|
|
46
|
+
if (senderAllowedResult) {
|
|
47
|
+
return { allowed: true };
|
|
48
|
+
}
|
|
49
|
+
// 处理未授权用户
|
|
50
|
+
if (dmPolicy === "pairing") {
|
|
51
|
+
const { code, created } = await core.channel.pairing.upsertPairingRequest({
|
|
52
|
+
channel: CHANNEL_ID,
|
|
53
|
+
id: senderId,
|
|
54
|
+
accountId: account.accountId,
|
|
55
|
+
meta: { name: senderId },
|
|
56
|
+
});
|
|
57
|
+
if (created) {
|
|
58
|
+
runtime.log?.(`[WeCom] Pairing request created for sender=${senderId}`);
|
|
59
|
+
try {
|
|
60
|
+
await sendWeComReply({
|
|
61
|
+
wsClient,
|
|
62
|
+
frame,
|
|
63
|
+
text: core.channel.pairing.buildPairingReply({
|
|
64
|
+
channel: CHANNEL_ID,
|
|
65
|
+
idLine: `您的企业微信用户ID: ${senderId}`,
|
|
66
|
+
code,
|
|
67
|
+
}),
|
|
68
|
+
runtime,
|
|
69
|
+
finish: true,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
runtime.error?.(`[WeCom] Failed to send pairing reply to ${senderId}: ${String(err)}`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
runtime.log?.(`[WeCom] Pairing request already exists for sender=${senderId}`);
|
|
78
|
+
}
|
|
79
|
+
return { allowed: false, pairingSent: created };
|
|
80
|
+
}
|
|
81
|
+
// allowlist 模式:直接拒绝未授权用户
|
|
82
|
+
runtime.log?.(`[WeCom] Blocked unauthorized sender ${senderId} (dmPolicy=${dmPolicy})`);
|
|
83
|
+
return { allowed: false };
|
|
84
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 企业微信群组访问控制模块
|
|
3
|
+
*
|
|
4
|
+
* 负责群组策略检查(groupPolicy、群组白名单、群内发送者白名单)
|
|
5
|
+
*/
|
|
6
|
+
import { CHANNEL_ID } from "./const.js";
|
|
7
|
+
// ============================================================================
|
|
8
|
+
// 内部辅助函数
|
|
9
|
+
// ============================================================================
|
|
10
|
+
/**
|
|
11
|
+
* 解析企业微信群组配置
|
|
12
|
+
*/
|
|
13
|
+
function resolveWeComGroupConfig(params) {
|
|
14
|
+
const groups = params.cfg?.groups ?? {};
|
|
15
|
+
const wildcard = groups["*"];
|
|
16
|
+
const groupId = params.groupId?.trim();
|
|
17
|
+
if (!groupId) {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
const direct = groups[groupId];
|
|
21
|
+
if (direct) {
|
|
22
|
+
return direct;
|
|
23
|
+
}
|
|
24
|
+
const lowered = groupId.toLowerCase();
|
|
25
|
+
const matchKey = Object.keys(groups).find((key) => key.toLowerCase() === lowered);
|
|
26
|
+
if (matchKey) {
|
|
27
|
+
return groups[matchKey];
|
|
28
|
+
}
|
|
29
|
+
return wildcard;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* 检查群组是否在允许列表中
|
|
33
|
+
*/
|
|
34
|
+
function isWeComGroupAllowed(params) {
|
|
35
|
+
const { groupPolicy } = params;
|
|
36
|
+
if (groupPolicy === "disabled") {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
if (groupPolicy === "open") {
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
// allowlist 模式:检查群组是否在允许列表中
|
|
43
|
+
const normalizedAllowFrom = params.allowFrom.map((entry) => String(entry).replace(new RegExp(`^${CHANNEL_ID}:`, "i"), "").trim());
|
|
44
|
+
if (normalizedAllowFrom.includes("*")) {
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
const normalizedGroupId = params.groupId.trim();
|
|
48
|
+
return normalizedAllowFrom.some((entry) => entry === normalizedGroupId || entry.toLowerCase() === normalizedGroupId.toLowerCase());
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* 检查群组内发送者是否在允许列表中
|
|
52
|
+
*/
|
|
53
|
+
function isGroupSenderAllowed(params) {
|
|
54
|
+
const { senderId, groupId, wecomConfig } = params;
|
|
55
|
+
const groupConfig = resolveWeComGroupConfig({
|
|
56
|
+
cfg: wecomConfig,
|
|
57
|
+
groupId,
|
|
58
|
+
});
|
|
59
|
+
const perGroupSenderAllowFrom = (groupConfig?.allowFrom ?? []).map((v) => String(v));
|
|
60
|
+
if (perGroupSenderAllowFrom.length === 0) {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
if (perGroupSenderAllowFrom.includes("*")) {
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
return perGroupSenderAllowFrom.some((entry) => {
|
|
67
|
+
const normalized = entry.replace(new RegExp(`^${CHANNEL_ID}:`, "i"), "").trim();
|
|
68
|
+
return normalized === senderId || normalized === `user:${senderId}`;
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
// ============================================================================
|
|
72
|
+
// 公开 API
|
|
73
|
+
// ============================================================================
|
|
74
|
+
/**
|
|
75
|
+
* 检查群组策略访问控制
|
|
76
|
+
* @returns 检查结果,包含是否允许继续处理
|
|
77
|
+
*/
|
|
78
|
+
export function checkGroupPolicy(params) {
|
|
79
|
+
const { chatId, senderId, account, config, runtime } = params;
|
|
80
|
+
const wecomConfig = (config.channels?.[CHANNEL_ID] ?? {});
|
|
81
|
+
const defaultGroupPolicy = config.channels?.[CHANNEL_ID]?.groupPolicy;
|
|
82
|
+
const groupPolicy = account.config.groupPolicy ?? defaultGroupPolicy ?? "open";
|
|
83
|
+
// const { groupPolicy, providerMissingFallbackApplied } = resolveOpenProviderRuntimeGroupPolicy({
|
|
84
|
+
// providerConfigPresent: config.channels?.[CHANNEL_ID] !== undefined,
|
|
85
|
+
// groupPolicy: wecomConfig.groupPolicy,
|
|
86
|
+
// defaultGroupPolicy,
|
|
87
|
+
// });
|
|
88
|
+
// warnMissingProviderGroupPolicyFallbackOnce({
|
|
89
|
+
// providerMissingFallbackApplied,
|
|
90
|
+
// providerKey: CHANNEL_ID,
|
|
91
|
+
// accountId: account.accountId,
|
|
92
|
+
// log: (msg) => runtime.log?.(msg),
|
|
93
|
+
// });
|
|
94
|
+
const groupAllowFrom = wecomConfig.groupAllowFrom ?? [];
|
|
95
|
+
const groupAllowed = isWeComGroupAllowed({
|
|
96
|
+
groupPolicy,
|
|
97
|
+
allowFrom: groupAllowFrom,
|
|
98
|
+
groupId: chatId,
|
|
99
|
+
});
|
|
100
|
+
if (!groupAllowed) {
|
|
101
|
+
runtime.log?.(`[WeCom] Group ${chatId} not allowed (groupPolicy=${groupPolicy})`);
|
|
102
|
+
return { allowed: false };
|
|
103
|
+
}
|
|
104
|
+
const senderAllowed = isGroupSenderAllowed({
|
|
105
|
+
senderId,
|
|
106
|
+
groupId: chatId,
|
|
107
|
+
wecomConfig,
|
|
108
|
+
});
|
|
109
|
+
if (!senderAllowed) {
|
|
110
|
+
runtime.log?.(`[WeCom] Sender ${senderId} not in group ${chatId} sender allowlist`);
|
|
111
|
+
return { allowed: false };
|
|
112
|
+
}
|
|
113
|
+
return { allowed: true };
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* 检查发送者是否在允许列表中(通用)
|
|
117
|
+
*/
|
|
118
|
+
export function isSenderAllowed(senderId, allowFrom) {
|
|
119
|
+
if (allowFrom.includes("*")) {
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
return allowFrom.some((entry) => {
|
|
123
|
+
const normalized = entry.replace(new RegExp(`^${CHANNEL_ID}:`, "i"), "").trim();
|
|
124
|
+
return normalized === senderId || normalized === `user:${senderId}`;
|
|
125
|
+
});
|
|
126
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* **WecomHttpOptions (HTTP 选项)**
|
|
3
|
+
*
|
|
4
|
+
* @property proxyUrl 代理服务器地址
|
|
5
|
+
* @property timeoutMs 请求超时时间 (毫秒)
|
|
6
|
+
* @property signal AbortSignal 信号
|
|
7
|
+
*/
|
|
8
|
+
export type WecomHttpOptions = {
|
|
9
|
+
proxyUrl?: string;
|
|
10
|
+
timeoutMs?: number;
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* **wecomFetch (统一 HTTP 请求)**
|
|
15
|
+
*
|
|
16
|
+
* 基于 `undici` 的 fetch 封装,自动处理 ProxyAgent 和 Timeout。
|
|
17
|
+
* 所有对企业微信 API 的调用都应经过此函数。
|
|
18
|
+
*/
|
|
19
|
+
export declare function wecomFetch(input: string | URL, init?: RequestInit, opts?: WecomHttpOptions): Promise<Response>;
|
|
20
|
+
/**
|
|
21
|
+
* **readResponseBodyAsBuffer (读取响应 Body)**
|
|
22
|
+
*
|
|
23
|
+
* 将 Response Body 读取为 Buffer,支持最大字节限制以防止内存溢出。
|
|
24
|
+
* 适用于下载媒体文件等场景。
|
|
25
|
+
*/
|
|
26
|
+
export declare function readResponseBodyAsBuffer(res: Response, maxBytes?: number): Promise<Buffer>;
|
package/dist/src/http.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { ProxyAgent, fetch as undiciFetch } from "undici";
|
|
2
|
+
const proxyDispatchers = new Map();
|
|
3
|
+
/**
|
|
4
|
+
* **getProxyDispatcher (获取代理 Dispatcher)**
|
|
5
|
+
*
|
|
6
|
+
* 缓存并复用 ProxyAgent,避免重复创建连接池。
|
|
7
|
+
*/
|
|
8
|
+
function getProxyDispatcher(proxyUrl) {
|
|
9
|
+
const existing = proxyDispatchers.get(proxyUrl);
|
|
10
|
+
if (existing)
|
|
11
|
+
return existing;
|
|
12
|
+
const created = new ProxyAgent(proxyUrl);
|
|
13
|
+
proxyDispatchers.set(proxyUrl, created);
|
|
14
|
+
return created;
|
|
15
|
+
}
|
|
16
|
+
function mergeAbortSignal(params) {
|
|
17
|
+
const signals = [];
|
|
18
|
+
if (params.signal)
|
|
19
|
+
signals.push(params.signal);
|
|
20
|
+
if (params.timeoutMs && Number.isFinite(params.timeoutMs) && params.timeoutMs > 0) {
|
|
21
|
+
signals.push(AbortSignal.timeout(params.timeoutMs));
|
|
22
|
+
}
|
|
23
|
+
if (!signals.length)
|
|
24
|
+
return undefined;
|
|
25
|
+
if (signals.length === 1)
|
|
26
|
+
return signals[0];
|
|
27
|
+
return AbortSignal.any(signals);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* **wecomFetch (统一 HTTP 请求)**
|
|
31
|
+
*
|
|
32
|
+
* 基于 `undici` 的 fetch 封装,自动处理 ProxyAgent 和 Timeout。
|
|
33
|
+
* 所有对企业微信 API 的调用都应经过此函数。
|
|
34
|
+
*/
|
|
35
|
+
export async function wecomFetch(input, init, opts) {
|
|
36
|
+
const proxyUrl = opts?.proxyUrl?.trim() ?? "";
|
|
37
|
+
const dispatcher = proxyUrl ? getProxyDispatcher(proxyUrl) : undefined;
|
|
38
|
+
const initSignal = init?.signal ?? undefined;
|
|
39
|
+
const signal = mergeAbortSignal({ signal: opts?.signal ?? initSignal, timeoutMs: opts?.timeoutMs });
|
|
40
|
+
const headers = new Headers(init?.headers ?? {});
|
|
41
|
+
if (!headers.has("User-Agent")) {
|
|
42
|
+
headers.set("User-Agent", "OpenClaw/2.0 (WeCom-Agent)");
|
|
43
|
+
}
|
|
44
|
+
const nextInit = {
|
|
45
|
+
...(init ?? {}),
|
|
46
|
+
...(signal ? { signal } : {}),
|
|
47
|
+
...(dispatcher ? { dispatcher } : {}),
|
|
48
|
+
headers,
|
|
49
|
+
};
|
|
50
|
+
try {
|
|
51
|
+
return await undiciFetch(input, nextInit);
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
if (err instanceof Error && err.name === "TypeError" && err.message === "fetch failed") {
|
|
55
|
+
const cause = err.cause;
|
|
56
|
+
console.error(`[wecom-http] fetch failed: ${input} (proxy: ${proxyUrl || "none"})${cause ? ` - cause: ${String(cause)}` : ""}`);
|
|
57
|
+
}
|
|
58
|
+
throw err;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* **readResponseBodyAsBuffer (读取响应 Body)**
|
|
63
|
+
*
|
|
64
|
+
* 将 Response Body 读取为 Buffer,支持最大字节限制以防止内存溢出。
|
|
65
|
+
* 适用于下载媒体文件等场景。
|
|
66
|
+
*/
|
|
67
|
+
export async function readResponseBodyAsBuffer(res, maxBytes) {
|
|
68
|
+
if (!res.body)
|
|
69
|
+
return Buffer.alloc(0);
|
|
70
|
+
const limit = maxBytes && Number.isFinite(maxBytes) && maxBytes > 0 ? maxBytes : undefined;
|
|
71
|
+
const chunks = [];
|
|
72
|
+
let total = 0;
|
|
73
|
+
const reader = res.body.getReader();
|
|
74
|
+
while (true) {
|
|
75
|
+
const { done, value } = await reader.read();
|
|
76
|
+
if (done)
|
|
77
|
+
break;
|
|
78
|
+
if (!value)
|
|
79
|
+
continue;
|
|
80
|
+
total += value.byteLength;
|
|
81
|
+
if (limit && total > limit) {
|
|
82
|
+
try {
|
|
83
|
+
await reader.cancel("body too large");
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
// ignore
|
|
87
|
+
}
|
|
88
|
+
throw new Error(`response body too large (>${limit} bytes)`);
|
|
89
|
+
}
|
|
90
|
+
chunks.push(value);
|
|
91
|
+
}
|
|
92
|
+
return Buffer.concat(chunks.map((c) => Buffer.from(c)));
|
|
93
|
+
}
|
package/dist/src/interface.d.ts
CHANGED
|
@@ -29,8 +29,6 @@ export interface MessageState {
|
|
|
29
29
|
hasMediaFailed?: boolean;
|
|
30
30
|
/** 媒体发送失败时的纯文本错误摘要(用于替换 thinking 流展示给用户) */
|
|
31
31
|
mediaErrorSummary?: string;
|
|
32
|
-
/** deliver 回调是否被调用过(用于区分"核心无回复"和"核心回复了空内容") */
|
|
33
|
-
deliverCalled?: boolean;
|
|
34
32
|
/** 流式回复是否已过期(errcode 846608,>6分钟),需降级为主动发送 */
|
|
35
33
|
streamExpired?: boolean;
|
|
36
34
|
/** 是否已成功发送过模板卡片 */
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 业务错误码检查拦截器
|
|
3
|
+
*
|
|
4
|
+
* 检查 tools/call 返回结果中是否包含需要清理缓存的业务错误码。
|
|
5
|
+
* MCP Server 可能在正常的 JSON-RPC 响应中返回业务层错误,
|
|
6
|
+
* 这些错误被包裹在 result.content[].text 中,需要解析后判断。
|
|
7
|
+
*
|
|
8
|
+
* 此拦截器对所有 call 调用生效。
|
|
9
|
+
*/
|
|
10
|
+
import { clearCategoryCache } from "../transport.js";
|
|
11
|
+
// ============================================================================
|
|
12
|
+
// 常量
|
|
13
|
+
// ============================================================================
|
|
14
|
+
/**
|
|
15
|
+
* 需要触发缓存清理的业务错误码集合
|
|
16
|
+
*
|
|
17
|
+
* 这些错误码出现在 MCP 工具调用返回的 content 文本中(业务层面),
|
|
18
|
+
* 与 JSON-RPC 层面的错误码不同,需要在此处额外检测。
|
|
19
|
+
*
|
|
20
|
+
* - 850002: 机器人未被授权使用对应能力,需清理缓存以便下次重新拉取配置
|
|
21
|
+
*/
|
|
22
|
+
const BIZ_CACHE_CLEAR_ERROR_CODES = new Set([850002]);
|
|
23
|
+
// ============================================================================
|
|
24
|
+
// 拦截器实现
|
|
25
|
+
// ============================================================================
|
|
26
|
+
export const bizErrorInterceptor = {
|
|
27
|
+
name: "biz-error",
|
|
28
|
+
/** 对所有 call 调用生效 */
|
|
29
|
+
match: () => true,
|
|
30
|
+
/** 检查返回结果中的业务错误码,必要时清理缓存 */
|
|
31
|
+
afterCall(ctx, result) {
|
|
32
|
+
checkBizErrorAndClearCache(result, ctx.category);
|
|
33
|
+
// 不修改 result,透传给下一个拦截器
|
|
34
|
+
return result;
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
// ============================================================================
|
|
38
|
+
// 内部实现
|
|
39
|
+
// ============================================================================
|
|
40
|
+
/**
|
|
41
|
+
* 检查 tools/call 的返回结果中是否包含需要清理缓存的业务错误码
|
|
42
|
+
*/
|
|
43
|
+
function checkBizErrorAndClearCache(result, category) {
|
|
44
|
+
if (!result || typeof result !== "object")
|
|
45
|
+
return;
|
|
46
|
+
const { content } = result;
|
|
47
|
+
if (!Array.isArray(content))
|
|
48
|
+
return;
|
|
49
|
+
for (const item of content) {
|
|
50
|
+
if (item.type !== "text" || !item.text)
|
|
51
|
+
continue;
|
|
52
|
+
try {
|
|
53
|
+
const parsed = JSON.parse(item.text);
|
|
54
|
+
if (typeof parsed.errcode === "number" && BIZ_CACHE_CLEAR_ERROR_CODES.has(parsed.errcode)) {
|
|
55
|
+
console.log(`[mcp] 检测到业务错误码 ${parsed.errcode} (category="${category}"),清理缓存`);
|
|
56
|
+
clearCategoryCache(category);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// text 不是 JSON 格式,跳过
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|