@zhin.js/adapter-wechat-mp 1.1.26 → 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 +109 -0
- package/LICENSE +21 -0
- package/README.md +2 -6
- package/lib/index.d.ts +1 -1
- package/lib/index.js +1 -1
- package/lib/protocol.d.ts +0 -4
- package/lib/protocol.js +9 -18
- package/lib/webhook.d.ts +2 -3
- package/lib/webhook.js +15 -33
- package/package.json +17 -22
- package/schema.json +0 -56
- package/src/index.ts +0 -1
- package/src/protocol.ts +10 -22
- package/src/webhook.ts +16 -38
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,114 @@
|
|
|
1
1
|
# @zhin.js/adapter-wechat-mp
|
|
2
2
|
|
|
3
|
+
## 1.1.27
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 57c6cdc: fix: 全仓审计修复
|
|
8
|
+
|
|
9
|
+
- kernel: 模板求值沙箱不再泄漏宿主对象——宿主函数的返回值与抛出的错误会重新包裹代理(`segments.map(x=>x).constructor.constructor(...)` 之前可拿到宿主 `Function`),并禁止通过代理写入/删除宿主属性。
|
|
10
|
+
- agent: exec 白名单正则按整体锚定(`git|npm` 不再匹配 `gitevil`);SSRF 主机名黑名单识别尾点形式(`localhost.`);Docker 沙箱 `always` 模式的 fail-closed 分支可被触达;声明缺失的 `chalk` 依赖。
|
|
11
|
+
- ai: 摘要按最新优先加载(超过 500 条时不再使用过期锚点);修复 `test` 脚本指向不存在的配置。
|
|
12
|
+
- cli: `ZHIN_LOG_LEVEL` 生效(修复运算符优先级);移除旧守护进程遗留的无引用进程辅助函数。
|
|
13
|
+
- logger: `formatCompact` 不再把 `config: 'yaml'`、`direction: 'in'` 这类非路径值改写成 `./yaml`。
|
|
14
|
+
- host-http: 未配置数据库时 `db:tables` 与有数据库时一致返回 `{ tables }`。
|
|
15
|
+
- a2a: 405 响应把 `Allow` 放进响应头。
|
|
16
|
+
- pagemanager: 内联进 `<script>` 的页面元数据转义 `<`。
|
|
17
|
+
- client: 事件历史请求失败时携带 HTTP 状态,token 失效可触发重新登录。
|
|
18
|
+
- scaffold-wizard / create-zhin-app: 修正适配器文档 URL 与模板里的 `@zhin.js/tool` 导入。
|
|
19
|
+
- adapter-wechat-mp: 签名比较改为常量时间。
|
|
20
|
+
- adapter-kook: 声明运行时依赖 `ws`。
|
|
21
|
+
- plugin-lottery: 遗漏值按最近一次出现计算;推送目标 schema 字段与实现一致(`endpointKey`)。
|
|
22
|
+
- plugin-code-runner: 语言校验改用自有属性判断。
|
|
23
|
+
- plugin-link-poster: 抓取前校验主机名白名单(修复 SSRF),超时覆盖响应体读取。
|
|
24
|
+
- 其余包:从 `files` 中移除不存在的目录。
|
|
25
|
+
- feature-kit / middleware: 修正 README 中层级错误的文档链接。
|
|
26
|
+
|
|
27
|
+
- e1fda87: fix: 按审计待审清单处理(安全、功能、清理)
|
|
28
|
+
|
|
29
|
+
**行为变更(升级前请阅读)**
|
|
30
|
+
|
|
31
|
+
- kernel / core / zhin.js:出站文本中的 `${…}` 不再用 `vm` 求值,只替换 `TemplateContext` 上能解析到值的属性路径(如 `${sender.name}`);表达式、函数调用、未知名字原样保留。整套 vm 沙箱(`evaluate` / `execute` / `compiler` / `getValueWithRuntime`)已移除。
|
|
32
|
+
- kernel / core / zhin.js:移除零引用的遗留导出——`Scheduler`、错误管理器与 `ZhinError` 子类、`compose`、`segment.from/toString`、AI 触发/准入函数、`@zhin.js/core/queue-im-field-contract`、`zhin.js/contexts`。
|
|
33
|
+
- agent:readonly 执行预设不再放行重定向、后台 `&`、进程替换、`find -delete/-exec`、`sed -i`、`sort -o`、`tee`、`xargs`、awk;curl/wget 校验每个 URL 与裸主机并识别更多上传参数;自定义 `execAllowlist` 中的只读命令带写入风险时改走审批。沙箱超时/取消会杀掉进程组或具名容器,默认镜像改为 `node:22-bookworm-slim` + `bash`。移除无生产调用的 `AuditLogger`、`AnomalyDetector`、旧 vision 回合等导出。
|
|
34
|
+
- ai:移除 `storage`、`FileStateCache`、`CostTracker`、`model-name-utils`、`./agent-step-checkpoint` 子路径、`ContextManager` 及旧压缩管线;延迟工具快照改为有界 LRU。
|
|
35
|
+
- 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 接管后不再自行退出。
|
|
36
|
+
- schedule:后台 reconcile 出错不再产生未处理 rejection(新增 `onStoreError`);启动途中 `stop()` 不再遗留定时器。
|
|
37
|
+
- schema:元组校验与 `safeParse`、JSON Schema 一致(空数组不通过,缺省的可选元组为 `undefined`)。
|
|
38
|
+
- client / contract:删除无后端路由的 agent-stream API、未使用的 `definePage` 与旧 PageManager 类型;`@zhin.js/contract` 不再依赖 `@zhin.js/ai`;客户端收到 401 会清除已保存的凭据;安装/更新/卸载 RPC 默认超时 120 秒。
|
|
39
|
+
- a2a:流式响应中途出错写入 SSE error 并结束;未配置 token 的非生产环境只接受本机请求;任务存储有上限与过期;Mailbox 凭据回退与生产环境缺密钥检查修复。
|
|
40
|
+
- speech:`provider: openai` 不再套用 Ollama 的默认 host/model;识别语言改为可配置,不再写死 `zh`。
|
|
41
|
+
- adapter-lark:支持 `encryptKey` 加密事件解密。adapter-github:Device Flow 可取消、带超时并回复失败原因。adapter-wecom / dingtalk:请求加超时并校验 HTTP 状态。adapter-weixin-ilink:输入关闭期间暂停轮询。adapter-milky:SSE 支持 CRLF、缓冲上限与空闲重连。adapter-onebot-events:好友删除通知改为 `notice.friend.decrease`。
|
|
42
|
+
- plugin-group-suite:`teachAllowRegex` 默认关闭,正则安全检查更严格。plugin-qrcode:改为本地生成,回复 data URL 图片。plugin-rss / short-url / link-poster:拒绝解析到内网的地址;rss 修复条目每周重复推送;short-url 的 Console 创建改为真实调用 is.gd。plugin-lottery:按 `historyLimit` 同步。
|
|
43
|
+
|
|
44
|
+
**其余**
|
|
45
|
+
|
|
46
|
+
- host-http:插件市场详情加缓存与包名校验,SSE 回放容忍背压。host-http-contract:新增 `readTextBody()`,九个适配器改用它。
|
|
47
|
+
- pagemanager:页面外壳 importmap 升级到 React 19.2.8 / react-router 7.12.0。console-contract:`definePage` 接受 `description` / `group` / `parent` / `fullWidth`。
|
|
48
|
+
- command:进度提示本地化,匹配不再重复拷贝消息段。runtime:源码监听降级后退避重试原生监听。
|
|
49
|
+
- html-renderer:删除未接线的 `aiTextAsImage`。create-zhin-app / scaffold-wizard:移除不起作用的"全局安装 CLI"与运行时选择提示。
|
|
50
|
+
- 依赖声明清理、发布清单不再携带解析不到的 `src` 目录、移除未使用的 Skill 挂载、README 与示例配置按当前实现更正。
|
|
51
|
+
|
|
52
|
+
- 120e225: 聊天角色(ADR 0056,2026-11-12 修订):zhin 角色 owner / admin / trusted 分四级、只来自授予;发言者的平台身份与机器人自身的平台身份是独立维度,命令、Agent 工具 / 技能、中间件与按钮按三条维度共用一个评估器过滤。升级说明见 docs/migrations/chat-roles.md。
|
|
53
|
+
|
|
54
|
+
- 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` 判断。
|
|
55
|
+
- @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` 删除。
|
|
56
|
+
- @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`,定义时报错并给出替代写法。
|
|
57
|
+
- @zhin.js/command(minor,破坏性):命令会话的发送者改为 `chatRole` / `platform`,不再从 metadata 读角色;`CONVERSATION_MANAGER_PERMIT` 改为 `admin`(平台群主不再自动满足);分发结果 `denied` 带 `denial`(第一条不满足的规则与原因);指令菜单只列出当前发送者在本会话可用的命令。
|
|
58
|
+
- @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`。
|
|
59
|
+
- @zhin.js/feature-kit:`OperationSession.sender` 改为 `chatRole` / `platform`。
|
|
60
|
+
- @zhin.js/im-contract:新增 `PlatformStanding`、`SelfStandingRequest`、`standingFromMemberRole`。
|
|
61
|
+
- @zhin.js/adapter:入站 sender 可带 `platform`;账号管理命令需要聊天角色 `owner`;`EndpointManagement` 新增可选 `inspectSelfStanding`,能力画像新增 `scene.selfStanding`(声明即须实现),`AdapterIndex.selfStanding` / `invalidateSelfStanding` 按会话缓存机器人自身身份。
|
|
62
|
+
- @zhin.js/middleware:入站中间件可声明 `permit`,不满足时跳过该中间件(机器人身份只读缓存)。
|
|
63
|
+
- @zhin.js/tool:定义工具时拒绝已移除的 permit 写法。
|
|
64
|
+
- @zhin.js/ai:注释更新。
|
|
65
|
+
- @zhin.js/console-protocol:`chat-roles.list|grant|revoke`(`iam.manage`);`ConsoleChatRoleSource` 只有 `grant`。
|
|
66
|
+
- @zhin.js/runtime:Host 配置 Schema 删除 `features.selfService.platformAdmins|roles|allowUsers`。
|
|
67
|
+
- @zhin.js/testing:伪造消息与 `PluginTestKit` 用 `sender.chatRole` 声明测试身份。
|
|
68
|
+
- @zhin.js/scaffold-wizard:ICQQ 向导不再写 `master`,完成后提示在 Console 账号「角色」页签或聊天 `角色 授予` 设置 owner。
|
|
69
|
+
- 适配器:配置 Schema 删除 `master` / `trusted`(以及预览版的 `roles`);群管理类工具同时声明发言者条件与机器人条件(如 `platform:admin` + `bot:admin`、`bot-permission:manage_roles`),NapCat / OneBot11 工具不再使用已移除的 `platform(adapter,…)` 写法。
|
|
70
|
+
- 插件:内容审核以 `inbound.bypass`(permit 列表,默认 `owner` 或 `platform:admin`)取代 `masters` / `inbound.bypassMasters`;群管、音乐、日历、地震、B 站、轮盘赌的权限改用 zhin 角色,订阅类命令只认 zhin `admin` / `owner`。
|
|
71
|
+
|
|
72
|
+
- 5cd9d3d: HTTP 路由契约改为 Web 标准 `Request` / `Response`(ADR 0054 §2,B1.0)
|
|
73
|
+
|
|
74
|
+
- host-http-contract:路由处理函数签名改为 `(request, context) => Response`,`context` 提供 `url`、`params`、`principal`、`remoteAddress`;新增 `readBodyBytes` / `readTextBody` / `readJsonBody`(带大小上限,超限先读完再报 413)、`jsonResponse` / `emptyResponse`、带背压的 `createResponseStream`(SSE、大文件下载)与 `WsConnection`。契约不再引用 `node:http` / `ws`。
|
|
75
|
+
- host-http:Node 服务器移到 `@zhin.js/host-http/node`(`createHttpHost`),负责 Node 请求与 `Request` / `Response` 的互转;认证结果经 `context.principal` 传给路由,删除旧的按请求取主体的辅助函数;未预期的异常只返回通用错误信息,细节写日志。
|
|
76
|
+
- runtime、mcp、a2a、gateway、zhin.js、calendar 插件与各适配器的 Webhook / 反向 WebSocket 路由迁移到新契约,行为不变。
|
|
77
|
+
|
|
78
|
+
- Updated dependencies [53932e5]
|
|
79
|
+
- Updated dependencies [57c6cdc]
|
|
80
|
+
- Updated dependencies [e1fda87]
|
|
81
|
+
- Updated dependencies [4e8ba38]
|
|
82
|
+
- Updated dependencies [a9c7a13]
|
|
83
|
+
- Updated dependencies [120e225]
|
|
84
|
+
- Updated dependencies [c2bbdcf]
|
|
85
|
+
- Updated dependencies [c2bbdcf]
|
|
86
|
+
- Updated dependencies [63595fc]
|
|
87
|
+
- Updated dependencies [fd055d2]
|
|
88
|
+
- Updated dependencies [4e8ba38]
|
|
89
|
+
- Updated dependencies [cc7a5f9]
|
|
90
|
+
- Updated dependencies [4e8ba38]
|
|
91
|
+
- Updated dependencies [f8bf684]
|
|
92
|
+
- Updated dependencies [e0bc008]
|
|
93
|
+
- Updated dependencies [5cd9d3d]
|
|
94
|
+
- Updated dependencies [5cd9d3d]
|
|
95
|
+
- Updated dependencies [c2bbdcf]
|
|
96
|
+
- Updated dependencies [f8bf684]
|
|
97
|
+
- Updated dependencies [663473b]
|
|
98
|
+
- Updated dependencies [c606d51]
|
|
99
|
+
- Updated dependencies [5cd9d3d]
|
|
100
|
+
- Updated dependencies [d655ef0]
|
|
101
|
+
- Updated dependencies [1e54b1e]
|
|
102
|
+
- @zhin.js/adapter@1.1.33
|
|
103
|
+
- @zhin.js/core@1.2.0
|
|
104
|
+
- @zhin.js/logger@1.1.3
|
|
105
|
+
- @zhin.js/host-http@1.2.0
|
|
106
|
+
- @zhin.js/feature-kit@1.1.16
|
|
107
|
+
- @zhin.js/console-contract@1.1.6
|
|
108
|
+
- @zhin.js/host-http-contract@1.2.0
|
|
109
|
+
- @zhin.js/im-contract@1.1.14
|
|
110
|
+
- @zhin.js/page@1.1.18
|
|
111
|
+
|
|
3
112
|
## 1.1.26
|
|
4
113
|
|
|
5
114
|
### 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/README.md
CHANGED
|
@@ -84,7 +84,7 @@ Runtime Host(`http`)须已 listen,Webhook 才可达。
|
|
|
84
84
|
|
|
85
85
|
新增仅保存,需手动启动;运行账号的普通配置更新只重连该账号。身份变化走明确替换,新账号不会继承旧 Session 或登录状态。账号凭据变化先按平台实际只读接口核验;平台无法核验时需明确替换。空白或遮蔽的密码不会覆盖既有密码。
|
|
86
86
|
|
|
87
|
-
读取需要 `wechat-mp:read
|
|
87
|
+
读取需要 `wechat-mp:read`(`read` 级别,内置角色 `viewer` 及以上都有),写入需要 `wechat-mp:write`(`operate` 级别,`operator` 及以上都有,绑定到本适配器的角色也算);首次迁移还需管理员身份,见[插件权限的级别](https://zhin.js.org/console/#插件权限的级别)。无持久化存储时管理操作不可用,提交结果未知时先刷新核实,不重复提交。
|
|
88
88
|
|
|
89
89
|
## 故障排查
|
|
90
90
|
|
|
@@ -96,14 +96,10 @@ Runtime Host(`http`)须已 listen,Webhook 才可达。
|
|
|
96
96
|
| `48001 api unauthorized` | 未认证订阅号无客服 API;保持默认 `replyMode: passive` |
|
|
97
97
|
| 加密模式报错 | `encodingAESKey`、`encrypt` 与公众平台「安全模式」设置一致 |
|
|
98
98
|
|
|
99
|
-
## AI 工具
|
|
100
|
-
|
|
101
|
-
技能说明见 `skills/wechat-mp/SKILL.md`。
|
|
102
|
-
|
|
103
99
|
## 文档链接
|
|
104
100
|
|
|
105
101
|
- [微信公众号适配器文档](https://zhin.js.org/adapters/wechat-mp)
|
|
106
|
-
- [适配器概览](https://zhin.js.org/
|
|
102
|
+
- [适配器概览](https://zhin.js.org/adapters/)
|
|
107
103
|
- [微信公众平台](https://mp.weixin.qq.com/)
|
|
108
104
|
|
|
109
105
|
## 许可证
|
package/lib/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { buildTextReply, computeSignatureHash, decryptEchostr, decryptMessage, encryptMessage, extractOutboundText, formatCustomerServiceBody, formatInboundContent, formatInboundId, isEncryptedEchostr, normalizeEchostrParam, parseXMLMessage, queryParam,
|
|
1
|
+
export { buildTextReply, computeSignatureHash, decryptEchostr, decryptMessage, encryptMessage, extractOutboundText, formatCustomerServiceBody, formatInboundContent, formatInboundId, isEncryptedEchostr, normalizeEchostrParam, parseXMLMessage, queryParam, resolveEventPassiveReply, resolveWeChatMpConfig, verifySignature, type ResolvedWeChatMpConfig, type TokenResponse, type WeChatAPIResponse, type WeChatMessage, type WeChatMpEndpointConfig, type WeChatWireSegment, } from './protocol.js';
|
|
2
2
|
export { getPassiveReplyCapture, recordPassiveReplyText, runWithPassiveReplyCapture, type PassiveReplyCapture, } from './passive-reply.js';
|
|
3
3
|
export { WeChatMpClient, type WeChatMpClientEventMap, type WeChatMpFetch, } from './client.js';
|
|
4
4
|
export { WeChatMpEndpoint, type WeChatMpEndpointOptions, } from './endpoint.js';
|
package/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { buildTextReply, computeSignatureHash, decryptEchostr, decryptMessage, encryptMessage, extractOutboundText, formatCustomerServiceBody, formatInboundContent, formatInboundId, isEncryptedEchostr, normalizeEchostrParam, parseXMLMessage, queryParam,
|
|
1
|
+
export { buildTextReply, computeSignatureHash, decryptEchostr, decryptMessage, encryptMessage, extractOutboundText, formatCustomerServiceBody, formatInboundContent, formatInboundId, isEncryptedEchostr, normalizeEchostrParam, parseXMLMessage, queryParam, resolveEventPassiveReply, resolveWeChatMpConfig, verifySignature, } from './protocol.js';
|
|
2
2
|
export { getPassiveReplyCapture, recordPassiveReplyText, runWithPassiveReplyCapture, } from './passive-reply.js';
|
|
3
3
|
export { WeChatMpClient, } from './client.js';
|
|
4
4
|
export { WeChatMpEndpoint, } from './endpoint.js';
|
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 WeChatMpEndpointConfig extends EndpointProfileConfiguration {
|
|
@@ -116,6 +115,3 @@ export declare function resolveEventPassiveReply(msg: WeChatMessage, locale?: Lo
|
|
|
116
115
|
export declare function formatCustomerServiceBody(target: string, payload: unknown): Record<string, unknown>;
|
|
117
116
|
/** Extract plain text from a rendered outbound payload (for passive XML). */
|
|
118
117
|
export declare function extractOutboundText(payload: unknown): string;
|
|
119
|
-
export declare function readTextBody(request: IncomingMessage, options?: {
|
|
120
|
-
readonly limit?: number;
|
|
121
|
-
}): Promise<string>;
|
package/lib/protocol.js
CHANGED
|
@@ -3,7 +3,7 @@ import { createMessages } from 'zhin.js/i18n';
|
|
|
3
3
|
* WeChat Official Account (MP) protocol helpers — no legacy Adapter/Endpoint.
|
|
4
4
|
* Canonicalization is owned by gateway/core before endpoint.send.
|
|
5
5
|
*/
|
|
6
|
-
import { createHash, createDecipheriv, createCipheriv, randomBytes } from 'node:crypto';
|
|
6
|
+
import { createHash, createDecipheriv, createCipheriv, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
7
7
|
import * as xml2js from 'xml2js';
|
|
8
8
|
export function resolveWeChatMpConfig(config) {
|
|
9
9
|
const id = requiredEndpointField(config.id, 'id');
|
|
@@ -59,7 +59,13 @@ export function verifySignature(token, params) {
|
|
|
59
59
|
const { signature, timestamp, nonce, echostr } = params;
|
|
60
60
|
if (!signature || !timestamp || !nonce)
|
|
61
61
|
return false;
|
|
62
|
-
return computeSignatureHash(token, { timestamp, nonce, echostr })
|
|
62
|
+
return safeEqualHex(computeSignatureHash(token, { timestamp, nonce, echostr }), signature);
|
|
63
|
+
}
|
|
64
|
+
/** Constant-time comparison for hex signatures (same approach as the other webhook adapters). */
|
|
65
|
+
function safeEqualHex(expected, actual) {
|
|
66
|
+
const a = Buffer.from(expected);
|
|
67
|
+
const b = Buffer.from(actual);
|
|
68
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
63
69
|
}
|
|
64
70
|
export function getAESKey(encodingAESKey) {
|
|
65
71
|
return Buffer.from(`${encodingAESKey}=`, 'base64');
|
|
@@ -107,7 +113,7 @@ export async function decryptMessage(encryptedXml, msgSignature, timestamp, nonc
|
|
|
107
113
|
const expected = createHash('sha1')
|
|
108
114
|
.update([token, timestamp, nonce, encrypt].sort().join(''))
|
|
109
115
|
.digest('hex');
|
|
110
|
-
if (expected
|
|
116
|
+
if (!safeEqualHex(expected, msgSignature)) {
|
|
111
117
|
throw new Error('msg_signature verification failed');
|
|
112
118
|
}
|
|
113
119
|
const aesKey = getAESKey(encodingAESKey);
|
|
@@ -337,18 +343,3 @@ export function extractOutboundText(payload) {
|
|
|
337
343
|
}
|
|
338
344
|
return parts.join('\n');
|
|
339
345
|
}
|
|
340
|
-
export async function readTextBody(request, options = {}) {
|
|
341
|
-
const limit = options.limit ?? 1_048_576;
|
|
342
|
-
const chunks = [];
|
|
343
|
-
let size = 0;
|
|
344
|
-
for await (const chunk of request) {
|
|
345
|
-
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
346
|
-
size += buffer.length;
|
|
347
|
-
if (size > limit) {
|
|
348
|
-
request.destroy();
|
|
349
|
-
throw new Error(`Request body exceeds ${limit} bytes`);
|
|
350
|
-
}
|
|
351
|
-
chunks.push(buffer);
|
|
352
|
-
}
|
|
353
|
-
return Buffer.concat(chunks).toString('utf8');
|
|
354
|
-
}
|
package/lib/webhook.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* WeChat MP webhook HTTP: URL verification + inbound message handling.
|
|
3
3
|
*/
|
|
4
|
-
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
5
4
|
import type { Locale } from 'zhin.js/i18n';
|
|
6
5
|
import type { HttpHost, HttpRouteRegistration } from '@zhin.js/host-http';
|
|
7
6
|
import type { CapabilityId } from 'zhin.js';
|
|
@@ -17,6 +16,6 @@ export interface WeChatMpWebhookHandler {
|
|
|
17
16
|
cacheReply?(msgId: string, replyXML: string): void;
|
|
18
17
|
}
|
|
19
18
|
export declare function registerWeChatMpWebhookRoutes(http: HttpHost, handler: WeChatMpWebhookHandler): HttpRouteRegistration[];
|
|
20
|
-
export declare function handleWeChatMpVerification(_request:
|
|
21
|
-
export declare function handleWeChatMpMessage(request:
|
|
19
|
+
export declare function handleWeChatMpVerification(_request: Request, url: URL, config: ResolvedWeChatMpConfig): Response;
|
|
20
|
+
export declare function handleWeChatMpMessage(request: Request, url: URL, handler: WeChatMpWebhookHandler): Promise<Response>;
|
|
22
21
|
export declare function collectPassiveReply(handler: WeChatMpWebhookHandler, wechatMsg: WeChatMessage, nativeEvent?: unknown): Promise<string>;
|
package/lib/webhook.js
CHANGED
|
@@ -1,19 +1,16 @@
|
|
|
1
|
+
import { readTextBody } from '@zhin.js/host-http-contract';
|
|
1
2
|
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
2
3
|
import { getPassiveReplyCapture, runWithPassiveReplyCapture, } from './passive-reply.js';
|
|
3
|
-
import { buildTextReply, computeSignatureHash, decryptEchostr, decryptMessage, encryptMessage, isEncryptedEchostr, normalizeEchostrParam, parseXMLMessage, queryParam,
|
|
4
|
+
import { buildTextReply, computeSignatureHash, decryptEchostr, decryptMessage, encryptMessage, isEncryptedEchostr, normalizeEchostrParam, parseXMLMessage, queryParam, resolveEventPassiveReply, verifySignature, wechatMpInboundConversation, } from './protocol.js';
|
|
4
5
|
const logger = getLogger('wechat-mp');
|
|
5
6
|
export function registerWeChatMpWebhookRoutes(http, handler) {
|
|
6
7
|
const path = handler.config.path;
|
|
7
8
|
return [
|
|
8
|
-
http.route('GET', path, (request,
|
|
9
|
-
|
|
10
|
-
}, { summary: 'WeChat MP URL verification', tags: ['wechat-mp'] }),
|
|
11
|
-
http.route('POST', path, async (request, response, url) => {
|
|
12
|
-
await handleWeChatMpMessage(request, response, url, handler);
|
|
13
|
-
}, { summary: 'WeChat MP inbound webhook', tags: ['wechat-mp'] }),
|
|
9
|
+
http.route('GET', path, (request, { url }) => handleWeChatMpVerification(request, url, handler.config), { summary: 'WeChat MP URL verification', tags: ['wechat-mp'] }),
|
|
10
|
+
http.route('POST', path, (request, { url }) => handleWeChatMpMessage(request, url, handler), { summary: 'WeChat MP inbound webhook', tags: ['wechat-mp'] }),
|
|
14
11
|
];
|
|
15
12
|
}
|
|
16
|
-
export function handleWeChatMpVerification(_request,
|
|
13
|
+
export function handleWeChatMpVerification(_request, url, config) {
|
|
17
14
|
const signature = queryParam(url.searchParams.get('signature'));
|
|
18
15
|
const msgSignature = queryParam(url.searchParams.get('msg_signature'));
|
|
19
16
|
const timestamp = queryParam(url.searchParams.get('timestamp'));
|
|
@@ -25,9 +22,7 @@ export function handleWeChatMpVerification(_request, response, url, config) {
|
|
|
25
22
|
? { signature: msgSignature, timestamp, nonce, echostr }
|
|
26
23
|
: { signature, timestamp, nonce };
|
|
27
24
|
if (!signToCheck || !timestamp || !nonce) {
|
|
28
|
-
|
|
29
|
-
response.end('Forbidden');
|
|
30
|
-
return;
|
|
25
|
+
return new Response('Forbidden', { status: 403, headers: { 'Content-Type': 'text/plain' } });
|
|
31
26
|
}
|
|
32
27
|
if (!verifySignature(config.token, signPayload)) {
|
|
33
28
|
const expected = computeSignatureHash(config.token, {
|
|
@@ -42,9 +37,7 @@ export function handleWeChatMpVerification(_request, response, url, config) {
|
|
|
42
37
|
expectedPrefix: expected.slice(0, 8),
|
|
43
38
|
gotPrefix: signToCheck.slice(0, 8),
|
|
44
39
|
}));
|
|
45
|
-
|
|
46
|
-
response.end('Forbidden');
|
|
47
|
-
return;
|
|
40
|
+
return new Response('Forbidden', { status: 403, headers: { 'Content-Type': 'text/plain' } });
|
|
48
41
|
}
|
|
49
42
|
let body = echostr;
|
|
50
43
|
if (secureMode && echostr && isEncryptedEchostr(echostr) && config.encodingAESKey) {
|
|
@@ -58,15 +51,12 @@ export function handleWeChatMpVerification(_request, response, url, config) {
|
|
|
58
51
|
ok: false,
|
|
59
52
|
error: error instanceof Error ? error.message : String(error),
|
|
60
53
|
}));
|
|
61
|
-
|
|
62
|
-
response.end('Forbidden');
|
|
63
|
-
return;
|
|
54
|
+
return new Response('Forbidden', { status: 403, headers: { 'Content-Type': 'text/plain' } });
|
|
64
55
|
}
|
|
65
56
|
}
|
|
66
|
-
|
|
67
|
-
response.end(body);
|
|
57
|
+
return new Response(body, { status: 200, headers: { 'Content-Type': 'text/plain' } });
|
|
68
58
|
}
|
|
69
|
-
export async function handleWeChatMpMessage(request,
|
|
59
|
+
export async function handleWeChatMpMessage(request, url, handler) {
|
|
70
60
|
try {
|
|
71
61
|
const config = handler.config;
|
|
72
62
|
const signature = queryParam(url.searchParams.get('signature'));
|
|
@@ -76,9 +66,7 @@ export async function handleWeChatMpMessage(request, response, url, handler) {
|
|
|
76
66
|
const encryptType = queryParam(url.searchParams.get('encrypt_type'));
|
|
77
67
|
if (!verifySignature(config.token, { signature, timestamp, nonce })) {
|
|
78
68
|
logger.error('Invalid signature');
|
|
79
|
-
|
|
80
|
-
response.end('Forbidden');
|
|
81
|
-
return;
|
|
69
|
+
return new Response('Forbidden', { status: 403, headers: { 'Content-Type': 'text/plain' } });
|
|
82
70
|
}
|
|
83
71
|
let xmlString = await readTextBody(request);
|
|
84
72
|
if (config.encrypt && encryptType === 'aes' && config.encodingAESKey) {
|
|
@@ -86,9 +74,7 @@ export async function handleWeChatMpMessage(request, response, url, handler) {
|
|
|
86
74
|
}
|
|
87
75
|
const wechatMessage = await parseXMLMessage(xmlString);
|
|
88
76
|
if (!wechatMessage) {
|
|
89
|
-
|
|
90
|
-
response.end('success');
|
|
91
|
-
return;
|
|
77
|
+
return new Response('success', { status: 200, headers: { 'Content-Type': 'text/plain' } });
|
|
92
78
|
}
|
|
93
79
|
// 微信 5s 重推去重:同一 MsgId 直接回放首次回复,避免二次 admit。
|
|
94
80
|
const msgId = wechatMessage.MsgId;
|
|
@@ -96,9 +82,7 @@ export async function handleWeChatMpMessage(request, response, url, handler) {
|
|
|
96
82
|
const cached = handler.getCachedReply(msgId);
|
|
97
83
|
if (cached !== undefined) {
|
|
98
84
|
logger.debug(formatCompact({ op: 'wechat_mp_dedup_replay', msgId }));
|
|
99
|
-
|
|
100
|
-
response.end(cached || 'success');
|
|
101
|
-
return;
|
|
85
|
+
return new Response(cached || 'success', { status: 200, headers: { 'Content-Type': cached ? 'text/xml' : 'text/plain' } });
|
|
102
86
|
}
|
|
103
87
|
}
|
|
104
88
|
const locale = wechatMessage.MsgType === 'event' && wechatMessage.Event === 'subscribe'
|
|
@@ -123,13 +107,11 @@ export async function handleWeChatMpMessage(request, response, url, handler) {
|
|
|
123
107
|
if (msgId && handler.cacheReply) {
|
|
124
108
|
handler.cacheReply(msgId, replyXML || '');
|
|
125
109
|
}
|
|
126
|
-
|
|
127
|
-
response.end(replyXML || 'success');
|
|
110
|
+
return new Response(replyXML || 'success', { status: 200, headers: { 'Content-Type': 'text/xml' } });
|
|
128
111
|
}
|
|
129
112
|
catch (error) {
|
|
130
113
|
logger.error('Error handling WeChat message:', error);
|
|
131
|
-
|
|
132
|
-
response.end('success');
|
|
114
|
+
return new Response('success', { status: 200, headers: { 'Content-Type': 'text/plain' } });
|
|
133
115
|
}
|
|
134
116
|
}
|
|
135
117
|
export async function collectPassiveReply(handler, wechatMsg, nativeEvent) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhin.js/adapter-wechat-mp",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.27",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Zhin.js WeChat Official Account adapter for Plugin Runtime (HTTP webhook)",
|
|
6
6
|
"main": "./lib/index.js",
|
|
@@ -8,22 +8,22 @@
|
|
|
8
8
|
"dependencies": {
|
|
9
9
|
"axios": "^1.20.0",
|
|
10
10
|
"xml2js": "^0.6.2",
|
|
11
|
-
"@zhin.js/adapter": "1.1.
|
|
12
|
-
"@zhin.js/console-contract": "1.1.
|
|
13
|
-
"@zhin.js/core": "1.
|
|
14
|
-
"@zhin.js/feature-kit": "1.1.
|
|
15
|
-
"@zhin.js/host-http": "1.
|
|
16
|
-
"@zhin.js/
|
|
17
|
-
"@zhin.js/
|
|
18
|
-
"@zhin.js/
|
|
19
|
-
"@zhin.js/
|
|
11
|
+
"@zhin.js/adapter": "1.1.33",
|
|
12
|
+
"@zhin.js/console-contract": "1.1.6",
|
|
13
|
+
"@zhin.js/core": "1.2.0",
|
|
14
|
+
"@zhin.js/feature-kit": "1.1.16",
|
|
15
|
+
"@zhin.js/host-http": "1.2.0",
|
|
16
|
+
"@zhin.js/host-http-contract": "1.2.0",
|
|
17
|
+
"@zhin.js/im-contract": "1.1.14",
|
|
18
|
+
"@zhin.js/logger": "1.1.3",
|
|
19
|
+
"@zhin.js/page": "1.1.18"
|
|
20
20
|
},
|
|
21
21
|
"peerDependencies": {
|
|
22
|
-
"@zhin.js/adapter": "^1.1.
|
|
23
|
-
"@zhin.js/command": "^1.
|
|
24
|
-
"@zhin.js/core": "^1.
|
|
25
|
-
"@zhin.js/host-http": "^1.
|
|
26
|
-
"zhin.js": "^1.1.
|
|
22
|
+
"@zhin.js/adapter": "^1.1.33",
|
|
23
|
+
"@zhin.js/command": "^1.2.0",
|
|
24
|
+
"@zhin.js/core": "^1.2.0",
|
|
25
|
+
"@zhin.js/host-http": "^1.2.0",
|
|
26
|
+
"zhin.js": "^1.1.26"
|
|
27
27
|
},
|
|
28
28
|
"peerDependenciesMeta": {
|
|
29
29
|
"@zhin.js/command": {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"@types/xml2js": "^0.4.14",
|
|
39
39
|
"typescript": "^6.0.3",
|
|
40
40
|
"vitest": "^4.1.10",
|
|
41
|
-
"zhin.js": "1.1.
|
|
41
|
+
"zhin.js": "1.1.26"
|
|
42
42
|
},
|
|
43
43
|
"keywords": [
|
|
44
44
|
"zhin",
|
|
@@ -71,7 +71,6 @@
|
|
|
71
71
|
"schema.json",
|
|
72
72
|
"src",
|
|
73
73
|
"lib",
|
|
74
|
-
"skills",
|
|
75
74
|
"README.md",
|
|
76
75
|
"CHANGELOG.md"
|
|
77
76
|
],
|
|
@@ -103,10 +102,6 @@
|
|
|
103
102
|
"package": "@zhin.js/command",
|
|
104
103
|
"api": "^1.0.0"
|
|
105
104
|
},
|
|
106
|
-
{
|
|
107
|
-
"package": "@zhin.js/skill",
|
|
108
|
-
"api": "^1.0.0"
|
|
109
|
-
},
|
|
110
105
|
{
|
|
111
106
|
"package": "@zhin.js/page",
|
|
112
107
|
"api": "^1.0.0"
|
|
@@ -117,6 +112,6 @@
|
|
|
117
112
|
"scripts": {
|
|
118
113
|
"build": "tsc",
|
|
119
114
|
"clean": "rimraf lib",
|
|
120
|
-
"test": "
|
|
115
|
+
"test": "vitest run --root ../../.. plugins/adapters/wechat-mp/tests"
|
|
121
116
|
}
|
|
122
117
|
}
|
package/schema.json
CHANGED
|
@@ -32,34 +32,6 @@
|
|
|
32
32
|
"type": "number",
|
|
33
33
|
"default": 4500
|
|
34
34
|
},
|
|
35
|
-
"master": {
|
|
36
|
-
"type": [
|
|
37
|
-
"string",
|
|
38
|
-
"number"
|
|
39
|
-
],
|
|
40
|
-
"description": "框架 master(WeChat OpenID;AI/工具权限、endpoint 管理)。endpoints[i].master 可逐项覆盖",
|
|
41
|
-
"x-i18n": {
|
|
42
|
-
"en": {
|
|
43
|
-
"description": "Framework masters (WeChat OpenID; AI/tool permissions and endpoint management). endpoints[i].master can override this value."
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
},
|
|
47
|
-
"trusted": {
|
|
48
|
-
"type": "array",
|
|
49
|
-
"items": {
|
|
50
|
-
"type": [
|
|
51
|
-
"string",
|
|
52
|
-
"number"
|
|
53
|
-
],
|
|
54
|
-
"description": "Trusted WeChat OpenID"
|
|
55
|
-
},
|
|
56
|
-
"description": "框架 trusted 用户列表(弱于 master)。endpoints[i].trusted 可逐项追加",
|
|
57
|
-
"x-i18n": {
|
|
58
|
-
"en": {
|
|
59
|
-
"description": "Framework trusted users, below master authority. endpoints[i].trusted can add users."
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
},
|
|
63
35
|
"endpoints": {
|
|
64
36
|
"type": "array",
|
|
65
37
|
"minItems": 1,
|
|
@@ -68,34 +40,6 @@
|
|
|
68
40
|
"type": "object",
|
|
69
41
|
"additionalProperties": false,
|
|
70
42
|
"properties": {
|
|
71
|
-
"master": {
|
|
72
|
-
"type": [
|
|
73
|
-
"string",
|
|
74
|
-
"number"
|
|
75
|
-
],
|
|
76
|
-
"description": "本 endpoint 的框架 master(WeChat OpenID);覆盖顶层 master",
|
|
77
|
-
"x-i18n": {
|
|
78
|
-
"en": {
|
|
79
|
-
"description": "Framework masters for this endpoint (WeChat OpenID), overriding the top-level master list."
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
},
|
|
83
|
-
"trusted": {
|
|
84
|
-
"type": "array",
|
|
85
|
-
"items": {
|
|
86
|
-
"type": [
|
|
87
|
-
"string",
|
|
88
|
-
"number"
|
|
89
|
-
],
|
|
90
|
-
"description": "Trusted WeChat OpenID"
|
|
91
|
-
},
|
|
92
|
-
"description": "本 endpoint 的 trusted 列表",
|
|
93
|
-
"x-i18n": {
|
|
94
|
-
"en": {
|
|
95
|
-
"description": "Trusted users for this endpoint."
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
},
|
|
99
43
|
"appId": {
|
|
100
44
|
"type": "string",
|
|
101
45
|
"description": "WeChat MP app ID"
|
package/src/index.ts
CHANGED
package/src/protocol.ts
CHANGED
|
@@ -5,8 +5,7 @@ import { createMessages, type Locale } from 'zhin.js/i18n';
|
|
|
5
5
|
* Canonicalization is owned by gateway/core before endpoint.send.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import { createHash, createDecipheriv, createCipheriv, randomBytes } from 'node:crypto';
|
|
9
|
-
import type { IncomingMessage } from 'node:http';
|
|
8
|
+
import { createHash, createDecipheriv, createCipheriv, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
10
9
|
import * as xml2js from 'xml2js';
|
|
11
10
|
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
12
11
|
|
|
@@ -161,7 +160,14 @@ export function verifySignature(
|
|
|
161
160
|
): boolean {
|
|
162
161
|
const { signature, timestamp, nonce, echostr } = params;
|
|
163
162
|
if (!signature || !timestamp || !nonce) return false;
|
|
164
|
-
return computeSignatureHash(token, { timestamp, nonce, echostr })
|
|
163
|
+
return safeEqualHex(computeSignatureHash(token, { timestamp, nonce, echostr }), signature);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Constant-time comparison for hex signatures (same approach as the other webhook adapters). */
|
|
167
|
+
function safeEqualHex(expected: string, actual: string): boolean {
|
|
168
|
+
const a = Buffer.from(expected);
|
|
169
|
+
const b = Buffer.from(actual);
|
|
170
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
165
171
|
}
|
|
166
172
|
|
|
167
173
|
export function getAESKey(encodingAESKey: string): Buffer {
|
|
@@ -228,7 +234,7 @@ export async function decryptMessage(
|
|
|
228
234
|
const expected = createHash('sha1')
|
|
229
235
|
.update([token, timestamp, nonce, encrypt].sort().join(''))
|
|
230
236
|
.digest('hex');
|
|
231
|
-
if (expected
|
|
237
|
+
if (!safeEqualHex(expected, msgSignature)) {
|
|
232
238
|
throw new Error('msg_signature verification failed');
|
|
233
239
|
}
|
|
234
240
|
|
|
@@ -494,21 +500,3 @@ export function extractOutboundText(payload: unknown): string {
|
|
|
494
500
|
return parts.join('\n');
|
|
495
501
|
}
|
|
496
502
|
|
|
497
|
-
export async function readTextBody(
|
|
498
|
-
request: IncomingMessage,
|
|
499
|
-
options: { readonly limit?: number } = {},
|
|
500
|
-
): Promise<string> {
|
|
501
|
-
const limit = options.limit ?? 1_048_576;
|
|
502
|
-
const chunks: Buffer[] = [];
|
|
503
|
-
let size = 0;
|
|
504
|
-
for await (const chunk of request) {
|
|
505
|
-
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
506
|
-
size += buffer.length;
|
|
507
|
-
if (size > limit) {
|
|
508
|
-
request.destroy();
|
|
509
|
-
throw new Error(`Request body exceeds ${limit} bytes`);
|
|
510
|
-
}
|
|
511
|
-
chunks.push(buffer);
|
|
512
|
-
}
|
|
513
|
-
return Buffer.concat(chunks).toString('utf8');
|
|
514
|
-
}
|
package/src/webhook.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* WeChat MP webhook HTTP: URL verification + inbound message handling.
|
|
3
3
|
*/
|
|
4
|
-
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
5
4
|
import type { Locale } from 'zhin.js/i18n';
|
|
6
5
|
import type { HttpHost, HttpRouteRegistration } from '@zhin.js/host-http';
|
|
6
|
+
import { readTextBody } from '@zhin.js/host-http-contract';
|
|
7
7
|
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
8
8
|
import type { CapabilityId } from 'zhin.js';
|
|
9
9
|
import {
|
|
@@ -22,7 +22,6 @@ import {
|
|
|
22
22
|
normalizeEchostrParam,
|
|
23
23
|
parseXMLMessage,
|
|
24
24
|
queryParam,
|
|
25
|
-
readTextBody,
|
|
26
25
|
resolveEventPassiveReply,
|
|
27
26
|
verifySignature,
|
|
28
27
|
wechatMpInboundConversation,
|
|
@@ -49,21 +48,16 @@ export function registerWeChatMpWebhookRoutes(
|
|
|
49
48
|
): HttpRouteRegistration[] {
|
|
50
49
|
const path = handler.config.path;
|
|
51
50
|
return [
|
|
52
|
-
http.route('GET', path, (request,
|
|
53
|
-
|
|
54
|
-
}, { summary: 'WeChat MP URL verification', tags: ['wechat-mp'] }),
|
|
55
|
-
http.route('POST', path, async (request, response, url) => {
|
|
56
|
-
await handleWeChatMpMessage(request, response, url, handler);
|
|
57
|
-
}, { summary: 'WeChat MP inbound webhook', tags: ['wechat-mp'] }),
|
|
51
|
+
http.route('GET', path, (request, { url }) => handleWeChatMpVerification(request, url, handler.config), { summary: 'WeChat MP URL verification', tags: ['wechat-mp'] }),
|
|
52
|
+
http.route('POST', path, (request, { url }) => handleWeChatMpMessage(request, url, handler), { summary: 'WeChat MP inbound webhook', tags: ['wechat-mp'] }),
|
|
58
53
|
];
|
|
59
54
|
}
|
|
60
55
|
|
|
61
56
|
export function handleWeChatMpVerification(
|
|
62
|
-
_request:
|
|
63
|
-
response: ServerResponse,
|
|
57
|
+
_request: Request,
|
|
64
58
|
url: URL,
|
|
65
59
|
config: ResolvedWeChatMpConfig,
|
|
66
|
-
):
|
|
60
|
+
): Response {
|
|
67
61
|
const signature = queryParam(url.searchParams.get('signature'));
|
|
68
62
|
const msgSignature = queryParam(url.searchParams.get('msg_signature'));
|
|
69
63
|
const timestamp = queryParam(url.searchParams.get('timestamp'));
|
|
@@ -76,9 +70,7 @@ export function handleWeChatMpVerification(
|
|
|
76
70
|
: { signature, timestamp, nonce };
|
|
77
71
|
|
|
78
72
|
if (!signToCheck || !timestamp || !nonce) {
|
|
79
|
-
|
|
80
|
-
response.end('Forbidden');
|
|
81
|
-
return;
|
|
73
|
+
return new Response('Forbidden', { status: 403, headers: { 'Content-Type': 'text/plain' } });
|
|
82
74
|
}
|
|
83
75
|
|
|
84
76
|
if (!verifySignature(config.token, signPayload)) {
|
|
@@ -94,9 +86,7 @@ export function handleWeChatMpVerification(
|
|
|
94
86
|
expectedPrefix: expected.slice(0, 8),
|
|
95
87
|
gotPrefix: signToCheck.slice(0, 8),
|
|
96
88
|
}));
|
|
97
|
-
|
|
98
|
-
response.end('Forbidden');
|
|
99
|
-
return;
|
|
89
|
+
return new Response('Forbidden', { status: 403, headers: { 'Content-Type': 'text/plain' } });
|
|
100
90
|
}
|
|
101
91
|
|
|
102
92
|
let body = echostr;
|
|
@@ -110,22 +100,18 @@ export function handleWeChatMpVerification(
|
|
|
110
100
|
ok: false,
|
|
111
101
|
error: error instanceof Error ? error.message : String(error),
|
|
112
102
|
}));
|
|
113
|
-
|
|
114
|
-
response.end('Forbidden');
|
|
115
|
-
return;
|
|
103
|
+
return new Response('Forbidden', { status: 403, headers: { 'Content-Type': 'text/plain' } });
|
|
116
104
|
}
|
|
117
105
|
}
|
|
118
106
|
|
|
119
|
-
|
|
120
|
-
response.end(body);
|
|
107
|
+
return new Response(body, { status: 200, headers: { 'Content-Type': 'text/plain' } });
|
|
121
108
|
}
|
|
122
109
|
|
|
123
110
|
export async function handleWeChatMpMessage(
|
|
124
|
-
request:
|
|
125
|
-
response: ServerResponse,
|
|
111
|
+
request: Request,
|
|
126
112
|
url: URL,
|
|
127
113
|
handler: WeChatMpWebhookHandler,
|
|
128
|
-
): Promise<
|
|
114
|
+
): Promise<Response> {
|
|
129
115
|
try {
|
|
130
116
|
const config = handler.config;
|
|
131
117
|
const signature = queryParam(url.searchParams.get('signature'));
|
|
@@ -136,9 +122,7 @@ export async function handleWeChatMpMessage(
|
|
|
136
122
|
|
|
137
123
|
if (!verifySignature(config.token, { signature, timestamp, nonce })) {
|
|
138
124
|
logger.error('Invalid signature');
|
|
139
|
-
|
|
140
|
-
response.end('Forbidden');
|
|
141
|
-
return;
|
|
125
|
+
return new Response('Forbidden', { status: 403, headers: { 'Content-Type': 'text/plain' } });
|
|
142
126
|
}
|
|
143
127
|
|
|
144
128
|
let xmlString = await readTextBody(request);
|
|
@@ -157,9 +141,7 @@ export async function handleWeChatMpMessage(
|
|
|
157
141
|
|
|
158
142
|
const wechatMessage = await parseXMLMessage(xmlString);
|
|
159
143
|
if (!wechatMessage) {
|
|
160
|
-
|
|
161
|
-
response.end('success');
|
|
162
|
-
return;
|
|
144
|
+
return new Response('success', { status: 200, headers: { 'Content-Type': 'text/plain' } });
|
|
163
145
|
}
|
|
164
146
|
|
|
165
147
|
// 微信 5s 重推去重:同一 MsgId 直接回放首次回复,避免二次 admit。
|
|
@@ -168,9 +150,7 @@ export async function handleWeChatMpMessage(
|
|
|
168
150
|
const cached = handler.getCachedReply(msgId);
|
|
169
151
|
if (cached !== undefined) {
|
|
170
152
|
logger.debug(formatCompact({ op: 'wechat_mp_dedup_replay', msgId }));
|
|
171
|
-
|
|
172
|
-
response.end(cached || 'success');
|
|
173
|
-
return;
|
|
153
|
+
return new Response(cached || 'success', { status: 200, headers: { 'Content-Type': cached ? 'text/xml' : 'text/plain' } });
|
|
174
154
|
}
|
|
175
155
|
}
|
|
176
156
|
|
|
@@ -207,12 +187,10 @@ export async function handleWeChatMpMessage(
|
|
|
207
187
|
handler.cacheReply(msgId, replyXML || '');
|
|
208
188
|
}
|
|
209
189
|
|
|
210
|
-
|
|
211
|
-
response.end(replyXML || 'success');
|
|
190
|
+
return new Response(replyXML || 'success', { status: 200, headers: { 'Content-Type': 'text/xml' } });
|
|
212
191
|
} catch (error) {
|
|
213
192
|
logger.error('Error handling WeChat message:', error);
|
|
214
|
-
|
|
215
|
-
response.end('success');
|
|
193
|
+
return new Response('success', { status: 200, headers: { 'Content-Type': 'text/plain' } });
|
|
216
194
|
}
|
|
217
195
|
}
|
|
218
196
|
|