@zhin.js/adapter-onebot12 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,148 @@
1
1
  # @zhin.js/adapter-onebot12
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
+ - 57c6cdc: fix: 全仓审计修复
12
+
13
+ - kernel: 模板求值沙箱不再泄漏宿主对象——宿主函数的返回值与抛出的错误会重新包裹代理(`segments.map(x=>x).constructor.constructor(...)` 之前可拿到宿主 `Function`),并禁止通过代理写入/删除宿主属性。
14
+ - agent: exec 白名单正则按整体锚定(`git|npm` 不再匹配 `gitevil`);SSRF 主机名黑名单识别尾点形式(`localhost.`);Docker 沙箱 `always` 模式的 fail-closed 分支可被触达;声明缺失的 `chalk` 依赖。
15
+ - ai: 摘要按最新优先加载(超过 500 条时不再使用过期锚点);修复 `test` 脚本指向不存在的配置。
16
+ - cli: `ZHIN_LOG_LEVEL` 生效(修复运算符优先级);移除旧守护进程遗留的无引用进程辅助函数。
17
+ - logger: `formatCompact` 不再把 `config: 'yaml'`、`direction: 'in'` 这类非路径值改写成 `./yaml`。
18
+ - host-http: 未配置数据库时 `db:tables` 与有数据库时一致返回 `{ tables }`。
19
+ - a2a: 405 响应把 `Allow` 放进响应头。
20
+ - pagemanager: 内联进 `<script>` 的页面元数据转义 `<`。
21
+ - client: 事件历史请求失败时携带 HTTP 状态,token 失效可触发重新登录。
22
+ - scaffold-wizard / create-zhin-app: 修正适配器文档 URL 与模板里的 `@zhin.js/tool` 导入。
23
+ - adapter-wechat-mp: 签名比较改为常量时间。
24
+ - adapter-kook: 声明运行时依赖 `ws`。
25
+ - plugin-lottery: 遗漏值按最近一次出现计算;推送目标 schema 字段与实现一致(`endpointKey`)。
26
+ - plugin-code-runner: 语言校验改用自有属性判断。
27
+ - plugin-link-poster: 抓取前校验主机名白名单(修复 SSRF),超时覆盖响应体读取。
28
+ - 其余包:从 `files` 中移除不存在的目录。
29
+ - feature-kit / middleware: 修正 README 中层级错误的文档链接。
30
+
31
+ - e1fda87: fix: 按审计待审清单处理(安全、功能、清理)
32
+
33
+ **行为变更(升级前请阅读)**
34
+
35
+ - kernel / core / zhin.js:出站文本中的 `${…}` 不再用 `vm` 求值,只替换 `TemplateContext` 上能解析到值的属性路径(如 `${sender.name}`);表达式、函数调用、未知名字原样保留。整套 vm 沙箱(`evaluate` / `execute` / `compiler` / `getValueWithRuntime`)已移除。
36
+ - kernel / core / zhin.js:移除零引用的遗留导出——`Scheduler`、错误管理器与 `ZhinError` 子类、`compose`、`segment.from/toString`、AI 触发/准入函数、`@zhin.js/core/queue-im-field-contract`、`zhin.js/contexts`。
37
+ - agent:readonly 执行预设不再放行重定向、后台 `&`、进程替换、`find -delete/-exec`、`sed -i`、`sort -o`、`tee`、`xargs`、awk;curl/wget 校验每个 URL 与裸主机并识别更多上传参数;自定义 `execAllowlist` 中的只读命令带写入风险时改走审批。沙箱超时/取消会杀掉进程组或具名容器,默认镜像改为 `node:22-bookworm-slim` + `bash`。移除无生产调用的 `AuditLogger`、`AnomalyDetector`、旧 vision 回合等导出。
38
+ - ai:移除 `storage`、`FileStateCache`、`CostTracker`、`model-name-utils`、`./agent-step-checkpoint` 子路径、`ContextManager` 及旧压缩管线;延迟工具快照改为有界 LRU。
39
+ - 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 接管后不再自行退出。
40
+ - schedule:后台 reconcile 出错不再产生未处理 rejection(新增 `onStoreError`);启动途中 `stop()` 不再遗留定时器。
41
+ - schema:元组校验与 `safeParse`、JSON Schema 一致(空数组不通过,缺省的可选元组为 `undefined`)。
42
+ - client / contract:删除无后端路由的 agent-stream API、未使用的 `definePage` 与旧 PageManager 类型;`@zhin.js/contract` 不再依赖 `@zhin.js/ai`;客户端收到 401 会清除已保存的凭据;安装/更新/卸载 RPC 默认超时 120 秒。
43
+ - a2a:流式响应中途出错写入 SSE error 并结束;未配置 token 的非生产环境只接受本机请求;任务存储有上限与过期;Mailbox 凭据回退与生产环境缺密钥检查修复。
44
+ - speech:`provider: openai` 不再套用 Ollama 的默认 host/model;识别语言改为可配置,不再写死 `zh`。
45
+ - adapter-lark:支持 `encryptKey` 加密事件解密。adapter-github:Device Flow 可取消、带超时并回复失败原因。adapter-wecom / dingtalk:请求加超时并校验 HTTP 状态。adapter-weixin-ilink:输入关闭期间暂停轮询。adapter-milky:SSE 支持 CRLF、缓冲上限与空闲重连。adapter-onebot-events:好友删除通知改为 `notice.friend.decrease`。
46
+ - plugin-group-suite:`teachAllowRegex` 默认关闭,正则安全检查更严格。plugin-qrcode:改为本地生成,回复 data URL 图片。plugin-rss / short-url / link-poster:拒绝解析到内网的地址;rss 修复条目每周重复推送;short-url 的 Console 创建改为真实调用 is.gd。plugin-lottery:按 `historyLimit` 同步。
47
+
48
+ **其余**
49
+
50
+ - host-http:插件市场详情加缓存与包名校验,SSE 回放容忍背压。host-http-contract:新增 `readTextBody()`,九个适配器改用它。
51
+ - pagemanager:页面外壳 importmap 升级到 React 19.2.8 / react-router 7.12.0。console-contract:`definePage` 接受 `description` / `group` / `parent` / `fullWidth`。
52
+ - command:进度提示本地化,匹配不再重复拷贝消息段。runtime:源码监听降级后退避重试原生监听。
53
+ - html-renderer:删除未接线的 `aiTextAsImage`。create-zhin-app / scaffold-wizard:移除不起作用的"全局安装 CLI"与运行时选择提示。
54
+ - 依赖声明清理、发布清单不再携带解析不到的 `src` 目录、移除未使用的 Skill 挂载、README 与示例配置按当前实现更正。
55
+
56
+ - 120e225: 聊天角色(ADR 0056,2026-11-12 修订):zhin 角色 owner / admin / trusted 分四级、只来自授予;发言者的平台身份与机器人自身的平台身份是独立维度,命令、Agent 工具 / 技能、中间件与按钮按三条维度共用一个评估器过滤。升级说明见 docs/migrations/chat-roles.md。
57
+
58
+ - 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` 判断。
59
+ - @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` 删除。
60
+ - @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`,定义时报错并给出替代写法。
61
+ - @zhin.js/command(minor,破坏性):命令会话的发送者改为 `chatRole` / `platform`,不再从 metadata 读角色;`CONVERSATION_MANAGER_PERMIT` 改为 `admin`(平台群主不再自动满足);分发结果 `denied` 带 `denial`(第一条不满足的规则与原因);指令菜单只列出当前发送者在本会话可用的命令。
62
+ - @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`。
63
+ - @zhin.js/feature-kit:`OperationSession.sender` 改为 `chatRole` / `platform`。
64
+ - @zhin.js/im-contract:新增 `PlatformStanding`、`SelfStandingRequest`、`standingFromMemberRole`。
65
+ - @zhin.js/adapter:入站 sender 可带 `platform`;账号管理命令需要聊天角色 `owner`;`EndpointManagement` 新增可选 `inspectSelfStanding`,能力画像新增 `scene.selfStanding`(声明即须实现),`AdapterIndex.selfStanding` / `invalidateSelfStanding` 按会话缓存机器人自身身份。
66
+ - @zhin.js/middleware:入站中间件可声明 `permit`,不满足时跳过该中间件(机器人身份只读缓存)。
67
+ - @zhin.js/tool:定义工具时拒绝已移除的 permit 写法。
68
+ - @zhin.js/ai:注释更新。
69
+ - @zhin.js/console-protocol:`chat-roles.list|grant|revoke`(`iam.manage`);`ConsoleChatRoleSource` 只有 `grant`。
70
+ - @zhin.js/runtime:Host 配置 Schema 删除 `features.selfService.platformAdmins|roles|allowUsers`。
71
+ - @zhin.js/testing:伪造消息与 `PluginTestKit` 用 `sender.chatRole` 声明测试身份。
72
+ - @zhin.js/scaffold-wizard:ICQQ 向导不再写 `master`,完成后提示在 Console 账号「角色」页签或聊天 `角色 授予` 设置 owner。
73
+ - 适配器:配置 Schema 删除 `master` / `trusted`(以及预览版的 `roles`);群管理类工具同时声明发言者条件与机器人条件(如 `platform:admin` + `bot:admin`、`bot-permission:manage_roles`),NapCat / OneBot11 工具不再使用已移除的 `platform(adapter,…)` 写法。
74
+ - 插件:内容审核以 `inbound.bypass`(permit 列表,默认 `owner` 或 `platform:admin`)取代 `masters` / `inbound.bypassMasters`;群管、音乐、日历、地震、B 站、轮盘赌的权限改用 zhin 角色,订阅类命令只认 zhin `admin` / `owner`。
75
+
76
+ - c2bbdcf: Console 访问控制(ADR 0049):用户、角色、会话、API 令牌与审计日志存入项目数据库,每个 Console RPC、`/api` 路由与 Host 鉴权的 WebSocket 都按 `@zhin.js/console-protocol` 的权限表放行,未登记的一律拒绝。
77
+
78
+ **破坏性变更**
79
+
80
+ - `http.tokens` 与演示模式(`scope: demo` / `user`)删除;配置里仍有 `http.tokens` 时 Host 拒绝启动。Host 配置 Schema 同步删除该字段。
81
+ - `http.token` 变为初始化令牌:只在创建第一个所有者之前有效,之后在所有接口上被拒绝。
82
+ - 未在 `CONSOLE_WS_PERMISSIONS` 登记、又使用 Host 鉴权的插件 WebSocket 不再接受 Console 账号;插件自己的 WebSocket 应改用 `ws(path, { auth: 'protocol' })` 并自行校验凭据(新增 `verifyProtocolAccessToken`、`isLoopbackAddress`)。
83
+ - OneBot 11 / 12、NapCat、Milky 的反向 WebSocket 改为只认适配器自己的 `access_token`;未配置 `access_token` 时只接受本机回环连接。
84
+ - `zhin doctor --live` 等改从 `ZHIN_CONSOLE_TOKEN` 读取 API 令牌(仍兼容 `ZHIN_HTTP_TOKEN`)。
85
+
86
+ **迁移步骤**(详见文档「升级到 Console 访问控制」)
87
+
88
+ 1. 升级后用 `http.token` 打开 Console 初始化向导创建第一个所有者,或运行 `zhin console init`(脚本:`zhin console init --yes --owner <名> --password-stdin`)。
89
+ 2. 删除配置里的 `http.tokens`,在 Console「访问控制」里为原来的令牌持有人创建用户并绑定角色(`viewer` / `operator` / `admin`);演示环境改用 `viewer` 账号。
90
+ 3. 自动化在 Console 签发 API 令牌,放进 `ZHIN_CONSOLE_TOKEN`。
91
+ 4. 从其他机器或容器连接的反向 WebSocket endpoint 补上 `access_token`。
92
+ 5. 忘记密码或所有者被锁时,停下 Host,用 `zhin console user passwd|enable|create` 离线恢复。
93
+
94
+ MCP / A2A 的 Bearer 访问同样接受用户 API 令牌(分别需要 `mcp.access`、`a2a.access`)。适配器与插件文档同步改为账号与角色的说法。
95
+
96
+ - 5cd9d3d: HTTP 路由契约改为 Web 标准 `Request` / `Response`(ADR 0054 §2,B1.0)
97
+
98
+ - host-http-contract:路由处理函数签名改为 `(request, context) => Response`,`context` 提供 `url`、`params`、`principal`、`remoteAddress`;新增 `readBodyBytes` / `readTextBody` / `readJsonBody`(带大小上限,超限先读完再报 413)、`jsonResponse` / `emptyResponse`、带背压的 `createResponseStream`(SSE、大文件下载)与 `WsConnection`。契约不再引用 `node:http` / `ws`。
99
+ - host-http:Node 服务器移到 `@zhin.js/host-http/node`(`createHttpHost`),负责 Node 请求与 `Request` / `Response` 的互转;认证结果经 `context.principal` 传给路由,删除旧的按请求取主体的辅助函数;未预期的异常只返回通用错误信息,细节写日志。
100
+ - runtime、mcp、a2a、gateway、zhin.js、calendar 插件与各适配器的 Webhook / 反向 WebSocket 路由迁移到新契约,行为不变。
101
+
102
+ - Updated dependencies [53932e5]
103
+ - Updated dependencies [57c6cdc]
104
+ - Updated dependencies [e1fda87]
105
+ - Updated dependencies [4e8ba38]
106
+ - Updated dependencies [a9c7a13]
107
+ - Updated dependencies [120e225]
108
+ - Updated dependencies [c2bbdcf]
109
+ - Updated dependencies [c2bbdcf]
110
+ - Updated dependencies [63595fc]
111
+ - Updated dependencies [fd055d2]
112
+ - Updated dependencies [4e8ba38]
113
+ - Updated dependencies [cc7a5f9]
114
+ - Updated dependencies [4e8ba38]
115
+ - Updated dependencies [f8bf684]
116
+ - Updated dependencies [e0bc008]
117
+ - Updated dependencies [5cd9d3d]
118
+ - Updated dependencies [5cd9d3d]
119
+ - Updated dependencies [c2bbdcf]
120
+ - Updated dependencies [f8bf684]
121
+ - Updated dependencies [663473b]
122
+ - Updated dependencies [c606d51]
123
+ - Updated dependencies [5cd9d3d]
124
+ - Updated dependencies [d655ef0]
125
+ - Updated dependencies [1e54b1e]
126
+ - @zhin.js/adapter@1.1.33
127
+ - @zhin.js/core@1.2.0
128
+ - @zhin.js/logger@1.1.3
129
+ - @zhin.js/host-http@1.2.0
130
+ - @zhin.js/feature-kit@1.1.16
131
+ - @zhin.js/adapter-onebot-events@0.0.6
132
+ - @zhin.js/console-contract@1.1.6
133
+ - @zhin.js/im-contract@1.1.14
134
+ - @zhin.js/page@1.1.18
135
+
136
+ ## 1.1.26
137
+
138
+ ### Patch Changes
139
+
140
+ - 0d76a7c: Overhaul Console interactive workbenches, platform-specific adapter account onboarding/login flows, DeclarativePageView visual/interactive capabilities, and official utility plugin Console pages.
141
+ - Updated dependencies [0d76a7c]
142
+ - @zhin.js/adapter@1.1.32
143
+ - @zhin.js/adapter-onebot-events@0.0.5
144
+ - @zhin.js/core@1.1.60
145
+
3
146
  ## 1.1.25
4
147
 
5
148
  ### 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
@@ -94,15 +94,11 @@ WS、反向 WS 和 Webhook 都在进入原生 SDK 前过滤其他 bot 的事件
94
94
  - 事件:`type`(meta/message/notice/request)、`detail_type`、`message` 等,见 [事件](https://12.onebot.dev/connect/data-protocol/event/)。
95
95
  - 动作:`send_message`、`delete_message`、`get_status` 等,见 [动作请求](https://12.onebot.dev/connect/data-protocol/action-request/)。
96
96
 
97
- ## AI 工具
98
-
99
- 技能说明见 `skills/onebot12/SKILL.md`。
100
-
101
97
  ## 文档链接
102
98
 
103
99
  - [OneBot 12 标准](https://12.onebot.dev/)
104
100
  - [OneBot Connect WebSocket](https://12.onebot.dev/connect/communication/websocket/)
105
- - [适配器概览](https://zhin.js.org/essentials/adapters)
101
+ - [适配器概览](https://zhin.js.org/adapters/)
106
102
 
107
103
  ## Console 页面
108
104
 
@@ -112,7 +108,7 @@ WS、反向 WS 和 Webhook 都在进入原生 SDK 前过滤其他 bot 的事件
112
108
  - 经所属 Adapter 增删持久化账号、启停单个 Endpoint;凭据由 Host 加密仓储保存,不改启动 YAML 或 `.env`,不重启进程;
113
109
  - 如果适配器要求登录,页面会显示 LoginAssist 的扫码 / 滑块 / 设备确认待办;
114
110
 
115
- 读取需要 `onebot12:read`,写操作需要 `onebot12:write`;管理员 full token 不受限。页面里的「添加 endpoint」等价于原来的 `onebot12 endpoint add`。
111
+ 读取需要 `onebot12:read`(`read` 级别,内置角色 `viewer` 及以上都有);增删改账号等写操作需要 `onebot12:write`(`operate` 级别,`operator` 及以上都有,绑定到本适配器的角色也算),首次迁移还需管理员身份;全局所有者不受限,见[插件权限的级别](https://zhin.js.org/console/#插件权限的级别)。页面里的「添加 endpoint」等价于原来的 `onebot12 endpoint add`。
116
112
 
117
113
  ## 故障排查
118
114
 
@@ -126,3 +122,7 @@ WS、反向 WS 和 Webhook 都在进入原生 SDK 前过滤其他 bot 的事件
126
122
  ## 许可证
127
123
 
128
124
  MIT License
125
+
126
+ ## 成员身份
127
+
128
+ OneBot v12 消息事件不带发送者群角色,不上报 `sender.platform`,能力画像也不声明 `scene.platformStanding`。详见 [ADR 0056 §1](https://github.com/zhinjs/zhin/blob/main/docs/adr/0056-chat-roles.md)。
@@ -2,12 +2,70 @@ export const onebot12ConsoleSpec = {
2
2
  adapterKey: 'onebot12',
3
3
  adapterDisplayName: 'OneBot 12',
4
4
  fields: [
5
- { key: 'platform', required: true, description: 'Selected OneBot12 bot platform' },
6
- { key: 'userId', required: true, description: 'Selected OneBot12 bot user ID' },
7
- { key: 'url', description: 'OneBot 实现 WebSocket URL(connection: ws 必填)', descriptionI18n: { en: 'OneBot WebSocket URL (required for connection: ws)' } },
8
- { key: 'path', description: 'HTTP/WS 路径(webhook / reverse-wss)', descriptionI18n: { en: 'HTTP/WS path (webhook / reverse-wss)' } },
9
- { key: 'api_url', description: 'HTTP action 端点(connection: webhook 出站必填)', descriptionI18n: { en: 'HTTP action endpoint (required for outbound connection: webhook)' } },
10
- { key: 'access_token', env: true, description: 'OneBot access token' },
5
+ {
6
+ key: 'platform',
7
+ required: true,
8
+ label: '所属平台 (Platform)',
9
+ labelI18n: { en: 'Platform' },
10
+ group: '连接模式',
11
+ groupI18n: { en: 'Connection Mode' },
12
+ placeholder: 'qq / wechat / telegram',
13
+ description: 'OneBot 12 机器人所属平台标识',
14
+ descriptionI18n: { en: 'Selected OneBot12 bot platform' },
15
+ },
16
+ {
17
+ key: 'userId',
18
+ required: true,
19
+ label: '机器人用户 ID (user_id)',
20
+ labelI18n: { en: 'Bot User ID' },
21
+ group: '连接模式',
22
+ groupI18n: { en: 'Connection Mode' },
23
+ placeholder: '123456789',
24
+ description: 'OneBot 12 机器人在对应平台的用户 ID',
25
+ descriptionI18n: { en: 'Selected OneBot12 bot user ID' },
26
+ },
27
+ {
28
+ key: 'url',
29
+ label: '正向 WebSocket 地址',
30
+ labelI18n: { en: 'Forward WebSocket URL' },
31
+ group: '连接模式',
32
+ groupI18n: { en: 'Connection Mode' },
33
+ placeholder: 'ws://127.0.0.1:6700',
34
+ description: 'OneBot 实现 WebSocket URL(connection: ws 必填)',
35
+ descriptionI18n: { en: 'OneBot WebSocket URL (required for connection: ws)' },
36
+ },
37
+ {
38
+ key: 'path',
39
+ label: 'Webhook / 反向 WS 路径',
40
+ labelI18n: { en: 'Webhook / Reverse WS Path' },
41
+ group: '连接模式',
42
+ groupI18n: { en: 'Connection Mode' },
43
+ placeholder: '/onebot/v12/ws',
44
+ description: 'HTTP/WS 路径(webhook / reverse-wss)',
45
+ descriptionI18n: { en: 'HTTP/WS path (webhook / reverse-wss)' },
46
+ },
47
+ {
48
+ key: 'api_url',
49
+ label: 'HTTP Action 地址',
50
+ labelI18n: { en: 'HTTP Action URL' },
51
+ group: '连接模式',
52
+ groupI18n: { en: 'Connection Mode' },
53
+ placeholder: 'http://127.0.0.1:5700',
54
+ description: 'HTTP action 端点(connection: webhook 出站必填)',
55
+ descriptionI18n: { en: 'HTTP action endpoint (required for outbound connection: webhook)' },
56
+ },
57
+ {
58
+ key: 'access_token',
59
+ env: true,
60
+ label: 'Access Token (访问令牌)',
61
+ labelI18n: { en: 'Access Token' },
62
+ group: '安全认证',
63
+ groupI18n: { en: 'Authentication' },
64
+ placeholder: '与 OneBot 12 实现一致的 Token',
65
+ placeholderI18n: { en: 'Token matching OneBot 12 server config' },
66
+ description: 'OneBot 12 接口鉴权令牌(Access Token)',
67
+ descriptionI18n: { en: 'OneBot access token' },
68
+ },
11
69
  ],
12
70
  docsUrl: 'https://zhin.js.org/adapters/onebot12',
13
71
  readPermission: 'onebot12:read',
package/lib/webhook.d.ts CHANGED
@@ -1,3 +1,6 @@
1
+ /**
2
+ * OneBot12 HTTP webhook endpoint — POST inbound + api_url outbound.
3
+ */
1
4
  import { endpointSpec, type Endpoint, type EndpointSpecification } from 'zhin.js/adapter';
2
5
  import type { HttpHost } from '@zhin.js/host-http';
3
6
  import type { CapabilityId } from 'zhin.js';
package/lib/webhook.js CHANGED
@@ -1,6 +1,9 @@
1
1
  import { createOnebot12SelfProfile } from './self-profile.js';
2
2
  import { toCanonicalSegments } from '@zhin.js/core';
3
3
  import { acceptHttpIngress } from 'imhelper';
4
+ /**
5
+ * OneBot12 HTTP webhook endpoint — POST inbound + api_url outbound.
6
+ */
4
7
  import { createEndpointSpecification, endpointSpec, createRecallEndpointControl, } from 'zhin.js/adapter';
5
8
  import { formatCompact, getLogger } from '@zhin.js/logger';
6
9
  import { createOneBot12EndpointManagement } from './endpoint-management.js';
@@ -165,35 +168,27 @@ export class OneBot12WebhookEndpoint extends Onebot12Client {
165
168
  }
166
169
  #setupRoutes() {
167
170
  const path = this.#options.config.path;
168
- this.#routeReleases.push(this.#options.http.route('POST', path, async (request, response) => {
169
- await this.#handleWebhook(request, response);
170
- }, { summary: 'OneBot12 webhook callback', tags: ['onebot12'] }));
171
+ this.#routeReleases.push(this.#options.http.route('POST', path, (request) => this.#handleWebhook(request), { summary: 'OneBot12 webhook callback', tags: ['onebot12'] }));
171
172
  }
172
- async #handleWebhook(request, response) {
173
+ async #handleWebhook(request) {
173
174
  try {
174
175
  if (!verifyOneBotAccessToken(this.#options.config.access_token, request)) {
175
- response.writeHead(403, { 'Content-Type': 'application/json' });
176
- response.end(JSON.stringify({ message: 'Unauthorized' }));
177
- return;
176
+ return new Response(JSON.stringify({ message: 'Unauthorized' }), { status: 403, headers: { 'Content-Type': 'application/json' } });
178
177
  }
179
178
  if (!this.#open) {
180
- response.writeHead(200, { 'Content-Type': 'application/json' });
181
- response.end(JSON.stringify({ status: 'ok' }));
182
- return;
179
+ return new Response(JSON.stringify({ status: 'ok' }), { status: 200, headers: { 'Content-Type': 'application/json' } });
183
180
  }
184
- await acceptHttpIngress(request, response, event => {
181
+ const result = await acceptHttpIngress(request, undefined, event => {
185
182
  if (!matchesOneBot12Self(this.#options.config, event))
186
183
  return;
187
184
  void this[endpointSpec].events.run(() => this.ingest(event))
188
185
  .catch(error => this.#warnPlatformEvent(error));
189
186
  });
187
+ return new Response(JSON.stringify(result.body), { status: result.status, headers: result.headers });
190
188
  }
191
189
  catch (error) {
192
190
  logger.error('OneBot12 webhook error:', error);
193
- if (!response.headersSent) {
194
- response.writeHead(500, { 'Content-Type': 'application/json' });
195
- response.end(JSON.stringify({ message: 'Internal Server Error' }));
196
- }
191
+ return new Response(JSON.stringify({ message: 'Internal Server Error' }), { status: 500, headers: { 'Content-Type': 'application/json' } });
197
192
  }
198
193
  }
199
194
  }
package/lib/ws-types.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { WsConnection } from '@zhin.js/host-http';
1
2
  /** Minimal WS surface used by the endpoint (real `ws` or test mock). */
2
3
  export interface OneBot12WsSocket {
3
4
  readonly readyState: number;
@@ -10,3 +11,8 @@ export interface OneBot12WsCreateOptions {
10
11
  readonly headers?: Record<string, string>;
11
12
  }
12
13
  export declare const WS_OPEN = 1;
14
+ /**
15
+ * A Host reverse-WebSocket connection seen through the OneBot12WsSocket surface. Protocol
16
+ * keepalive (ping / pong) belongs to the Host transport, so `ping` is absent.
17
+ */
18
+ export declare function socketOfConnection(connection: WsConnection): OneBot12WsSocket;
package/lib/ws-types.js CHANGED
@@ -1 +1,32 @@
1
1
  export const WS_OPEN = 1;
2
+ /**
3
+ * A Host reverse-WebSocket connection seen through the OneBot12WsSocket surface. Protocol
4
+ * keepalive (ping / pong) belongs to the Host transport, so `ping` is absent.
5
+ */
6
+ export function socketOfConnection(connection) {
7
+ let readyState = 1;
8
+ connection.onClose(() => { readyState = 3; });
9
+ const subscriptions = new Map();
10
+ const off = (_event, listener) => {
11
+ subscriptions.get(listener)?.();
12
+ subscriptions.delete(listener);
13
+ };
14
+ return {
15
+ get readyState() { return readyState; },
16
+ send: (data) => connection.send(data),
17
+ close: (code, reason) => connection.close(code, reason),
18
+ on(event, listener) {
19
+ if (event === 'message') {
20
+ subscriptions.set(listener, connection.onMessage((data) => {
21
+ listener(typeof data === 'string' ? data : Buffer.from(data));
22
+ }));
23
+ }
24
+ else if (event === 'close') {
25
+ subscriptions.set(listener, connection.onClose((code, reason) => listener(code, reason)));
26
+ }
27
+ // 'error' surfaces as a close on a WsConnection; 'open' already happened.
28
+ },
29
+ off,
30
+ removeListener: off,
31
+ };
32
+ }
package/lib/wss-auth.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import type { IncomingMessage } from 'node:http';
2
- export declare function verifyOneBotAccessToken(accessToken: string | undefined, request: IncomingMessage): boolean;
1
+ import { type ProtocolAuthRequest } from '@zhin.js/host-http';
2
+ export declare function verifyOneBotAccessToken(accessToken: string | undefined, request: ProtocolAuthRequest): boolean;
package/lib/wss-auth.js CHANGED
@@ -1,16 +1,7 @@
1
+ import { verifyProtocolAccessToken } from '@zhin.js/host-http';
1
2
  export function verifyOneBotAccessToken(accessToken, request) {
3
+ // Webhook semantics: no configured token admits any caller (reverse sockets use verifyProtocolAccessToken).
2
4
  if (!accessToken)
3
5
  return true;
4
- const auth = request.headers.authorization ?? '';
5
- if (auth === `Bearer ${accessToken}`)
6
- return true;
7
- try {
8
- const url = new URL(request.url ?? '/', 'http://localhost');
9
- if (url.searchParams.get('access_token') === accessToken)
10
- return true;
11
- }
12
- catch {
13
- /* ignore */
14
- }
15
- return false;
6
+ return verifyProtocolAccessToken(accessToken, request);
16
7
  }
@@ -2,7 +2,7 @@
2
2
  * OneBot12 reverse WSS endpoint — accepts inbound WebSocket from OneBot implementation.
3
3
  */
4
4
  import { endpointSpec, type Endpoint, type EndpointSpecification } from 'zhin.js/adapter';
5
- import type { HttpHost } from '@zhin.js/host-http';
5
+ import { type HttpHost } from '@zhin.js/host-http';
6
6
  import type { CapabilityId } from 'zhin.js';
7
7
  import { type OneBot12WssConfig } from './protocol.js';
8
8
  import { Onebot12Client } from './client.js';
@@ -4,13 +4,14 @@ import { toCanonicalSegments } from '@zhin.js/core';
4
4
  * OneBot12 reverse WSS endpoint — accepts inbound WebSocket from OneBot implementation.
5
5
  */
6
6
  import { createEndpointSpecification, endpointSpec, createEndpointLifecycle, createRecallEndpointControl, } from 'zhin.js/adapter';
7
+ import { verifyProtocolAccessToken } from '@zhin.js/host-http';
7
8
  import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
8
9
  import { createOneBot12EndpointManagement } from './endpoint-management.js';
9
10
  import { buildSendMessageParams, matchesOneBot12Self, extractQuoteId, formatInboundContent, formatOutboundSegments, isBotMentioned, isMessageEvent, onebot12InboundConversation, senderNickname, senderUserId, uploadOneBot12MediaSegments, } from './protocol.js';
10
11
  import { receiveOneBot12SideEvent } from './side-event-dispatch.js';
11
12
  import { createOneBot12ContentPort } from './content-port.js';
12
13
  import { callOnebot12Client, readOnebot12Response, onebot12ClientOptions, forwardOnebot12ClientEvents, Onebot12Client } from './client.js';
13
- import { verifyOneBotAccessToken } from './wss-auth.js';
14
+ import { socketOfConnection } from './ws-types.js';
14
15
  import { createOneBot12Rpc } from './ws-transport.js';
15
16
  export class OneBot12WssEndpoint extends Onebot12Client {
16
17
  [endpointSpec];
@@ -67,15 +68,16 @@ export class OneBot12WssEndpoint extends Onebot12Client {
67
68
  if (this.#started)
68
69
  return;
69
70
  if (!this.#options.config.access_token) {
70
- // wss 模式未配 access_token 时任何连接都会被放行(verifyOneBotAccessToken 直接 return true)
71
+ // 未配 access_token 时只接受本机回环连接(verifyProtocolAccessToken)。
71
72
  this.#logger.warn(formatCompact({
72
73
  endpoint: this.#options.config.id,
73
74
  mode: 'wss',
74
75
  ok: false,
75
- error: 'missing access_token',
76
+ error: 'missing access_token: only loopback peers are accepted',
76
77
  }));
77
78
  }
78
- const handle = this.#options.http.ws(this.#options.config.path);
79
+ // The peer authenticates with this endpoint's own access_token, not a Console credential.
80
+ const handle = this.#options.http.ws(this.#options.config.path, { auth: 'protocol' });
79
81
  this.#wsRelease = handle.onConnection((connection) => {
80
82
  this.#connectionTask = this.#connectionTask
81
83
  .then(() => this.#acceptConnection(connection))
@@ -183,11 +185,11 @@ export class OneBot12WssEndpoint extends Onebot12Client {
183
185
  }));
184
186
  }
185
187
  async #acceptConnection(connection) {
186
- if (!verifyOneBotAccessToken(this.#options.config.access_token, connection.request)) {
187
- connection.socket.close(4003, 'Unauthorized');
188
+ if (!verifyProtocolAccessToken(this.#options.config.access_token, connection)) {
189
+ connection.close(4003, 'Unauthorized');
188
190
  return;
189
191
  }
190
- const socket = connection.socket;
192
+ const socket = socketOfConnection(connection);
191
193
  await this.#connectionLifecycle.stop();
192
194
  this.#rpc.disconnect('连接已替换');
193
195
  await this.#connectionLifecycle.start(async (lifecycleHandle) => {
@@ -229,7 +231,7 @@ export class OneBot12WssEndpoint extends Onebot12Client {
229
231
  this.#logger.debug(formatCompact({
230
232
  endpoint: this.#options.config.id,
231
233
  mode: 'wss',
232
- peer: connection.request.socket.remoteAddress,
234
+ peer: connection.remoteAddress,
233
235
  }));
234
236
  }
235
237
  #callAction(action, params) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/adapter-onebot12",
3
- "version": "1.1.25",
3
+ "version": "1.1.27",
4
4
  "description": "Zhin.js OneBot 12 adapter for Plugin Runtime (WebSocket client)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -19,7 +19,6 @@
19
19
  "schema.json",
20
20
  "src",
21
21
  "lib",
22
- "skills",
23
22
  "README.md",
24
23
  "CHANGELOG.md"
25
24
  ],
@@ -35,37 +34,36 @@
35
34
  "license": "MIT",
36
35
  "repository": {
37
36
  "type": "git",
38
- "url": "https://github.com/zhinjs/zhin",
37
+ "url": "git+https://github.com/zhinjs/zhin.git",
39
38
  "directory": "plugins/adapters/onebot12"
40
39
  },
41
40
  "dependencies": {
42
41
  "@imhelper/onebot-v12": "1.0.7",
43
42
  "imhelper": "1.0.7",
44
43
  "ws": "^8.21.1",
45
- "@zhin.js/adapter-onebot-events": "0.0.4",
46
- "@zhin.js/adapter": "1.1.31",
47
- "@zhin.js/console-contract": "1.1.5",
48
- "@zhin.js/core": "1.1.59",
49
- "@zhin.js/feature-kit": "1.1.15",
50
- "@zhin.js/host-http": "1.1.17",
51
- "@zhin.js/im-contract": "1.1.13",
52
- "@zhin.js/logger": "1.1.2",
53
- "@zhin.js/page": "1.1.17",
54
- "@zhin.js/skill": "1.1.16"
44
+ "@zhin.js/adapter-onebot-events": "0.0.6",
45
+ "@zhin.js/adapter": "1.1.33",
46
+ "@zhin.js/console-contract": "1.1.6",
47
+ "@zhin.js/core": "1.2.0",
48
+ "@zhin.js/feature-kit": "1.1.16",
49
+ "@zhin.js/host-http": "1.2.0",
50
+ "@zhin.js/im-contract": "1.1.14",
51
+ "@zhin.js/logger": "1.1.3",
52
+ "@zhin.js/page": "1.1.18"
55
53
  },
56
54
  "devDependencies": {
57
55
  "@types/node": "^26.1.2",
58
56
  "@types/ws": "^8.18.1",
59
57
  "typescript": "^6.0.3",
60
58
  "vitest": "^4.1.10",
61
- "@zhin.js/host-http": "1.1.17",
62
- "zhin.js": "1.1.24"
59
+ "@zhin.js/host-http": "1.2.0",
60
+ "zhin.js": "1.1.26"
63
61
  },
64
62
  "peerDependencies": {
65
- "@zhin.js/adapter": "^1.1.31",
66
- "@zhin.js/command": "^1.1.17",
67
- "@zhin.js/core": "^1.1.59",
68
- "zhin.js": "^1.1.24"
63
+ "@zhin.js/adapter": "^1.1.33",
64
+ "@zhin.js/command": "^1.2.0",
65
+ "@zhin.js/core": "^1.2.0",
66
+ "zhin.js": "^1.1.26"
69
67
  },
70
68
  "peerDependenciesMeta": {
71
69
  "@zhin.js/command": {
@@ -102,10 +100,6 @@
102
100
  "package": "@zhin.js/command",
103
101
  "api": "^1.0.0"
104
102
  },
105
- {
106
- "package": "@zhin.js/skill",
107
- "api": "^1.0.0"
108
- },
109
103
  {
110
104
  "package": "@zhin.js/page",
111
105
  "api": "^1.0.0"
@@ -116,6 +110,6 @@
116
110
  "scripts": {
117
111
  "build": "tsc",
118
112
  "clean": "rimraf lib",
119
- "test": "NODE_OPTIONS=--experimental-strip-types vitest run --root ../../.. plugins/adapters/onebot12/tests"
113
+ "test": "vitest run --root ../../.. plugins/adapters/onebot12/tests"
120
114
  }
121
115
  }
package/schema.json CHANGED
@@ -21,34 +21,6 @@
21
21
  "type": "number",
22
22
  "default": 30000
23
23
  },
24
- "master": {
25
- "type": [
26
- "string",
27
- "number"
28
- ],
29
- "description": "框架 master(platform user id;AI/工具权限、endpoint 管理)。endpoints[i].master 可逐项覆盖",
30
- "x-i18n": {
31
- "en": {
32
- "description": "Framework masters (platform user id; AI/tool permissions and endpoint management). endpoints[i].master can override this value."
33
- }
34
- }
35
- },
36
- "trusted": {
37
- "type": "array",
38
- "items": {
39
- "type": [
40
- "string",
41
- "number"
42
- ],
43
- "description": "Trusted platform user id"
44
- },
45
- "description": "框架 trusted 用户列表(弱于 master)。endpoints[i].trusted 可逐项追加",
46
- "x-i18n": {
47
- "en": {
48
- "description": "Framework trusted users, below master authority. endpoints[i].trusted can add users."
49
- }
50
- }
51
- },
52
24
  "endpoints": {
53
25
  "type": "array",
54
26
  "minItems": 1,
@@ -57,34 +29,6 @@
57
29
  "type": "object",
58
30
  "additionalProperties": false,
59
31
  "properties": {
60
- "master": {
61
- "type": [
62
- "string",
63
- "number"
64
- ],
65
- "description": "本 endpoint 的框架 master(platform user id);覆盖顶层 master",
66
- "x-i18n": {
67
- "en": {
68
- "description": "Framework masters for this endpoint (platform user id), overriding the top-level master list."
69
- }
70
- }
71
- },
72
- "trusted": {
73
- "type": "array",
74
- "items": {
75
- "type": [
76
- "string",
77
- "number"
78
- ],
79
- "description": "Trusted platform user id"
80
- },
81
- "description": "本 endpoint 的 trusted 列表",
82
- "x-i18n": {
83
- "en": {
84
- "description": "Trusted users for this endpoint."
85
- }
86
- }
87
- },
88
32
  "connection": {
89
33
  "type": "string",
90
34
  "enum": [
@@ -7,12 +7,70 @@ export const onebot12ConsoleSpec = {
7
7
  adapterKey: 'onebot12',
8
8
  adapterDisplayName: 'OneBot 12',
9
9
  fields: [
10
- { key: 'platform', required: true, description: 'Selected OneBot12 bot platform' },
11
- { key: 'userId', required: true, description: 'Selected OneBot12 bot user ID' },
12
- { key: 'url', description: 'OneBot 实现 WebSocket URL(connection: ws 必填)', descriptionI18n: { en: 'OneBot WebSocket URL (required for connection: ws)' } },
13
- { key: 'path', description: 'HTTP/WS 路径(webhook / reverse-wss)', descriptionI18n: { en: 'HTTP/WS path (webhook / reverse-wss)' } },
14
- { key: 'api_url', description: 'HTTP action 端点(connection: webhook 出站必填)', descriptionI18n: { en: 'HTTP action endpoint (required for outbound connection: webhook)' } },
15
- { key: 'access_token', env: true, description: 'OneBot access token' },
10
+ {
11
+ key: 'platform',
12
+ required: true,
13
+ label: '所属平台 (Platform)',
14
+ labelI18n: { en: 'Platform' },
15
+ group: '连接模式',
16
+ groupI18n: { en: 'Connection Mode' },
17
+ placeholder: 'qq / wechat / telegram',
18
+ description: 'OneBot 12 机器人所属平台标识',
19
+ descriptionI18n: { en: 'Selected OneBot12 bot platform' },
20
+ },
21
+ {
22
+ key: 'userId',
23
+ required: true,
24
+ label: '机器人用户 ID (user_id)',
25
+ labelI18n: { en: 'Bot User ID' },
26
+ group: '连接模式',
27
+ groupI18n: { en: 'Connection Mode' },
28
+ placeholder: '123456789',
29
+ description: 'OneBot 12 机器人在对应平台的用户 ID',
30
+ descriptionI18n: { en: 'Selected OneBot12 bot user ID' },
31
+ },
32
+ {
33
+ key: 'url',
34
+ label: '正向 WebSocket 地址',
35
+ labelI18n: { en: 'Forward WebSocket URL' },
36
+ group: '连接模式',
37
+ groupI18n: { en: 'Connection Mode' },
38
+ placeholder: 'ws://127.0.0.1:6700',
39
+ description: 'OneBot 实现 WebSocket URL(connection: ws 必填)',
40
+ descriptionI18n: { en: 'OneBot WebSocket URL (required for connection: ws)' },
41
+ },
42
+ {
43
+ key: 'path',
44
+ label: 'Webhook / 反向 WS 路径',
45
+ labelI18n: { en: 'Webhook / Reverse WS Path' },
46
+ group: '连接模式',
47
+ groupI18n: { en: 'Connection Mode' },
48
+ placeholder: '/onebot/v12/ws',
49
+ description: 'HTTP/WS 路径(webhook / reverse-wss)',
50
+ descriptionI18n: { en: 'HTTP/WS path (webhook / reverse-wss)' },
51
+ },
52
+ {
53
+ key: 'api_url',
54
+ label: 'HTTP Action 地址',
55
+ labelI18n: { en: 'HTTP Action URL' },
56
+ group: '连接模式',
57
+ groupI18n: { en: 'Connection Mode' },
58
+ placeholder: 'http://127.0.0.1:5700',
59
+ description: 'HTTP action 端点(connection: webhook 出站必填)',
60
+ descriptionI18n: { en: 'HTTP action endpoint (required for outbound connection: webhook)' },
61
+ },
62
+ {
63
+ key: 'access_token',
64
+ env: true,
65
+ label: 'Access Token (访问令牌)',
66
+ labelI18n: { en: 'Access Token' },
67
+ group: '安全认证',
68
+ groupI18n: { en: 'Authentication' },
69
+ placeholder: '与 OneBot 12 实现一致的 Token',
70
+ placeholderI18n: { en: 'Token matching OneBot 12 server config' },
71
+ description: 'OneBot 12 接口鉴权令牌(Access Token)',
72
+ descriptionI18n: { en: 'OneBot access token' },
73
+ },
16
74
  ] as readonly AdapterConsoleField[],
17
75
  docsUrl: 'https://zhin.js.org/adapters/onebot12',
18
76
  readPermission: 'onebot12:read',
package/src/webhook.ts CHANGED
@@ -4,7 +4,6 @@ import { acceptHttpIngress } from 'imhelper';
4
4
  /**
5
5
  * OneBot12 HTTP webhook endpoint — POST inbound + api_url outbound.
6
6
  */
7
- import type { IncomingMessage, ServerResponse } from 'node:http';
8
7
  import {
9
8
  createEndpointSpecification, endpointSpec,
10
9
  type Endpoint, type EndpointSpecification,
@@ -208,35 +207,27 @@ export class OneBot12WebhookEndpoint extends Onebot12Client implements Endpoint
208
207
  #setupRoutes(): void {
209
208
  const path = this.#options.config.path;
210
209
  this.#routeReleases.push(
211
- this.#options.http.route('POST', path, async (request, response) => {
212
- await this.#handleWebhook(request, response);
213
- }, { summary: 'OneBot12 webhook callback', tags: ['onebot12'] }),
210
+ this.#options.http.route('POST', path, (request) => this.#handleWebhook(request), { summary: 'OneBot12 webhook callback', tags: ['onebot12'] }),
214
211
  );
215
212
  }
216
213
 
217
- async #handleWebhook(request: IncomingMessage, response: ServerResponse): Promise<void> {
214
+ async #handleWebhook(request: Request): Promise<Response> {
218
215
  try {
219
216
  if (!verifyOneBotAccessToken(this.#options.config.access_token, request)) {
220
- response.writeHead(403, { 'Content-Type': 'application/json' });
221
- response.end(JSON.stringify({ message: 'Unauthorized' }));
222
- return;
217
+ return new Response(JSON.stringify({ message: 'Unauthorized' }), { status: 403, headers: { 'Content-Type': 'application/json' } });
223
218
  }
224
219
  if (!this.#open) {
225
- response.writeHead(200, { 'Content-Type': 'application/json' });
226
- response.end(JSON.stringify({ status: 'ok' }));
227
- return;
220
+ return new Response(JSON.stringify({ status: 'ok' }), { status: 200, headers: { 'Content-Type': 'application/json' } });
228
221
  }
229
- await acceptHttpIngress<OneBot12Event>(request, response, event => {
222
+ const result = await acceptHttpIngress<OneBot12Event>(request, undefined, event => {
230
223
  if (!matchesOneBot12Self(this.#options.config, event)) return;
231
224
  void this[endpointSpec].events.run(() => this.ingest(event as Parameters<Onebot12Client['ingest']>[0]))
232
225
  .catch(error => this.#warnPlatformEvent(error));
233
226
  });
227
+ return new Response(JSON.stringify(result.body), { status: result.status, headers: result.headers });
234
228
  } catch (error) {
235
229
  logger.error('OneBot12 webhook error:', error);
236
- if (!response.headersSent) {
237
- response.writeHead(500, { 'Content-Type': 'application/json' });
238
- response.end(JSON.stringify({ message: 'Internal Server Error' }));
239
- }
230
+ return new Response(JSON.stringify({ message: 'Internal Server Error' }), { status: 500, headers: { 'Content-Type': 'application/json' } });
240
231
  }
241
232
  }
242
233
  }
package/src/ws-types.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { WsConnection } from '@zhin.js/host-http';
2
+
1
3
 
2
4
  /** Minimal WS surface used by the endpoint (real `ws` or test mock). */
3
5
  export interface OneBot12WsSocket {
@@ -13,3 +15,34 @@ export interface OneBot12WsCreateOptions {
13
15
  }
14
16
 
15
17
  export const WS_OPEN = 1;
18
+
19
+ /**
20
+ * A Host reverse-WebSocket connection seen through the OneBot12WsSocket surface. Protocol
21
+ * keepalive (ping / pong) belongs to the Host transport, so `ping` is absent.
22
+ */
23
+ export function socketOfConnection(connection: WsConnection): OneBot12WsSocket {
24
+ let readyState = 1;
25
+ connection.onClose(() => { readyState = 3; });
26
+ const subscriptions = new Map<(...args: unknown[]) => void, () => void>();
27
+ const off = (_event: string, listener: (...args: unknown[]) => void): void => {
28
+ subscriptions.get(listener)?.();
29
+ subscriptions.delete(listener);
30
+ };
31
+ return {
32
+ get readyState() { return readyState; },
33
+ send: (data: string) => connection.send(data),
34
+ close: (code?: number, reason?: string) => connection.close(code, reason),
35
+ on(event: string, listener: (...args: unknown[]) => void) {
36
+ if (event === 'message') {
37
+ subscriptions.set(listener, connection.onMessage((data) => {
38
+ listener(typeof data === 'string' ? data : Buffer.from(data));
39
+ }));
40
+ } else if (event === 'close') {
41
+ subscriptions.set(listener, connection.onClose((code, reason) => listener(code, reason)));
42
+ }
43
+ // 'error' surfaces as a close on a WsConnection; 'open' already happened.
44
+ },
45
+ off,
46
+ removeListener: off,
47
+ } as OneBot12WsSocket;
48
+ }
package/src/wss-auth.ts CHANGED
@@ -1,17 +1,10 @@
1
- import type { IncomingMessage } from 'node:http';
1
+ import { verifyProtocolAccessToken, type ProtocolAuthRequest } from '@zhin.js/host-http';
2
2
 
3
3
  export function verifyOneBotAccessToken(
4
4
  accessToken: string | undefined,
5
- request: IncomingMessage,
5
+ request: ProtocolAuthRequest,
6
6
  ): boolean {
7
+ // Webhook semantics: no configured token admits any caller (reverse sockets use verifyProtocolAccessToken).
7
8
  if (!accessToken) return true;
8
- const auth = request.headers.authorization ?? '';
9
- if (auth === `Bearer ${accessToken}`) return true;
10
- try {
11
- const url = new URL(request.url ?? '/', 'http://localhost');
12
- if (url.searchParams.get('access_token') === accessToken) return true;
13
- } catch {
14
- /* ignore */
15
- }
16
- return false;
9
+ return verifyProtocolAccessToken(accessToken, request);
17
10
  }
@@ -14,7 +14,7 @@ import {
14
14
  type EndpointSendRequest,
15
15
  type PendingRpcRequest,
16
16
  } from 'zhin.js/adapter';
17
- import type { HttpHost, WsConnection } from '@zhin.js/host-http';
17
+ import { verifyProtocolAccessToken, type HttpHost, type WsConnection } from '@zhin.js/host-http';
18
18
  import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
19
19
  import type { CapabilityId } from 'zhin.js';
20
20
  import { createOneBot12EndpointManagement } from './endpoint-management.js';
@@ -36,8 +36,7 @@ import {
36
36
  import { receiveOneBot12SideEvent } from './side-event-dispatch.js';
37
37
  import { createOneBot12ContentPort } from './content-port.js';
38
38
  import { callOnebot12Client, readOnebot12Response, onebot12ClientOptions, forwardOnebot12ClientEvents, Onebot12Client } from './client.js';
39
- import { verifyOneBotAccessToken } from './wss-auth.js';
40
- import { type OneBot12WsSocket } from './ws-types.js';
39
+ import { socketOfConnection, type OneBot12WsSocket } from './ws-types.js';
41
40
  import { createOneBot12Rpc, type OneBot12Rpc } from './ws-transport.js';
42
41
 
43
42
  export interface OneBot12WssEndpointOptions {
@@ -102,15 +101,16 @@ export class OneBot12WssEndpoint extends Onebot12Client implements Endpoint {
102
101
  async #start(): Promise<void> {
103
102
  if (this.#started) return;
104
103
  if (!this.#options.config.access_token) {
105
- // wss 模式未配 access_token 时任何连接都会被放行(verifyOneBotAccessToken 直接 return true)
104
+ // 未配 access_token 时只接受本机回环连接(verifyProtocolAccessToken)。
106
105
  this.#logger.warn(formatCompact({
107
106
  endpoint: this.#options.config.id,
108
107
  mode: 'wss',
109
108
  ok: false,
110
- error: 'missing access_token',
109
+ error: 'missing access_token: only loopback peers are accepted',
111
110
  }));
112
111
  }
113
- const handle = this.#options.http.ws(this.#options.config.path);
112
+ // The peer authenticates with this endpoint's own access_token, not a Console credential.
113
+ const handle = this.#options.http.ws(this.#options.config.path, { auth: 'protocol' });
114
114
  this.#wsRelease = handle.onConnection((connection) => {
115
115
  this.#connectionTask = this.#connectionTask
116
116
  .then(() => this.#acceptConnection(connection))
@@ -221,11 +221,11 @@ export class OneBot12WssEndpoint extends Onebot12Client implements Endpoint {
221
221
  }
222
222
 
223
223
  async #acceptConnection(connection: WsConnection): Promise<void> {
224
- if (!verifyOneBotAccessToken(this.#options.config.access_token, connection.request)) {
225
- connection.socket.close(4003, 'Unauthorized');
224
+ if (!verifyProtocolAccessToken(this.#options.config.access_token, connection)) {
225
+ connection.close(4003, 'Unauthorized');
226
226
  return;
227
227
  }
228
- const socket = connection.socket as unknown as OneBot12WsSocket;
228
+ const socket = socketOfConnection(connection);
229
229
  await this.#connectionLifecycle.stop();
230
230
  this.#rpc.disconnect('连接已替换');
231
231
  await this.#connectionLifecycle.start(async (lifecycleHandle) => {
@@ -263,7 +263,7 @@ export class OneBot12WssEndpoint extends Onebot12Client implements Endpoint {
263
263
  this.#logger.debug(formatCompact({
264
264
  endpoint: this.#options.config.id,
265
265
  mode: 'wss',
266
- peer: connection.request.socket.remoteAddress,
266
+ peer: connection.remoteAddress,
267
267
  }));
268
268
  }
269
269