@zhin.js/adapter-wecom 1.1.25 → 1.1.27

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/CHANGELOG.md CHANGED
@@ -1,5 +1,170 @@
1
1
  # @zhin.js/adapter-wecom
2
2
 
3
+ ## 1.1.27
4
+
5
+ ### Patch Changes
6
+
7
+ - c606d51: 各适配器按平台能力上报入站发送者的 `sender.platform`(ADR 0056 §1),并在能力画像 `scene.platformStanding` 中声明:OneBot11、NapCat、Milky、ICQQ 群消息上报群主 / 管理员 / 成员;QQ 官方频道上报频道主 / 超级管理员与身份组;Discord 服务器频道上报所有者 / 管理员 / 成员、身份组与 snake*case 权限位;Telegram 群消息按 `getChatMember` 上报 creator / administrator / member / 已离开,以及管理员的 `can*\*` 权限;KOOK 服务器频道上报服务器主 / 管理员角色、角色列表与权限位;飞书、钉钉群消息上报群主 / 管理员 / 成员;Sandbox 把模拟角色作为平台身份上报,不再授予框架主人角色。Satori、Slack、OneBot12、企业微信、LINE 的事件不带可靠的成员身份,不上报。README 补充「成员身份」说明。
8
+
9
+ 机器人自身身份(`management.inspectSelfStanding` + 能力画像 `scene.selfStanding`,供 `bot:*` permit):ICQQ、OneBot11、NapCat、Milky 群(`get_group_member_info` self);QQ 官方群(`getBotState`)与频道(机器人频道成员身份组);Discord(`guild.members.me` 身份组与频道权限);Telegram(`getChatMember` bot);KOOK(`/v3/user/view` self 的服务器角色与权限位);飞书(`chat.get` 群主与 `bot_manager_id_list`)。钉钉没有对应接口,不声明。群管理类 Agent 工具补上 `bot:admin` / `bot:owner` / `bot-permission:*`,需要发言者是群管的平台操作改用 `platform:admin` 等。
10
+
11
+ - 53932e5: 修复平台身份 permit 与操作目标不一致的问题(ADR 0056 §5):`platform:*` / `platform-permission:*` / `bot:*` / `bot-permission:*` 按**当前会话**判定,但群管理工具此前接受模型传入的任意群 / 服务器 / 频道 ID,机器人同在 A、B 两群当管理员时,A 群管理员可让 Agent 在 B 群踢人。
12
+
13
+ - 目标改为取自当前会话、去掉目标 ID 入参(模型传入的 ID 被忽略):ICQQ(踢人、禁言、设管理员、头衔、公告、匿名;设精华校验消息属于本群)、Telegram(邀请链接、置顶 / 取消置顶、群描述、默认权限)、Discord(加 / 移除身份组、身份组列表、建子线程)、KOOK(黑名单、授予 / 撤销 / 创建 / 删除角色)、飞书(加成员、设 / 撤管理员、改群信息、解散群)、NapCat(群公告、删公告、头衔、群头像;精华消息校验属于本群)、OneBot11(头衔)、QQ 官方频道(身份组增删建与列表、子频道列表、成员详情;子频道详情只限本频道)。核心场景治理工具工厂(`createSceneManagementTools`)同样只作用于调用消息所在会话,没有会话时拒绝;Agent 侧同名工厂改用与核心一致的 `platform:<地位>` + `bot:<地位>`(此前误作 zhin 角色)。
14
+ - 钉钉群管理接口使用旧版 `chatid`(无法由当前会话推出),`dingtalk_add_chat_members` / `dingtalk_update_chat` 改为要求 zhin `owner`(`update_chat` 此前没有任何门禁);`dingtalk_create_chat` 改为要求 zhin `trusted`(`admin` / `owner` 亦满足),不再依赖钉钉从不上报的 `platform-permission:chat_owner`。
15
+ - Slack 不上报发言者平台身份,频道工具改用 zhin 角色并只作用于当前频道:话题、用途、邀请、置顶 / 取消置顶要求 `admin`,归档 / 恢复归档要求 `owner`;`PERMITS.md` 同步修正。
16
+ - Discord:加 / 移除身份组要求目标身份组低于发起者的最高身份组(服务器主豁免;托管身份组拒绝),低位 `manage_roles` 管理员不能借机器人给自己加更高身份组。平台权限统一为服务器级:机器人自身改读 `GuildMember.permissions`(不再用频道级 `permissionsFor`);Interactions 模式的位域含频道覆盖,只上报不能被频道覆盖的权限(管理员上报全部),并用最近一次交互的 `app_permissions` 上报机器人自身身份(同一口径,10 分钟内有效)。
17
+ - Telegram:`set_permissions` 改要求 `platform-permission:restrict_members`,`set_description` 改 `change_info`,`create_invite` 改 `invite_users`;发送者 `getChatMember` 并发合并为一次、失败负缓存 10 秒,收到 `chat_member` / `my_chat_member` 更新时以新状态覆盖缓存(默认 `allowedUpdates` 增加这两项);restricted 成员的个人 `can_*` 不再作为平台权限上报(与普通成员一致,只有管理员上报权限)。
18
+ - KOOK:服务器主与持有「管理员」位的成员(含机器人自身)展开为全部权限;并入「全体成员」(role_id 0)的基础权限。
19
+ - 飞书:`chat.get` 失败或未返回 `owner_id` 时发送者 / 机器人地位为未知(不再报确定的 `member` 并缓存 60 秒),失败负缓存 10 秒。
20
+ - QQ 官方:发送者平台身份只在频道子频道上报(群、单聊、频道私信不上报)。
21
+ - `AdapterIndex.selfStanding`:共享查询使用独立的 10 秒期限,调用方的 `signal` 只中止自己的等待,不再取消他人共享的查询或把结果缓存为未知;查询期间被 `invalidateSelfStanding` 失效时不写回旧结果。
22
+ - OneBot11 / NapCat / Milky:机器人自身身份不再永久记住首次 `get_login_info` 的账号(重连或换号后刷新;只为合并突发请求复用 5 秒,查询失败即丢弃)。
23
+ - 删除遗留导出(生成永不匹配的 permit 或已不再注册):`discordGroupPermitResolver` / `checkDiscordPlatformPermit` / `normalizeDiscordSenderForPermit`、`telegramGroupPermitResolver` / `checkTelegramPlatformPermit` / `normalizeTelegramChatMember`、`kookGroupPermitResolver` / `checkKookPlatformPermit` / `normalizeKookSenderForPermit` / `KookSenderInfo`、`larkGroupPermitResolver` / `checkLarkPlatformPermit` / `normalizeLarkSenderForPermit`、`slackGroupPermitResolver` / `checkSlackPlatformPermit` / `normalizeSlackSenderForPermit`、`dingtalkGroupPermitResolver` / `checkDingtalkPlatformPermit` / `normalizeDingtalkSenderForPermit`、`wecomGroupPermitResolver` / `checkWecomPlatformPermit` / `normalizeWecomSenderForPermit`、`qqGuildPermitResolver` / `checkQqPlatformPermit` / `normalizeQqGuildSenderForPermit`。permit 一律交给内置评估器(`@zhin.js/permission`),`platformPermit()` 仍保留;各适配器 `PERMITS.md` 按实际上报的字段重写。
24
+
25
+ - 89b63fa: 适配器工具的操作目标与角色层级收尾(ADR 0056 §5):
26
+
27
+ - KOOK:`kook_grant_role` / `kook_revoke_role` 要求目标角色严格低于发起者的最高角色(KOOK 角色 `position` 值越小优先级越高;服务器主豁免;「全体成员」与不存在的角色拒绝),低位 `manage_roles` 成员不能借机器人给自己授予更高角色;`kook_blacklist` 拉黑时要求目标成员低于发起者、不能拉黑服务器主;`kook_list_roles` 改为只读当前服务器(去掉 `guild_id`)。
28
+ - 不带层级限定 owner 的工具不再接受任意群 / 频道 / 会话 ID,目标改为取自当前会话(模型传入的 ID 被忽略):
29
+ - ICQQ:`group_invite`、`group_member_info`、`group_sign`、`poke`、`group_files`、`list_muted`;
30
+ - Discord:`discord_react`、`discord_send_embed`(当前频道 / 线程 / 私信)、`discord_forum_post`(在当前帖子所属的论坛发帖);
31
+ - NapCat:精华列表、群公告列表、群文件(根目录、下载链接、上传)、群消息历史、AI 语音与角色、群详情、禁言列表、群签到;`get_friend_msg_history` 只读当前私聊;`send_poke` 在当前会话;`send_forward_msg` 发往当前会话,引用已有消息的节点只能引用当前会话的消息;
32
+ - Slack:`slack_add_reaction`、`slack_remove_reaction`、`slack_edit_message`;
33
+ - Telegram:`telegram_list_admins`、`telegram_member_count`、`telegram_react`、`telegram_send_poll`、`telegram_send_sticker`;
34
+ - LINE:`line_get_group_members`。
35
+ - 本身就跨会话的工具改为要求全局层 `owner`(`owner@global`):NapCat `forward_single_msg`(转发任意消息到任意好友 / 群)、`upload_group_file`(`file` 可为宿主本地路径)、钉钉 `dingtalk_send_work_notice`、企业微信 `wecom_send_text`(发给任意用户)。
36
+ - 各适配器 `PERMITS.md` 同步(Slack `slack_unarchive`、钉钉跨群工具更正为 `owner@global`)。
37
+
38
+ - 74f34c0: 适配器 Agent 工具不再读取宿主文件、不再绕过出站发送链:
39
+
40
+ - 读取宿主文件的工具要求全局层 `owner`(`owner@global`):飞书 `lark_upload_file`(本地路径)、NapCat `set_group_portrait`(另需 `bot:admin`)、`set_avatar`(同时是机器人账号身份)、`download_file`(由宿主网络拉取任意 URL 并写入宿主文件)。NapCat `ocr_image`、`send_group_notice` 的图片与 `send_forward_msg` 节点内的媒体只接受 http(s) 链接、`base64://` 或平台文件标识,拒绝 `file://` 与本机路径。
41
+ - 发消息的工具改经 IM 出站链(`outboundMessageToken` → 渲染 → 出站中间件 → Endpoint),平台特有内容用适配器的命名空间段:Discord `send_embed` → `discord:embed`;Telegram `send_poll` / `send_sticker` → `telegram:poll` / `telegram:sticker`(贴纸只接受 file_id 或 http(s) 链接);NapCat `send_forward_msg` → `napcat:node`(OneBot `node` 段);企业微信 `send_text` 以当前账号发往指定用户的会话。
42
+ - `pnpm check:harness-paths` 增加检查:适配器 Agent 工具直调平台发送接口即失败;无法由出站链表达的调用(钉钉工作通知、NapCat 单条原生转发与 AI 语音、Discord 建论坛帖 / 子线程)登记在 `scripts/agent-send-bypass-allowlist.json` 并写明理由。
43
+
44
+ - 57c6cdc: fix: 全仓审计修复
45
+
46
+ - kernel: 模板求值沙箱不再泄漏宿主对象——宿主函数的返回值与抛出的错误会重新包裹代理(`segments.map(x=>x).constructor.constructor(...)` 之前可拿到宿主 `Function`),并禁止通过代理写入/删除宿主属性。
47
+ - agent: exec 白名单正则按整体锚定(`git|npm` 不再匹配 `gitevil`);SSRF 主机名黑名单识别尾点形式(`localhost.`);Docker 沙箱 `always` 模式的 fail-closed 分支可被触达;声明缺失的 `chalk` 依赖。
48
+ - ai: 摘要按最新优先加载(超过 500 条时不再使用过期锚点);修复 `test` 脚本指向不存在的配置。
49
+ - cli: `ZHIN_LOG_LEVEL` 生效(修复运算符优先级);移除旧守护进程遗留的无引用进程辅助函数。
50
+ - logger: `formatCompact` 不再把 `config: 'yaml'`、`direction: 'in'` 这类非路径值改写成 `./yaml`。
51
+ - host-http: 未配置数据库时 `db:tables` 与有数据库时一致返回 `{ tables }`。
52
+ - a2a: 405 响应把 `Allow` 放进响应头。
53
+ - pagemanager: 内联进 `<script>` 的页面元数据转义 `<`。
54
+ - client: 事件历史请求失败时携带 HTTP 状态,token 失效可触发重新登录。
55
+ - scaffold-wizard / create-zhin-app: 修正适配器文档 URL 与模板里的 `@zhin.js/tool` 导入。
56
+ - adapter-wechat-mp: 签名比较改为常量时间。
57
+ - adapter-kook: 声明运行时依赖 `ws`。
58
+ - plugin-lottery: 遗漏值按最近一次出现计算;推送目标 schema 字段与实现一致(`endpointKey`)。
59
+ - plugin-code-runner: 语言校验改用自有属性判断。
60
+ - plugin-link-poster: 抓取前校验主机名白名单(修复 SSRF),超时覆盖响应体读取。
61
+ - 其余包:从 `files` 中移除不存在的目录。
62
+ - feature-kit / middleware: 修正 README 中层级错误的文档链接。
63
+
64
+ - e1fda87: fix: 按审计待审清单处理(安全、功能、清理)
65
+
66
+ **行为变更(升级前请阅读)**
67
+
68
+ - kernel / core / zhin.js:出站文本中的 `${…}` 不再用 `vm` 求值,只替换 `TemplateContext` 上能解析到值的属性路径(如 `${sender.name}`);表达式、函数调用、未知名字原样保留。整套 vm 沙箱(`evaluate` / `execute` / `compiler` / `getValueWithRuntime`)已移除。
69
+ - kernel / core / zhin.js:移除零引用的遗留导出——`Scheduler`、错误管理器与 `ZhinError` 子类、`compose`、`segment.from/toString`、AI 触发/准入函数、`@zhin.js/core/queue-im-field-contract`、`zhin.js/contexts`。
70
+ - agent:readonly 执行预设不再放行重定向、后台 `&`、进程替换、`find -delete/-exec`、`sed -i`、`sort -o`、`tee`、`xargs`、awk;curl/wget 校验每个 URL 与裸主机并识别更多上传参数;自定义 `execAllowlist` 中的只读命令带写入风险时改走审批。沙箱超时/取消会杀掉进程组或具名容器,默认镜像改为 `node:22-bookworm-slim` + `bash`。移除无生产调用的 `AuditLogger`、`AnomalyDetector`、旧 vision 回合等导出。
71
+ - ai:移除 `storage`、`FileStateCache`、`CostTracker`、`model-name-utils`、`./agent-step-checkpoint` 子路径、`ContextManager` 及旧压缩管线;延迟工具快照改为有界 LRU。
72
+ - cli:`zhin send` / `watch` / `schedule` 改为与运行中的 Host 通信(新增 `POST /message/send` 与 `/assistant/jobs` 写接口),`schedule` 不再支持离线改文件;移除 `zhin uninstall service`(用 `zhin service uninstall`)、`build --analyze`、`install -S`;`zhin stop` 杀不掉进程时保留 pid 文件并以非零退出;`runtime migrate` 新增 `verify`;未设置 `TZ` 时调度默认时区改为系统时区;不带 `ZHIN_SUPERVISOR_PID` 的进程被 init 接管后不再自行退出。
73
+ - schedule:后台 reconcile 出错不再产生未处理 rejection(新增 `onStoreError`);启动途中 `stop()` 不再遗留定时器。
74
+ - schema:元组校验与 `safeParse`、JSON Schema 一致(空数组不通过,缺省的可选元组为 `undefined`)。
75
+ - client / contract:删除无后端路由的 agent-stream API、未使用的 `definePage` 与旧 PageManager 类型;`@zhin.js/contract` 不再依赖 `@zhin.js/ai`;客户端收到 401 会清除已保存的凭据;安装/更新/卸载 RPC 默认超时 120 秒。
76
+ - a2a:流式响应中途出错写入 SSE error 并结束;未配置 token 的非生产环境只接受本机请求;任务存储有上限与过期;Mailbox 凭据回退与生产环境缺密钥检查修复。
77
+ - speech:`provider: openai` 不再套用 Ollama 的默认 host/model;识别语言改为可配置,不再写死 `zh`。
78
+ - adapter-lark:支持 `encryptKey` 加密事件解密。adapter-github:Device Flow 可取消、带超时并回复失败原因。adapter-wecom / dingtalk:请求加超时并校验 HTTP 状态。adapter-weixin-ilink:输入关闭期间暂停轮询。adapter-milky:SSE 支持 CRLF、缓冲上限与空闲重连。adapter-onebot-events:好友删除通知改为 `notice.friend.decrease`。
79
+ - plugin-group-suite:`teachAllowRegex` 默认关闭,正则安全检查更严格。plugin-qrcode:改为本地生成,回复 data URL 图片。plugin-rss / short-url / link-poster:拒绝解析到内网的地址;rss 修复条目每周重复推送;short-url 的 Console 创建改为真实调用 is.gd。plugin-lottery:按 `historyLimit` 同步。
80
+
81
+ **其余**
82
+
83
+ - host-http:插件市场详情加缓存与包名校验,SSE 回放容忍背压。host-http-contract:新增 `readTextBody()`,九个适配器改用它。
84
+ - pagemanager:页面外壳 importmap 升级到 React 19.2.8 / react-router 7.12.0。console-contract:`definePage` 接受 `description` / `group` / `parent` / `fullWidth`。
85
+ - command:进度提示本地化,匹配不再重复拷贝消息段。runtime:源码监听降级后退避重试原生监听。
86
+ - html-renderer:删除未接线的 `aiTextAsImage`。create-zhin-app / scaffold-wizard:移除不起作用的"全局安装 CLI"与运行时选择提示。
87
+ - 依赖声明清理、发布清单不再携带解析不到的 `src` 目录、移除未使用的 Skill 挂载、README 与示例配置按当前实现更正。
88
+
89
+ - 120e225: 聊天角色(ADR 0056,2026-11-12 修订):zhin 角色 owner / admin / trusted 分四级、只来自授予;发言者的平台身份与机器人自身的平台身份是独立维度,命令、Agent 工具 / 技能、中间件与按钮按三条维度共用一个评估器过滤。升级说明见 docs/migrations/chat-roles.md。
90
+
91
+ - zhin.js:实例首次启动把适配器 `master` / `trusted`、`endpoints[i].master|trusted` 与 `ai.trigger.masters|trusted` 迁入项目数据库 `chat_roles`(先记入 `.zhin/chat-roles-migration.json`,再从配置移除并记日志);之后配置再出现这些字段时启动报错并指向升级指南。平台身份不再映射为 zhin 角色:删除 `roles.mappings`(适配器块与 `endpoints[i].roles` 出现即启动报错)、`chat_role_mappings` 表与 Console `chat-roles.mappings` / `chat-roles.set-mappings`;`features.selfService.platformAdmins|roles|allowUsers` 删除;群内「功能」「角色」命令只认 zhin 角色,平台群主不再自动具备;聊天改配置、聊天重启、Agent 主人审批按 zhin `owner` 判断。
92
+ - @zhin.js/core(minor,破坏性):角色模型与解析移入 core(`ChatRoleService`、`createChatRoleSenderEnricher`),入站消息带 `sender.chatRole` 与归一的 `sender.platform`;删除 `SenderRole`、`senderRolesFromMessage`、`roleSatisfies` 等,`master` 改名 `owner`;删除映射规则 API(`createMappingChatRoleSource`、`DEFAULT_CHAT_ROLE_MAPPINGS` 等)与 `ChatRoleSource`;`createSenderEnricher` / `createConfigurationChatAuthorizer` 改为基于聊天角色。IM Runtime 为 PermissionHost 提供机器人自身身份(经 Adapter 索引缓存),机器人的角色变化事件使缓存失效;命令拒绝回复说明缺少的平台 / 机器人条件;`<Button permit>` 按点击者鉴权;场景治理工具工厂同时要求 `platform:*` 与 `bot:*`;`ai.trigger.masters|trusted` 删除。
93
+ - @zhin.js/permission(minor,破坏性):permit 语法 `owner` / `admin` / `trusted` / `role(...)`(zhin 角色)、`platform:owner|admin`、`platform-role:<id>`、`platform-permission:<name>`(发言者平台身份),新增 `bot:owner|admin`、`bot-role:<id>`、`bot-permission:<name>`(机器人自身平台身份,`PermissionSubject.bot`);`PermissionHost` 新增 `setBotStandingResolver`、`withBotStanding`、`firstDenied`,`checkAll` 可带 `source` 解析机器人身份;新增 `describeDeniedPermit`、`permitsNeedBotStanding`。删除 `role(master)`、`scene_admin`、`scene_owner`、`platform(adapter,perm)` 及 `registerPlatform`、`createSceneRolePlatformChecker`、`platformPermission`、`definePlatformPermission`,定义时报错并给出替代写法。
94
+ - @zhin.js/command(minor,破坏性):命令会话的发送者改为 `chatRole` / `platform`,不再从 metadata 读角色;`CONVERSATION_MANAGER_PERMIT` 改为 `admin`(平台群主不再自动满足);分发结果 `denied` 带 `denial`(第一条不满足的规则与原因);指令菜单只列出当前发送者在本会话可用的命令。
95
+ - @zhin.js/agent(minor,破坏性):危险工具、文件 / exec 策略、主人审批、Agent 回合主体只读 zhin 角色(`principal.roles` 只含展开的聊天角色,平台地位在 `principal.platform`);`SenderRole` → `PrincipalRole`,`SELF_CHANGE_MASTER_ROLE` → `SELF_CHANGE_OWNER_ROLE`;回合开始时读取机器人自身身份(`contextState.bot.platform`),按三条维度过滤 tool / skill / Agent 包后才披露,执行工具时再校验一次;群规「群主和管理员豁免」改为平台群主 / 管理员与 zhin `owner`。
96
+ - @zhin.js/feature-kit:`OperationSession.sender` 改为 `chatRole` / `platform`。
97
+ - @zhin.js/im-contract:新增 `PlatformStanding`、`SelfStandingRequest`、`standingFromMemberRole`。
98
+ - @zhin.js/adapter:入站 sender 可带 `platform`;账号管理命令需要聊天角色 `owner`;`EndpointManagement` 新增可选 `inspectSelfStanding`,能力画像新增 `scene.selfStanding`(声明即须实现),`AdapterIndex.selfStanding` / `invalidateSelfStanding` 按会话缓存机器人自身身份。
99
+ - @zhin.js/middleware:入站中间件可声明 `permit`,不满足时跳过该中间件(机器人身份只读缓存)。
100
+ - @zhin.js/tool:定义工具时拒绝已移除的 permit 写法。
101
+ - @zhin.js/ai:注释更新。
102
+ - @zhin.js/console-protocol:`chat-roles.list|grant|revoke`(`iam.manage`);`ConsoleChatRoleSource` 只有 `grant`。
103
+ - @zhin.js/runtime:Host 配置 Schema 删除 `features.selfService.platformAdmins|roles|allowUsers`。
104
+ - @zhin.js/testing:伪造消息与 `PluginTestKit` 用 `sender.chatRole` 声明测试身份。
105
+ - @zhin.js/scaffold-wizard:ICQQ 向导不再写 `master`,完成后提示在 Console 账号「角色」页签或聊天 `角色 授予` 设置 owner。
106
+ - 适配器:配置 Schema 删除 `master` / `trusted`(以及预览版的 `roles`);群管理类工具同时声明发言者条件与机器人条件(如 `platform:admin` + `bot:admin`、`bot-permission:manage_roles`),NapCat / OneBot11 工具不再使用已移除的 `platform(adapter,…)` 写法。
107
+ - 插件:内容审核以 `inbound.bypass`(permit 列表,默认 `owner` 或 `platform:admin`)取代 `masters` / `inbound.bypassMasters`;群管、音乐、日历、地震、B 站、轮盘赌的权限改用 zhin 角色,订阅类命令只认 zhin `admin` / `owner`。
108
+
109
+ - 5cd9d3d: HTTP 路由契约改为 Web 标准 `Request` / `Response`(ADR 0054 §2,B1.0)
110
+
111
+ - host-http-contract:路由处理函数签名改为 `(request, context) => Response`,`context` 提供 `url`、`params`、`principal`、`remoteAddress`;新增 `readBodyBytes` / `readTextBody` / `readJsonBody`(带大小上限,超限先读完再报 413)、`jsonResponse` / `emptyResponse`、带背压的 `createResponseStream`(SSE、大文件下载)与 `WsConnection`。契约不再引用 `node:http` / `ws`。
112
+ - host-http:Node 服务器移到 `@zhin.js/host-http/node`(`createHttpHost`),负责 Node 请求与 `Request` / `Response` 的互转;认证结果经 `context.principal` 传给路由,删除旧的按请求取主体的辅助函数;未预期的异常只返回通用错误信息,细节写日志。
113
+ - runtime、mcp、a2a、gateway、zhin.js、calendar 插件与各适配器的 Webhook / 反向 WebSocket 路由迁移到新契约,行为不变。
114
+
115
+ - 663473b: Agent 模型输出不能再借出站媒体段发送宿主文件(ADR 0056 §2):
116
+
117
+ - 此前模型可以在回复里写 `{"kind":"file","value":"file:///etc/passwd"}`(或 `/etc/passwd`)这样的「平台文件引用」,Agent 发布层原样放行,OneBot / NapCat 会把它当作本地文件读取上传;模型以 `path` 引用工作区文件时也只做了工作区与敏感文件名检查,没有按发起人角色做 `read_file` 的读取判定(普通成员可发出 `.git/config`、`package.json`)。
118
+ - Core 新增不可信来源的出站媒体策略:`untrustedContent(content, trust)` 包装的内容在渲染器里(出站中间件与 Endpoint 之前,出站链仍唯一)只允许 http(s) 链接、有上限的内联数据(默认 25 MiB)与裸平台文件标识;本地路径(含 `file://`)只在 `trust.authorizePath` 认可或由可信代码 `trustedMediaRef()` 构造时放行;嵌套的本地来源拒绝,`html` 只保留文字,不做 `${…}` 模板替换。被拒的段替换为可见提示(「[图片未发送:媒体来源不被允许]」)并记录 `op=outbound_media_refused`。
119
+ - Agent 的回复、流式回复(`OpenReplyStreamOptions.mediaTrust`)、场景事件回复、主动发送与 QQ / ICQQ / Telegram / Discord / NapCat / 企业微信的 Agent 工具发送都按不可信来源投递;模型引用的本地路径按发起人文件角色(只有全局 `owner` 是 `owner`)做与 `read_file` 相同的判定,需要确认的敏感读取直接拒绝。插件代码自己构造的内容不受影响;工作区内工具生成的截图、图表与 Agent 落盘的大附件照常发送。
120
+
121
+ - 68659cd: `zod` 改为运行时依赖(原为可选对等依赖):插件运行时在启动时就会加载这些包的约定目录(Agent 工具、命令等),其中静态导入了 `zod`;生成的项目里没有安装可选对等依赖,启动会报 `Cannot find package 'zod'`。范围为 `^4.6.7`(已修复的版本)。
122
+ - Updated dependencies [53932e5]
123
+ - Updated dependencies [57c6cdc]
124
+ - Updated dependencies [e1fda87]
125
+ - Updated dependencies [4e8ba38]
126
+ - Updated dependencies [a9c7a13]
127
+ - Updated dependencies [120e225]
128
+ - Updated dependencies [c2bbdcf]
129
+ - Updated dependencies [c2bbdcf]
130
+ - Updated dependencies [63595fc]
131
+ - Updated dependencies [fd055d2]
132
+ - Updated dependencies [4e8ba38]
133
+ - Updated dependencies [cc7a5f9]
134
+ - Updated dependencies [4e8ba38]
135
+ - Updated dependencies [f8bf684]
136
+ - Updated dependencies [e0bc008]
137
+ - Updated dependencies [5cd9d3d]
138
+ - Updated dependencies [5cd9d3d]
139
+ - Updated dependencies [c2bbdcf]
140
+ - Updated dependencies [f8bf684]
141
+ - Updated dependencies [663473b]
142
+ - Updated dependencies [c606d51]
143
+ - Updated dependencies [5cd9d3d]
144
+ - Updated dependencies [d655ef0]
145
+ - Updated dependencies [1e54b1e]
146
+ - @zhin.js/adapter@1.1.33
147
+ - @zhin.js/core@1.2.0
148
+ - @zhin.js/logger@1.1.3
149
+ - @zhin.js/host-http@1.2.0
150
+ - @zhin.js/feature-kit@1.1.16
151
+ - @zhin.js/agent-feature@1.1.17
152
+ - @zhin.js/console-contract@1.1.6
153
+ - @zhin.js/host-http-contract@1.2.0
154
+ - @zhin.js/skill@1.1.17
155
+ - @zhin.js/tool@1.1.19
156
+ - @zhin.js/im-contract@1.1.14
157
+ - @zhin.js/page@1.1.18
158
+
159
+ ## 1.1.26
160
+
161
+ ### Patch Changes
162
+
163
+ - 0d76a7c: Overhaul Console interactive workbenches, platform-specific adapter account onboarding/login flows, DeclarativePageView visual/interactive capabilities, and official utility plugin Console pages.
164
+ - Updated dependencies [0d76a7c]
165
+ - @zhin.js/adapter@1.1.32
166
+ - @zhin.js/core@1.1.60
167
+
3
168
  ## 1.1.25
4
169
 
5
170
  ### Patch Changes
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 凉菜
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/PERMITS.md CHANGED
@@ -1,19 +1,7 @@
1
1
  # 企业微信 WeCom Platform Permits
2
2
 
3
- ## 入站字段
3
+ ## 入站字段(ADR 0056 §1)
4
4
 
5
- | 字段 | 来源 |
6
- |------|------|
7
- | `$sender.role` | 默认 `member`;需业务侧扩展企业微信可见性/管理权限 |
8
- | `$sender.permissions` | `chat_owner` · `chat_admin` |
5
+ 企业微信回调不提供群内地位、角色或权限位:本适配器不上报 `sender.platform`,也不声明 `scene.platformStanding` / `scene.selfStanding`,因此 `platform:*` 与 `bot:*` permit 在企业微信会话中都不满足。需要门禁的工具请使用 zhin 角色(`owner` / `admin` / `trusted`)。
9
6
 
10
- ## Permit 词汇表
11
-
12
- | `platform(wecom,…)` | 含义 |
13
- |---------------------|------|
14
- | `chat_owner` | 群主 |
15
- | `chat_admin` | 群管理员 |
16
-
17
- ## 工厂映射
18
-
19
- `scene_admin` → `chat_admin` · `scene_owner` → `chat_owner`
7
+ `wecom_send_text` 可向任意用户发消息(不在当前会话),要求全局层 zhin `owner`(`owner@global`)。
package/README.md CHANGED
@@ -112,7 +112,7 @@ Access Token 在过期前 5 分钟自动刷新。
112
112
 
113
113
  新增仅保存,需手动启动;运行账号的普通配置更新只重连该账号。身份变化走明确替换,新账号不会继承旧 Session 或登录状态。账号凭据变化先按平台实际只读接口核验;平台无法核验时需明确替换。空白或遮蔽的密码不会覆盖既有密码。
114
114
 
115
- 读取需要 `wecom:read`,写入需要 `wecom:write`;首次迁移还需管理员身份。无持久化存储时管理操作不可用,提交结果未知时先刷新核实,不重复提交。
115
+ 读取需要 `wecom:read`(`read` 级别,内置角色 `viewer` 及以上都有),写入需要 `wecom:write`(`operate` 级别,`operator` 及以上都有,绑定到本适配器的角色也算);首次迁移还需管理员身份,见[插件权限的级别](https://zhin.js.org/console/#插件权限的级别)。无持久化存储时管理操作不可用,提交结果未知时先刷新核实,不重复提交。
116
116
 
117
117
  ## 故障排查
118
118
 
@@ -127,7 +127,7 @@ Access Token 在过期前 5 分钟自动刷新。
127
127
  | 类别 | 路径 |
128
128
  |------|------|
129
129
  | Permit 词汇 | `PERMITS.md` |
130
- | 平台工具(4 个) | `tools/` |
130
+ | 平台工具(4 个) | `agents/wecom/skills/wecom/tools/` |
131
131
  | 技能说明 | `agents/wecom/skills/wecom/SKILL.md` |
132
132
 
133
133
  ## 平台权限(platform permit)
@@ -143,3 +143,7 @@ Access Token 在过期前 5 分钟自动刷新。
143
143
  ## 许可证
144
144
 
145
145
  MIT License
146
+
147
+ ## 成员身份
148
+
149
+ 企业微信回调不带发送者群角色,不上报 `sender.platform`,能力画像也不声明 `scene.platformStanding`。详见 [ADR 0056 §1](https://github.com/zhinjs/zhin/blob/main/docs/adr/0056-chat-roles.md)。
@@ -1,18 +1,34 @@
1
1
  // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
2
  import { messages as t } from "../../../../messages.js";
3
3
  import { defineAgentTool } from '@zhin.js/tool';
4
+ import { outboundMessageToken, untrustedContent } from '@zhin.js/core/runtime';
5
+ import { resolveChatType } from '@zhin.js/adapter-wecom';
4
6
  import { z } from 'zod';
5
7
  export default defineAgentTool({
6
- description: '向指定企业微信用户发送文本消息',
8
+ description: '用当前企业微信应用账号向指定用户发送文本消息(可发给任意用户,仅全局主人可用)',
7
9
  inputSchema: z.object({
8
10
  user_id: z.string().describe('用户 ID'),
9
11
  content: z.string().describe('消息内容'),
10
12
  }),
11
13
  adapter: 'wecom',
12
14
  tags: ['wecom'],
15
+ // Messages any user of the organization, outside the current conversation: host-global (ADR 0056 §5).
16
+ permissions: ['owner@global'],
13
17
  async execute({ user_id, content }, context) {
14
- const endpoint = context.$client;
15
- const success = await endpoint.sendTextMessage(user_id, content);
18
+ const { origin } = context;
19
+ const endpoint = origin?.kind === 'im' && origin.platform === 'wecom' ? origin.conversation?.endpoint : undefined;
20
+ const id = user_id.trim();
21
+ if (!endpoint || !id)
22
+ return { success: false, message: t(context.locale, 'sendFailed') };
23
+ context.signal?.throwIfAborted();
24
+ // Through the IM outbound chain (renderer → outbound middleware → Endpoint), from the current account.
25
+ const receipt = await context.use(outboundMessageToken).send({
26
+ requester: context.owner.id,
27
+ conversation: { endpoint, kind: resolveChatType(id), id },
28
+ // Model-authored text: literal (no template paths), never media from the host.
29
+ content: untrustedContent(content, { source: 'wecom:agent-tool', locale: context.locale }),
30
+ });
31
+ const success = receipt.status === 'sent';
16
32
  return { success, message: success ? t(context.locale, 'messageSent') : t(context.locale, 'sendFailed') };
17
33
  },
18
34
  });
@@ -1,18 +1,33 @@
1
1
  import { messages as t } from "../../../../messages.js";
2
2
  import { defineAgentTool } from '@zhin.js/tool';
3
+ import { outboundMessageToken, untrustedContent } from '@zhin.js/core/runtime';
4
+ import { resolveChatType } from '@zhin.js/adapter-wecom';
3
5
  import { z } from 'zod';
6
+
4
7
  export default defineAgentTool<{ user_id: string; content: string }>({
5
- description: '向指定企业微信用户发送文本消息',
8
+ description: '用当前企业微信应用账号向指定用户发送文本消息(可发给任意用户,仅全局主人可用)',
6
9
  inputSchema: z.object({
7
10
  user_id: z.string().describe('用户 ID'),
8
11
  content: z.string().describe('消息内容'),
9
12
  }),
10
13
  adapter: 'wecom',
11
14
  tags: ['wecom'],
12
- async execute({ user_id, content }: { user_id: string; content: string }, context) {
13
- const endpoint = context.$client;
14
- const success = await endpoint.sendTextMessage(user_id, content);
15
+ // Messages any user of the organization, outside the current conversation: host-global (ADR 0056 §5).
16
+ permissions: ['owner@global'],
17
+ async execute({ user_id, content }, context) {
18
+ const { origin } = context;
19
+ const endpoint = origin?.kind === 'im' && origin.platform === 'wecom' ? origin.conversation?.endpoint : undefined;
20
+ const id = user_id.trim();
21
+ if (!endpoint || !id) return { success: false, message: t(context.locale, 'sendFailed') };
22
+ context.signal?.throwIfAborted();
23
+ // Through the IM outbound chain (renderer → outbound middleware → Endpoint), from the current account.
24
+ const receipt = await context.use(outboundMessageToken).send({
25
+ requester: context.owner.id,
26
+ conversation: { endpoint, kind: resolveChatType(id), id },
27
+ // Model-authored text: literal (no template paths), never media from the host.
28
+ content: untrustedContent(content, { source: 'wecom:agent-tool', locale: context.locale }),
29
+ });
30
+ const success = receipt.status === 'sent';
15
31
  return { success, message: success ? t(context.locale, 'messageSent') : t(context.locale, 'sendFailed') };
16
32
  },
17
33
  });
18
-
package/lib/adapter.js CHANGED
@@ -11,7 +11,7 @@ export class WecomAdapter extends Adapter {
11
11
  get configurationIdentityProbeFields() { return ['agentSecret', 'apiBaseUrl']; }
12
12
  async identifyConfiguration(input, signal, _changed) {
13
13
  const config = resolveWecomConfig(input);
14
- const fetch = async (url, init) => { signal.throwIfAborted(); return globalThis.fetch(url, { ...init, signal }); };
14
+ const fetch = async (url, init) => { signal.throwIfAborted(); return globalThis.fetch(url, { ...init, signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal }); };
15
15
  const client = new WecomClient({ id: this.descriptor.id, config, fetch });
16
16
  const response = await client.getApplicationInfo();
17
17
  if (typeof response.agentid !== 'string' && typeof response.agentid !== 'number')
package/lib/client.js CHANGED
@@ -173,8 +173,11 @@ export class WecomClient extends EventEmitter {
173
173
  await createEndpointOperation({ signal }).prepare(() => this.#ensureAccessToken());
174
174
  const binary = await createEndpointOperation({ signal }).prepare(() => resolveMediaBinary(media, { signal }));
175
175
  const form = buildMediaUploadForm(binary);
176
- const url = `${this.#options.config.apiBaseUrl}/cgi-bin/media/upload?access_token=${this.#accessToken.access_token}&type=image`;
177
- const response = await this.#fetch(url, { method: 'POST', body: form, signal });
176
+ const query = new URLSearchParams({ access_token: this.#accessToken.access_token, type: 'image' });
177
+ const url = `${this.#options.config.apiBaseUrl}/cgi-bin/media/upload?${query.toString()}`;
178
+ const response = await this.#fetch(url, { method: 'POST', body: form, signal: requestSignal(signal) });
179
+ if (!response.ok)
180
+ throw new Error(`WeCom media upload failed: HTTP ${response.status}`);
178
181
  const data = await response.json();
179
182
  if (data.errcode === 0 && data.media_id)
180
183
  return data.media_id;
@@ -302,7 +305,7 @@ export class WecomClient extends EventEmitter {
302
305
  method,
303
306
  headers: { 'Content-Type': 'application/json; charset=utf-8' },
304
307
  body: body && method === 'POST' ? JSON.stringify(body) : undefined,
305
- signal: options.signal,
308
+ signal: requestSignal(options.signal),
306
309
  });
307
310
  if (!response.ok) {
308
311
  const text = await response.text().catch(() => '');
@@ -327,8 +330,12 @@ export class WecomClient extends EventEmitter {
327
330
  }
328
331
  async #refreshAccessToken() {
329
332
  const { corpId, agentSecret, apiBaseUrl } = this.#options.config;
330
- const url = `${apiBaseUrl}/cgi-bin/gettoken?corpid=${corpId}&corpsecret=${agentSecret}`;
331
- const response = await this.#fetch(url);
333
+ const query = new URLSearchParams({ corpid: corpId, corpsecret: agentSecret });
334
+ const url = `${apiBaseUrl}/cgi-bin/gettoken?${query.toString()}`;
335
+ // The refresh promise is shared by every sender, so it must never hang.
336
+ const response = await this.#fetch(url, { signal: requestSignal() });
337
+ if (!response.ok)
338
+ throw new Error(`Failed to get access token: HTTP ${response.status}`);
332
339
  const data = await response.json();
333
340
  if (data.errcode === 0 && data.access_token) {
334
341
  this.#accessToken = {
@@ -342,3 +349,8 @@ export class WecomClient extends EventEmitter {
342
349
  throw new Error(`Failed to get access token: ${data.errmsg} (${data.errcode})`);
343
350
  }
344
351
  }
352
+ const REQUEST_TIMEOUT_MS = 30_000;
353
+ function requestSignal(signal) {
354
+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
355
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
356
+ }
@@ -2,11 +2,68 @@ export const wecomConsoleSpec = {
2
2
  adapterKey: 'wecom',
3
3
  adapterDisplayName: '企业微信',
4
4
  fields: [
5
- { key: 'corpId', required: true, env: true, description: '企业 corpId', descriptionI18n: { en: 'WeCom corporation ID' } },
6
- { key: 'agentId', required: true, description: '应用 AgentId', descriptionI18n: { en: 'WeCom application AgentId' } },
7
- { key: 'agentSecret', required: true, env: true, description: '应用 secret', descriptionI18n: { en: 'Application secret' } },
8
- { key: 'token', required: true, env: true, description: '回调 token', descriptionI18n: { en: 'Callback token' } },
9
- { key: 'encodingAESKey', required: true, env: true, description: '回调加解密 key', descriptionI18n: { en: 'Callback encryption key' } },
5
+ {
6
+ key: 'corpId',
7
+ required: true,
8
+ env: true,
9
+ label: '企业 ID (CorpID)',
10
+ labelI18n: { en: 'CorpID' },
11
+ group: '企业应用凭证',
12
+ groupI18n: { en: 'Enterprise App Credentials' },
13
+ placeholder: 'ww1234567890abcdef',
14
+ description: '企业微信管理后台「我的企业」中的企业 ID',
15
+ descriptionI18n: { en: 'WeCom corporation ID' },
16
+ },
17
+ {
18
+ key: 'agentId',
19
+ required: true,
20
+ label: '应用 AgentId',
21
+ labelI18n: { en: 'Application AgentId' },
22
+ group: '企业应用凭证',
23
+ groupI18n: { en: 'Enterprise App Credentials' },
24
+ placeholder: '1000002',
25
+ description: '自建应用的 AgentId(数字编号)',
26
+ descriptionI18n: { en: 'WeCom application AgentId' },
27
+ },
28
+ {
29
+ key: 'agentSecret',
30
+ required: true,
31
+ env: true,
32
+ label: '应用 Secret',
33
+ labelI18n: { en: 'Application Secret' },
34
+ group: '企业应用凭证',
35
+ groupI18n: { en: 'Enterprise App Credentials' },
36
+ placeholder: '自建应用的 Secret 密钥',
37
+ placeholderI18n: { en: 'WeCom application secret' },
38
+ description: '自建应用的 Secret 密钥',
39
+ descriptionI18n: { en: 'Application secret' },
40
+ },
41
+ {
42
+ key: 'token',
43
+ required: true,
44
+ env: true,
45
+ label: '接收消息 Token',
46
+ labelI18n: { en: 'Callback Token' },
47
+ group: '事件回调与加解密',
48
+ groupI18n: { en: 'Event Callback & Encryption' },
49
+ placeholder: 'API 接收消息配置的 Token',
50
+ placeholderI18n: { en: 'Callback verification token' },
51
+ description: '「接收消息 → 设置 API 接收」中的 Token',
52
+ descriptionI18n: { en: 'Callback token' },
53
+ },
54
+ {
55
+ key: 'encodingAESKey',
56
+ required: true,
57
+ env: true,
58
+ label: 'EncodingAESKey (消息加解密密钥)',
59
+ labelI18n: { en: 'EncodingAESKey' },
60
+ group: '事件回调与加解密',
61
+ groupI18n: { en: 'Event Callback & Encryption' },
62
+ placeholder: '43 位字符的 EncodingAESKey',
63
+ placeholderI18n: { en: '43-char EncodingAESKey' },
64
+ description: '「接收消息 → 设置 API 接收」中的 EncodingAESKey',
65
+ descriptionI18n: { en: 'Callback encryption key' },
66
+ },
10
67
  ],
11
68
  docsUrl: 'https://zhin.js.org/adapters/wecom',
12
69
  readPermission: 'wecom:read',
package/lib/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { buildSendRequestBody, decryptMessage, extractEncryptFromXml, formatInboundContent, formatOutboundBody, getAesKey, normalizeEchostrParam, normalizeWebhookPath, parseXmlMessage, queryParam, readTextBody, resolveChatType, resolveWecomConfig, verifySignature, type AccessToken, type ResolvedWecomConfig, type WecomEndpointConfig, type WecomApiResponse, type WecomMessage, type WecomSendBody, type WecomWireSegment, } from './protocol.js';
1
+ export { buildSendRequestBody, decryptMessage, extractEncryptFromXml, formatInboundContent, formatOutboundBody, getAesKey, normalizeEchostrParam, normalizeWebhookPath, parseXmlMessage, queryParam, resolveChatType, resolveWecomConfig, verifySignature, type AccessToken, type ResolvedWecomConfig, type WecomEndpointConfig, type WecomApiResponse, type WecomMessage, type WecomSendBody, type WecomWireSegment, } from './protocol.js';
2
2
  export { type WecomClientEventMap } from './client.js';
3
- export { checkWecomPlatformPermit, normalizeWecomSenderForPermit, platformPermit, wecomGroupPermitResolver, } from './platform-permit.js';
3
+ export { platformPermit } from './platform-permit.js';
4
4
  export { WecomEndpoint, type WecomEndpointOptions, type WecomFetch, } from './endpoint.js';
5
5
  export { buildMediaUploadForm, readOutboundImageMedia, resolveMediaBinary, type MediaBinary, type WecomMediaUploadResult, } from './media-upload.js';
6
6
  export { registerWecomWebhookRoutes, handleWecomVerificationRequest, handleWecomWebhookRequest, type WecomWebhookHandler, } from './webhook.js';
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
- export { buildSendRequestBody, decryptMessage, extractEncryptFromXml, formatInboundContent, formatOutboundBody, getAesKey, normalizeEchostrParam, normalizeWebhookPath, parseXmlMessage, queryParam, readTextBody, resolveChatType, resolveWecomConfig, verifySignature, } from './protocol.js';
2
- export { checkWecomPlatformPermit, normalizeWecomSenderForPermit, platformPermit, wecomGroupPermitResolver, } from './platform-permit.js';
1
+ export { buildSendRequestBody, decryptMessage, extractEncryptFromXml, formatInboundContent, formatOutboundBody, getAesKey, normalizeEchostrParam, normalizeWebhookPath, parseXmlMessage, queryParam, resolveChatType, resolveWecomConfig, verifySignature, } from './protocol.js';
2
+ export { platformPermit } from './platform-permit.js';
3
3
  export { WecomEndpoint, } from './endpoint.js';
4
4
  export { buildMediaUploadForm, readOutboundImageMedia, resolveMediaBinary, } from './media-upload.js';
5
5
  export { registerWecomWebhookRoutes, handleWecomVerificationRequest, handleWecomWebhookRequest, } from './webhook.js';
@@ -1,14 +1,7 @@
1
1
  /**
2
- * 企业微信 WeCom platform permit
2
+ * 企业微信 WeCom platform permit helper(ADR 0056 §5)。
3
+ *
4
+ * 平台身份由适配器上报到 `sender.platform`,permit 由内置评估器(`@zhin.js/permission`)判断;
5
+ * 适配器不再导出自有的 permit 解析器或检查函数。
3
6
  */
4
- import type { PermissionSubject } from '@zhin.js/permission';
5
7
  export declare function platformPermit(perm: string): string;
6
- export declare function wecomGroupPermitResolver(logicalPerm: string): string;
7
- export declare function normalizeWecomSenderForPermit(input: {
8
- isOwner?: boolean;
9
- isAdmin?: boolean;
10
- }): {
11
- role?: string;
12
- permissions?: string[];
13
- };
14
- export declare function checkWecomPlatformPermit(perm: string, subject: PermissionSubject): boolean;
@@ -1,33 +1,9 @@
1
- const ADAPTER = 'wecom';
1
+ /**
2
+ * 企业微信 WeCom platform permit helper(ADR 0056 §5)。
3
+ *
4
+ * 平台身份由适配器上报到 `sender.platform`,permit 由内置评估器(`@zhin.js/permission`)判断;
5
+ * 适配器不再导出自有的 permit 解析器或检查函数。
6
+ */
2
7
  export function platformPermit(perm) {
3
- return `platform(${ADAPTER},${perm})`;
4
- }
5
- const FACTORY_PERM_MAP = {
6
- scene_admin: 'chat_admin',
7
- scene_owner: 'chat_owner',
8
- };
9
- export function wecomGroupPermitResolver(logicalPerm) {
10
- return platformPermit(FACTORY_PERM_MAP[logicalPerm] ?? logicalPerm);
11
- }
12
- export function normalizeWecomSenderForPermit(input) {
13
- if (input.isOwner) {
14
- return { role: 'owner', permissions: ['chat_owner', 'chat_admin'] };
15
- }
16
- if (input.isAdmin) {
17
- return { role: 'admin', permissions: ['chat_admin'] };
18
- }
19
- return { role: 'member', permissions: [] };
20
- }
21
- export function checkWecomPlatformPermit(perm, subject) {
22
- const role = subject.sender?.role?.[0];
23
- const permissions = subject.sender?.permissions ?? [];
24
- const has = (t) => permissions.includes(t);
25
- switch (perm) {
26
- case 'chat_owner':
27
- return role === 'owner' || has('chat_owner');
28
- case 'chat_admin':
29
- return role === 'owner' || role === 'admin' || has('chat_admin') || has('chat_owner');
30
- default:
31
- return false;
32
- }
8
+ return `platform-permission:${perm}`;
33
9
  }
package/lib/protocol.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import type { EndpointProfileConfiguration } from 'zhin.js/adapter';
2
2
  import { type Locale } from 'zhin.js/i18n';
3
- import type { IncomingMessage } from 'node:http';
4
3
  import type { ConversationRef } from '@zhin.js/im-contract';
5
4
  /** One endpoint config after AdapterIndex expands `plugins.<instanceKey>.endpoints`. */
6
5
  export interface WecomEndpointConfig extends EndpointProfileConfiguration {
@@ -92,6 +91,3 @@ export declare function resolveChatType(fromUserName: string): 'group' | 'privat
92
91
  export declare function wecomInboundConversation(endpointKey: string, msg: WecomMessage): ConversationRef;
93
92
  export declare function formatOutboundBody(payload: unknown, locale?: Locale): WecomSendBody;
94
93
  export declare function buildSendRequestBody(targetId: string, content: WecomSendBody, agentId: string | number): Record<string, unknown>;
95
- export declare function readTextBody(request: IncomingMessage, options?: {
96
- readonly limit?: number;
97
- }): Promise<string>;
package/lib/protocol.js CHANGED
@@ -255,18 +255,3 @@ export function buildSendRequestBody(targetId, content, agentId) {
255
255
  }
256
256
  return body;
257
257
  }
258
- export async function readTextBody(request, options = {}) {
259
- const limit = options.limit ?? 1_048_576;
260
- const chunks = [];
261
- let size = 0;
262
- for await (const chunk of request) {
263
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
264
- size += buffer.length;
265
- if (size > limit) {
266
- request.destroy();
267
- throw new Error(`Request body exceeds ${limit} bytes`);
268
- }
269
- chunks.push(buffer);
270
- }
271
- return Buffer.concat(chunks).toString('utf8');
272
- }
package/lib/webhook.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  /**
2
2
  * WeCom webhook HTTP: URL verification (GET) + encrypted inbound (POST).
3
3
  */
4
- import type { IncomingMessage, ServerResponse } from 'node:http';
5
4
  import type { HttpHost, HttpRouteRegistration } from '@zhin.js/host-http';
6
5
  import { type ResolvedWecomConfig, type WecomMessage } from './protocol.js';
7
6
  export interface WecomWebhookHandler {
@@ -10,5 +9,5 @@ export interface WecomWebhookHandler {
10
9
  admit(msg: WecomMessage): void;
11
10
  }
12
11
  export declare function registerWecomWebhookRoutes(http: HttpHost, handler: WecomWebhookHandler): HttpRouteRegistration[];
13
- export declare function handleWecomVerificationRequest(_request: IncomingMessage, response: ServerResponse, url: URL, handler: WecomWebhookHandler): void;
14
- export declare function handleWecomWebhookRequest(request: IncomingMessage, response: ServerResponse, url: URL, handler: WecomWebhookHandler): Promise<void>;
12
+ export declare function handleWecomVerificationRequest(_request: Request, url: URL, handler: WecomWebhookHandler): Response;
13
+ export declare function handleWecomWebhookRequest(request: Request, url: URL, handler: WecomWebhookHandler): Promise<Response>;