Compare commits

..

20 Commits
dev2 ... v1.8.2

Author SHA1 Message Date
snowluma-bot[bot]
71b0bda8f4 Merge pull request #44 from SnowLuma/dev
chore: promote dev → main (90884df)
2026-05-17 11:29:18 +00:00
墨梓柒
133cfc0c0e Merge pull request #40 from SnowLuma/revert/pr-38-c2c-video-sceneType
Revert "fix(send): keep c2c video compatQMsgSceneType at 2 (#38)"
2026-05-16 16:44:38 +08:00
DrSmoothl
b959783ded Revert "fix(send): keep c2c video compatQMsgSceneType at 2 (#38)"
This reverts commit 463e0ffb5d.
2026-05-16 14:54:56 +08:00
时瑾
463e0ffb5d fix(send): keep c2c video compatQMsgSceneType at 2 (#38)
Commit 29f28d6 changed c2c video `compatQmsgSceneType` from 2 to 1
as a "symmetric asymmetry" cleanup, matching the image/ptt convention
where the field tracks the upload's sceneType (c2c=1, group=2). For
video this is wrong.

Image and ptt have *different* legacy compat elements per scene
(notOnlineImage vs customFace; ptt c2c vs group), so the server needs
to know which scene shape to emit. The legacy `videoFile` element
(packet element type 19) has no scene split — fromChatType /
toChatType live inside the element itself — so the QQ NT server
emits a single group-shaped compat payload regardless. NapCat
hardcodes `compatQMsgSceneType: 2` for *both* UploadGroupVideo and
UploadPrivateVideo for exactly this reason.

Setting it to 1 on c2c made the server emit a c2c-scene shaped
compat blob that older QQ clients failed to resolve, showing the
message as "视频已过期" on those receivers. Newer clients only read
the commonElem(48, 11) and displayed fine — which is why only "some
devices" saw the breakage.

Keep `commonElem.businessType = isGroup ? 21 : 11` untouched — that
piece of 29f28d6 is still correct and is what fixed PbSendMsg
result=79.
2026-05-16 14:22:49 +08:00
snowluma-bot[bot]
9d55e86b1c Merge pull request #37 from SnowLuma/dev
chore: promote dev → main (7da52bc)
2026-05-15 23:18:33 +08:00
snowluma-bot[bot]
07449788c6 Merge pull request #36 from SnowLuma/dev
chore: promote dev → main (85b59bc)
2026-05-15 01:48:08 +08:00
snowluma-bot[bot]
fe4af70562 Merge pull request #34 from SnowLuma/dev
chore: promote dev → main (564eec2)
2026-05-14 20:50:46 +08:00
snowluma-bot[bot]
545a732385 Merge pull request #30 from SnowLuma/dev
chore: promote dev → main (ada591b)
2026-05-13 16:55:55 +08:00
snowluma-bot[bot]
c2f22d8daf Merge pull request #29 from SnowLuma/dev
chore: promote dev → main (6abde40)
2026-05-13 16:23:42 +08:00
snowluma-bot[bot]
9216b54427 Merge pull request #28 from SnowLuma/dev
chore: promote dev → main (1b2dd83)
2026-05-12 22:06:52 +08:00
snowluma-bot[bot]
fd9a239241 Merge pull request #27 from SnowLuma/dev
chore: promote dev → main (8636222)
2026-05-11 15:32:46 +00:00
snowluma-bot[bot]
5a4028d5dc Merge pull request #25 from SnowLuma/dev
chore: promote dev → main (6f6ce11)
2026-05-10 10:17:23 +08:00
snowluma-bot[bot]
d02e7cc3ab Merge pull request #23 from SnowLuma/dev
chore: promote dev → main (bec23c4)
2026-05-10 01:32:20 +08:00
snowluma-bot[bot]
9938545788 Merge pull request #21 from SnowLuma/dev
chore: promote dev → main (a7b3809)
2026-05-09 19:40:04 +08:00
snowluma-bot[bot]
7149bc8689 Merge pull request #20 from SnowLuma/dev
chore: promote dev → main (c39b3f5)
2026-05-09 19:33:40 +08:00
snowluma-bot[bot]
9802128421 Merge pull request #19 from SnowLuma/dev
chore: promote dev → main (2af273b)
2026-05-09 16:40:37 +08:00
墨梓柒
a572d05c25 Merge pull request #18 from SnowLuma/dependabot/npm_and_yarn/hono-4.12.18
build(deps-dev): bump hono from 4.12.14 to 4.12.18
2026-05-09 16:03:21 +08:00
dependabot[bot]
cb06624d12 build(deps-dev): bump hono from 4.12.14 to 4.12.18
Bumps [hono](https://github.com/honojs/hono) from 4.12.14 to 4.12.18.
- [Release notes](https://github.com/honojs/hono/releases)
- [Commits](https://github.com/honojs/hono/compare/v4.12.14...v4.12.18)

---
updated-dependencies:
- dependency-name: hono
  dependency-version: 4.12.18
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-09 08:01:11 +00:00
snowluma-bot[bot]
7b93839186 Merge pull request #17 from SnowLuma/dev
chore: promote dev → main (1565749)
2026-05-09 15:37:22 +08:00
snowluma-bot[bot]
d0085ec052 Merge pull request #15 from SnowLuma/dev
chore: promote dev → main (c3b328f)
2026-05-09 15:04:19 +08:00
522 changed files with 12766 additions and 34612 deletions

View File

@@ -1,15 +0,0 @@
root = true
[*]
charset = utf-8
end_of_line = crlf
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.{json,yml,yaml,md}]
indent_size = 2
[*.md]
trim_trailing_whitespace = false

View File

@@ -1,119 +0,0 @@
name: Bug 反馈
description: 报告一个可复现的问题
title: "[Bug] "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
感谢花时间反馈 Bug。请尽量填全以下信息,方便我们定位问题。
在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有相同问题。
- type: checkboxes
id: preflight
attributes:
label: 提交前检查
options:
- label: 我已搜索过 Issues,确认没有重复的反馈
required: true
- label: 我使用的是 [最新 Release](https://github.com/SnowLuma/SnowLuma/releases) 或当前 `dev` 分支构建
required: true
- type: input
id: snowluma-version
attributes:
label: SnowLuma 版本
description: 启动日志首行或 `package.json` 里的版本号
placeholder: "例如 1.8.5"
validations:
required: true
- type: dropdown
id: adapter
attributes:
label: 出问题的适配器
description: 可多选
multiple: true
options:
- WebSocket Server
- WebSocket Client
- HTTP Server
- HTTP Post
- WebUI
- Bridge / Core(协议层)
- 其他 / 不确定
validations:
required: true
- type: input
id: os
attributes:
label: 操作系统
placeholder: "例如 Windows 11 23H2 / macOS 14.5 / Ubuntu 22.04"
validations:
required: true
- type: input
id: node-version
attributes:
label: Node.js 版本
description: '`node -v` 的输出。如果使用预构建包可填"预构建包"'
placeholder: "例如 v20.11.0 或 预构建包"
validations:
required: true
- type: input
id: qq-version
attributes:
label: QQ 客户端版本
description: QQ NT 客户端的版本号
placeholder: "例如 9.9.15-29722"
- type: textarea
id: description
attributes:
label: 问题描述
description: 简要说明发生了什么
validations:
required: true
- type: textarea
id: reproduce
attributes:
label: 复现步骤
description: 详细列出如何触发这个问题
placeholder: |
1. 启动 SnowLuma 并登录账号 ...
2. 通过 HTTP Server 调用 `send_group_msg` ...
3. 观察到 ...
validations:
required: true
- type: textarea
id: expected
attributes:
label: 期望行为
validations:
required: true
- type: textarea
id: actual
attributes:
label: 实际行为
validations:
required: true
- type: textarea
id: logs
attributes:
label: 相关日志 / 错误堆栈
description: |
粘贴控制台日志、SSE 实时日志或错误堆栈。
请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
render: shell
- type: textarea
id: extra
attributes:
label: 补充信息
description: 配置片段(脱敏后)、截图、相关 Issue / PR 链接等

View File

@@ -1,11 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: QQ 群
url: https://qm.qq.com/q/g3UMLpWALe
about: 日常使用问题、快速交流可以先来 QQ 群
- name: Telegram
url: https://t.me/napcatqq
about: 海外用户交流频道
- name: Releases
url: https://github.com/SnowLuma/SnowLuma/releases
about: 在反馈 Bug 前,请先确认已使用最新发布版本

View File

@@ -1,76 +0,0 @@
name: 功能请求
description: 提议一个新功能或对现有功能的增强
title: "[Feature] "
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
感谢您的建议。在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有类似提案。
- type: checkboxes
id: preflight
attributes:
label: 提交前检查
options:
- label: 我已搜索过 Issues,确认没有重复的提案
required: true
- type: dropdown
id: scope
attributes:
label: 涉及范围
multiple: true
options:
- OneBot 协议 / 消息段
- WebSocket Server / Client 适配器
- HTTP Server / Post 适配器
- WebUI 管理面板
- SDK (`@snowluma/sdk`)
- UI 组件 (`@snowluma/ui`)
- Bridge / Core(协议层)
- 构建 / 发布流程
- 文档
- 其他
validations:
required: true
- type: textarea
id: problem
attributes:
label: 需求场景 / 当前痛点
description: 这个功能要解决什么问题?目前是如何变通处理的?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: 期望方案
description: 您希望它如何工作?如果是 API 改动,建议给出示例输入 / 输出
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: 已考虑的替代方案
description: 还想过哪些其他实现路径,为什么放弃
- type: textarea
id: references
attributes:
label: 参考链接
description: 例如 OneBot 规范条目、其他实现的对应特性、相关 Issue / PR
placeholder: |
- OneBot v11 规范: https://github.com/botuniverse/onebot-11/...
- 相关讨论: #xxx
- type: checkboxes
id: willingness
attributes:
label: 您是否愿意提交 PR 来实现这个功能?
options:
- label: 愿意,且需要维护者讨论方案后再动手
- label: 愿意,已有大致实现思路
- label: 暂时只提建议

View File

@@ -110,6 +110,10 @@ jobs:
SNOWLUMA_TARGET: ${{ matrix.target }}
run: pnpm run build:all
- name: Bundle runtime dependencies
working-directory: dist
run: npm install --omit=dev
# Naming convention:
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22

1
.gitignore vendored
View File

@@ -11,7 +11,6 @@ dist/
/config/
/data/
logs/
# macOS metadata
.DS_Store

133
README.md
View File

@@ -1,131 +1,22 @@
<h1 align="center">❄️ SnowLuma</h1>
# ❄️ SnowLuma
> Next Remote Protocol Framework.
<p align="center">
<i>Next Remote Protocol Framework.</i>
</p>
<p align="center">
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="Release" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
<a href="https://github.com/SnowLuma/SnowLuma/actions"><img alt="Build" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/release.yml?branch=main&style=flat-square&label=build"></a>
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="@snowluma/sdk" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=%40snowluma%2Fsdk&color=cb3837"></a>
<a href="https://www.npmjs.com/package/@snowluma/ui"><img alt="@snowluma/ui" src="https://img.shields.io/npm/v/%40snowluma%2Fui?style=flat-square&label=%40snowluma%2Fui&color=cb3837"></a>
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
</p>
<p align="center">
<a href="https://github.com/SnowLuma/SnowLuma/releases">Releases</a> ·
<a href="https://github.com/SnowLuma/SnowLuma/issues">Issues</a> ·
<a href="https://qm.qq.com/q/g3UMLpWALe">QQ 群</a> ·
<a href="https://t.me/napcatqq">Telegram</a>
</p>
---
## 简介
SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。
项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。
## 特性
- **OneBot v11 兼容** —— 涵盖文本、图片、视频、语音、合并转发、戳一戳、Markdown、JSON、XML 等常用消息段。
- **多账号并行** —— 同一进程可同时托管多个 QQ 账号,会话彼此独立。
- **多种适配器** —— WebSocket Server / WebSocket Client / HTTP Server / HTTP Post,HTTP 服务端同时支持 `application/json` 与 `application/x-www-form-urlencoded`。
- **WebUI 管理面板** —— 浏览器登录、密码强度校验、登录限流、SSE 实时日志、配置热更新。
- **TypeScript 全链路** —— Bridge / OneBot / SDK / UI 均使用 TypeScript,发布到 npm 的 `@snowluma/sdk` 与 `@snowluma/ui` 可直接供下游应用消费。
- **数据持久化** —— 好友、群、群成员等关系数据落 SQLite,跨重启可用。
## 快速开始
下载预构建发布包:
```bash
# 从 Releases 下载 zip,解压到任意目录
./launcher.bat # Windows
```
或从源码开发:
```bash
git clone https://github.com/SnowLuma/SnowLuma.git
cd SnowLuma
pnpm install
pnpm build
pnpm start
```
WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial credentials: user=admin password=<...>`,登录后请立即修改。
若未完成首次改密就关闭进程,下次启动会自动重新生成一个新的随机密码。
## 工作区
本仓库使用 pnpm monorepo 管理,各包职责如下:
| 包 | 说明 |
| --- | --- |
| [`@snowluma/core`](packages/core) | 核心:协议层 / Bridge / OneBot / WebUI 全部在此。 |
| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 |
| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 |
| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 |
| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb<N, T>`,Vite 插件在构建时把 `protobuf_encode<T>` / `protobuf_decode<T>` 替换为内联 codec,零运行时反射。 |
| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 |
| [`webui`](packages/webui) | Web 管理面板前端。 |
## 架构
```mermaid
flowchart TD
A([QQ 客户端])
B["协议层<br/><sub>packet pipeline · cmd 分派</sub>"]
C["Bridge 层<br/><sub>会话调度 · 花名册缓存 · 消息发送</sub>"]
D["OneBot 层<br/><sub>Event Converter · Action Handler</sub>"]
E([WS / HTTP / WebUI])
A --> B --> C --> D --> E
```
## 文档
- [路线图](RoadMap.md)
- [贡献指南](CONTRIBUTING.md)
- [行为准则](CODE_OF_CONDUCT.md)
## 开发命令
```bash
pnpm dev # 启动 core dev server
pnpm dev:web # 启动 webui dev server
pnpm test # 运行 core 测试
pnpm typecheck # 全仓库 type check
pnpm build:all # 构建 core + sdk + webui
```
## 关于项目
项目处于开发初期,仅支持部分功能,高速迭代中,随时可能出现破坏性更新。
## 鸣谢
[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto
- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。
[NapCatQQ](https://github.com/NapNeko/NapCatQQ) - Scaner/Packet
## 贡献者
## 辅助编程
感谢每一位为 SnowLuma 提交过代码的伙伴。
推荐 Opus4.6 + Gemini3.1pro 对本项目辅助开发
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors">
<img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="Contributors" />
</a>
本项目大量使用Ai技术。
## Star 趋势
## 加入我们
[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
<a href="https://star-history.com/#SnowLuma/SnowLuma&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
</picture>
</a>
## 社区
- QQ 群:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
- 问题反馈:[GitHub Issues](https://github.com/SnowLuma/SnowLuma/issues)
[SnowLuma-TG](https://t.me/napcatqq)

View File

@@ -1,491 +1,3 @@
# SnowLuma v3 — 目标架构
> v2 已完成:UID/UIN Service(SQLite 持久化)、tsx+map Debug、包拆分、proto-defs 剥离、消息 hot-path 优化(17.5μs → 4.7μs)、NapCat 风格 Api 层、Bridge/Account 分层(v2 发布在 `@snowluma/bridge`,v3 重命名为 `@snowluma/channel`)。
---
## 0. 数据流总览(一图概览所有权)
```
┌─ @snowluma/channel-hook ─────────┐ ┌─ @snowluma/channel-socket ──────┐
│ HookManager + HookChannel │ │ SocketChannel (future) │
│ — 仅 send/recv + pid/hook state — │ │ — 仅 send/recv + socket state — │
└────────────┬─────────────────────┘ └─────────────┬───────────────────┘
│ Channel 实例 │
└───────────┬──────────────────────────┘
│ 通过 ChannelAdapter 注册
▼
┌─ @snowluma/core ──── Hub(主入口 / 持有一切)──────────────┐
│ │
│ 内部:Map<uin, Core> │
│ │
│ channel available ──► ctx = capability(channel) │
│ ──► core = new Core(ctx) │
│ ──► emit 'core-online' { uin, apis, events, ... } │
│ │
│ channel gone ──► core.dispose() + emit 'core-offline' { uin } │
└─────────────────────────────────────┬─────────────────────────────────┘
│ 顶层 lifecycle 事件(仅 2 个)
▼
┌─ @snowluma/onebot ──────────────────────────────────────────────────────┐
│ hub.events.on('core-online', ctx => { │
│ this.byUin.set(ctx.uin, ctx); │
│ ctx.events.on('group_message', e => …); // 每账号 bus │
│ }); │
│ // 处理 OneBot action: │
│ this.byUin.get(uin)?.apis.message.sendGroup(...) │
└─────────────────────────────────────────────────────────────────────────┘
```
**核心约定**:
- `Channel` / adapter 包 **只**做 send/recv + 自己的内部状态(pid set / hook session / socket fd)。完全无业务。
- `Hub` 是**主入口**,独占持有 Channels + Cores。`Core` 实例由它构造,外部拿不到 Core 类本身。
- `Core` 通过 **ctx**(capability,一个 POJO)拿到 send/recv,从不直接持有 Channel。
- 外部消费者(OneBot / WebUI)只拿 `CoreCtx`(Core 的对外投影:`{ uin, apis, events, identity }`),不知道 Core 类的存在。
- 每个账号一个 `events`(在 Core 上),不做全局 bus;Hub 只 emit 两个顶层生命周期事件。
---
## 1. 目标包结构
```
SnowLuma/
├── packages/
│ │
│ │ ── Infrastructure(无业务) ──
│ ├── common/ logger / packet-sender / protocol-types / async-context
│ ├── proto-defs/ protobuf TS 接口定义
│ ├── proton/ protobuf codec 编译时生成器
│ ├── runtime/ native .node 产物清单
│ ├── ui/ Tailwind v4 + shadcn 组件(前端)
│ │
│ │ ── Protocol(解析层,纯函数) ──
│ ├── protocol/ events / identity-service / msg-push / oidb / highway /
│ │ element-builder / packet-pipeline / event-bus
│ │
│ │ ── Channel & adapters(transport 端口与实现) ──
│ ├── channel/ ⭐ Channel 接口 + 抽象类 + ChannelAdapter 端口
│ │ —— 只定义接口和最小抽象,**不**含 Hub
│ ├── channel-hook/ ⭐ HookManager + HookChannel + HookAdapter
│ │ —— 现 @snowluma/channel 大部分内容搬来
│ ├── channel-socket/ ⭐ 未来:SocketChannel + SocketAdapter
│ │
│ │ ── Core(主入口 + 业务封装) ──
│ ├── core/ ⭐ Core + Hub + CoreCtx + ApiHub + 协议封装
│ │ —— Hub 在这里(避免 channel↔core 循环)
│ │
│ │ ── Inbound(外部协议消费 CoreCtx) ──
│ ├── onebot/ OneBot v11 (HTTP + WS)
│ ├── websocket/ 底层 WS server(被 onebot / webui-backend 共用)
│ ├── webui-backend/ ⭐ Hono server + REST/WS(拆自 webui)
│ ├── webui-frontend/ ⭐ Vite SPA(拆自 webui)
│ └── sdk/ TS SDK
│
├── package.json
└── pnpm-workspace.yaml
```
⭐ 标记的是 v3 改动。
### 1.1 关键变动
| 当前 | 目标 | 备注 |
|---|---|---|
| `@snowluma/bridge`(hook + transport + adapter + manager) | `@snowluma/channel`(仅接口 + abstract Channel)+ `@snowluma/channel-hook`(hook 实现) | 包名 v2 叫 bridge,v3 重命名;hook 全套迁出独立包 |
| `@snowluma/core`(含 Account + AccountManager) | `core`:Core + Hub | Account → Core;AccountManager 折进 Hub |
| —— | `channel-socket` | 新建 stub |
| `@snowluma/webui` | `webui-backend` + `webui-frontend` | 前后端拆分 |
### 1.2 依赖 DAG(无环)
```
common ◄── proton, proto-defs, protocol, runtime, ui, channel
proto-defs ◄── protocol
proton ◄── protocol
protocol ◄── core
channel ◄── channel-hook, channel-socket, core
channel-hook ◄── core
channel-socket ◄── core
core ◄── onebot, webui-backend
websocket ◄── onebot, webui-backend
ui ◄── webui-frontend
```
**核心要点**:`core` 是唯一一处同时知道 `channel` 端口 + 业务实现的地方。Channel 包不反向依赖 core,因此 Hub **住在 core**,而不是 channel —— 名字保留 `Hub` 是因为它语义上仍是「channel 集群的指挥官」。
---
## 2. 三个关键类型 / 接口(设计核心)
整个系统由 **3 个类型** 串起来。每个职责单一、边界清晰。
### 2.1 `Channel`(在 `@snowluma/channel`)—— 纯 transport
```ts
// packages/channel/src/channel.ts
export type ChannelKind = 'inject' | 'socket';
export interface Channel {
readonly kind: ChannelKind;
readonly uin: string;
readonly id: string; // adapter:uin 形式
sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult>;
setPacketHandler(h: ((pkt: PacketInfo) => void) | null): void;
deliverPacket(pkt: PacketInfo): void; // adapter 内部用
dispose(): void;
}
```
Adapter 包(`channel-hook` / `channel-socket`)的具体类(`HookChannel` / `SocketChannel`)实现 `Channel`。它们的内部状态(PID set、hook session、socket fd)对外不可见。
### 2.2 `ChannelCtx`(在 `@snowluma/channel`)—— channel → core 的能力 POJO
```ts
// packages/channel/src/channel-ctx.ts
export interface ChannelCtx {
readonly uin: string;
readonly kind: ChannelKind;
readonly sendRawPacket: (cmd: string, body: Uint8Array) => Promise<SendPacketResult>;
readonly onPacket: (h: (pkt: PacketInfo) => void) => void;
readonly dispose: () => void;
}
// Hub 用 makeCtx(channel) 把 Channel 投影成 ChannelCtx:
export function makeChannelCtx(b: Channel): ChannelCtx {
return {
uin: b.uin, kind: b.kind,
sendRawPacket: (c, x) => b.sendRawPacket(c, x),
onPacket: (h) => b.setPacketHandler(h),
dispose: () => b.dispose(),
};
}
```
**关键设计**:`Core` 只接收 `ChannelCtx`(capability POJO),**不**持有 `Channel` 类引用。这样 `core` 包不依赖任何 adapter 实现细节,连 Channel 抽象类都不用 import。
### 2.3 `CoreCtx`(在 `@snowluma/core`)—— core → onebot 的能力 POJO
```ts
// packages/core/src/core-ctx.ts
export interface CoreCtx {
readonly uin: string;
readonly kind: ChannelKind;
readonly apis: ApiHub; // 所有 typed api(message/contacts/...)
readonly events: EventBus; // 该账号的事件(per-uin)
readonly identity: IdentityService; // UID/UIN/group roster
}
```
**关键设计**:OneBot 拿到的就是这个 POJO 投影,**不**持有 `Core` 类引用。Hub 在 `core-online` 事件里把 `CoreCtx` 透出去;OneBot 按 uin 存起来用。
---
## 3. `Hub` —— 主入口完整实现
所有所有权、生命周期、装配都在这里。**外部 main.ts 只跟它打交道。**
```ts
// packages/core/src/hub.ts
import { Channel, ChannelAdapter, ChannelAdapterHost, makeChannelCtx } from '@snowluma/channel';
import { Core } from './core';
import type { CoreCtx } from './core-ctx';
import { TypedEmitter } from '@snowluma/common/typed-emitter';
type Lifecycle = {
'core-online': CoreCtx;
'core-offline': { uin: string };
};
export class Hub {
private readonly cores = new Map<string, Core>();
private readonly adapters: ChannelAdapter[] = [];
readonly events = new TypedEmitter<Lifecycle>();
registerAdapter(a: ChannelAdapter): void {
this.adapters.push(a);
}
async start(): Promise<void> {
const host: ChannelAdapterHost = {
onChannelReady: (b) => this.onChannelReady(b),
onChannelGone: (uin) => this.onChannelGone(uin),
};
await Promise.all(this.adapters.map((a) => a.start(host)));
}
async stop(): Promise<void> {
await Promise.all(this.adapters.map((a) => a.stop()));
for (const c of this.cores.values()) c.dispose();
this.cores.clear();
}
// ─── private ───────────────────────────────
private onChannelReady(channel: Channel): void {
const stale = this.cores.get(channel.uin);
if (stale) {
stale.dispose();
this.events.emit('core-offline', { uin: channel.uin });
}
const core = new Core(makeChannelCtx(channel));
this.cores.set(channel.uin, core);
this.events.emit('core-online', core.publicCtx);
}
private onChannelGone(uin: string): void {
const core = this.cores.get(uin);
if (!core) return;
core.dispose();
this.cores.delete(uin);
this.events.emit('core-offline', { uin });
}
}
```
## 4. `Core` 实现要点
```ts
// packages/core/src/core.ts
import type { ChannelCtx } from '@snowluma/channel';
import { EventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { buildApiHub, type ApiHub } from './apis';
import type { CoreCtx } from './core-ctx';
export class Core {
readonly events = new EventBus(); // ← 每账号一个 bus
readonly identity: IdentityService;
readonly apis: ApiHub;
private readonly pipeline: IncomingPacketPipeline;
constructor(private readonly channelCtx: ChannelCtx) {
this.identity = IdentityService.openForUin(channelCtx.uin);
this.pipeline = new IncomingPacketPipeline(this.events, this.identity);
this.apis = buildApiHub(this); // apis 内部持 Core 引用,调 sendRawPacket
channelCtx.onPacket((pkt) => this.pipeline.process(pkt));
}
// 给外部消费者的投影(只读 POJO,不暴露 Core 实例)
get publicCtx(): CoreCtx {
return {
uin: this.channelCtx.uin,
kind: this.channelCtx.kind,
apis: this.apis,
events: this.events,
identity: this.identity,
};
}
// apis 内部通过 core 调发包
sendRawPacket(cmd: string, body: Uint8Array) {
return this.channelCtx.sendRawPacket(cmd, body);
}
dispose(): void {
this.channelCtx.dispose();
this.identity.close();
}
}
```
## 5. OneBot 消费 `CoreCtx`
```ts
// packages/onebot/src/manager.ts
import type { Hub, CoreCtx } from '@snowluma/core';
export class OneBotManager {
private readonly byUin = new Map<string, CoreCtx>();
bind(hub: Hub): void {
hub.events.on('core-online', (ctx) => this.attach(ctx));
hub.events.on('core-offline', ({ uin }) => this.detach(uin));
}
private attach(ctx: CoreCtx): void {
this.byUin.set(ctx.uin, ctx);
ctx.events.on('group_message', (e) => this.dispatchGroupMessage(ctx, e));
ctx.events.on('private_message',(e) => this.dispatchPrivateMessage(ctx, e));
// ... 其它 kind
}
private detach(uin: string): void {
this.byUin.delete(uin);
// ctx.events 随 Core dispose 一起释放
}
// 处理 OneBot HTTP/WS action:用 uin 查到 ctx,直接调 apis
async handleSendGroupMsg(uin: string, groupId: number, msg: OneBotMsg) {
const ctx = this.byUin.get(uin);
if (!ctx) throw new Error(`unknown uin: ${uin}`);
return ctx.apis.message.sendGroup(groupId, msg); // ← 直接调封装好的 api
}
}
```
## 6. 主入口(`packages/core/src/index.ts`)
```ts
import { HookAdapter } from '@snowluma/channel-hook';
import { OneBotManager } from '@snowluma/onebot';
import { Hub } from './hub';
const hub = new Hub();
hub.registerAdapter(new HookAdapter({ autoLoadOnDiscovery: true }));
// hub.registerAdapter(new SocketAdapter()); // 未来
const onebot = new OneBotManager();
onebot.bind(hub);
await hub.start();
await initWebUI(port, onebot, /* hookManager from adapter */);
```
9 行装配,每行都是有意义的所有权声明。
---
## 7. 为什么这样设计优雅
### 7.1 单向数据流
```
adapter → Channel → ChannelCtx → Core → CoreCtx → OneBot
transport capability capability
```
**没有反向引用**:Core 不知道 Channel 类,OneBot 不知道 Core 类。每层只看到「下一层的能力 POJO」。
### 7.2 单一所有者
`Hub.cores: Map<uin, Core>` 是 **唯一** 持有 Core 的地方。OneBot 只持 `CoreCtx`(投影,不算所有权)。Core 销毁 = 从这个 Map 里删 = 所有 ctx 同时失效。无需引用计数、无需 GC 协调。
### 7.3 每账号独立 EventBus
Core 自带 `events: EventBus`,互不干扰。OneBot 通过 `core-online` 拿到 ctx 后立即 subscribe,`core-offline` 时 Core 已 dispose,bus 自然失效,不会泄漏。**没有全局 bus**,没有「哪个账号的事件」问题。
### 7.4 完全可测
- 测 Channel:mock `setPacketHandler` 回调(已在 `account-private-routing.test.ts` 用 `FakeChannel` 验证)
- 测 Core:传 `ChannelCtx` POJO 即可,无需真 Channel
- 测 OneBot:emit 一个 `core-online` + 假 `CoreCtx`
- 测 Hub:用 fake `ChannelAdapter`
每层都能独立测试。
### 7.5 内部还要避免 ctx 漫天的两个小招
**(a) Api 类捕获 deps(已做)**
```ts
class MessageApi {
constructor(private readonly core: Core) {}
// 方法签名只有业务参数:
async sendGroup(groupId: number, msg: Msg) { this.core.sendRawPacket(...) }
}
```
**(b) AsyncLocalStorage 处理日志 / trace(建议引入)**
```ts
// packages/common/src/async-context.ts
import { AsyncLocalStorage } from 'node:async_hooks';
const als = new AsyncLocalStorage<{ uin?: string; trace?: string }>();
export const runInContext = <T>(c: { uin?: string; trace?: string }, fn: () => T) =>
als.run(c, fn);
export const ctx = () => als.getStore() ?? {};
// logger 自动 prefix [uin],业务代码不用接 log 参数
```
在 `Core.constructor` 给 `onPacket` 包一层:
```ts
channelCtx.onPacket((pkt) => {
runInContext({ uin: channelCtx.uin, trace: `pkt:${pkt.seqId}` }, () => {
this.pipeline.process(pkt);
});
});
```
所有下游 `log.info()` 自动带 `[10001]` 前缀,不污染业务签名。开销 ~50ns/call。
---
## 8. 不要的设计(保持简单)
| 方案 | 不做的原因 |
|---|---|
| **`CoreFactory` 抽象** | Core 只一种,多此一举。直接 `new Core(ctx)` |
| **全局 EventBus** | 每账号自己的 bus 更清晰,OneBot 按 uin 订阅,不混杂 |
| **`AccountManager` 独立层** | 多余的中间层,折进 `Hub` |
| **`InboundAdapter` 抽象** | OneBot / WebUI 数量有限且固定,直接 `bm.events.on(...)` 即可,不抽插件层 |
| **DI 容器(tsyringe 等)** | 9 行手动装配已经清晰,DI 引入反射/装饰器元数据反而难调 |
| **Effect monad / Reader monad** | TS 缺 do-notation,类型噪音 > 收益 |
| **CQRS / Event-sourced state** | 当前状态量级(10 账号 × 100 群)远未到 |
---
## 9. 迁移路线(每步独立可 ship)
> typecheck + 全测试通过才进下一步。
**Step 1** —— ⭐ 重命名 + 拆现有的 `@snowluma/bridge`
- `packages/bridge/` 重命名为 `packages/channel/`;package.json name 改为 `@snowluma/channel`
- 新建 `packages/channel-hook/`,从 `@snowluma/channel` 搬:`hook-manager.ts` / `hook-session.ts` / `hook-packet-client.ts` / `injector.ts` / `pipe-watcher.ts` / `qq-hook-client.ts` / `qq-port-probe.ts` / `hook-channel.ts`(原 inject-bridge.ts)/ `hook-adapter.ts`(原 inject-adapter.ts)
- `@snowluma/channel` 留:`channel.ts`(abstract,原 bridge.ts)/ `channel-interface.ts` / `channel-ctx.ts`(新)/ `adapter.ts`(端口)+ `makeChannelCtx` 工具
- 删除:`manager.ts`(原 BridgeManager)(搬到 core/hub.ts)/ `socket-channel.ts` + `socket-adapter.ts`(搬到 `channel-socket` stub)
**Step 2** —— ⭐ 重塑 `@snowluma/core`
- 删除:`account/account.ts` / `account-interface.ts` / `account-context.ts` / `account-manager.ts`
- 新建:`core.ts`(吸收 Account 业务,构造接 `ChannelCtx`)/ `core-ctx.ts` / `hub.ts`
- `apis/` 内部 `AccountContext` → `Core`(直接拿 Core 类型)
- `index.ts` 9 行装配(见 §6)
**Step 3** —— OneBot 适配 CoreCtx
- 全局 `AccountInterface` → `CoreCtx`
- `OneBotManager.bind(hub)` 订阅 `'core-online'` / `'core-offline'`
- 内部 `byUin.get(uin).apis.<area>.method()` 调 api
**Step 4** —— 引入 `AsyncLocalStorage`
- `packages/common/src/async-context.ts`
- `logger.ts` 自动读 ALS,加 `[uin]` 前缀
- `Core.constructor` 在 `onPacket` 回调外包 `runInContext`
**Step 5** —— `channel-socket` stub 包(占位)
- 把 `socket-channel.ts` / `socket-adapter.ts` 搬过来
- 实现 placeholder,让 `ChannelAdapter` 端口齐
**Step 6** —— ⭐ 拆 `webui` 为 `webui-backend` + `webui-frontend`
- Hono server + REST/WS → `webui-backend`,依赖 `@snowluma/core`(消费 `CoreCtx`)
- Vite SPA + UI → `webui-frontend`,依赖 `@snowluma/ui`
---
## 10. 设计原则速查
- **单向数据流**:`adapter → Channel → ChannelCtx → Core → CoreCtx → OneBot`,无反向引用
- **能力 POJO 跨层传递**:层间用 `{ uin, sendRawPacket, ... }` / `{ uin, apis, events, ... }` 这种纯数据,不传类实例
- **单一所有者**:`Hub.cores` 是 Core 唯一容器,消费者只持投影
- **每账号自带 EventBus**:避免全局 bus 混杂,订阅生命周期与 Core 绑定
- **Class 封装 deps**:构造时捕获,方法签名只剩业务参数
- **AsyncLocalStorage 跨切面**:日志 / trace 不进显式参数
- **不引入过度抽象**:no factory / no DI / no Effect monad / no global bus
- **可测**:每层接 POJO,fake 一下就能测
---
## 11. v2.0.0 已完成
- ✅ UID/UIN Service + SQLite 持久化
- ✅ tsx 免打包 Debug
- ✅ Common / OneBot / Core / Bridge / Protocol / proto-defs 拆包
- ✅ 消息 hot-path 优化(17.5μs → 4.7μs,better-sqlite3 + prepared-statement cache)
- ✅ NapCat 风格 Api 层(13 Api 类)
- ✅ Bridge / Account 严格分层(v2 中间形态;v3 重命名为 Channel + Core,并用 ctx 替代直接引用)
- ✅ `@snowluma/bridge` 完整 transport 包(v3 重命名为 `@snowluma/channel`)
# V2.0.0 前计划
- [x] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
- [ ] 优化Debug体验,实现免打包Debug,同时数据目录正确。

View File

@@ -1,105 +0,0 @@
import js from '@eslint/js';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import { defineConfig, globalIgnores } from 'eslint/config';
import globals from 'globals';
import tseslint from 'typescript-eslint';
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1');
export default defineConfig([
globalIgnores([
'**/dist/**',
'**/node_modules/**',
'**/coverage/**',
'**/.turbo/**',
'**/.vite/**',
'**/*.tsbuildinfo',
'**/test/fixtures/**',
'packages/runtime/native/**',
]),
{
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
extends: [js.configs.recommended],
languageOptions: {
ecmaVersion: 2023,
sourceType: 'module',
globals: {
...globals.es2023,
...globals.node,
},
},
rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'no-unused-vars': 'off',
'no-useless-assignment': 'off',
'prefer-const': 'off',
'preserve-caught-error': 'off',
},
},
{
files: ['**/*.{ts,tsx}'],
extends: [tseslint.configs.recommended],
languageOptions: {
parserOptions: {
tsconfigRootDir,
},
},
rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'prefer-const': 'off',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-empty-object-type': 'off',
'@typescript-eslint/no-this-alias': 'off',
'@typescript-eslint/no-unused-vars': [
'warn',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
},
},
{
files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
},
},
{
files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
},
},
{
// OIDB service layer is namespace-per-cmd by design — the
// structural-typing contract (namespace IS the OidbCallSpec) and
// the file:cmd 1:1 mapping are the whole point. Disable the
// module-syntax preference here only.
files: [
'packages/protocol/src/oidb-services/**/*.ts',
'packages/protocol/tests/oidb-services/**/*.ts',
],
rules: {
'@typescript-eslint/no-namespace': 'off',
},
},
{
files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'],
extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite],
languageOptions: {
globals: globals.browser,
parserOptions: {
tsconfigRootDir,
},
},
rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'prefer-const': 'off',
'react-refresh/only-export-components': 'off',
'react-hooks/set-state-in-effect': 'off',
},
},
]);

View File

@@ -1,6 +1,6 @@
{
"name": "snowluma-monorepo",
"version": "1.9.2",
"version": "1.8.2",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -15,34 +15,21 @@
"test": "pnpm --filter @snowluma/core test",
"test:watch": "pnpm --filter @snowluma/core test:watch",
"typecheck": "pnpm -r --if-present typecheck",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"lint": "pnpm -r --if-present lint",
"start": "node dist/index.mjs",
"bump": "node tools/bump-version.mjs",
"release": "node tools/release.mjs"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@vitest/coverage-istanbul": "4.1.4",
"@vitest/coverage-v8": "^4.1.4",
"cross-env": "^10.1.0",
"eslint": "^10.2.0",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.5.0",
"jiti": "^2.6.1",
"typescript": "catalog:",
"typescript-eslint": "^8.58.2"
"typescript": "catalog:"
},
"pnpm": {
"peerDependencyRules": {
"allowedVersions": {
"eslint-plugin-react-hooks>eslint": "10"
}
},
"onlyBuiltDependencies": [
"better-sqlite3"
]
}
},
"packageManager": "pnpm@10.28.0",
"engines": {

View File

@@ -1,69 +0,0 @@
{
"name": "@snowluma/channel-hook",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma `inject` channel implementation — in-process NTQQ hook runtime. Bundles HookManager / HookSession / pipe-watcher / injector / qq-hook-client plus the `HookChannel` and `HookAdapter` that `Hub` (in @snowluma/core) registers as the primary transport on Windows. Depends on `@snowluma/channel` for the abstract `Channel` + `ChannelAdapter` contracts.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./hook-channel": {
"types": "./src/hook-channel.ts",
"default": "./src/hook-channel.ts"
},
"./hook-adapter": {
"types": "./src/hook-adapter.ts",
"default": "./src/hook-adapter.ts"
},
"./hook-manager": {
"types": "./src/hook-manager.ts",
"default": "./src/hook-manager.ts"
},
"./hook-session": {
"types": "./src/hook-session.ts",
"default": "./src/hook-session.ts"
},
"./hook-packet-client": {
"types": "./src/hook-packet-client.ts",
"default": "./src/hook-packet-client.ts"
},
"./injector": {
"types": "./src/injector.ts",
"default": "./src/injector.ts"
},
"./pipe-watcher": {
"types": "./src/pipe-watcher.ts",
"default": "./src/pipe-watcher.ts"
},
"./qq-hook-client": {
"types": "./src/qq-hook-client.ts",
"default": "./src/qq-hook-client.ts"
},
"./qq-port-probe": {
"types": "./src/qq-port-probe.ts",
"default": "./src/qq-port-probe.ts"
},
"./types": {
"types": "./src/types.ts",
"default": "./src/types.ts"
}
},
"scripts": {
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/channel": "workspace:*",
"@snowluma/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
}
}

View File

@@ -1,174 +0,0 @@
import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { HookChannel } from './hook-channel';
import { HookManager, type HookManagerDeps, type HookSink } from './hook-manager';
/** Subset of `HookManagerDeps` the operator is allowed to forward
* through the adapter. The `sink` is owned by the adapter itself and
* intentionally not exposed. */
export type HookAdapterOptions = Omit<HookManagerDeps, 'sink'>;
/**
* `HookAdapter` — the `ChannelAdapter` for the NTQQ hook runtime. It
* owns the `HookManager` and translates its three sink callbacks
* (`onHookLogin` / `onPacket` / `onPidDisconnected`) into lifecycle
* events on a per-UIN `HookChannel`.
*
* Why an adapter rather than letting the `Hub` keep the hook sink:
* this is the only place in the codebase that legitimately needs to
* know about PIDs. Quarantining that knowledge here keeps the `Hub`
* (and everything above it) free of `pid`, leaving the door open for
* a future `SocketAdapter` that doesn't have the concept at all.
*
* Internal bookkeeping:
*
* - `pidToUin` — quick "which UIN does this PID feed?" lookup,
* populated on login (and lazily during defensive
* packet routing for PIDs that arrived ahead of
* their login notification).
* - `pidToSender` — the live `PacketSender` per PID, so a re-login
* from the same PID rotates the outbound sender
* without dropping the channel.
* - `uinToPids` — reverse index for fast "did this UIN lose its
* last PID?" checks on disconnect.
* - `channelsByUin` — one `HookChannel` per UIN; the hub only sees
* `Channel` instances, never the PID set living
* inside them.
*/
export class HookAdapter implements ChannelAdapter, HookSink {
readonly kind = 'inject' as const;
private readonly hookManager_: HookManager;
private readonly pidToUin = new Map<number, string>();
private readonly pidToSender = new Map<number, PacketSender>();
private readonly uinToPids = new Map<string, Set<number>>();
private readonly channelsByUin = new Map<string, HookChannel>();
private host_: ChannelAdapterHost | null = null;
private disposed_ = false;
constructor(opts: HookAdapterOptions = {}) {
// `sink: this` wires HookManager → adapter sink. The HookManager
// doesn't know about the broader ChannelAdapter contract; it only
// sees the three sink methods we implement below.
this.hookManager_ = new HookManager({ ...opts, sink: this });
}
/** The underlying `HookManager`, exposed so WebUI can keep its
* `/api/processes/*` endpoints pointing at the hook process table.
* Higher-level code (OneBot, channel consumers) MUST NOT reach into
* this — that's the whole point of the adapter layer. */
get hookManager(): HookManager { return this.hookManager_; }
// ─── ChannelAdapter contract ─────────────────────────────────────
start(host: ChannelAdapterHost): void {
this.host_ = host;
host.log.debug('hook adapter started');
}
dispose(): void {
if (this.disposed_) return;
this.disposed_ = true;
// Tear down hook sessions first so no more sink callbacks fire.
this.hookManager_.dispose();
// Then proactively remove every channel we published; the hub
// will call `channel.dispose()` on its way out.
for (const id of [...this.channelsByUin.values()].map(c => c.id)) {
this.host_?.removeChannel(id);
}
this.pidToUin.clear();
this.pidToSender.clear();
this.uinToPids.clear();
this.channelsByUin.clear();
this.host_ = null;
}
// ─── HookSink contract (called by HookManager) ──────────────────
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (this.disposed_ || !isRealUin(uin)) return;
this.recordPidMapping(pid, uin, packetClient);
const channel = this.ensureChannel(uin);
channel.attachPid(pid, packetClient);
}
onPacket(pkt: PacketInfo): void {
if (this.disposed_ || !pkt.uin || !isRealUin(pkt.uin)) return;
const uin = pkt.uin;
const channel = this.ensureChannel(uin);
// Defensive: a packet may arrive before its login notification
// when the channel is being re-adopted (SnowLuma restarted while
// the hook stayed resident in QQ.exe). If we have a sender for
// this PID, weave it in so subsequent sends through this channel
// succeed.
if (pkt.pid) {
const sender = this.pidToSender.get(pkt.pid);
if (sender && !this.pidToUin.has(pkt.pid)) {
this.recordPidMapping(pkt.pid, uin, sender);
channel.attachPid(pkt.pid, sender);
}
}
channel.deliverPacket(pkt);
}
onPidDisconnected(pid: number): void {
if (this.disposed_) return;
this.pidToSender.delete(pid);
const uin = this.pidToUin.get(pid);
if (!uin) return;
this.pidToUin.delete(pid);
const pids = this.uinToPids.get(uin);
if (pids) {
pids.delete(pid);
if (pids.size === 0) this.uinToPids.delete(uin);
}
const channel = this.channelsByUin.get(uin);
if (!channel) return;
channel.detachPid(pid);
if (channel.isEmpty) {
this.channelsByUin.delete(uin);
this.host_?.removeChannel(channel.id);
}
}
// ─── internal ────────────────────────────────────────────────────
private recordPidMapping(pid: number, uin: string, sender: PacketSender): void {
this.pidToUin.set(pid, uin);
this.pidToSender.set(pid, sender);
let pids = this.uinToPids.get(uin);
if (!pids) {
pids = new Set();
this.uinToPids.set(uin, pids);
}
pids.add(pid);
}
private ensureChannel(uin: string): HookChannel {
let channel = this.channelsByUin.get(uin);
if (channel) return channel;
channel = new HookChannel(uin);
this.channelsByUin.set(uin, channel);
this.host_?.addChannel(channel);
return channel;
}
}
// QQ uins are 5-12 decimal digits; "0" is the hook's "no login yet"
// sentinel. Anything else (empty, alpha, too short) is a sign the hook
// callback fired before login info was probed — we ignore those.
function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}

View File

@@ -1,82 +0,0 @@
import { Channel } from '@snowluma/channel';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
/**
* `HookChannel` — concrete transport backed by the in-process NTQQ
* hook. One UIN may be served simultaneously by several injected
* processes; the channel therefore tracks an unordered set of PIDs and
* keeps a single live `PacketSender` (the most recently logged-in
* pipe) for outbound traffic.
*
* PID bookkeeping is scoped to this transport because the socket-only
* runtime never has the concept; quarantining it here keeps the
* abstract `Channel` and the `Hub` free of pid awareness.
*
* The owning `HookAdapter` is responsible for calling
* `attachPid(pid, sender)` on every successful hook login,
* `detachPid(pid)` when the watcher reports a pipe drop, and tearing
* the channel down once `isEmpty` returns true.
*/
export class HookChannel extends Channel {
readonly kind = 'inject' as const;
readonly uin: string;
private readonly pids_ = new Set<number>();
private packetClient_: PacketSender | null = null;
constructor(uin: string) {
super();
this.uin = uin;
}
get id(): string { return `inject:${this.uin}`; }
/** PIDs currently routing packets into this channel. Read-only view
* for diagnostics — mutate only via `attachPid` / `detachPid`. */
get pids(): ReadonlySet<number> { return this.pids_; }
/** True iff no PID is currently bound; the adapter uses this to
* decide when to remove the channel from the `Hub`. */
get isEmpty(): boolean { return this.pids_.size === 0; }
/** Bind a freshly-logged-in PID (and its outbound `PacketSender`)
* to this channel. Idempotent — re-binding the same PID just rotates
* the active sender. */
attachPid(pid: number, sender: PacketSender): void {
this.pids_.add(pid);
this.packetClient_ = sender;
}
/** Forget a PID. If it owned the active sender we drop it; the next
* `attachPid` (or pipe-up) will install a fresh one. */
detachPid(pid: number): void {
this.pids_.delete(pid);
if (this.pids_.size === 0) {
this.packetClient_ = null;
}
}
override async sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs = 15000,
): Promise<SendPacketResult> {
const client = this.packetClient_;
if (!client) {
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: 'hook channel has no live packet sender',
responseData: null,
};
}
return client.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
}
override dispose(): void {
super.dispose();
this.packetClient_ = null;
this.pids_.clear();
}
}

View File

@@ -1,15 +0,0 @@
// `@snowluma/channel-hook` — the `inject` channel implementation
// (NTQQ in-process hook). Registered with `Hub` from `@snowluma/core`
// as a `ChannelAdapter` of kind `'inject'`. Everything pid-related is
// scoped to this package — neither `@snowluma/channel` nor anything
// downstream knows about it.
// ─── Hook runtime ──────────────────────────────────────────────────
export {
HookManager, type HookSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
type HookProcessStatus, type QqPortLoginInfo
} from './hook-manager';
// ─── Concrete Channel + Adapter ────────────────────────────────────
export { HookChannel } from './hook-channel';
export { HookAdapter, type HookAdapterOptions } from './hook-adapter';

View File

@@ -1,168 +0,0 @@
import { exec } from 'child_process';
import net from 'net';
import { promisify } from 'util';
const execAsync = promisify(exec);
const PORT_RANGE_START = 9210;
const PORT_RANGE_END = 9219;
const PROBE_TIMEOUT_MS = 1000;
const CONNECTION_TIMEOUT_MS = 500;
export interface QqPortLoginInfo {
port: number;
uin: string;
uid?: string;
nickName?: string;
loggedIn: boolean;
}
interface JwtPayload {
errCode: number;
errMsg: string;
port: number;
uin?: string;
uid?: string;
nickName?: string;
data?: {
uin?: string;
url?: string;
};
iat: number;
}
function decodeJwt(token: string): JwtPayload | null {
try {
const parts = token.split('.');
if (parts.length !== 3) return null;
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
return JSON.parse(payload);
} catch {
return null;
}
}
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
return new Promise((resolve) => {
const client = new net.Socket();
const link = 'tencent://';
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
let responseData = '';
let timer: NodeJS.Timeout;
const cleanup = () => {
clearTimeout(timer);
client.removeAllListeners();
client.destroy();
};
timer = setTimeout(() => {
cleanup();
resolve(null);
}, PROBE_TIMEOUT_MS);
client.setTimeout(CONNECTION_TIMEOUT_MS);
client.connect(port, '127.0.0.1', () => {
client.write(payload);
});
client.on('data', (data) => {
responseData += data.toString();
});
client.on('close', () => {
cleanup();
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
if (!jwtMatch) {
resolve(null);
return;
}
const decoded = decodeJwt(jwtMatch[0]);
if (!decoded || decoded.errCode !== 0) {
resolve(null);
return;
}
const uin = decoded.uin || decoded.data?.uin || '';
resolve({
port,
uin,
uid: decoded.uid,
nickName: decoded.nickName,
loggedIn: uin.length > 0,
});
});
client.on('error', () => {
cleanup();
resolve(null);
});
client.on('timeout', () => {
cleanup();
resolve(null);
});
});
}
async function getProcessPorts(pid: number): Promise<number[]> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
const parts = line.trim().split(/\s+/);
if (parts.length < 5) continue;
const owningPid = parts[parts.length - 1];
if (owningPid !== String(pid)) continue;
const localAddr = parts[1];
const portMatch = localAddr.match(/:(\d+)$/);
if (!portMatch) continue;
const port = Number(portMatch[1]);
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
ports.add(port);
}
}
return Array.from(ports);
} else {
const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
const match = line.match(/:(\d+)\s/);
if (match) {
const port = Number(match[1]);
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
ports.add(port);
}
}
}
return Array.from(ports);
}
} catch {
return [];
}
}
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
const ports = await getProcessPorts(pid);
if (ports.length === 0) {
for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) {
const info = await probePort(port);
if (info) return info;
}
return null;
}
for (const port of ports) {
const info = await probePort(port);
if (info) return info;
}
return null;
}

View File

@@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": [
"node"
],
"noEmit": true
},
"include": [
"src/**/*",
"tests"
],
"exclude": [
"node_modules"
]
}

View File

@@ -1,8 +0,0 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
environment: 'node',
},
});

View File

@@ -1,34 +0,0 @@
{
"name": "@snowluma/channel-socket",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma `socket` channel implementation — placeholder for the future pure-socket runtime (no QQ.exe, no hook). Today registers as a no-op `ChannelAdapter` so the Hub-adapter architecture is exercised end-to-end. Will gain a `SocketClient` long-lived TCP login session when the protocol runtime lands.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./socket-channel": {
"types": "./src/socket-channel.ts",
"default": "./src/socket-channel.ts"
},
"./socket-adapter": {
"types": "./src/socket-adapter.ts",
"default": "./src/socket-adapter.ts"
}
},
"scripts": {
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/channel": "workspace:*",
"@snowluma/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:"
}
}

View File

@@ -1,8 +0,0 @@
// `@snowluma/channel-socket` — future pure-socket transport (no
// QQ.exe, no hook). Today an empty stub so `Hub` can register it as a
// `ChannelAdapter` of kind `'socket'` and exercise the adapter pool
// end-to-end. Will materialise a real `SocketChannel` once the
// pure-socket login client lands.
export { SocketChannel } from './socket-channel';
export { SocketAdapter } from './socket-adapter';

View File

@@ -1,30 +0,0 @@
import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel';
/**
* `SocketAdapter` — placeholder for the future pure-socket runtime.
* Once a `SocketClient` (long-lived TCP login session, heartbeat,
* reconnect loop, …) lands, this adapter will:
*
* 1. Read its account list from runtime config.
* 2. Spin up one `SocketClient` per configured account.
* 3. On successful login, materialise a `SocketChannel` and call
* `host.addChannel(channel)`.
* 4. On logout / fatal error, call `host.removeChannel(channel.id)`.
*
* Until that lands the adapter is registered as a no-op so the wider
* architecture (Hub → ChannelAdapter[] → Channel → Core) is already in
* place and exercised in production. Registering it is harmless:
* `start()` does nothing, `dispose()` does nothing, no channels are
* ever produced.
*/
export class SocketAdapter implements ChannelAdapter {
readonly kind = 'socket' as const;
start(host: ChannelAdapterHost): void {
host.log.debug('socket adapter is a stub; no socket clients will be opened');
}
dispose(): void {
// Nothing to tear down yet.
}
}

View File

@@ -1,41 +0,0 @@
import { Channel } from '@snowluma/channel';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
/**
* `SocketChannel` — placeholder transport for the future pure-socket
* runtime (no QQ.exe, no hook). It already participates in the `Hub`
* (in `@snowluma/core`) so the wider architecture (ChannelAdapter pool
* → Hub → Core → OneBot) is exercised end-to-end today; once a real
* `SocketClient` lands the transport will gain a constructor argument
* and `sendRawPacket` will route through it.
*
* Until then `sendRawPacket` returns a structured "not implemented"
* failure rather than throwing, so the surrounding code treats it as
* a regular transport-down result.
*/
export class SocketChannel extends Channel {
readonly kind = 'socket' as const;
readonly uin: string;
constructor(uin: string) {
super();
this.uin = uin;
}
get id(): string { return `socket:${this.uin}`; }
override async sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult> {
void serviceCmd; void body; void timeoutMs;
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: 'socket channel transport is not yet implemented',
responseData: null,
};
}
}

View File

@@ -1,15 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": [
"node"
],
"noEmit": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}

View File

@@ -1,44 +0,0 @@
{
"name": "@snowluma/channel",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma transport abstract layer. Defines the `Channel` abstract base + `ChannelCtx` capability POJO + `ChannelAdapter` port that `Hub` (in @snowluma/core) consumes. Concrete transports live in `@snowluma/channel-hook` (in-process NTQQ hook) and `@snowluma/channel-socket` (future pure-socket).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./channel": {
"types": "./src/channel.ts",
"default": "./src/channel.ts"
},
"./channel-interface": {
"types": "./src/channel-interface.ts",
"default": "./src/channel-interface.ts"
},
"./channel-ctx": {
"types": "./src/channel-ctx.ts",
"default": "./src/channel-ctx.ts"
},
"./adapter": {
"types": "./src/adapter.ts",
"default": "./src/adapter.ts"
}
},
"scripts": {
"test": "vitest run --passWithNoTests",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
}
}

View File

@@ -1,15 +0,0 @@
import type { Logger } from '@snowluma/common/logger';
import type { Channel } from './channel';
import type { ChannelKind } from './channel-interface';
export interface ChannelAdapterHost {
addChannel(channel: Channel): void;
removeChannel(channelId: string): void;
readonly log: Logger;
}
export interface ChannelAdapter {
readonly kind: ChannelKind;
start(host: ChannelAdapterHost): Promise<void> | void;
dispose(): Promise<void> | void;
}

View File

@@ -1,26 +0,0 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { Channel } from './channel';
import type { ChannelKind } from './channel-interface';
export interface ChannelCtx {
readonly uin: string;
readonly kind: ChannelKind;
readonly sendRawPacket: (
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
) => Promise<SendPacketResult>;
readonly onPacket: (handler: ((pkt: PacketInfo) => void) | null) => void;
readonly dispose: () => void;
}
export function makeChannelCtx(channel: Channel): ChannelCtx {
return {
uin: channel.uin,
kind: channel.kind,
sendRawPacket: (cmd, body, timeoutMs) => channel.sendRawPacket(cmd, body, timeoutMs),
onPacket: (handler) => channel.setPacketHandler(handler),
dispose: () => channel.dispose(),
};
}

View File

@@ -1,73 +0,0 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
/**
* Discriminator for the two channel transport implementations:
*
* - `'inject'` — backed by an in-process NTQQ hook (one or more
* QQ.exe processes injected with the SnowLuma DLL,
* talking over named pipes). Implemented by
* `HookChannel` in `@snowluma/channel-hook`.
* - `'socket'` — backed by a direct protocol client (no QQ.exe, no
* hook). Reserved for the future pure-protocol
* runtime; `SocketChannel` is a stub until then.
*
* Mirrored on `CoreCtx.kind` so account-level consumers can branch on
* transport without `instanceof` checks against a concrete subclass
* (diagnostics, kind-specific WebUI panels, …).
*/
export type ChannelKind = 'inject' | 'socket';
/**
* `ChannelInterface` — **strictly transport**. A channel owns one
* wire-level connection to QQ for a given UIN: it sends opaque packets
* out and surfaces received packets to whoever subscribed via
* `setPacketHandler`.
*
* It deliberately knows nothing about identity caches, the event bus,
* the api hub, or the cmd-dispatch pipeline — that machinery lives on
* the `Core` layer (`@snowluma/core`) which wraps a `Channel` (via a
* `ChannelCtx` capability POJO) to expose a business-level API to
* OneBot and friends.
*
* Direct consumers are limited to:
* - `ChannelAdapter` implementations (they create / dispose channels
* and pump received packets through `deliverPacket`),
* - `Hub` in `@snowluma/core` (the only place that turns a `Channel`
* into a `ChannelCtx` and hands the ctx to `Core`),
* - `Core` (only via the `ChannelCtx` projection; never holds a
* Channel reference directly).
*
* OneBot and api modules NEVER import `ChannelInterface`; they consume
* `CoreCtx` from `@snowluma/core`.
*/
export interface ChannelInterface {
/** Transport family backing this channel. */
readonly kind: ChannelKind;
/** Stable, unique-per-live-channel id inside the `Hub`
* (e.g. `'inject:3161592748'`). */
readonly id: string;
/** QQ number this transport carries. */
readonly uin: string;
/** Wire-level send. The only escape hatch the apis layer eventually
* routes through (via `Core.sendRawPacket` → `ChannelCtx.sendRawPacket`). */
sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult>;
/** Subscribe to inbound packets. Called once by `Hub` (via
* `ChannelCtx.onPacket`) when a `Core` is constructed on top of this
* channel. Passing `null` detaches. */
setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void;
/** Adapter-side hook: feed a freshly-received packet into the
* current subscriber (if any). Called by `ChannelAdapter`s when
* their underlying runtime delivers a frame. */
deliverPacket(pkt: PacketInfo): void;
/** Release transport-side resources. Idempotent. */
dispose(): void;
}

View File

@@ -1,34 +0,0 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { ChannelInterface, ChannelKind } from './channel-interface';
export abstract class Channel implements ChannelInterface {
abstract readonly kind: ChannelKind;
abstract readonly id: string;
abstract readonly uin: string;
abstract sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult>;
private packetHandler_: ((pkt: PacketInfo) => void) | null = null;
private disposed_ = false;
setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void {
this.packetHandler_ = handler;
}
deliverPacket(pkt: PacketInfo): void {
this.packetHandler_?.(pkt);
}
get isDisposed(): boolean { return this.disposed_; }
dispose(): void {
if (this.disposed_) return;
this.disposed_ = true;
this.packetHandler_ = null;
}
}

View File

@@ -1,5 +0,0 @@
export { type ChannelAdapter, type ChannelAdapterHost } from './adapter';
export { Channel } from './channel';
export { makeChannelCtx, type ChannelCtx } from './channel-ctx';
export { type ChannelInterface, type ChannelKind } from './channel-interface';

View File

@@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": [
"node"
],
"noEmit": true
},
"include": [
"src/**/*",
"tests"
],
"exclude": [
"node_modules"
]
}

View File

@@ -1,8 +0,0 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
environment: 'node',
},
});

View File

@@ -1,54 +0,0 @@
{
"name": "@snowluma/common",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./logger": {
"types": "./src/logger.ts",
"default": "./src/logger.ts"
},
"./hex": {
"types": "./src/hex.ts",
"default": "./src/hex.ts"
},
"./json": {
"types": "./src/json.ts",
"default": "./src/json.ts"
},
"./log-file-transport": {
"types": "./src/log-file-transport.ts",
"default": "./src/log-file-transport.ts"
},
"./log-summary": {
"types": "./src/log-summary.ts",
"default": "./src/log-summary.ts"
},
"./packet-sender": {
"types": "./src/packet-sender.ts",
"default": "./src/packet-sender.ts"
},
"./protocol-types": {
"types": "./src/protocol-types.ts",
"default": "./src/protocol-types.ts"
},
"./runtime": {
"types": "./src/runtime.ts",
"default": "./src/runtime.ts"
}
},
"scripts": {
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:"
}
}

View File

@@ -1,6 +0,0 @@
export type JsonPrimitive = string | number | boolean | null;
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
export interface JsonObject {
[key: string]: JsonValue;
}
export type JsonArray = JsonValue[];

View File

@@ -1,274 +0,0 @@
import fs from 'node:fs';
import path from 'node:path';
const DEFAULT_DIR = 'logs';
const DEFAULT_MAX_MB = 50;
const DEFAULT_RETAIN_DAYS = 7;
const FILE_PREFIX = 'snowluma-';
const FILE_SUFFIX = '.log';
const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/;
// eslint-disable-next-line no-control-regex
const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
// Preserve TAB (0x09), LF (0x0A) and ESC (0x1B) — TAB / LF for legit
// multi-line records (stack traces), ESC is stripped through ANSI_RE.
// eslint-disable-next-line no-control-regex
const CTRL_RE = /[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g;
function parsePositiveInt(v: string | undefined, dflt: number): number {
if (!v) return dflt;
const n = Number.parseInt(v, 10);
return Number.isFinite(n) && n > 0 ? n : dflt;
}
function todayString(d: Date = new Date()): string {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
function dateOf(s: string): Date {
const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10));
return new Date(y!, m! - 1, d!);
}
function stripAnsi(line: string): string {
return line.replace(ANSI_RE, '').replace(CTRL_RE, '');
}
interface OpenFile {
stream: fs.WriteStream;
bytes: number;
date: string;
splitIndex: number;
path: string;
}
/**
* Owns one output directory: keeps at most one open WriteStream, handles
* daily rollover, per-file size cap, and retention cleanup. The shared
* top-level dir uses one of these; each per-UIN sub-dir gets its own.
*/
class FileWriter {
private disabled = false;
private file: OpenFile | null = null;
constructor(
private readonly dir: string,
private readonly maxBytes: number,
private readonly retainDays: number,
) {
try {
fs.mkdirSync(dir, { recursive: true });
} catch (err) {
this.disabled = true;
console.error(
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
);
return;
}
this.cleanup();
}
get isDisabled(): boolean {
return this.disabled;
}
get currentPath(): string | null {
return this.file?.path ?? null;
}
write(data: string, bytes: number): void {
if (this.disabled) return;
const today = todayString();
this.ensureForToday(today);
if (!this.file) return;
if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) {
this.rotateBySize();
if (!this.file) return;
}
this.file.stream.write(data);
this.file.bytes += bytes;
}
close(): Promise<void> {
const f = this.file;
this.file = null;
if (!f) return Promise.resolve();
return new Promise((resolve) => {
try {
f.stream.end(() => resolve());
} catch {
resolve();
}
});
}
private ensureForToday(today: string): void {
if (this.file && this.file.date === today) return;
if (this.file) {
try {
this.file.stream.end();
} catch {
/* ignore */
}
this.file = null;
this.cleanup();
}
// Resume from the highest existing split index for today (so two
// process starts on the same day share files / don't clobber).
let idx = 0;
while (fs.existsSync(this.pathFor(today, idx + 1))) idx++;
this.file = this.openFile(today, idx);
}
private rotateBySize(): void {
if (!this.file) return;
const date = this.file.date;
try {
this.file.stream.end();
} catch {
/* ignore */
}
let next = this.file.splitIndex + 1;
while (fs.existsSync(this.pathFor(date, next))) next++;
this.file = this.openFile(date, next);
}
private openFile(date: string, splitIndex: number): OpenFile | null {
const p = this.pathFor(date, splitIndex);
try {
let bytes = 0;
try {
bytes = fs.statSync(p).size;
} catch {
/* file doesn't exist yet */
}
const stream = fs.createWriteStream(p, { flags: 'a' });
stream.on('error', (err) => {
console.error(`[logger] file write error on ${p}: ${err.message}`);
});
return { stream, bytes, date, splitIndex, path: p };
} catch (err) {
console.error(
`[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`,
);
return null;
}
}
private pathFor(date: string, splitIndex: number): string {
const tail = splitIndex > 0 ? `.${splitIndex}` : '';
return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`);
}
private cleanup(): void {
let entries: string[];
try {
entries = fs.readdirSync(this.dir);
} catch {
return;
}
const retainMs = this.retainDays * 24 * 60 * 60 * 1000;
const cutoff = Date.now() - retainMs;
for (const name of entries) {
const m = FILE_RE.exec(name);
if (!m) continue;
const dateStr = m[1]!;
if (dateOf(dateStr).getTime() < cutoff) {
try {
fs.unlinkSync(path.join(this.dir, name));
} catch {
/* ignore */
}
}
}
}
}
export class FileTransport {
private readonly dir: string;
private readonly maxBytes: number;
private readonly retainDays: number;
private readonly enabled: boolean;
private readonly perUinEnabled: boolean;
private shared: FileWriter | null = null;
private perUin = new Map<number, FileWriter>();
constructor() {
this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR;
this.maxBytes =
parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024;
this.retainDays = parsePositiveInt(
process.env.SNOWLUMA_LOG_RETAIN_DAYS,
DEFAULT_RETAIN_DAYS,
);
this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0';
this.perUinEnabled = process.env.SNOWLUMA_LOG_PER_UIN !== '0';
if (this.enabled) {
const w = new FileWriter(this.dir, this.maxBytes, this.retainDays);
this.shared = w.isDisabled ? null : w;
}
}
/** True when no file output will happen (env disable or init failure). */
get isDisabled(): boolean {
return !this.shared;
}
/** Current shared-file path (or null if disabled / not yet opened). */
get currentPath(): string | null {
return this.shared?.currentPath ?? null;
}
/** Path of the per-UIN file for the given UIN, if open. */
perUinPath(uin: number): string | null {
return this.perUin.get(uin)?.currentPath ?? null;
}
write(line: string, uin?: number): void {
if (!this.shared) return;
const data = stripAnsi(line) + '\n';
const bytes = Buffer.byteLength(data, 'utf8');
this.shared.write(data, bytes);
if (uin !== undefined && this.perUinEnabled) {
let w = this.perUin.get(uin);
if (!w) {
w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.retainDays);
if (w.isDisabled) return;
this.perUin.set(uin, w);
}
w.write(data, bytes);
}
}
async close(): Promise<void> {
const closes: Promise<void>[] = [];
if (this.shared) closes.push(this.shared.close());
for (const w of this.perUin.values()) closes.push(w.close());
this.shared = null;
this.perUin.clear();
await Promise.all(closes);
}
}
let singleton: FileTransport | null = null;
export function getFileTransport(): FileTransport {
if (!singleton) singleton = new FileTransport();
return singleton;
}
/** Reset state between tests. Closes all active file handles. */
export async function _resetFileTransportForTesting(): Promise<void> {
if (singleton) await singleton.close();
singleton = null;
}

View File

@@ -1,51 +0,0 @@
const MAX_FIELD = 40;
const MAX_TOTAL = 200;
function valueRepr(v: unknown): string {
if (v === null) return 'null';
if (v === undefined) return 'undefined';
switch (typeof v) {
case 'string':
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
case 'number':
case 'boolean':
case 'bigint':
return String(v);
case 'object':
if (Array.isArray(v)) return `[len=${v.length}]`;
return '{...}';
default:
return typeof v;
}
}
/**
* Render a params object as a single line for logging. Skips deep
* traversal: nested objects collapse to `{...}`, arrays to `[len=N]`.
* Strings are quoted; long ones are truncated with an ellipsis.
*
* Output is capped at MAX_TOTAL chars; on overflow the tail is
* replaced with `...` so the next field doesn't get half-rendered.
*/
export function summarizeParams(params: unknown): string {
if (params === null || params === undefined) return '{}';
if (typeof params !== 'object') {
const s = String(params);
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s;
}
if (Array.isArray(params)) return `[len=${params.length}]`;
const out: string[] = [];
let total = 0;
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
const entry = `${k}=${valueRepr(v)}`;
// +1 accounts for the separating space we'd insert when joining.
if (total > 0 && total + entry.length + 1 > MAX_TOTAL) {
out.push('...');
break;
}
out.push(entry);
total += entry.length + (out.length > 1 ? 1 : 0);
}
return out.join(' ');
}

View File

@@ -1,228 +0,0 @@
import { format } from 'util';
import { getFileTransport } from './log-file-transport';
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
export interface LogEntry {
id: number;
time: string;
level: LogLevel;
scope: string;
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
uin?: number;
message: string;
line: string;
}
interface LogOptions {
scope: string;
uin?: number;
/** Free-form meta carried across `.child(...)` calls. Currently only
* `uin` is rendered, but the bag is preserved for future fields
* (requestId / traceId / etc.). */
meta?: Record<string, unknown>;
}
const UIN_SLOT_WIDTH = 12;
const LEVEL_WEIGHT: Record<LogLevel, number> = {
debug: 10,
info: 20,
success: 25,
warn: 30,
error: 40,
};
const LEVEL_LABEL: Record<LogLevel, string> = {
debug: 'DEBUG',
info: 'INFO',
success: 'OK',
warn: 'WARN',
error: 'ERROR',
};
const COLOR_CODE: Record<LogLevel, number> = {
debug: 90,
info: 36,
success: 32,
warn: 33,
error: 31,
};
const COLOR_SCOPE = 35;
const COLOR_DIM = 2;
const COLOR_RESET = '\x1b[0m';
const MAX_LOG_ENTRIES = 1000;
const logEntries: LogEntry[] = [];
const logSubscribers = new Set<(entry: LogEntry) => void>();
let nextLogId = 1;
function resolveMinLevel(): LogLevel {
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
return raw;
}
return 'info';
}
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
// setLogLevel() lets WebUI / SDK callers flip it without a restart.
// Only governs console + ring buffer + subscribers; the file
// transport always sees debug-and-up regardless.
let currentLevel: LogLevel = resolveMinLevel();
function shouldLog(level: LogLevel): boolean {
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
}
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
export function getLogLevel(): LogLevel {
return currentLevel;
}
/**
* Change the console / subscriber level at runtime. Invalid input is
* a no-op (returns false). File transport is unaffected — it always
* sees every level so post-mortems remain useful.
*/
export function setLogLevel(level: string): boolean {
const lower = String(level).toLowerCase();
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
currentLevel = lower as LogLevel;
return true;
}
function useColor(): boolean {
if (process.env.NO_COLOR === '1') return false;
return Boolean(process.stdout.isTTY);
}
function ansi(code: number, text: string): string {
return `\x1b[${code}m${text}${COLOR_RESET}`;
}
function currentTime(): string {
const d = new Date();
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
const ss = String(d.getSeconds()).padStart(2, '0');
return `${hh}:${mm}:${ss}`;
}
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
const message = format(...args);
const ts = currentTime();
const label = LEVEL_LABEL[level].padEnd(5, ' ');
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
if (!useColor()) {
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
}
const cTs = ansi(COLOR_DIM, ts);
const cLabel = ansi(COLOR_CODE[level], label);
// Pad first, then color only the visible tag so escape codes don't eat
// into the alignment width.
const cUin = uinTag
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
: ' '.repeat(UIN_SLOT_WIDTH);
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
}
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
// Console / subscriber level filter. File output is debug-and-up always;
// see log-file-transport.ts.
const passesConsole = shouldLog(level);
const message = format(...args);
const line = render(level, options, args);
const entry: LogEntry = {
id: nextLogId++,
time: new Date().toISOString(),
level,
scope: options.scope,
...(options.uin !== undefined ? { uin: options.uin } : {}),
message,
line,
};
if (passesConsole) {
logEntries.push(entry);
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
for (const subscriber of logSubscribers) subscriber(entry);
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
// Strip ASCII control characters before writing to terminal to prevent
// BEL (0x07) in user-provided strings (e.g. group member names) from
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
// sequences emitted by render() pass through intact.
// eslint-disable-next-line no-control-regex
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
}
// File transport always sees every level (debug-and-up) for post-mortem
// value; ANSI stripping happens inside the transport. UIN routes the
// line to its per-account sub-file in addition to the shared one.
getFileTransport().write(line, options.uin);
}
/**
* Flush and close the underlying log file. Call from shutdown hooks
* (SIGINT / SIGTERM / uncaughtException) so the WriteStream's internal
* buffer makes it to disk. Returns a promise that resolves once the OS
* has finalized the write.
*/
export function closeLogger(): Promise<void> {
return getFileTransport().close();
}
export function getRecentLogs(limit = 300): LogEntry[] {
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
return logEntries.slice(-n);
}
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
logSubscribers.add(callback);
return () => {
logSubscribers.delete(callback);
};
}
export interface Logger {
debug: (...args: unknown[]) => void;
info: (...args: unknown[]) => void;
success: (...args: unknown[]) => void;
warn: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
/**
* Derive a new logger that inherits this one's scope and carries
* additional metadata. Currently `uin` is the only key with rendering
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
* other keys are preserved on the options bag for forward compat.
*/
child: (meta: { uin?: number;[k: string]: unknown }) => Logger;
}
function makeLogger(opts: LogOptions): Logger {
return {
debug: (...args: unknown[]) => emit('debug', opts, args),
info: (...args: unknown[]) => emit('info', opts, args),
success: (...args: unknown[]) => emit('success', opts, args),
warn: (...args: unknown[]) => emit('warn', opts, args),
error: (...args: unknown[]) => emit('error', opts, args),
child: (meta) => {
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
return makeLogger({
scope: opts.scope,
uin: nextUin,
meta: { ...(opts.meta ?? {}), ...meta },
});
},
};
}
export function createLogger(scope: string): Logger {
return makeLogger({ scope });
}

View File

@@ -1,13 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"],
"noEmit": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}

View File

@@ -1,36 +1,10 @@
{
"name": "@snowluma/core",
"version": "1.9.2",
"version": "1.8.2",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
"main": "../../dist/index.mjs",
"exports": {
".": {
"types": "./src/index.ts",
"default": "../../dist/index.mjs"
},
"./core": {
"types": "./src/core.ts",
"default": "./src/core.ts"
},
"./core-context": {
"types": "./src/core-context.ts",
"default": "./src/core-context.ts"
},
"./core-ctx": {
"types": "./src/core-ctx.ts",
"default": "./src/core-ctx.ts"
},
"./hub": {
"types": "./src/hub.ts",
"default": "./src/hub.ts"
},
"./apis": {
"types": "./src/apis/index.ts",
"default": "./src/apis/index.ts"
}
},
"scripts": {
"build": "vite build",
"build:all": "cross-env BUILD_WEBUI=true vite build",
@@ -40,14 +14,6 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/channel": "workspace:*",
"@snowluma/channel-hook": "workspace:*",
"@snowluma/channel-socket": "workspace:*",
"@snowluma/common": "workspace:*",
"@snowluma/onebot": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
"devDependencies": {

View File

@@ -1,233 +0,0 @@
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
import type {
FriendInfo,
GroupMemberInfo,
GroupRequestInfo,
QQGroupInfo,
UserProfileInfo,
} from '@snowluma/protocol/qq-info';
import type { CoreContext } from '../core-context';
/**
* One row of an `OidbSvcTrpcTcp.0x9067_202` (download rkey) response.
* Cached for the duration of `ttlSeconds` and consumed by the OneBot
* media-URL resolver / message converter when a download URL must be
* minted on the fly. Lives at the apis layer (not on `Bridge`) because
* only `apis.contacts.fetchDownloadRKeys` materialises these rows.
*/
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
storeId: number;
createTime: number;
type: number;
}
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
type FriendPropertySource = {
additional?: Array<{
type?: number;
layer1?: {
properties?: Array<{
code?: number;
value?: string;
}>;
};
}>;
};
export function buildFriendProperties(raw: FriendPropertySource): Map<number, string> {
const props = new Map<number, string>();
for (const additional of raw.additional ?? []) {
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
for (const property of additional.layer1.properties ?? []) {
props.set(property.code ?? 0, property.value ?? '');
}
}
return props;
}
export function permissionToRole(permission: number): string {
switch (permission) {
case 1: return 'owner';
case 2: return 'admin';
default: return 'member';
}
}
const MEMBER_LIST_TTL_MS = 60_000;
export class ContactsApi {
/**
* Per-group inflight + last-fetch cache for `fetchGroupMemberList`.
* Keyed by groupId, lives for the lifetime of the Bridge.
*
* Without this, a busy OneBot client (e.g. MaiBot calling
* `get_group_member_info` once per inbound message) triggers one
* OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips
* Tencent risk-control and gets the account banned for 7 days.
*/
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
constructor(private readonly ctx: CoreContext) { }
async fetchFriendList(): Promise<FriendInfo[]> {
const friends: FriendInfo[] = [];
let nextUin: number | null = null;
do {
const resp = await FetchFriendListPage.invoke(this.ctx, { nextUin });
for (const raw of resp.friends ?? []) {
const props = buildFriendProperties(raw);
friends.push({
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
});
}
nextUin = resp.next?.uin ?? null;
if (nextUin === 0) nextUin = null;
} while (nextUin !== null);
this.ctx.identity.rememberFriends(friends);
return friends;
}
async fetchGroupList(): Promise<QQGroupInfo[]> {
const resp = await FetchGroupList.invoke(this.ctx);
const groups: QQGroupInfo[] = [];
for (const raw of resp.groups ?? []) {
groups.push({
groupId: raw.groupUin ?? 0,
groupName: raw.info?.groupName ?? '',
remark: raw.customInfo?.remark ?? '',
memberCount: raw.info?.memberCount ?? 0,
memberMax: raw.info?.memberMax ?? 0,
members: new Map(),
});
}
this.ctx.identity.rememberGroups(groups);
return groups;
}
async fetchGroupMemberList(
groupId: number,
options: { force?: boolean } = {},
): Promise<GroupMemberInfo[]> {
const now = Date.now();
const last = this.memberListLastFetch.get(groupId);
if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) {
return last.data;
}
const inflight = this.memberListInflight.get(groupId);
if (inflight) return inflight;
const task = (async () => {
try {
const data = await this.fetchGroupMemberListUncached(groupId);
this.memberListLastFetch.set(groupId, { at: Date.now(), data });
return data;
} finally {
this.memberListInflight.delete(groupId);
}
})();
this.memberListInflight.set(groupId, task);
return task;
}
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
const members: GroupMemberInfo[] = [];
let token = '';
do {
const resp = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
for (const raw of resp.members ?? []) {
members.push({
uin: raw.uin?.uin ?? 0,
uid: raw.uin?.uid ?? '',
nickname: raw.memberName ?? '',
card: raw.memberCard?.memberCard ?? '',
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
});
}
token = resp.token ?? '';
} while (token);
this.ctx.identity.rememberGroupMembers(groupId, members);
return members;
}
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {
const info = await FetchUserProfile.invoke(this.ctx, { uin });
this.ctx.identity.rememberUserProfile(info);
return info;
}
/** Look up a user profile by UID (string form). Used for strangers
* whose UIN we don't have yet — typically the requester on a
* group join request push. Mirrors Lagrange's `FetchUserInfoEvent
* .Create(targetUid)` path. */
async fetchUserProfileByUid(uid: string): Promise<UserProfileInfo> {
const info = await FetchUserProfileByUid.invoke(this.ctx, { uid });
if (info.uin > 0) this.ctx.identity.rememberUserProfile(info);
return info;
}
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> {
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered });
const requests: GroupRequestInfo[] = [];
for (const raw of resp.requests ?? []) {
requests.push({
groupId: raw.group?.groupUin ?? 0,
groupName: raw.group?.groupName ?? '',
targetUid: raw.target?.uid ?? '',
targetUin: 0,
targetName: raw.target?.name ?? '',
invitorUid: raw.invitor?.uid ?? '',
invitorUin: 0,
invitorName: raw.invitor?.name ?? '',
operatorUid: raw.operatorUser?.uid ?? '',
operatorUin: 0,
operatorName: raw.operatorUser?.name ?? '',
sequence: Number(raw.sequence ?? 0),
state: raw.state ?? 0,
eventType: raw.eventType ?? 0,
comment: raw.comment ?? '',
filtered,
});
}
this.ctx.identity.rememberGroupRequests(requests);
return requests;
}
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
const resp = await FetchDownloadRkeys.invoke(this.ctx);
const result: DownloadRKeyInfo[] = [];
for (const entry of resp.downloadRkey?.rkeys ?? []) {
const rkey = entry.rkey ?? '';
const type = entry.type ?? 0;
if (rkey && type) {
result.push({
rkey,
ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
storeId: entry.storeId ?? 0,
createTime: entry.rkeyCreateTime ?? 0,
type,
});
}
}
return result;
}
}

View File

@@ -1,91 +0,0 @@
import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice';
import {
FetchAiVoiceList,
type AiVoiceCategory as NamespaceAiVoiceCategory,
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
import type { CoreContext } from '../core-context';
import type { MediaIndexNode } from './shared';
// ─────────────── public types (re-exported from bridge.ts as before) ───
export type StrangerStatus = NamespaceStrangerStatus;
export const AiVoiceChatType = {
Unknown: 0,
Sound: 1,
Sing: 2,
} as const;
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
export type AiVoiceCategory = NamespaceAiVoiceCategory;
export interface AiVoiceItem {
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export class ExtrasApi {
constructor(private readonly ctx: CoreContext) { }
// ─────────────── Group todo (0xF90) ───────────────
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
}
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
}
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
}
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
/**
* Returns `null` on transport / decode failure rather than throwing,
* so the OneBot action can produce a clean retcode without try/catch
* gymnastics. Namespace throws on transport failure → swallow here.
*/
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
try {
return await GetStrangerStatus.invoke(this.ctx, { uin });
} catch {
return null;
}
}
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
}
/**
* Trigger AI voice synthesis. Server may return an empty msgInfo while
* the render is in-flight; we retry until a node materialises or the
* cap is hit. napcat uses the same 30-retry budget.
*
* The returned MediaIndexNode plugs directly into
* `apis.groupFile.getPttUrl`, which already handles every other
* download-URL fetch in SnowLuma.
*/
async fetchAiVoice(
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType | number,
maxRetries = 30,
): Promise<MediaIndexNode> {
// Random 32-bit session id — server uses this to deduplicate polls.
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
for (let i = 0; i < maxRetries; i++) {
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
if (node) return node as MediaIndexNode;
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
}

View File

@@ -1,560 +0,0 @@
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type {
LongMsgResult,
RecvLongMsgReq,
RecvLongMsgResp,
SendLongMsgReq,
SendLongMsgResp,
} from '@snowluma/proto-defs/longmsg';
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
import { parseMsgPush } from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { CoreContext } from '../core-context';
import { resolveSelfUid, toInt } from './shared';
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
// of the process — that's enough because OneBot clients typically
// resolve a forward immediately after receiving the parent message.
const forwardResCache = new Map<string, ForwardNodePayload[]>();
// Per-layer piggyback entry. Each level of a nested forward attaches
// its own msgBody under a uuid `actionCommand`, so when the receiver
// fetches the outermost res_id it gets every layer in one shot
// (modelled on NapCat's `uploadForwardedNodesPacket` — see
// `dev/NapCatQQ/.../SendMsg.ts:208-347`). Lagrange.Core master + V2
// both ship a single-action model and silently break when the
// recipient is a NapCat instance trying to walk the tree.
interface ForwardInnerAction {
uuid: string;
msgBody: PushMsgBody[];
}
interface ForwardUploadResult {
resId: string;
// The current level's msgBody + uuid — what an outer caller would
// piggyback to expose this layer through the tree.
msgBody: PushMsgBody[];
uuid: string;
// All accumulated piggyback entries from deeper levels. Outer
// callers concatenate these to their own actions list so the
// outermost upload carries the full tree.
innerActions: ForwardInnerAction[];
}
// Local hex-decode helper — avoids importing the heavyweight `pipeline`
// module just for one call. Mirrors `highway/pipeline.ts::hexToBytes`.
function hexToBytesLocal(hex: string): Uint8Array {
const s = hex.trim();
if (!s) return new Uint8Array(0);
const len = s.length >> 1;
const out = new Uint8Array(len);
for (let i = 0; i < len; i++) {
out[i] = parseInt(s.substr(i * 2, 2), 16);
}
return out;
}
async function buildForwardPushBody(
bridge: BridgeContext,
node: ForwardNodePayload,
groupId?: number,
userUid?: string,
): Promise<PushMsgBody> {
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
const nickname = node.nickname.trim() || String(fromUin);
// image/record/video upload inside a forward node must be scoped to the
// forward's recipient: group → groupId, private → recipient uid.
// Without this the OIDB upload (0x11c4/0x11c5) has no scene and the
// element builder throws "private image target uid is missing".
//
// `forwardFake: true` keeps `{type:'file'}` segments in the
// long-msg payload: group → emitted as transElem(24) in elems[],
// c2c → handled below via msgContent (FileExtra { file: NotOnlineFile }).
// The QQ-NT live-send pipeline would reject these (transElem(24) →
// result=79; notOnlineFile via PbSendMsg doesn't render), but the
// long-msg upload service stores the bytes verbatim and the
// receiver decodes them through the normal msg-push path.
const sendCtx = groupId !== undefined
? { bridge, groupId, forwardFake: true }
: userUid
? { bridge, userUid, forwardFake: true }
: { bridge, forwardFake: true };
const elems = await buildSendElems(node.elements, sendCtx);
const now = Math.floor(Date.now() / 1000);
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
const seq = Math.floor(Math.random() * 9000000) + 1000000;
// c2c-file in a forward node — element-builder intentionally skips
// it (RichText.notOnlineFile + msgContent live outside elems[]). For
// forward fake-send we mirror what an inbound c2c file message looks
// like on the wire: serialise the FileExtra blob and ride it on
// `body.msgContent`. The receiver's rich-body-decoder reads from
// `msgContent` first (see msg-push/rich-body-decoder.ts:446+), so
// the bubble renders with the right file name + size when the
// forward is expanded. Only the FIRST c2c file in a node ships —
// QQ NT's bubble can only carry one msgContent payload, same as
// a live c2c send. Group nodes ignore this branch entirely (the
// transElem(24) elems[] entry above covers them).
let msgContent: Uint8Array | undefined;
if (groupId === undefined) {
const fileEl = node.elements.find(e => e.type === 'file' && e.fileId);
if (fileEl) {
// Honour inline segment fields first; fall back to the upload
// metadata cache (populated by upload_private_file). Without
// size/md5 the receiver would render "0 B" so prefer recovering
// them — see same logic in modules/message-actions.ts.
const cached = bridge.recallUploadedFile(fileEl.fileId ?? '');
const fileMd5 = fileEl.md5Hex
? hexToBytesLocal(fileEl.md5Hex)
: (cached?.fileMd5 ?? new Uint8Array(0));
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
const fileHash = fileEl.fileHash ?? cached?.fileHash ?? '';
const sevenDays = 7 * 24 * 60 * 60;
msgContent = protobuf_encode<FileExtra>({
file: {
fileType: 0,
fileUuid: fileEl.fileId!,
fileMd5,
fileName,
fileSize: BigInt(fileSize),
subcmd: 1,
dangerEvel: 0,
expireTime: now + sevenDays,
fileHash,
},
});
}
}
return {
responseHead: {
fromUin,
toUid: bridge.identity.selfUid ?? '',
forward: {
friendName: nickname,
},
},
contentHead: {
msgType: 9,
subType: 4,
msgId: random,
sequence: seq,
timestamp: now,
divSeq: 0,
},
body: {
richText: {
elems,
},
...(msgContent ? { msgContent } : {}),
},
};
}
// Inner forward preview metadata — kept minimal here (the OneBot
// `parseForwardNodes` caller can override these on the top-level
// node by passing custom forwardSource/forwardSummary on the
// non-nested send path; nested levels just get sensible defaults
// since they're synthesised by us and never reach OneBot input).
function deriveInnerSource(innerNodes: ForwardNodePayload[], isGroup: boolean): string {
const nicks: string[] = [];
const seen = new Set<string>();
for (const node of innerNodes) {
const name = (node.nickname ?? '').trim();
if (name && !seen.has(name)) {
seen.add(name);
nicks.push(name);
}
if (nicks.length >= 4) break;
}
if (nicks.length === 0) return isGroup ? '群聊的聊天记录' : '聊天记录';
return `${nicks.join('和')}的聊天记录`;
}
function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> {
return innerNodes.slice(0, 4).map(node => {
const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户');
const previewText = previewFromElements(node.elements);
return { text: previewText ? `${name}: ${previewText}` : name };
});
}
function previewFromElements(elements: MessageElement[]): string {
for (const elem of elements) {
if (elem.type === 'text' && elem.text) return elem.text.slice(0, 30);
if (elem.type === 'image') return '[图片]';
if (elem.type === 'record') return '[语音]';
if (elem.type === 'video') return '[视频]';
if (elem.type === 'file') return '[文件]';
if (elem.type === 'forward') return '[聊天记录]';
if (elem.type === 'face') return '[表情]';
}
return '';
}
export class ForwardApi {
constructor(private readonly ctx: CoreContext) { }
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
return resId;
}
/**
* Recursive upload with NapCat-style piggyback. Each invocation:
* 1. Walks `nodes`. For any node whose `innerForward` is set,
* recursively uploads that inner chain first (which itself runs
* this same recursion).
* 2. Replaces the node's `elements` with an ARK preview pointing at
* the inner res_id (and inner uuid for receiver-side walking).
* 3. Accumulates the inner level's `{uuid, msgBody}` plus all of
* ITS accumulated `innerActions` into this level's piggyback list.
* 4. Encodes this level's long-msg payload as
* `[MultiMsg + thisMsgBody, ...innerActions]`, uploads it,
* returns `{resId, msgBody, uuid, innerActions}` so an outer
* caller can keep piggybacking up the tree.
*/
private async uploadRecursive(
nodes: ForwardNodePayload[],
groupId?: number,
userId?: number,
): Promise<ForwardUploadResult> {
if (!Array.isArray(nodes) || nodes.length === 0) {
throw new Error('forward nodes are required');
}
const bridge = this.ctx;
// For a private forward to `userId`, any image/record/video inside a node
// needs the recipient's uid as upload scene. Resolve it once up-front,
// and only when at least one node actually contains media (saves an RPC
// for text-only forwards). Also need it when a node is itself a nested
// forward — the inner upload uses the same scene.
let userUid: string | undefined;
if (groupId === undefined && userId !== undefined && userId > 0) {
const needsUid = nodes.some(node => !!node.innerForward
|| node.elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video'));
if (needsUid) {
const resolved = await this.ctx.resolveUserUid(userId);
if (resolved) userUid = resolved;
}
}
// Walk nodes and resolve nested forwards first (so we know their
// res_id / uuid before encoding the outer ARK previews). Build
// `processedNodes` with elements rewritten for nested layers,
// and collect every inner level's piggyback in `myInnerActions`.
//
// CRITICAL: the same uuid (`inner.uuid`) MUST be baked into the
// outer's preview element as `forwardUuid` AND used as the
// `actionCommand` for the outer's piggyback entry. That's the
// alignment the QQ-NT receiver uses to find the inner layer
// inside the outer's LongMsgResult without a second server fetch
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
const myInnerActions: ForwardInnerAction[] = [];
const processedNodes: ForwardNodePayload[] = [];
const isGroup = groupId !== undefined;
for (const node of nodes) {
if (node.innerForward && node.innerForward.length > 0) {
const inner = await this.uploadRecursive(node.innerForward, groupId, userId);
// NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}`
// + the entire `inner.innerPacketMsg` array up to its caller. We
// mirror that — `inner.uuid` indexes the inner level itself,
// and `inner.innerActions` already contains deeper layers.
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
myInnerActions.push(...inner.innerActions);
// Replace the inner placeholder element with a forward preview
// pointing at the inner res_id. `forwardUuid: inner.uuid`
// baked into the LightApp JSON's `meta.detail.uniseq` is what
// closes the loop with our piggyback action above.
const previewElement: MessageElement = {
type: 'forward',
resId: inner.resId,
forwardUuid: inner.uuid,
forwardSource: deriveInnerSource(node.innerForward, isGroup),
forwardSummary: `查看${node.innerForward.length}条转发消息`,
forwardPrompt: '[聊天记录]',
forwardNews: previewLinesFromNodes(node.innerForward),
forwardTSum: node.innerForward.length,
};
processedNodes.push({
userUin: node.userUin,
nickname: node.nickname,
elements: [previewElement],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
});
} else {
processedNodes.push(node);
}
}
// Encode this level's msgBody.
const msgBody = await Promise.all(processedNodes.map(
node => buildForwardPushBody(bridge, node, groupId, userUid),
));
// Compose the action list: own MultiMsg + piggybacked inner actions.
const longMsgResult = protobuf_encode<LongMsgResult>({
action: [
{ actionCommand: 'MultiMsg', actionData: { msgBody } },
...myInnerActions.map(a => ({
actionCommand: a.uuid,
actionData: { msgBody: a.msgBody },
})),
],
});
const selfUid = await resolveSelfUid(bridge);
const info: SendLongMsgReq['info'] = {
type: groupId ? 3 : 1,
uid: { uid: groupId ? String(groupId) : selfUid },
payload: gzipSync(Buffer.from(longMsgResult)),
};
if (groupId) info.groupUin = groupId;
const request = protobuf_encode<SendLongMsgReq>({
info,
settings: {
field1: 4,
field2: 1,
field3: 7,
field4: 0,
},
});
const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'upload forward message failed');
}
const resp = protobuf_decode<SendLongMsgResp>(result.responseData);
const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : '';
if (!resId) {
throw new Error('upload forward message response missing res_id');
}
forwardResCache.set(resId, processedNodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId ?? groupId,
senderCard: node.senderCard,
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
})));
return {
resId,
msgBody,
// UUID generated here so the OUTER caller can use it as both
// (1) the `actionCommand` for its piggyback entry carrying our
// msgBody, and
// (2) the `forwardUuid` baked into its forward-preview element
// pointing at our resId.
// Receivers walking the outer's LongMsgResult find the inner
// layer by matching `uniseq` from (2) against `actionCommand`
// from (1) — no separate fetch needed.
uuid: randomUUID(),
innerActions: myInnerActions,
};
}
async fetch(resId: string): Promise<ForwardNodePayload[]> {
const bridge = this.ctx;
const cached = forwardResCache.get(resId);
if (cached) {
return cached.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
}));
}
const selfUid = await resolveSelfUid(bridge);
const request = protobuf_encode<RecvLongMsgReq>({
info: {
uid: { uid: selfUid },
resId,
acquire: true,
},
settings: {
field1: 2,
field2: 0,
field3: 0,
field4: 0,
},
});
const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'download forward message failed');
}
const resp = protobuf_decode<RecvLongMsgResp>(result.responseData);
const payload = resp?.result?.payload;
if (!(payload instanceof Uint8Array) || payload.length === 0) {
throw new Error('download forward message payload is empty');
}
const inflate = gunzipSync(Buffer.from(payload));
const longMsg = protobuf_decode<LongMsgResult>(inflate);
const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : [];
const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg');
const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody) ? mainAction!.actionData!.msgBody : [];
// Piggyback index: any non-`MultiMsg` action carries an inner
// layer keyed by the uuid the sender baked into its forward
// preview's `uniseq`. Build a lookup so we can resolve inner
// forwards (via their uniseq → inner msgBody) without a second
// server roundtrip — matches the sender-side piggyback emitted in
// `uploadRecursive` above.
const piggybackByUuid = new Map<string, PushMsgBody[]>();
for (const action of actions) {
const cmd = action?.actionCommand;
if (!cmd || cmd === 'MultiMsg') continue;
const body = Array.isArray(action.actionData?.msgBody) ? action.actionData.msgBody : [];
piggybackByUuid.set(cmd, body);
}
const nodes = this.decodeMsgBodiesToNodes(msgBodyList);
// Walk the decoded outer nodes for inner-forward previews
// (`type: 'forward', forwardUuid: <uniseq>`). For each, pull the
// matching piggyback body, decode it into inner nodes, and seed
// the cache by the inner resId so a follow-up `fetch(innerResId)`
// hits the cache instead of the wire.
if (piggybackByUuid.size > 0) {
this.consumePiggybacks(nodes, piggybackByUuid);
}
if (nodes.length > 0) {
forwardResCache.set(resId, cloneNodes(nodes));
}
return nodes;
}
/** Walk a list of PushMsgBody, run each through the regular msg-push
* pipeline, and shape the result into ForwardNodePayloads. Extracted
* so both the outer + piggyback decode paths share one implementation. */
private decodeMsgBodiesToNodes(msgBodyList: PushMsgBody[]): ForwardNodePayload[] {
const out: ForwardNodePayload[] = [];
for (const msgBody of msgBodyList) {
const wrapped = protobuf_encode<PushMsg>({ message: msgBody });
const pkt: PacketInfo = {
pid: 0,
uin: this.ctx.identity.uin,
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 0,
retCode: 0,
fromClient: false,
body: wrapped,
};
const events = parseMsgPush(pkt, this.ctx.identity);
const event = events.find(e =>
e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
if (!event) continue;
if (event.kind === 'group_message') {
out.push({
userUin: event.senderUin,
nickname: event.senderCard || event.senderNick,
elements: event.elements,
time: event.time,
msgId: event.msgId,
msgSeq: event.msgSeq,
groupId: event.groupId,
senderCard: event.senderCard,
messageType: 'group',
});
} else if (event.kind === 'friend_message') {
out.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
time: event.time,
msgId: event.msgId,
msgSeq: event.msgSeq,
messageType: 'private',
});
} else {
out.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
time: event.time,
msgSeq: event.msgSeq,
groupId: event.groupId,
messageType: 'private',
});
}
}
return out;
}
/** Recursively resolve forward previews against the piggyback table.
* For every `{type: 'forward', resId, forwardUuid}` element we find,
* look up the uniseq in the piggyback map; if hit, decode the
* inner msgBody and cache it by inner resId, then descend into that
* inner layer to resolve deeper nestings carried in the SAME
* piggyback set (NapCat hoists the entire tree's piggybacks onto
* the outermost action list). */
private consumePiggybacks(
nodes: ForwardNodePayload[],
piggybackByUuid: Map<string, PushMsgBody[]>,
): void {
const seen = new Set<string>();
const visit = (chain: ForwardNodePayload[]): void => {
for (const node of chain) {
for (const elem of node.elements) {
if (elem.type !== 'forward') continue;
const uuid = elem.forwardUuid;
const innerResId = elem.resId;
if (!uuid || !innerResId || seen.has(uuid)) continue;
const body = piggybackByUuid.get(uuid);
if (!body) continue;
seen.add(uuid);
const innerNodes = this.decodeMsgBodiesToNodes(body);
forwardResCache.set(innerResId, cloneNodes(innerNodes));
visit(innerNodes);
}
}
};
visit(nodes);
}
}
function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] {
return nodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
}));
}

View File

@@ -1,29 +0,0 @@
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
import type { CoreContext } from '../core-context';
export class FriendApi {
constructor(private readonly ctx: CoreContext) { }
/**
* Accept or reject an inbound friend request. `uidOrFlag` is either a
* pre-resolved UID string or a numeric uin (then resolved on the fly).
*/
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
}
async delete(userId: number, block = false): Promise<void> {
await DeleteFriend.invoke(this.ctx, { userId, block });
// Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
// shouldn't make the delete itself look failed.
try { await this.ctx.apis.contacts.fetchFriendList(); } catch { /* ignore */ }
}
setRemark(userId: number, remark: string): Promise<void> {
return SetFriendRemark.invoke(this.ctx, { userId, remark });
}
}

View File

@@ -1,87 +0,0 @@
import { GetAtAllRemain } from '@snowluma/protocol/oidb-services/group-admin/get-at-all-remain';
import { KickMember } from '@snowluma/protocol/oidb-services/group-admin/kick-member';
import { KickMembers } from '@snowluma/protocol/oidb-services/group-admin/kick-members';
import { LeaveGroup } from '@snowluma/protocol/oidb-services/group-admin/leave-group';
import { MuteAll } from '@snowluma/protocol/oidb-services/group-admin/mute-all';
import { MuteMember } from '@snowluma/protocol/oidb-services/group-admin/mute-member';
import { SetAddOption } from '@snowluma/protocol/oidb-services/group-admin/set-add-option';
import { SetAddRequest } from '@snowluma/protocol/oidb-services/group-admin/set-add-request';
import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin';
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
import type { CoreContext } from '../core-context';
export class GroupAdminApi {
constructor(private readonly ctx: CoreContext) { }
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
}
muteAll(groupId: number, enable: boolean): Promise<void> {
return MuteAll.invoke(this.ctx, { groupId, enable });
}
setAddOption(groupId: number, addType: number): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType });
}
setSearch(groupId: number): Promise<void> {
return SetSearch.invoke(this.ctx, { groupId });
}
setAddRequest(
groupId: number, sequence: number, eventType: number,
approve: boolean, reason = '', filtered = false,
): Promise<void> {
return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered });
}
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
return KickMember.invoke(this.ctx, { groupId, userId, reject, reason });
}
kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
}
leave(groupId: number): Promise<void> {
return LeaveGroup.invoke(this.ctx, { groupId });
}
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
}
setCard(groupId: number, userId: number, card: string): Promise<void> {
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
}
setName(groupId: number, name: string): Promise<void> {
return SetGroupName.invoke(this.ctx, { groupId, name });
}
setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title });
}
/**
* The bot's local-only label for a group. Lives here rather than
* `FriendApi` because the semantic is "operate on a group" rather
* than "operate on a contact list".
*/
setRemark(groupId: number, remark: string): Promise<void> {
return SetGroupRemark.invoke(this.ctx, { groupId, remark });
}
getAtAllRemain(groupId: number): Promise<{
can_at_all: boolean;
remain_at_all_count_for_group: number;
remain_at_all_count_for_uin: number;
}> {
return GetAtAllRemain.invoke(this.ctx, { groupId });
}
}

View File

@@ -1,279 +0,0 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import type {
DeleteMediasRequest,
DeleteMediasResponse,
DoQunCommentRequest,
DoQunCommentResponse,
DoQunLikeRequest,
DoQunLikeResponse,
GetMediaListRequest,
GetMediaListResponse,
MediaInfo,
} from '@snowluma/proto-defs/oidb-actions/group-album';
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
function convertBigIntToString(obj: unknown): JsonValue {
if (obj === null || obj === undefined) return null;
if (typeof obj === 'bigint') return obj.toString();
if (Array.isArray(obj)) return obj.map(convertBigIntToString);
if (typeof obj === 'object') {
const result: JsonObject = {};
for (const [key, value] of Object.entries(obj)) {
result[key] = convertBigIntToString(value);
}
return result;
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') return obj;
return null;
}
export class GroupAlbumApi {
constructor(private readonly ctx: CoreContext) { }
// 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。
async list(groupId: number): Promise<GroupAlbumList> {
const groupCode = groupId.toString();
const uin = this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
return albumData?.album || [];
}
// 上传图片到现有相册(HTTP 分片上传)。
async upload(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void> {
const groupCode = groupId.toString();
const uin = this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
}
async getMediaList(groupId: number, albumId: string, attachInfo = ''): Promise<GroupAlbumMediaResult> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protobuf_encode<GetMediaListRequest>({
field1: 0,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
reqInfo: {
groupId: groupId.toString(),
albumId,
field3: 0,
attachInfo,
field5: '',
},
traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
body,
15000,
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to get album media list');
}
const resp = protobuf_decode<GetMediaListResponse>(result.responseData);
if (resp.field1 !== 0) {
throw new Error(`fetch album media list error: retCode ${resp.field1 ?? 'unknown'}`);
}
const data = resp.data ?? {};
const mediaList = data.mediaList ?? [];
const nextAttachInfo = data.nextAttachInfo ?? '';
return convertBigIntToString({ mediaList, nextAttachInfo }) as unknown as GroupAlbumMediaResult;
}
async comment(groupId: number, albumId: string, lloc: string, content: string): Promise<GroupAlbumCommentResult> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const clientKey = Date.now().toString();
const uin = this.ctx.identity.uin;
const body = protobuf_encode<DoQunCommentRequest>({
field1: 8527,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
body: {
groupId: groupId.toString(),
field3: 2,
reqBody: {
field1: { field3: 0, field4: '' },
field2: {
field1: { uin },
},
field5: {
field1: {
field2: {
field1: 0, field2: '',
lloc,
field4: '', field6: '', field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0,
},
},
albumId,
field5: 0,
},
},
field5: {
field2: { uin },
field3: {
field1: 0,
field2: content,
field3: '', field4: '', field5: 0, field6: '',
},
clientKey,
},
},
traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
body,
15000,
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to comment on album media');
}
const resp = protobuf_decode<DoQunCommentResponse>(result.responseData);
const resCode = resp.field1;
if (resCode !== 0 && resCode !== 8527 && !resp.comment) {
throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`);
}
const commentData = resp.comment?.data ?? {};
return convertBigIntToString({
id: commentData.id ?? '',
user: { uin: commentData.user?.uin ?? '' },
content: commentData.content ?? [],
time: commentData.time ?? '0',
clientKey: commentData.clientKey ?? '',
}) as unknown as GroupAlbumCommentResult;
}
async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<JsonValue> {
const uin = this.ctx.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const type = isLike ? 2 : 1;
const status = isLike ? 0 : 1;
let id = '';
if (lloc) {
id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
} else {
id = `421_1_0_${groupId}|${albumId}|${batchId}`;
}
const body = protobuf_encode<DoQunLikeRequest>({
field1: 5495,
field2: 'h5_test',
field3: 'h5_test',
body: {
type,
like: { id, status },
publish: {
cellCommon: {
time: BigInt(Date.now()),
feedId: `422_0_${batchId}`,
},
cellUserInfo: {
user: { uin },
},
cellMedia: {
albumId,
batchId: BigInt(batchId),
},
cellQunInfo: {
qunId: groupId.toString(),
},
},
clientKey,
},
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
body,
15000,
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to like album media');
}
const resp = protobuf_decode<DoQunLikeResponse>(result.responseData);
const resCode = resp.field1;
if (resCode !== 5495) {
throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`);
}
return convertBigIntToString(resp.body?.like ?? {});
}
async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> {
const uin = this.ctx.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protobuf_encode<DeleteMediasRequest>({
field1: 8694,
field2: 'h5_test',
field3: 'h5_test',
body: {
groupId: groupId.toString(),
albumId,
lloc,
},
traceId: clientKey,
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
body,
15000,
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to delete album media');
}
const resp = protobuf_decode<DeleteMediasResponse>(result.responseData);
const resCode = resp.field1;
const errCode = resp.field2;
const errMsg = resp.field3;
if (resCode !== 8694 || errCode) {
throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`);
}
return { success: true };
}
}
export interface GroupAlbumMediaResult {
mediaList: Array<JsonValue & Partial<MediaInfo>>;
nextAttachInfo: string;
}
export type GroupAlbumList = NonNullable<Awaited<ReturnType<typeof getGroupAlbumList>>>['album'];
export interface GroupAlbumCommentResult {
id: string;
user: { uin: string };
content: Array<{ type: number; content: string }>;
time: string;
clientKey: string;
}

View File

@@ -1,641 +0,0 @@
import { toHexUpper } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils';
import { protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/create-group-folder';
import { DeleteGroupFile } from '@snowluma/protocol/oidb-services/group-file/delete-group-file';
import { DeleteGroupFolder } from '@snowluma/protocol/oidb-services/group-file/delete-group-folder';
import { GetGroupFileCount } from '@snowluma/protocol/oidb-services/group-file/get-group-file-count';
import { GetGroupFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-file-url';
import { GetGroupPttUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-ptt-url';
import { GetGroupVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-video-url';
import { GetPrivateFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-file-url';
import { GetPrivatePttUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-ptt-url';
import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-video-url';
import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page';
import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file';
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request';
import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request';
import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
const log = createLogger('GroupFile');
// ─────────────── public result types ───────────────
export interface GroupFileInfo {
fileId: string;
fileName: string;
busId: number;
fileSize: number;
uploadTime: number;
deadTime: number;
modifyTime: number;
downloadTimes: number;
uploader: number;
uploaderName: string;
}
export interface GroupFolderInfo {
folderId: string;
folderName: string;
createTime: number;
creator: number;
creatorName: string;
totalFileCount: number;
}
export interface GroupFilesResult {
files: GroupFileInfo[];
folders: GroupFolderInfo[];
}
export interface UploadFileResult {
fileId: string | null;
fileHash?: string | null;
}
// Re-export so callers don't have to dig into apis/shared.
export type { MediaIndexNode } from './shared';
// ─────────────── file-specific helpers ───────────────
function normalizeDirectory(dir?: string): string {
if (!dir || !dir.trim()) return '/';
return dir;
}
function bytesToHexUpper(data: unknown): string {
if (!(data instanceof Uint8Array) || data.length === 0) return '';
return toHexUpper(data);
}
// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives
// little-endian-packed (byte0 = first dotted octet) and we unpack it the
// same way. Force-unsigned the shift to keep negative ints (high bit set)
// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000
// into a negative number.
function int32ToIpv4Dotted(value: number): string {
const b1 = value & 0xFF;
const b2 = (value >>> 8) & 0xFF;
const b3 = (value >>> 16) & 0xFF;
const b4 = (value >>> 24) & 0xFF;
return `${b1}.${b2}.${b3}.${b4}`;
}
function normalizeUploadFileName(name: string, fallback: string): string {
const trimmed = name.trim();
if (trimmed) return trimmed;
const safeFallback = fallback.trim();
return safeFallback || 'file.bin';
}
function md5First10MB(bytes: Uint8Array): Uint8Array {
const limit = Math.min(bytes.length, 10 * 1024 * 1024);
return computeMd5(bytes.subarray(0, limit));
}
function buildGroupFileUploadExt(
senderUin: number,
groupId: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
fileId: string,
uploadKey: Uint8Array,
checkKey: Uint8Array,
uploadHost: string,
uploadPort: number,
): Uint8Array {
return protobuf_encode<FileUploadExt>({
unknown1: 100,
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
senderUin: BigInt(senderUin),
receiverUin: BigInt(groupId),
groupCode: BigInt(groupId),
},
fileEntry: {
fileSize: BigInt(Math.max(0, fileSize)),
md5,
md5S2: md5,
checkKey,
fileId,
uploadKey,
},
clientInfo: {
clientType: 3,
appId: '100',
terminalType: 3,
clientVer: '1.1.1',
unknown: 4,
},
fileNameInfo: {
fileName,
},
host: {
hosts: [
{
url: {
host: uploadHost,
unknown: 1,
},
port: uploadPort,
},
],
},
},
unknown200: 0,
});
}
function buildPrivateFileUploadExt(
senderUin: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
sha1: Uint8Array,
fileId: string,
uploadKey: Uint8Array,
uploadHost: string,
uploadPort: number,
): Uint8Array {
return protobuf_encode<FileUploadExt>({
unknown1: 100,
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
senderUin: BigInt(senderUin),
receiverUin: 0n,
groupCode: 0n,
},
fileEntry: {
fileSize: BigInt(Math.max(0, fileSize)),
md5,
md5S2: md5,
checkKey: sha1,
fileId,
uploadKey,
},
clientInfo: {
clientType: 3,
appId: '100',
terminalType: 3,
clientVer: '1.1.1',
unknown: 4,
},
fileNameInfo: {
fileName,
},
host: {
hosts: [
{
url: {
host: uploadHost,
unknown: 1,
},
port: uploadPort,
},
],
},
},
unknown3: 0,
unknown200: 1,
});
}
export class GroupFileApi {
constructor(private readonly ctx: CoreContext) { }
// ─────────────── publish (group file → chat) ───────────────
publish(groupId: number, fileId: string): Promise<void> {
if (!fileId) throw new Error('publish requires fileId');
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
}
// ─────────────── count ───────────────
getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> {
return GetGroupFileCount.invoke(this.ctx, { groupId });
}
// ─────────────── upload (3-stage: OIDB preflight → highway → publish) ───────────────
async upload(
groupId: number,
source: string,
name = '',
folderId = '/',
uploadFile = true,
): Promise<UploadFileResult> {
const bridge = this.ctx;
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
// so override the default 1 GiB cap with the protocol ceiling.
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('group file is empty');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
groupId,
fileName,
folderId: normalizeDirectory(folderId),
fileSize: loaded.bytes.length,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
});
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
if (!fileId) throw new Error('group file upload response missing file_id');
// Remember the upload so a later `send_group_msg` carrying just the
// file_id can route via `publish` without forcing the OneBot caller
// to thread fileName/size/md5 separately. For groups the wire
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
// mainly for log-line correctness; the c2c counterpart in
// `uploadPrivate` is where the cache is actually load-bearing.
this.ctx.rememberUploadedFile({
fileId,
scope: 'group',
groupId,
fileName,
fileSize: loaded.bytes.length,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|| '';
const uploadPort = toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
throw new Error('group file upload host is invalid');
}
const ext = buildGroupFileUploadExt(
senderUin,
groupId,
fileName,
loaded.bytes.length,
hashes.md5,
fileId,
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
uploadHost,
uploadPort,
);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
}
// Stage 3: file is on the server, now publish it as a chat message.
//
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
// the chat shows nothing. The publish step goes via a dedicated OIDB
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the
// caller opts out via `uploadFile=false` (treat that as "I only
// wanted the slot allocated, hold the chat post"). Routes through
// `this.publish` so tests can mock at the same Api boundary.
if (uploadFile) {
try {
await this.publish(groupId, fileId);
} catch (err) {
// The bytes are already on the server and the fileId is valid —
// fail loud but don't lose the upload result the action handler
// committed to returning. Callers can still resolve the file by
// id; they'll just have to re-publish it themselves.
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
fileId, err instanceof Error ? err.message : String(err));
}
}
return { fileId };
}
async uploadPrivate(
userId: number,
source: string,
name = '',
uploadFile = true,
): Promise<UploadFileResult> {
const bridge = this.ctx;
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('private file is empty');
const targetUid = await this.ctx.resolveUserUid(userId);
let selfUid = this.ctx.identity.selfUid;
if (!selfUid) {
const selfUin = toInt(this.ctx.identity.uin);
if (selfUin > 0) {
selfUid = await this.ctx.resolveUserUid(selfUin);
}
}
if (!selfUid) throw new Error('self uid is unavailable');
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const upload = await UploadPrivateFileRequest.invoke(this.ctx, {
senderUid: selfUid,
receiverUid: targetUid,
fileName,
fileSize: loaded.bytes.length,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
md510MCheckSum: md5First10MB(loaded.bytes),
});
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null;
const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
if (!fileId) throw new Error('private file upload response missing file_id');
// Cache the metadata so a later `send_private_msg` carrying just
// `{type:'file', file_id}` can resurrect the full c2c-file packet
// (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without
// this the recipient sees a 0-byte file because the OneBot send path
// has no way to recover those fields from the file_id alone.
this.ctx.rememberUploadedFile({
fileId,
scope: 'private',
userId,
fileName,
fileSize: loaded.bytes.length,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
fileHash: fileHash ?? '',
rememberedAt: Date.now(),
});
if (!upload.boolFileExist && uploadFile) {
// Host selection.
//
// Current QQ-NT server rollout has stopped populating the legacy
// `uploadIp` (field 60) entirely. The host now arrives as the first
// entry of `rtpMediaPlatformUploadAddress` (field 210, repeated
// IPv4 message) — same place acidify reads it from since their
// 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort`
// (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN);
// acidify uses `inIP`/`inPort` exclusively and so do we, because
// that's the address the highway PUT actually needs to reach.
//
// The 32-bit IPs are little-endian-packed (byte0 = first octet)
// per acidify's `Int.toIpString()`. Cross-checked the byte order
// by inspecting their highway flow — there's no separate htonl
// step, so the integer is already in network-octet-first order.
//
// Older server versions still populate the legacy string fields
// (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain /
// uploadDns), so we fall through to those after rtpMediaPlatform.
// Pair an HTTPS-flavored host with `uploadHttpsPort` if that's
// what we picked.
const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress)
&& upload.rtpMediaPlatformUploadAddress[0])
? upload.rtpMediaPlatformUploadAddress[0] : null;
const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0
? int32ToIpv4Dotted(rtpFirst.inIP) : '';
const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number'
? rtpFirst.inPort : 0;
const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0])
? upload.uploadIpList[0] : '';
const uploadHost = (rtpInIP)
|| (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| (typeof upload.uploadDomain === 'string' && upload.uploadDomain)
|| (ipListFirst)
|| (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain)
|| (typeof upload.uploadDns === 'string' && upload.uploadDns)
|| '';
const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst
&& typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain;
const uploadPort = rtpInIP && rtpInPort > 0
? rtpInPort
: httpsHostUsed && toInt(upload.uploadHttpsPort) > 0
? toInt(upload.uploadHttpsPort)
: toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress)
? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({
outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort,
iPType: e.iPType,
})))
: '[]';
log.warn(
'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s',
rtpDump,
upload.uploadIp ?? '', upload.uploadDomain ?? '',
JSON.stringify(upload.uploadIpList ?? []),
upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '',
upload.uploadLanip ?? '', upload.uploadPort ?? 0,
upload.uploadHttpsPort ?? 0,
);
throw new Error('private file upload host is invalid');
}
const ext = buildPrivateFileUploadExt(
senderUin,
fileName,
loaded.bytes.length,
hashes.md5,
hashes.sha1,
fileId,
upload.mediaPlatformUploadKey instanceof Uint8Array
? upload.mediaPlatformUploadKey
: (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
uploadHost,
uploadPort,
);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
}
// Stage 3: publish the file as a c2c chat message. C2C files use
// `RichText.notOnlineFile` (parallel to `elems`), so we go through
// the dedicated `sendC2cFile` on MessageApi instead of `sendPrivate`
// which only knows about elems[]. NapCat does the same atomic
// upload+send dance — without it the file sits on the server and
// the recipient sees nothing.
if (uploadFile) {
try {
await this.ctx.apis.message.sendC2cFile(userId, targetUid, {
fileId,
fileName,
fileSize: loaded.bytes.length,
fileMd5: hashes.md5,
fileHash: fileHash ?? '',
});
} catch (err) {
log.warn('private file uploaded (fileId=%s) but chat post failed: %s',
fileId, err instanceof Error ? err.message : String(err));
}
}
return { fileId, fileHash };
}
// ─────────────── list (paginated loop) ───────────────
async list(groupId: number, folderId = '/'): Promise<GroupFilesResult> {
const targetDirectory = normalizeDirectory(folderId);
const files: GroupFileInfo[] = [];
const folders: GroupFolderInfo[] = [];
const pageSize = 20;
let startIndex = 0;
for (let page = 0; page < 200; page++) {
const list = await ListGroupFilesPage.invoke(this.ctx, {
groupId, targetDirectory, startIndex, pageSize,
});
if (!list) break;
ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
for (const item of list.items ?? []) {
const type = toInt(item?.type);
if (type === 1 && item?.fileInfo) {
const file = item.fileInfo;
const uploader = toInt(file.uploaderUin);
const cached = this.ctx.identity.findGroupMember(groupId, uploader);
files.push({
fileId: typeof file.fileId === 'string' ? file.fileId : '',
fileName: typeof file.fileName === 'string' ? file.fileName : '',
busId: toInt(file.busId),
fileSize: toInt(file.fileSize),
uploadTime: toInt(file.uploadedTime),
deadTime: toInt(file.expireTime),
modifyTime: toInt(file.modifiedTime),
downloadTimes: toInt(file.downloadedTimes),
uploader,
uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName)
|| cached?.card
|| cached?.nickname
|| '',
});
} else if (type === 2 && item?.folderInfo) {
const folder = item.folderInfo;
const creator = toInt(folder.creatorUin);
const cached = this.ctx.identity.findGroupMember(groupId, creator);
folders.push({
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
createTime: toInt(folder.createTime),
creator,
creatorName: (typeof folder.creatorName === 'string' && folder.creatorName)
|| cached?.card
|| cached?.nickname
|| '',
totalFileCount: toInt(folder.totalFileCount),
});
}
}
if (list.isEnd) break;
startIndex += pageSize;
}
return { files, folders };
}
// ─────────────── url fetch (group / private files) ───────────────
async getUrl(groupId: number, fileId: string, busId = 102): Promise<string> {
const download = await GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording);
const dns = (typeof download.downloadDns === 'string' && download.downloadDns)
|| (typeof download.downloadIp === 'string' && download.downloadIp)
|| '';
const hexUrl = bytesToHexUpper(download.downloadUrl);
if (!dns || !hexUrl) {
throw new Error('group file url response invalid');
}
// Keep the same behavior as Lagrange: append file_id after ?fname=
return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`;
}
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
const bridge = this.ctx;
const selfUid = await resolveSelfUid(bridge);
void userId;
const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
const server = typeof result?.server === 'string' ? result.server : '';
const port = toInt(result?.port);
const url = typeof result?.url === 'string' ? result.url : '';
if (!server || !port || !url) {
throw new Error('private file url response invalid');
}
return `http://${server}:${port}${url}&isthumb=0`;
}
// ─────────────── delete / move ───────────────
delete(groupId: number, fileId: string): Promise<void> {
return DeleteGroupFile.invoke(this.ctx, { groupId, fileId });
}
move(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> {
return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory });
}
// ─────────────── folders ───────────────
createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
return CreateGroupFolder.invoke(this.ctx, {
groupId, parentId: normalizeDirectory(parentId), folderName: name,
});
}
deleteFolder(groupId: number, folderId: string): Promise<void> {
return DeleteGroupFolder.invoke(this.ctx, { groupId, folderId });
}
renameFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> {
return RenameGroupFolder.invoke(this.ctx, { groupId, folderId, newFolderName });
}
// ─────────────── rich-media URL by node ───────────────
getPttUrl(groupId: number, node: MediaIndexNode): Promise<string> {
return GetGroupPttUrl.invoke(this.ctx, { groupId, node });
}
async getPrivatePttUrl(node: MediaIndexNode): Promise<string> {
const bridge = this.ctx;
const selfUid = await resolveSelfUid(bridge);
return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node });
}
getVideoUrl(groupId: number, node: MediaIndexNode): Promise<string> {
return GetGroupVideoUrl.invoke(this.ctx, { groupId, node });
}
async getPrivateVideoUrl(node: MediaIndexNode): Promise<string> {
const bridge = this.ctx;
const selfUid = await resolveSelfUid(bridge);
return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node });
}
}

View File

@@ -1,87 +0,0 @@
import type { CoreContext } from '../core-context';
import { ContactsApi } from './contacts';
import { ExtrasApi } from './extras';
import { ForwardApi } from './forward';
import { FriendApi } from './friend';
import { GroupAdminApi } from './group-admin';
import { GroupAlbumApi } from './group-album';
import { GroupFileApi } from './group-file';
import { InteractionApi } from './interaction';
import { MessageApi } from './message';
import { MiscApi } from './misc';
import { ProfileApi } from './profile';
import { WebApi } from './web';
export interface ApiHub {
/** Send/recall/markRead operations across c2c + group + c2c-file. */
readonly message: MessageApi;
/** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
readonly contacts: ContactsApi;
/** Group moderation: mute/kick/admin/card/name/title/leave + join-policy. */
readonly groupAdmin: GroupAdminApi;
/** Group file CRUD + private (c2c) file upload + media URL resolvers. */
readonly groupFile: GroupFileApi;
/** Group photo album: list/upload/comment/like/delete + media listing. */
readonly groupAlbum: GroupAlbumApi;
/** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */
readonly interaction: InteractionApi;
/** Friend roster mutations: handleRequest / delete / setRemark. */
readonly friend: FriendApi;
/** Personal profile: status / avatar / nickname / likes / custom-faces. */
readonly profile: ProfileApi;
/** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */
readonly forward: ForwardApi;
/** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */
readonly misc: MiscApi;
/** Tier-2 napcat-parity: group todo / stranger status / AI voice. */
readonly extras: ExtrasApi;
/** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */
readonly web: WebApi;
}
/**
* Construct the ApiHub for a Bridge. Called once from the Bridge
* constructor. Eager construction means every Bridge instance pays
* the cost up-front (a few object allocations) — there's no lazy
* path because that would require either a thunk-based wrapper or
* runtime-mutated `apis.xxx` slots, neither of which is worth the
* complexity for ~13 small classes.
*/
export function buildApiHub(ctx: CoreContext): ApiHub {
return {
message: new MessageApi(ctx),
contacts: new ContactsApi(ctx),
groupAdmin: new GroupAdminApi(ctx),
groupFile: new GroupFileApi(ctx),
groupAlbum: new GroupAlbumApi(ctx),
interaction: new InteractionApi(ctx),
friend: new FriendApi(ctx),
profile: new ProfileApi(ctx),
forward: new ForwardApi(ctx),
misc: new MiscApi(ctx),
extras: new ExtrasApi(ctx),
web: new WebApi(ctx),
};
}
// Re-export the Api classes themselves so callers can write
// `import type { MessageApi } from '@snowluma/core/.../apis'` for
// signature use. Concrete instances always come from `bridge.apis.*`.
export { ContactsApi, type DownloadRKeyInfo } from './contacts';
export {
AiVoiceChatType, ExtrasApi, type AiVoiceCategory,
type AiVoiceItem,
type StrangerStatus
} from './extras';
export { ForwardApi } from './forward';
export { FriendApi } from './friend';
export { GroupAdminApi } from './group-admin';
export { GroupAlbumApi } from './group-album';
export { GroupFileApi } from './group-file';
export { InteractionApi } from './interaction';
export { MessageApi, type SendMessageReceipt } from './message';
export { MiscApi } from './misc';
export { ProfileApi } from './profile';
export { type MediaIndexNode } from './shared';
export { WebApi, type ClientKeyInfo, type WebHonorInfo, type WebNoticeInfo } from './web';

View File

@@ -1,68 +0,0 @@
// InteractionApi — facade over interactive-engagement OIDB cmds
// (poke / like / reaction / essence / emoji-like-list). Every method
// is a one-line forwarder to a self-contained namespace under
// @snowluma/protocol/oidb-services. The facade exists purely to keep
// the `bridge.apis.interaction.X(...)` ergonomic call style; all wire
// work (envelope build / encode / send / decode) lives in the
// namespace files.
import { SendLike } from '@snowluma/protocol/oidb-services/interaction/send-like';
import { SendPoke } from '@snowluma/protocol/oidb-services/interaction/send-poke';
import { SetEssence } from '@snowluma/protocol/oidb-services/interaction/set-essence';
import { FetchReactionSummary } from '@snowluma/protocol/oidb-services/reaction/fetch-reaction-summary';
import { GetEmojiLikes } from '@snowluma/protocol/oidb-services/reaction/get-emoji-likes';
import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-reaction';
import type { CoreContext } from '../core-context';
export class InteractionApi {
constructor(private readonly ctx: CoreContext) { }
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
}
sendLike(userId: number, count: number): Promise<void> {
return SendLike.invoke(this.ctx, { userId, count });
}
setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet });
}
setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable });
}
/**
* Legacy stub: see `GetEmojiLikes` namespace comment for why this
* SSO path can never surface the user list. Real data lives in
* ReactionStore on the OneBot side.
*/
async getEmojiLikes(
groupId: number,
sequence: number,
emojiId: string,
emojiType = 1,
count = 10,
cookie = '',
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
try {
return await GetEmojiLikes.invoke(this.ctx, { groupId, sequence, emojiId, emojiType, count, cookie });
} catch {
return { users: [], cookie: '', isLast: true };
}
}
/**
* Fetch the per-emoji reaction summary on a group message via
* 0x9084_1 — emoji_id + reactor count + last-reaction timestamp.
* Cross-checked against the local ReactionStore cache for callers
* that need to detect cache gaps.
*/
fetchReactionSummary(
groupId: number,
sequence: number,
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>> {
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
}
}

View File

@@ -1,337 +0,0 @@
import type {
SendMessageRequest,
SendMessageResponse,
} from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import type {
C2CRecallRequest,
GroupRecallRequest,
SsoReadedReportReq,
} from '@snowluma/proto-defs/oidb-actions/base';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { MessageElement } from '@snowluma/protocol/events';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
/**
* Receipt returned by every typed `send*Message` call. The OneBot
* adapter feeds these into its `MessageStore` so later `recall_msg`
* actions can resolve the wire-level coordinates (sequence + random)
* from the `message_id` it previously emitted.
*/
export interface SendMessageReceipt {
messageId: number;
sequence: number;
clientSequence: number;
random: number;
timestamp: number;
}
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
export class MessageApi {
constructor(private readonly ctx: CoreContext) { }
/**
* Send a message to a QQ group.
*
* Wraps `MessageSvc.PbSendMsg` with `routingHead.grp.groupCode`.
* Media elements (image / record / video) trigger highway uploads
* inside `buildSendElems` — see `element-builder.ts`.
*
* Returns a `SendMessageReceipt` carrying the assigned messageId,
* group sequence, and timestamps; callers cache this for later
* `recall` / reply lookups.
*/
async sendGroup(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
const protoElems = await buildSendElems(elements, { bridge: this.ctx, groupId });
const random = this.ctx.nextMessageRandom();
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
grp: { groupCode: BigInt(groupId) },
},
contentHead: {
type: 1,
},
messageBody: {
richText: {
elems: protoElems,
},
},
clientSequence: 0,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
multiSendSeq: 0,
});
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`);
}
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) throw new Error('failed to decode SendMessageResponse');
if (response.result != null && response.result !== 0) {
throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.groupSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: 0, random, timestamp };
}
/**
* Send a c2c (private) message.
*
* Resolves the recipient's UID only when the message carries media
* — text-only messages skip the lookup. Routes through `c2c.uin`
* (and optionally `c2c.uid` for the media case).
*/
async sendPrivate(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
let userUid = '';
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
if (hasMedia) {
userUid = await this.ctx.resolveUserUid(userUin);
}
const protoElems = await buildSendElems(elements, { bridge: this.ctx, userUid });
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
c2c: {
uin: userUin,
...(userUid ? { uid: userUid } : {}),
},
},
contentHead: {
type: 1,
subType: 0,
c2cCmd: 11,
},
messageBody: {
richText: {
elems: protoElems,
},
},
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: {
msgFlag: Math.floor(Date.now() / 1000),
},
multiSendSeq: 0,
});
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`);
}
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) throw new Error('failed to decode SendMessageResponse');
if (response.result != null && response.result !== 0) {
throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.privateSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
}
/**
* Send a c2c file as a chat message.
*
* The wire shape isn't the same as a regular c2c message — the c2c
* file path uses three slots that differ from a normal text/image
* send (verified against `dev/Lagrange.Core/.../MessagePacker.cs:
* BuildPacketBase` + `FileEntity.PackMessageContent`):
*
* 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of
* `routingHead.c2c { uin, uid }`. The server rejects c2c file
* messages routed through the regular c2c slot.
* 2. `messageBody.msgContent` carries the serialised
* `FileExtra { file: NotOnlineFile }` bytes. NOT
* `richText.notOnlineFile` — the receiver doesn't read that
* slot for file metadata.
* 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The
* previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT
* server doesn't recognise.
*
* NotOnlineFile carries three required-on-send fields the receiver
* itself ignores but the server's intake validator checks:
* - `subcmd: 1` — c2c file send command code
* - `dangerEvel: 0` — virus-scan severity, always 0 client-side
* - `expireTime` — 7 days from now (Lagrange convention)
*/
async sendC2cFile(
userUin: number,
userUid: string,
info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string },
): Promise<SendMessageReceipt> {
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
const nowSec = Math.floor(Date.now() / 1000);
const sevenDaysSec = 7 * 24 * 60 * 60;
const fileExtraBytes = protobuf_encode<FileExtra>({
file: {
fileType: 0,
fileUuid: info.fileId,
fileMd5: info.fileMd5,
fileName: info.fileName,
fileSize: BigInt(info.fileSize),
subcmd: 1,
dangerEvel: 0,
expireTime: nowSec + sevenDaysSec,
fileHash: info.fileHash ?? '',
},
});
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
trans0x211: { ccCmd: 4, uid: userUid },
},
contentHead: {
type: 1,
subType: 0,
},
messageBody: {
msgContent: fileExtraBytes,
},
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: { msgFlag: nowSec },
multiSendSeq: 0,
});
// `userUin` is part of the public contract (the OneBot layer
// threads it through for symmetry with `sendPrivate`) but the
// wire shape only needs the uid. Silence the unused-parameter
// lint without changing the signature.
void userUin;
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`);
}
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) throw new Error('failed to decode SendMessageResponse');
if (response.result != null && response.result !== 0) {
throw new Error(`send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.privateSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
}
/**
* Recall (revoke) a group message by sequence number. Server-side
* the message ages out after the standard 2-minute window unless
* the user is an admin/owner.
*/
async recallGroup(groupId: number, sequence: number): Promise<void> {
const request = protobuf_encode<GroupRecallRequest>({
type: 1,
groupUin: groupId,
info: { sequence, random: 0, field3: 0 },
settings: { field1: 0 },
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall group message failed');
}
/**
* Recall a c2c (private) message. Needs more positional info than
* the group variant because c2c messages are identified by the
* `(clientSequence, msgSequence, random, timestamp)` tuple rather
* than a single group-side sequence.
*/
async recallPrivate(
userUin: number,
clientSeq: number,
msgSeq: number,
random: number,
timestamp: number,
): Promise<void> {
const targetUid = await this.ctx.resolveUserUid(userUin);
const request = protobuf_encode<C2CRecallRequest>({
type: 1,
targetUid,
info: {
clientSequence: clientSeq,
random,
messageId: BigInt((0x01000000 * 0x100000000) + random),
timestamp,
field5: 0,
messageSequence: msgSeq,
},
settings: { field1: false, field2: false },
field6: false,
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
}
/**
* Push a group read-report (`trpc.msg.msg_svc.MsgService.SsoReadedReport`)
* advancing the bot's last-read marker to `sequence`. Mirrors the QQ
* NT client's own "scrolled to bottom" behaviour so subsequent
* sync packets don't replay messages we've already processed.
*/
async markGroupRead(groupId: number, sequence: number): Promise<void> {
const request = protobuf_encode<SsoReadedReportReq>({
groupList: [
{
groupUin: BigInt(groupId),
lastReadSeq: BigInt(sequence),
},
],
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark group message read failed');
}
}
/**
* Push a c2c read-report. Same wire-cmd as the group variant but
* keyed by friend uid (resolved from uin via IdentityService).
* `lastReadTime` defaults to "now" — matches the QQ NT client
* which also uses wall-clock seconds rather than the read-message
* timestamp.
*/
async markPrivateRead(userId: number, sequence: number): Promise<void> {
const uid = await this.ctx.resolveUserUid(userId);
const request = protobuf_encode<SsoReadedReportReq>({
c2cList: [
{
uid,
lastReadTime: BigInt(Math.floor(Date.now() / 1000)),
lastReadSeq: BigInt(sequence),
},
],
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark private message read failed');
}
}
}

View File

@@ -1,78 +0,0 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import type {
MiniAppShareReq,
MiniAppShareResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
// Migrated OIDB cmds — facade methods are one-line forwarders.
import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button';
import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign';
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
import type { CoreContext } from '../core-context';
export class MiscApi {
constructor(private readonly ctx: CoreContext) { }
translateEn2Zh(words: string[]): Promise<string[]> {
return TranslateEnToZh.invoke(this.ctx, { words });
}
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
let appid = '1109937557'; // default: bilibili
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
if (type === 'weibo') {
appid = '1109224783';
iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
} else if (type !== 'bili') {
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
}
const request = protobuf_encode<MiniAppShareReq>({
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
body: { appid, title, desc, picUrl, jumpUrl, iconUrl },
});
const result = await this.ctx.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
if (!result.success || !result.responseData) {
throw new Error(result.errorMessage || 'get mini app ark failed');
}
const decoded = protobuf_decode<MiniAppShareResp>(result.responseData);
const jsonStr = decoded?.body?.jsonStr;
if (!jsonStr) {
throw new Error('mini app share json empty');
}
const parsed = JSON.parse(jsonStr) as Record<string, JsonObject | string | number | boolean | null>;
return {
data: {
ver: parsed.ver,
prompt: parsed.prompt,
config: parsed.config,
app: parsed.appName,
view: parsed.appView,
meta: parsed.metaData,
miniappShareOrigin: 3,
miniappOpenRefer: '10002',
},
};
}
clickInlineKeyboardButton(
groupId: number,
botAppid: number,
buttonId: string,
callbackData: string,
msgSeq: number,
): Promise<JsonValue> {
return ClickInlineKeyboardButton.invoke(this.ctx, { groupId, botAppid, buttonId, callbackData, msgSeq });
}
sendGroupSign(groupId: number): Promise<void> {
return SendGroupSign.invoke(this.ctx, { groupId });
}
}

View File

@@ -1,147 +0,0 @@
import type {
FaceroamOpReq,
FaceroamOpResp,
GroupAvatarExtra,
SetStatusReq,
SetStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status';
import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile';
import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
export class ProfileApi {
constructor(private readonly ctx: CoreContext) { }
// ─────────────── status / profile setters ───────────────
async setOnlineStatus(status: number, extStatus = 0, batteryStatus = 100): Promise<void> {
await this.dispatchSetStatus({ status, extStatus, batteryStatus });
}
/**
* DIY (custom) online status. napcat fixes status=10 / extStatus=2000
* — the values QQ associates with "I have a custom status string" —
* and threads the faceId / wording / faceType through the customExt
* sub-message of the same SetStatus wire call.
*/
async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void> {
await this.dispatchSetStatus({
status: 10,
extStatus: 2000,
batteryStatus: 0,
customExt: { faceId, text: wording, faceType },
});
}
private async dispatchSetStatus(value: {
status: number;
extStatus: number;
batteryStatus: number;
customExt?: { faceId: number; text: string; faceType: number };
}): Promise<void> {
const request = protobuf_encode<SetStatusReq>(value);
const result = await this.ctx.sendRawPacket(
'trpc.qq_new_tech.status_svc.StatusService.SetStatus',
request,
);
if (!result.success) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
if (result.responseData && result.responseData.length > 0) {
const resp = protobuf_decode<SetStatusResp>(result.responseData);
if (!resp) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
if (resp.errCode !== undefined && resp.errCode !== 0) {
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
}
}
}
setProfile(nickname?: string, personalNote?: string): Promise<void> {
return SetProfile.invoke(this.ctx, { nickname, personalNote });
}
setSelfLongNick(longNick: string): Promise<void> {
return SetSelfLongNick.invoke(this.ctx, { longNick });
}
setInputStatus(userId: number, eventType: number): Promise<void> {
return SetInputStatus.invoke(this.ctx, { userId, eventType });
}
async setAvatar(source: string): Promise<void> {
const bridge = this.ctx;
const loaded = await loadBinarySource(source, 'avatar');
if (!loaded.bytes.length) throw new Error('avatar file is empty');
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0));
}
/**
* Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar:
* - same highway HTTP upload as personal avatar
* - cmdId 3000 (instead of 90)
* - GroupAvatarExtra proto carried as the `extend` blob, with the
* four protocol-prescribed constants (type=101, field5=3, field6=1,
* field3.field1=1) and the target groupUin.
*
* Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar.
*/
async setGroupAvatar(groupId: number, source: string): Promise<void> {
const bridge = this.ctx;
const loaded = await loadBinarySource(source, 'group-avatar');
if (!loaded.bytes.length) throw new Error('group avatar file is empty');
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
const extra = protobuf_encode<GroupAvatarExtra>({
type: 101,
groupUin: groupId,
field3: { field1: 1 },
field5: 3,
field6: 1,
});
await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra);
}
// ─────────────── queries on me / my contacts ───────────────
getLike(userId?: number, start = 0, limit = 10): Promise<LikeInfo> {
return GetLike.invoke(this.ctx, { userId, start, limit });
}
getUnidirectionalFriendList(): Promise<UnidirectionalFriendEntry[]> {
return GetUnidirectionalFriendList.invoke(this.ctx);
}
async fetchCustomFace(count = 10): Promise<string[]> {
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(this.ctx.identity.uin),
field3: 1,
field6: 1,
};
const request = protobuf_encode<FaceroamOpReq>(req);
const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
}
const resp = protobuf_decode<FaceroamOpResp>(result.responseData);
if (!resp || resp.retCode !== 0) {
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
}
const faceIds = resp.item?.faceIds || [];
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`);
}
}

View File

@@ -1,335 +0,0 @@
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor';
import {
deleteGroupNotice as deleteGroupNoticeHttp,
getGroupNoticeWebAPI,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
type SetNoticeRetSuccess,
} from '@snowluma/protocol/web/group-notice';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
import type { CoreContext } from '../core-context';
export type ClientKeyInfo = NamespaceClientKeyInfo;
export interface WebHonorInfo {
[key: string]: import('@snowluma/common/json').JsonValue;
group_id: number;
current_talkative: WebHonorItem | null;
talkative_list: WebHonorItem[];
performer_list: WebHonorItem[];
legend_list: WebHonorItem[];
emotion_list: WebHonorItem[];
strong_newbie_list: WebHonorItem[];
}
export interface WebNoticeInfo {
[key: string]: import('@snowluma/common/json').JsonValue;
notice_id: string;
sender_id: number;
publish_time: number;
message: {
text: string;
image: Array<{ id: string; height: number; width: number }>;
images: Array<{ id: string; height: number; width: number }>;
};
settings: import('@snowluma/common/json').JsonValue;
read_num: number;
}
// ─────────────── private helpers (cookie acquisition) ───────────────
function forceFetchClientKeyInner(bridge: BridgeContext): Promise<ClientKeyInfo> {
return ForceFetchClientKey.invoke(bridge);
}
function getPSkey(bridge: BridgeContext, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
return GetPskey.invoke(bridge, { domainList });
}
async function getCookies(bridge: BridgeContext, domain: string): Promise<Record<string, string>> {
const ClientKeyData = await forceFetchClientKeyInner(bridge);
// Build the ptlogin2 jump URL: this is the canonical way for the
// bot to swap its clientKey for cookie-jar entries on a given
// qq.com subdomain.
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
const data = await RequestUtil.HttpsGetCookies(requestUrl);
if (!data['p_skey'] || data['p_skey'].length === 0) {
// ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey
// for the same domain. Errors are swallowed so the caller can
// still proceed with whatever cookies it did get.
try {
const pskeyData = await getPSkey(bridge, [domain]);
const pskey = pskeyData.domainPskeyMap.get(domain);
if (pskey) {
data['p_skey'] = pskey;
}
} catch {
return data;
}
}
return data;
}
async function getSKey(bridge: BridgeContext): Promise<string> {
const ClientKeyData = await forceFetchClientKeyInner(bridge);
if (!ClientKeyData.clientKey) {
throw new Error('getClientKey Error: clientKey is empty');
}
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=' + u1 +
'&keyindex=' + ClientKeyData.keyIndex;
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
const skey = cookies['skey'];
if (!skey) {
throw new Error('SKey is Empty');
}
return skey;
}
/**
* Standard QQ bkn hash (also known as token / csrf_token) derived from
* skey or p_skey. djb2 hash truncated to 31 bits.
*/
function getBknFromSKey(skey: string): number {
let hash = 5381;
for (let i = 0; i < skey.length; i++) {
hash += (hash << 5) + skey.charCodeAt(i);
}
return hash & 2147483647;
}
export class WebApi {
constructor(private readonly ctx: CoreContext) { }
// ─────────────── cookie / token primitives ───────────────
async forceFetchClientKey(): Promise<ClientKeyInfo> {
return forceFetchClientKeyInner(this.ctx);
}
/** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi
* (qzone.qq.com) and by every other web helper here. */
async getCookies(domain: string): Promise<Record<string, string>> {
return getCookies(this.ctx, domain);
}
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
async getCookiesStr(domain: string): Promise<string> {
const cookieObject = await getCookies(this.ctx, domain);
return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
}
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
async getCsrfToken(): Promise<number> {
const skey = await getSKey(this.ctx);
if (!skey) {
throw new Error('SKey is Empty');
}
return getBknFromSKey(skey);
}
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
async getCredentials(domain: string): Promise<{ cookies: string; token: number; csrf_token: number }> {
const cookieObject = await getCookies(this.ctx, domain);
const cookiesStr = Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
const token = skey ? getBknFromSKey(skey) : 0;
return {
cookies: cookiesStr,
token,
csrf_token: token,
};
}
// ─────────────── group essence ───────────────
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<GroupEssenceMsgRet> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
}
/** Walks every page and returns the concatenated result. */
async getEssenceAll(groupId: number): Promise<GroupEssenceMsgRet[]> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await getGroupEssenceMsgAll(cookieObject, groupCode);
}
// ─────────────── group honor ───────────────
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<WebHonorInfo> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const honorInfo: WebHonorInfo = {
group_id: groupId,
current_talkative: null,
talkative_list: [],
performer_list: [],
legend_list: [],
emotion_list: [],
strong_newbie_list: [],
};
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
if (talkativeList.length > 0) {
honorInfo.current_talkative = talkativeList[0];
honorInfo.talkative_list = talkativeList;
}
}
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
}
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
}
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
}
return honorInfo;
}
// ─────────────── group notice ───────────────
async sendNotice(
groupId: number,
content: string,
options?: {
image?: string; // local path, http URL, or undefined (text-only)
pinned?: number;
type?: number;
confirm_required?: number;
},
): Promise<SetNoticeRetSuccess> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
let picId = '';
let imgWidth = 540;
let imgHeight = 300;
if (options?.image) {
let imageBuffer: Buffer;
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
const response = await fetch(options.image);
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
imageBuffer = Buffer.from(await response.arrayBuffer());
} else {
const { readFileSync } = await import('fs');
imageBuffer = readFileSync(options.image);
}
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
if (picInfo) {
picId = picInfo.id;
imgWidth = picInfo.width;
imgHeight = picInfo.height;
}
}
const ret = await setGroupNoticeWebAPI(
cookieObject,
groupCode,
content,
options?.pinned ?? 0,
options?.type ?? 1,
1,
1,
options?.confirm_required ?? 1,
picId,
imgWidth,
imgHeight,
);
if (!ret || ret.ec !== 0) {
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
}
return ret;
}
async getNotice(groupId: number): Promise<WebNoticeInfo[]> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
if (!ret) {
throw new Error('获取公告失败');
}
const retNotices: WebNoticeInfo[] = [];
if (ret.feeds) {
for (const key in ret.feeds) {
const feed = ret.feeds[key];
if (!feed) continue;
const image = feed.msg?.pics?.map((pic) => ({
id: pic.id,
height: pic.h,
width: pic.w,
})) || [];
retNotices.push({
notice_id: feed.fid,
sender_id: feed.u,
publish_time: feed.pubt,
message: {
text: feed.msg?.text || '',
image,
images: image,
},
settings: feed.settings,
read_num: feed.read_num,
});
}
}
return retNotices;
}
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
}
}

View File

@@ -0,0 +1,155 @@
// Tier-2 napcat-parity actions ported as pure oidb calls. Each function
// here corresponds to one napcat PacketApi.pkt.operation.* entry; the
// schemas live in proto/oidb-action.ts. Nothing in this file touches
// the NTQQ NodeIKernel — every wire trip is one runOidb round-trip.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
OidbGroupTodoSchema,
OidbStrangerStatusReqSchema,
OidbStrangerStatusRespSchema,
OidbAiVoiceListReqSchema,
OidbAiVoiceListRespSchema,
OidbAiVoiceReqSchema,
OidbAiVoiceRespSchema,
} from '../proto/oidb-action';
import type { MediaIndexNode } from './shared';
// ─────────────── Group todo (0xF90) ───────────────
export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_1',
oidbCmd: 0xF90, subCmd: 1,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_2',
oidbCmd: 0xF90, subCmd: 2,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_3',
oidbCmd: 0xF90, subCmd: 3,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
export interface StrangerStatus {
status: number;
ext_status: number;
}
/**
* Mirror napcat's GetStrangerStatus: decode the extBigInt status word.
* Values ≤10 fold into a 10×status; everything else is split into the
* high-byte / low-byte ext_status the OneBot dialect uses.
*
* Returns null on transport / decode failure rather than throwing, so
* the OneBot action can produce a clean retcode without try/catch
* gymnastics.
*/
export async function getStrangerStatus(bridge: Bridge, uin: number): Promise<StrangerStatus | null> {
try {
const resp = await runOidb<{ data?: { status?: { value?: bigint | number } } }>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: {
schema: OidbStrangerStatusReqSchema,
value: { uin, key: [{ key: 27372 }] },
},
response: { schema: OidbStrangerStatusRespSchema },
});
const raw = resp?.data?.status?.value;
if (raw === undefined || raw === null) return null;
const extBig = typeof raw === 'bigint' ? raw : BigInt(raw);
if (extBig <= 10n) {
return { status: Number(extBig) * 10, ext_status: 0 };
}
const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn));
return { status: 10, ext_status: status };
} catch {
return null;
}
}
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
export const AiVoiceChatType = {
Unknown: 0,
Sound: 1,
Sing: 2,
} as const;
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
export interface AiVoiceItem {
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export interface AiVoiceCategory {
category: string;
voices: AiVoiceItem[];
}
export async function fetchAiVoiceList(
bridge: Bridge,
groupId: number,
chatType: AiVoiceChatType,
): Promise<AiVoiceCategory[]> {
const resp = await runOidb<{ content?: AiVoiceCategory[] }>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x929d_0',
oidbCmd: 0x929D, subCmd: 0,
request: { schema: OidbAiVoiceListReqSchema, value: { groupUin: groupId, chatType } },
response: { schema: OidbAiVoiceListRespSchema },
});
return resp?.content ?? [];
}
/**
* Trigger AI voice synthesis. Server may return an empty msgInfo while
* the render is in-flight; we retry until a node materialises or the
* cap is hit. napcat uses the same 30-retry budget.
*
* The returned MediaIndexNode plugs directly into
* `bridge.fetchGroupPttUrlByNode`, which already handles every other
* download-URL fetch in SnowLuma.
*/
export async function fetchAiVoice(
bridge: Bridge,
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType,
maxRetries = 30,
): Promise<MediaIndexNode> {
// Random 32-bit session id — server uses this to deduplicate polls.
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
for (let i = 0; i < maxRetries; i++) {
const resp = await runOidb<{
statusCode?: number;
msgInfo?: { msgInfoBody?: Array<{ index?: MediaIndexNode }> };
}>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x929b_0',
oidbCmd: 0x929B, subCmd: 0,
request: {
schema: OidbAiVoiceReqSchema,
value: { groupUin: groupId, voiceId, text, chatType, session: { sessionId } },
},
response: { schema: OidbAiVoiceRespSchema },
});
const node = resp?.msgInfo?.msgInfoBody?.[0]?.index;
if (node) return node;
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}

View File

@@ -0,0 +1,241 @@
// Forward-message upload / download via the long-message service.
// Uses gzipped protobufs over `trpc.group.long_msg_interface`.
// An in-memory cache keeps res_ids stable across rapid re-fetches
// from the same OneBot client (avoids re-decoding the same payload).
import type { Bridge } from '../bridge';
import { gunzipSync, gzipSync } from 'zlib';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { buildSendElems } from '../element-builder';
import { parseMsgPush } from '../msg-push';
import type { ForwardNodePayload } from '../events';
import type { PacketInfo } from '../../protocol/types';
import {
LongMsgResultSchema,
RecvLongMsgReqSchema,
RecvLongMsgRespSchema,
SendLongMsgReqSchema,
SendLongMsgRespSchema,
} from '../proto/longmsg';
import { PushMsgSchema } from '../proto/message';
import { resolveSelfUid, toInt } from './shared';
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
// of the process — that's enough because OneBot clients typically
// resolve a forward immediately after receiving the parent message.
const forwardResCache = new Map<string, ForwardNodePayload[]>();
async function buildForwardPushBody(
bridge: Bridge,
node: ForwardNodePayload,
groupId?: number,
): Promise<Record<string, unknown>> {
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
const nickname = node.nickname.trim() || String(fromUin);
const sendCtx = groupId !== undefined
? { bridge, groupId }
: { bridge };
const elems = await buildSendElems(node.elements, sendCtx);
const now = Math.floor(Date.now() / 1000);
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
const seq = Math.floor(Math.random() * 9000000) + 1000000;
return {
responseHead: {
fromUin,
toUid: bridge.identity.selfUid ?? '',
forward: {
friendName: nickname,
},
},
contentHead: {
msgType: 9,
subType: 4,
msgId: random,
sequence: seq,
timestamp: now,
divSeq: 0,
},
body: {
richText: {
elems,
},
},
};
}
export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePayload[], groupId?: number): Promise<string> {
if (!Array.isArray(nodes) || nodes.length === 0) {
throw new Error('forward nodes are required');
}
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId)));
const longMsgResult = protoEncode({
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: msgBody as any },
},
],
}, LongMsgResultSchema);
const selfUid = await resolveSelfUid(bridge);
const info: any = {
type: groupId ? 3 : 1,
uid: { uid: groupId ? String(groupId) : selfUid },
payload: gzipSync(Buffer.from(longMsgResult)),
};
if (groupId) info.groupUin = groupId;
const request = protoEncode({
info,
settings: {
field1: 4,
field2: 1,
field3: 7,
field4: 0,
},
}, SendLongMsgReqSchema);
const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'upload forward message failed');
}
const resp = protoDecode(result.responseData, SendLongMsgRespSchema);
const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : '';
if (!resId) {
throw new Error('upload forward message response missing res_id');
}
forwardResCache.set(resId, nodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId ?? groupId,
senderCard: node.senderCard,
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
})));
return resId;
}
export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise<ForwardNodePayload[]> {
const cached = forwardResCache.get(resId);
if (cached) {
return cached.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
}));
}
const selfUid = await resolveSelfUid(bridge);
const request = protoEncode({
info: {
uid: { uid: selfUid },
resId,
acquire: true,
},
settings: {
field1: 2,
field2: 0,
field3: 0,
field4: 0,
},
}, RecvLongMsgReqSchema);
const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'download forward message failed');
}
const resp = protoDecode(result.responseData, RecvLongMsgRespSchema);
const payload = resp?.result?.payload;
if (!(payload instanceof Uint8Array) || payload.length === 0) {
throw new Error('download forward message payload is empty');
}
const inflate = gunzipSync(Buffer.from(payload));
const longMsg = protoDecode(inflate, LongMsgResultSchema);
const action = longMsg?.action?.find((item: any) => item?.actionCommand === 'MultiMsg');
const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : [];
const nodes: ForwardNodePayload[] = [];
for (const msgBody of msgBodyList) {
const wrapped = protoEncode({ message: msgBody }, PushMsgSchema);
const pkt: PacketInfo = {
pid: 0,
uin: bridge.identity.uin,
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 0,
retCode: 0,
fromClient: false,
body: wrapped,
};
const events = parseMsgPush(pkt, bridge.identity);
const event = events.find(e =>
e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
if (!event) continue;
if (event.kind === 'group_message') {
nodes.push({
userUin: event.senderUin,
nickname: event.senderCard || event.senderNick,
elements: event.elements,
time: event.time,
msgId: event.msgId,
msgSeq: event.msgSeq,
groupId: event.groupId,
senderCard: event.senderCard,
messageType: 'group',
});
} else if (event.kind === 'friend_message') {
nodes.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
time: event.time,
msgId: event.msgId,
msgSeq: event.msgSeq,
messageType: 'private',
});
} else {
nodes.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
time: event.time,
msgSeq: event.msgSeq,
groupId: event.groupId,
messageType: 'private',
});
}
}
if (nodes.length > 0) {
forwardResCache.set(resId, nodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
})));
}
return nodes;
}

View File

@@ -0,0 +1,64 @@
// Friend-list operations: accept/reject add request, delete, set the
// local remark label. Each one resolves a UID first because the OIDB
// protocol uses opaque UIDs rather than QQ uin numbers.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
OidbDeleteFriendSchema,
OidbFriendRequestActionSchema,
OidbSetFriendRemarkSchema,
} from '../proto/oidb-action';
export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise<void> {
let targetUid = uidOrFlag;
if (/^\d+$/.test(uidOrFlag)) {
targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10));
}
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xb5d_44',
oidbCmd: 0xB5D, subCmd: 44,
request: { schema: OidbFriendRequestActionSchema, value: { accept: approve ? 3 : 5, targetUid } },
});
}
export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise<void> {
const targetUid = await bridge.resolveUserUid(userId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x126b_0',
oidbCmd: 0x126B, subCmd: 0,
request: {
schema: OidbDeleteFriendSchema,
value: {
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: {
field1: 8,
field2: 8,
field3: 50,
},
},
block,
field4: false,
},
},
},
});
// Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
// shouldn't make the delete itself look failed.
try { await bridge.fetchFriendList(); } catch { /* ignore */ }
}
export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xb6e_2',
oidbCmd: 0xB6E, subCmd: 2,
request: { schema: OidbSetFriendRemarkSchema, value: { targetUid: uid, remark } },
});
}

View File

@@ -0,0 +1,216 @@
// Group admin actions: mute/kick/leave/role/profile + join-request approval.
// Every function ultimately routes through one OIDB schema; the function
// names match the OneBot action names (set_group_kick, set_group_ban, ...)
// so callers can grep across the two layers.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
Oidb0x89a_0AddOptionSchema,
Oidb0x89a_0SearchSchema,
Oidb0x8a0ReqSchema,
Oidb0x8a7ReqSchema,
Oidb0x8a7RespSchema,
OidbGroupRequestActionSchema,
OidbKickMemberSchema,
OidbLeaveGroupSchema,
OidbMuteAllSchema,
OidbMuteMemberSchema,
OidbRenameGroupSchema,
OidbRenameMemberSchema,
OidbSetAdminSchema,
OidbSpecialTitleSchema,
Oidb0xf16ReqSchema,
} from '../proto/oidb-action';
// ─────────────── mute / un-mute ───────────────
export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1253_1',
oidbCmd: 0x1253, subCmd: 1,
request: {
schema: OidbMuteMemberSchema,
value: { groupUin: groupId, type: 1, body: { targetUid: uid, duration } },
},
});
}
export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: OidbMuteAllSchema,
value: { groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } },
},
});
}
// ─────────────── join-policy ───────────────
export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0AddOptionSchema,
value: { groupUin: BigInt(groupId), settings: { addType }, field12: 0 },
},
});
}
export async function setGroupSearch(bridge: Bridge, groupId: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0SearchSchema,
value: { groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 },
},
});
}
export async function setGroupAddRequest(
bridge: Bridge, groupId: number, sequence: number, eventType: number,
approve: boolean, reason = '', filtered = false,
): Promise<void> {
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
await runOidb(bridge, {
cmd,
oidbCmd: 0x10C8, subCmd,
request: {
schema: OidbGroupRequestActionSchema,
value: { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
isUid: true,
},
});
}
// ─────────────── kick / leave ───────────────
export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: OidbKickMemberSchema,
value: { groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason },
},
});
}
export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise<void> {
const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId)));
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: Oidb0x8a0ReqSchema,
value: { groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 },
},
});
}
export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1097_1',
oidbCmd: 0x1097, subCmd: 1,
request: { schema: OidbLeaveGroupSchema, value: { groupUin: groupId } },
});
}
// ─────────────── role / display name ───────────────
export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1096_1',
oidbCmd: 0x1096, subCmd: 1,
request: { schema: OidbSetAdminSchema, value: { groupUin: groupId, uid, isAdmin: enable } },
});
}
export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8fc_3',
oidbCmd: 0x8FC, subCmd: 3,
request: {
schema: OidbRenameMemberSchema,
value: { groupUin: groupId, body: { targetUid: uid, targetName: card } },
},
});
}
export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_15',
oidbCmd: 0x89A, subCmd: 15,
request: { schema: OidbRenameGroupSchema, value: { groupUin: groupId, body: { targetName: name } } },
});
}
export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8fc_2',
oidbCmd: 0x8FC, subCmd: 2,
request: {
schema: OidbSpecialTitleSchema,
value: { groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } },
},
});
}
// ─────────────── personal-side metadata ───────────────
// setGroupRemark is the bot's local-only label for the group; it lives
// here rather than in friend.ts because the semantic is "operate on a
// group" rather than "operate on a contact list".
export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf16_1',
oidbCmd: 0xF16, subCmd: 1,
request: { schema: Oidb0xf16ReqSchema, value: { inner: { groupId: BigInt(groupId), remark }, field12: 0 } },
});
}
// ─────────────── group-level quota query ───────────────
export async function getGroupAtAllRemain(
bridge: Bridge,
groupId: number,
) {
const req = {
basic1: 1,
basic2: 2,
basic3: 1,
uin: BigInt(bridge.identity.uin),
groupId: BigInt(groupId),
type: 0,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a7_0',
oidbCmd: 0x8A7, subCmd: 0,
request: { schema: Oidb0x8a7ReqSchema, value: req },
response: { schema: Oidb0x8a7RespSchema },
});
if (!result) {
throw new Error('get group at all remain result empty');
}
// Cast numbers to plain Number: the OIDB layer may surface uint32 as
// BigInt and the WebUI JSON serializer chokes on those.
return {
can_at_all: !!result.canAtAll,
remain_at_all_count_for_group: Number(result.groupRemain || 0),
remain_at_all_count_for_uin: Number(result.uinRemain || 0),
};
}

View File

@@ -0,0 +1,826 @@
// Group + private file operations: upload (with highway fast-path),
// folder management, file listing, file/media URL fetch. All upload
// paths share the same shape (resolve target → OIDB metadata exchange
// → highway HTTP PUT if the server says we must), but the OIDB schemas
// and field layouts differ enough between group and private that they
// stay as separate functions.
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils';
import {
OidbGroupFileCountViewReqSchema,
OidbGroupFileCountViewRespSchema,
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
OidbGroupFileViewReqSchema,
OidbGroupFileViewRespSchema,
OidbPrivateFileDownloadReqSchema,
OidbPrivateFileDownloadRespSchema,
OidbPrivateFileUploadReqSchema,
OidbPrivateFileUploadRespSchema,
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
} from '../proto/oidb-action';
import { FileUploadExtSchema } from '../proto/highway';
import { toHexUpper } from '../../utils/hex';
import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared';
// ─────────────── public result types ───────────────
export interface GroupFileInfo {
fileId: string;
fileName: string;
busId: number;
fileSize: number;
uploadTime: number;
deadTime: number;
modifyTime: number;
downloadTimes: number;
uploader: number;
uploaderName: string;
}
export interface GroupFolderInfo {
folderId: string;
folderName: string;
createTime: number;
creator: number;
creatorName: string;
totalFileCount: number;
}
export interface GroupFilesResult {
files: GroupFileInfo[];
folders: GroupFolderInfo[];
}
export interface UploadFileResult {
fileId: string | null;
fileHash?: string | null;
}
// Re-export so this file is a one-stop-shop for the file API surface
// (bridge.ts imports MediaIndexNode through here for type symmetry).
export type { MediaIndexNode } from './shared';
// ─────────────── file-specific helpers ───────────────
function normalizeDirectory(dir?: string): string {
if (!dir || !dir.trim()) return '/';
return dir;
}
function bytesToHexUpper(data: unknown): string {
if (!(data instanceof Uint8Array) || data.length === 0) return '';
return toHexUpper(data);
}
function normalizeUploadFileName(name: string, fallback: string): string {
const trimmed = name.trim();
if (trimmed) return trimmed;
const safeFallback = fallback.trim();
return safeFallback || 'file.bin';
}
function md5First10MB(bytes: Uint8Array): Uint8Array {
const limit = Math.min(bytes.length, 10 * 1024 * 1024);
return computeMd5(bytes.subarray(0, limit));
}
function buildGroupFileUploadExt(
senderUin: number,
groupId: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
fileId: string,
uploadKey: Uint8Array,
checkKey: Uint8Array,
uploadHost: string,
uploadPort: number,
): Uint8Array {
return protoEncode({
unknown1: 100,
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
senderUin: BigInt(senderUin),
receiverUin: BigInt(groupId),
groupCode: BigInt(groupId),
},
fileEntry: {
fileSize: BigInt(Math.max(0, fileSize)),
md5,
md5S2: md5,
checkKey,
fileId,
uploadKey,
},
clientInfo: {
clientType: 3,
appId: '100',
terminalType: 3,
clientVer: '1.1.1',
unknown: 4,
},
fileNameInfo: {
fileName,
},
host: {
hosts: [
{
url: {
host: uploadHost,
unknown: 1,
},
port: uploadPort,
},
],
},
},
unknown200: 0,
}, FileUploadExtSchema);
}
function buildPrivateFileUploadExt(
senderUin: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
sha1: Uint8Array,
fileId: string,
uploadKey: Uint8Array,
uploadHost: string,
uploadPort: number,
): Uint8Array {
return protoEncode({
unknown1: 100,
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
senderUin: BigInt(senderUin),
receiverUin: 0n,
groupCode: 0n,
},
fileEntry: {
fileSize: BigInt(Math.max(0, fileSize)),
md5,
md5S2: md5,
checkKey: sha1,
fileId,
uploadKey,
},
clientInfo: {
clientType: 3,
appId: '100',
terminalType: 3,
clientVer: '1.1.1',
unknown: 4,
},
fileNameInfo: {
fileName,
},
host: {
hosts: [
{
url: {
host: uploadHost,
unknown: 1,
},
port: uploadPort,
},
],
},
},
unknown3: 0,
unknown200: 1,
}, FileUploadExtSchema);
}
function normalizeMediaNode(node: MediaIndexNode): Record<string, unknown> {
const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : '';
if (!fileUuid) throw new Error('media node fileUuid is required');
const info = node.info ?? {};
const type = info.type ?? {};
return {
info: {
fileSize: toInt(info.fileSize),
fileHash: typeof info.fileHash === 'string' ? info.fileHash : '',
fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '',
fileName: typeof info.fileName === 'string' ? info.fileName : '',
type: {
type: toInt(type.type),
picFormat: toInt(type.picFormat),
videoFormat: toInt(type.videoFormat),
voiceFormat: toInt(type.voiceFormat),
},
width: toInt(info.width),
height: toInt(info.height),
time: toInt(info.time),
original: toInt(info.original),
},
fileUuid,
storeId: toInt(node.storeId),
uploadTime: toInt(node.uploadTime),
ttl: toInt(node.ttl),
subType: toInt(node.subType),
};
}
async function fetchNtv2DownloadUrl(
bridge: Bridge,
serviceCmd: string,
oidbCmd: number,
payload: Record<string, unknown>,
): Promise<string> {
const resp = await runOidb<any>(bridge, {
cmd: serviceCmd,
oidbCmd, subCmd: 200,
request: { schema: NTV2RichMediaReqSchema, value: payload, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined);
const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : '';
const path = typeof resp?.download?.info?.urlPath === 'string' ? resp.download.info.urlPath : '';
const rKeyParam = typeof resp?.download?.rKeyParam === 'string' ? resp.download.rKeyParam : '';
if (!domain || !path) {
throw new Error('ntv2 download response invalid');
}
return `https://${domain}${path}${rKeyParam}`;
}
// ─────────────── file count ───────────────
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d8_3',
oidbCmd: 0x6D8, subCmd: 3,
request: {
schema: OidbGroupFileCountViewReqSchema,
value: { count: { groupUin: groupId, appId: 7, busId: 0 } },
},
response: { schema: OidbGroupFileCountViewRespSchema },
});
return {
fileCount: toInt(resp?.count?.fileCount ?? 0),
maxCount: toInt(resp?.count?.maxCount ?? 10000),
};
}
// ─────────────── upload ───────────────
export async function uploadGroupFile(
bridge: Bridge,
groupId: number,
source: string,
name = '',
folderId = '/',
uploadFile = true,
): Promise<UploadFileResult> {
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
// so override the default 1 GiB cap with the protocol ceiling.
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('group file is empty');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_0',
oidbCmd: 0x6D6, subCmd: 0,
request: {
schema: OidbGroupFileReqSchema,
value: {
file: {
groupUin: groupId,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: normalizeDirectory(folderId),
fileName,
localDirectory: `/${fileName}`,
fileSize: BigInt(loaded.bytes.length),
fileSha1: hashes.sha1,
fileSha3: new Uint8Array(0),
fileMd5: hashes.md5,
field15: true,
},
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
const upload = resp?.upload;
if (!upload) throw new Error('group file upload response missing');
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
if (!fileId) throw new Error('group file upload response missing file_id');
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(bridge.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|| '';
const uploadPort = toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
throw new Error('group file upload host is invalid');
}
const ext = buildGroupFileUploadExt(
senderUin,
groupId,
fileName,
loaded.bytes.length,
hashes.md5,
fileId,
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
uploadHost,
uploadPort,
);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
}
return { fileId };
}
export async function uploadPrivateFile(
bridge: Bridge,
userId: number,
source: string,
name = '',
uploadFile = true,
): Promise<UploadFileResult> {
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
// so override the default 1 GiB cap with the protocol ceiling.
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('private file is empty');
const targetUid = await bridge.resolveUserUid(userId);
let selfUid = bridge.identity.selfUid;
if (!selfUid) {
const selfUin = toInt(bridge.identity.uin);
if (selfUin > 0) {
selfUid = await bridge.resolveUserUid(selfUin);
}
}
if (!selfUid) throw new Error('self uid is unavailable');
const senderUin = toInt(bridge.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xe37_1700',
oidbCmd: 0xE37, subCmd: 1700,
request: {
schema: OidbPrivateFileUploadReqSchema,
value: {
command: 1700,
seq: 0,
upload: {
senderUid: selfUid,
receiverUid: targetUid,
fileSize: loaded.bytes.length,
fileName,
md510MCheckSum: md5First10MB(loaded.bytes),
sha1CheckSum: hashes.sha1,
localPath: '/',
md5CheckSum: hashes.md5,
sha3CheckSum: new Uint8Array(0),
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
},
},
response: { schema: OidbPrivateFileUploadRespSchema },
});
const upload = resp?.upload;
if (!upload) throw new Error('private file upload response missing');
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null;
const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
if (!fileId) throw new Error('private file upload response missing file_id');
if (!upload.boolFileExist && uploadFile) {
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| '';
const uploadPort = toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
throw new Error('private file upload host is invalid');
}
const ext = buildPrivateFileUploadExt(
senderUin,
fileName,
loaded.bytes.length,
hashes.md5,
hashes.sha1,
fileId,
upload.mediaPlatformUploadKey instanceof Uint8Array
? upload.mediaPlatformUploadKey
: (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
uploadHost,
uploadPort,
);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
}
return { fileId, fileHash };
}
// ─────────────── list ───────────────
export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId = '/'): Promise<GroupFilesResult> {
const targetDirectory = normalizeDirectory(folderId);
const files: GroupFileInfo[] = [];
const folders: GroupFolderInfo[] = [];
const pageSize = 20;
let startIndex = 0;
for (let page = 0; page < 200; page++) {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d8_1',
oidbCmd: 0x6D8, subCmd: 1,
request: {
schema: OidbGroupFileViewReqSchema,
value: {
list: {
groupUin: groupId,
appId: 7,
targetDirectory,
fileCount: pageSize,
sortBy: 1,
startIndex,
field17: 2,
field18: 0,
},
},
isUid: true,
},
response: { schema: OidbGroupFileViewRespSchema },
});
const list = resp?.list;
if (!list) break;
ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
for (const item of list.items ?? []) {
const type = toInt(item?.type);
if (type === 1 && item?.fileInfo) {
const file = item.fileInfo;
const uploader = toInt(file.uploaderUin);
const cached = bridge.identity.findGroupMember(groupId, uploader);
files.push({
fileId: typeof file.fileId === 'string' ? file.fileId : '',
fileName: typeof file.fileName === 'string' ? file.fileName : '',
busId: toInt(file.busId),
fileSize: toInt(file.fileSize),
uploadTime: toInt(file.uploadedTime),
deadTime: toInt(file.expireTime),
modifyTime: toInt(file.modifiedTime),
downloadTimes: toInt(file.downloadedTimes),
uploader,
uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName)
|| cached?.card
|| cached?.nickname
|| '',
});
} else if (type === 2 && item?.folderInfo) {
const folder = item.folderInfo;
const creator = toInt(folder.creatorUin);
const cached = bridge.identity.findGroupMember(groupId, creator);
folders.push({
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
createTime: toInt(folder.createTime),
creator,
creatorName: (typeof folder.creatorName === 'string' && folder.creatorName)
|| cached?.card
|| cached?.nickname
|| '',
totalFileCount: toInt(folder.totalFileCount),
});
}
}
if (list.isEnd) break;
startIndex += pageSize;
}
return { files, folders };
}
// ─────────────── url fetch (group / private files) ───────────────
export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise<string> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_2',
oidbCmd: 0x6D6, subCmd: 2,
request: {
schema: OidbGroupFileReqSchema,
value: {
download: {
groupUin: groupId,
appId: 7,
busId,
fileId,
},
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
const download = resp?.download;
if (!download) throw new Error('group file url response missing');
ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording);
const dns = (typeof download.downloadDns === 'string' && download.downloadDns)
|| (typeof download.downloadIp === 'string' && download.downloadIp)
|| '';
const hexUrl = bytesToHexUpper(download.downloadUrl);
if (!dns || !hexUrl) {
throw new Error('group file url response invalid');
}
// Keep the same behavior as Lagrange: append file_id after ?fname=
return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`;
}
export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> {
const uid = await bridge.resolveUserUid(userId);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xe37_1200',
oidbCmd: 0xE37, subCmd: 1200,
request: {
schema: OidbPrivateFileDownloadReqSchema,
value: {
subCommand: 1200,
field2: 1,
body: {
receiverUid: uid,
fileUuid: fileId,
type: 2,
fileHash,
t2: 0,
},
field101: 3,
field102: 103,
field200: 1,
field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
},
},
response: { schema: OidbPrivateFileDownloadRespSchema },
});
const result = resp?.body?.result;
const server = typeof result?.server === 'string' ? result.server : '';
const port = toInt(result?.port);
const url = typeof result?.url === 'string' ? result.url : '';
if (!server || !port || !url) {
throw new Error('private file url response invalid');
}
return `http://${server}:${port}${url}&isthumb=0`;
}
// ─────────────── delete / move ───────────────
export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_3',
oidbCmd: 0x6D6, subCmd: 3,
request: {
schema: OidbGroupFileReqSchema,
value: {
delete: {
groupUin: groupId,
busId: 102,
fileId,
},
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
const result = resp?.delete;
if (!result) throw new Error('group file delete response missing');
ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording);
}
export async function moveGroupFile(
bridge: Bridge,
groupId: number,
fileId: string,
parentDirectory: string,
targetDirectory: string,
): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_5',
oidbCmd: 0x6D6, subCmd: 5,
request: {
schema: OidbGroupFileReqSchema,
value: {
move: {
groupUin: groupId,
appId: 7,
busId: 102,
fileId,
parentDirectory,
targetDirectory,
},
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
const result = resp?.move;
if (!result) throw new Error('group file move response missing');
ensureRetCodeZero('group file move', result.retCode, result.retMsg, result.clientWording);
}
// ─────────────── folders ───────────────
export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_0',
oidbCmd: 0x6D7, subCmd: 0,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
create: {
groupUin: groupId,
rootDirectory: normalizeDirectory(parentId),
folderName: name,
},
},
isUid: true,
},
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.create;
if (!result) throw new Error('group folder create response missing');
ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording);
}
export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_1',
oidbCmd: 0x6D7, subCmd: 1,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
delete: {
groupUin: groupId,
folderId,
},
},
isUid: true,
},
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.delete;
if (!result) throw new Error('group folder delete response missing');
ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording);
}
export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_2',
oidbCmd: 0x6D7, subCmd: 2,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
rename: {
groupUin: groupId,
folderId,
newFolderName,
},
},
isUid: true,
},
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.rename;
if (!result) throw new Error('group folder rename response missing');
ensureRetCodeZero('group folder rename', result.retcode, result.retMsg, result.clientWording);
}
// ─────────────── rich-media URL by node ───────────────
export async function fetchGroupPttUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise<string> {
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126e_200', 0x126E, {
reqHead: {
common: { requestId: 4, command: 200 },
scene: {
requestType: 1,
businessType: 3,
sceneType: 2,
group: { groupUin: groupId },
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchPrivatePttUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise<string> {
const selfUid = await resolveSelfUid(bridge);
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126d_200', 0x126D, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 1,
businessType: 3,
sceneType: 1,
c2c: {
accountType: 2,
targetUid: selfUid,
},
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchGroupVideoUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise<string> {
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11ea_200', 0x11EA, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 2,
businessType: 2,
sceneType: 2,
group: { groupUin: groupId },
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchPrivateVideoUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise<string> {
const selfUid = await resolveSelfUid(bridge);
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11e9_200', 0x11E9, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 2,
businessType: 2,
sceneType: 1,
c2c: {
accountType: 2,
targetUid: selfUid,
},
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}

View File

@@ -0,0 +1,104 @@
// Operations targeting an existing message: recall (group / private),
// mark-as-read (group / private), and the "essence" highlight toggle.
// All of these take a message identifier and modify server-side state
// without producing a downstream observable event.
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import {
C2CRecallRequestSchema,
GroupRecallRequestSchema,
OidbEssenceSchema,
SsoReadedReportReqSchema,
} from '../proto/oidb-action';
export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise<void> {
const request = protoEncode({
type: 1,
groupUin: groupId,
info: { sequence, random: 0, field3: 0 },
settings: { field1: 0 },
}, GroupRecallRequestSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall group message failed');
}
export async function recallPrivateMessage(
bridge: Bridge, userUin: number, clientSeq: number,
msgSeq: number, random: number, timestamp: number,
): Promise<void> {
const targetUid = await bridge.resolveUserUid(userUin);
const request = protoEncode({
type: 1,
targetUid,
info: {
clientSequence: clientSeq,
random,
messageId: BigInt((0x01000000 * 0x100000000) + random),
timestamp,
field5: 0,
messageSequence: msgSeq,
},
settings: { field1: false, field2: false },
field6: false,
}, C2CRecallRequestSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
}
export async function markPrivateMessageRead(
bridge: Bridge,
userId: number,
msgSeq: number,
timestamp: number = Math.floor(Date.now() / 1000),
): Promise<void> {
const uid = await bridge.resolveUserUid(userId);
const request = protoEncode({
c2cList: [
{
uid,
lastReadTime: BigInt(timestamp),
lastReadSeq: BigInt(msgSeq),
},
],
}, SsoReadedReportReqSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark private message read failed');
}
}
export async function markGroupMessageRead(
bridge: Bridge,
groupId: number,
msgSeq: number,
): Promise<void> {
const request = protoEncode({
groupList: [
{
groupUin: BigInt(groupId),
lastReadSeq: BigInt(msgSeq),
},
],
}, SsoReadedReportReqSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark group message read failed');
}
}
export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
const subCmd = enable ? 1 : 2;
const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2';
await runOidb(bridge, {
cmd,
oidbCmd: 0xEAC, subCmd,
request: { schema: OidbEssenceSchema, value: { groupUin: groupId, sequence, random } },
});
}

View File

@@ -0,0 +1,86 @@
// Lightweight social-interaction actions: poke, like, emoji reaction,
// and the related read-side "who reacted with X" query. None of these
// edit message content — they're purely social signals.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
Oidb0x9083ReqSchema,
Oidb0x9083RespSchema,
OidbGroupReactionSchema,
OidbLikeSchema,
OidbPokeSchema,
} from '../proto/oidb-action';
export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xed3_1',
oidbCmd: 0xED3, subCmd: 1,
request: {
schema: OidbPokeSchema,
value: {
uin: targetUin ?? peerUin,
groupUin: isGroup ? peerUin : 0,
friendUin: isGroup ? 0 : peerUin,
ext: 0,
},
},
});
}
export async function sendLike(bridge: Bridge, userId: number, count: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x7e5_104',
oidbCmd: 0x7E5, subCmd: 104,
request: { schema: OidbLikeSchema, value: { targetUin: userId, count } },
});
}
export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
const subCmd = isSet ? 1 : 2;
const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2';
// Same heuristic NapCat uses: QQ face ids are 1–3 digits ("76"),
// unicode codepoints are longer ("128516"). Server requires the
// type field to pick the right resolution table; omitting it makes
// unicode reactions silently fail.
const type = code.length > 3 ? 2 : 1;
await runOidb(bridge, {
cmd,
oidbCmd: 0x9082, subCmd,
request: {
schema: OidbGroupReactionSchema,
value: { groupUin: groupId, sequence, code, type },
},
});
}
export async function getEmojiLikes(
bridge: Bridge,
groupId: number,
sequence: number,
emojiId: string,
emojiType: number = 1,
count: number = 10,
cookie: string = '',
): Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }> {
const req = {
groupId: BigInt(groupId),
sequence,
emojiType,
emojiId,
cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0),
field7: 0,
count,
field12: 1,
};
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x9083_1',
oidbCmd: 0x9083, subCmd: 1,
request: { schema: Oidb0x9083ReqSchema, value: req },
response: { schema: Oidb0x9083RespSchema },
});
const uin = resp?.inner?.userInfo?.uin;
const users = uin ? [{ uin: Number(uin) }] : [];
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
return { users, cookie: respCookie, isLast: !respCookie };
}

View File

@@ -0,0 +1,164 @@
// Grab-bag: action verbs that don't share a theme with anything else.
// Kept together so the directory stays small; if any of these grow new
// related siblings, lift the whole group out into its own file.
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import {
MiniAppShareReqSchema,
MiniAppShareRespSchema,
Oidb0x112eReqSchema,
Oidb0x112eRespSchema,
Oidb0x990ReqSchema,
Oidb0x990RespSchema,
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema,
} from '../proto/oidb-action';
export async function translateEn2Zh(
bridge: Bridge,
words: string[],
) {
const req = {
translateReq: {
srcLang: 'en',
dstLang: 'zh',
words: words,
},
tag10: 1,
tag12: 1,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x990_2',
oidbCmd: 0x990, subCmd: 2,
request: { schema: Oidb0x990ReqSchema, value: req },
response: { schema: Oidb0x990RespSchema },
});
const resp = result?.translateResp;
if (!resp) {
throw new Error('translate response empty');
}
return resp.dstWords || [];
}
export async function getMiniAppArk(
bridge: Bridge,
type: string,
title: string,
desc: string,
picUrl: string,
jumpUrl: string,
) {
let appid = '1109937557'; // default: bilibili
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
if (type === 'weibo') {
appid = '1109224783';
iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
} else if (type !== 'bili') {
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
}
const request = protoEncode({
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
body: {
appid,
title,
desc,
picUrl,
jumpUrl,
iconUrl,
},
}, MiniAppShareReqSchema);
const result = await bridge.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
if (!result.success || !result.responseData) {
throw new Error(result.errorMessage || 'get mini app ark failed');
}
const decoded = protoDecode(result.responseData, MiniAppShareRespSchema);
const jsonStr = decoded?.body?.jsonStr;
if (!jsonStr) {
throw new Error('mini app share json empty');
}
const parsed = JSON.parse(jsonStr);
return {
data: {
ver: parsed.ver,
prompt: parsed.prompt,
config: parsed.config,
app: parsed.appName,
view: parsed.appView,
meta: parsed.metaData,
miniappShareOrigin: 3,
miniappOpenRefer: '10002',
},
};
}
export async function clickInlineKeyboardButton(
bridge: Bridge,
groupId: number,
botAppid: number,
buttonId: string,
callbackData: string,
msgSeq: number,
) {
const req = {
botAppid: BigInt(botAppid),
msgSeq: BigInt(msgSeq),
buttonId: String(buttonId),
callbackData: String(callbackData || ''),
unknown7: 0,
groupId: BigInt(groupId),
unknown9: 1,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112e_1',
oidbCmd: 0x112E, subCmd: 1,
request: { schema: Oidb0x112eReqSchema, value: req },
response: { schema: Oidb0x112eRespSchema },
});
if (!result) {
throw new Error('click inline keyboard button result empty');
}
return {
result: Number(result.result || 0),
errMsg: result.errMsg || '',
status: 0,
promptText: result.promptText || '',
promptType: 0,
promptIcon: 0,
};
}
export async function sendGroupSign(
bridge: Bridge,
groupId: number,
) {
const req = {
signInInfo: {
uin: String(bridge.identity.uin),
groupId: String(groupId),
version: '9.0.90',
},
};
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xEB7_1',
oidbCmd: 0xEB7, subCmd: 1,
request: { schema: Oidb0xeb7ReqSchema, value: req },
response: { schema: Oidb0xeb7RespSchema },
});
}

View File

@@ -0,0 +1,313 @@
// Operations that touch the bot's own profile / status, plus the
// related queries about my profile likes and unidirectional friends.
// All of these read/write fields on the self-uin via OIDB.
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, loadBinarySource } from '../highway/utils';
import {
FaceroamOpReqSchema,
FaceroamOpRespSchema,
GroupAvatarExtraSchema,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
Oidb0x7edReqSchema,
Oidb0x7edRespSchema,
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema,
Oidb0xe17ReqSchema,
Oidb0xe17RespSchema,
OidbSetProfileSchema,
SetStatusReqSchema,
SetStatusRespSchema,
} from '../proto/oidb-action';
import { resolveSelfUid } from './shared';
// ─────────────── status / profile setters ───────────────
export async function setOnlineStatus(
bridge: Bridge,
status: number,
extStatus: number = 0,
batteryStatus: number = 100,
): Promise<void> {
await dispatchSetStatus(bridge, { status, extStatus, batteryStatus });
}
/**
* DIY (custom) online status. napcat fixes status=10 / extStatus=2000
* — the values QQ associates with "I have a custom status string" —
* and threads the faceId / wording / faceType through the customExt
* sub-message of the same SetStatus wire call.
*/
export async function setDiyOnlineStatus(
bridge: Bridge,
faceId: number,
wording: string,
faceType: number,
): Promise<void> {
await dispatchSetStatus(bridge, {
status: 10,
extStatus: 2000,
batteryStatus: 0,
customExt: { faceId, text: wording, faceType },
});
}
async function dispatchSetStatus(
bridge: Bridge,
value: {
status: number;
extStatus: number;
batteryStatus: number;
customExt?: { faceId: number; text: string; faceType: number };
},
): Promise<void> {
const request = protoEncode(value, SetStatusReqSchema);
const result = await bridge.sendRawPacket('trpc.qq_new_tech.status_svc.StatusService.SetStatus', request);
if (!result.success) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
if (result.responseData && result.responseData.length > 0) {
const resp = protoDecode(result.responseData, SetStatusRespSchema);
if (!resp) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
if (resp.errCode !== undefined && resp.errCode !== 0) {
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
}
}
}
export async function setProfile(
bridge: Bridge,
nickname?: string,
personalNote?: string,
): Promise<void> {
const uin = BigInt(bridge.identity.uin);
const stringProfiles: any[] = [];
const intProfiles: any[] = [];
if (nickname !== undefined) {
stringProfiles.push({ fieldId: 20002, value: nickname });
}
if (personalNote !== undefined) {
stringProfiles.push({ fieldId: 102, value: personalNote });
}
if (stringProfiles.length === 0 && intProfiles.length === 0) {
return;
}
const req = {
uin,
stringProfiles,
};
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112a_2',
oidbCmd: 0x112A, subCmd: 2,
request: { schema: OidbSetProfileSchema, value: req },
});
}
export async function setSelfLongNick(
bridge: Bridge,
longNick: string,
) {
const req = {
uin: BigInt(bridge.identity.uin),
profile: {
tag: 102,
value: String(longNick),
},
};
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112a_2',
oidbCmd: 0x112A, subCmd: 2,
request: { schema: Oidb0x112aReqSchema, value: req },
response: { schema: Oidb0x112aRespSchema },
});
}
export async function setInputStatus(
bridge: Bridge,
userId: number,
eventType: number,
) {
const targetUid = await bridge.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
}
const req = {
reqBody: {
uid: targetUid,
chatType: 0,
eventType: eventType,
},
};
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xcd4_1',
oidbCmd: 0xCD4, subCmd: 1,
request: { schema: Oidb0xcd4ReqSchema, value: req },
response: { schema: Oidb0xcd4RespSchema },
});
}
export async function setAvatar(
bridge: Bridge,
source: string,
): Promise<void> {
const loaded = await loadBinarySource(source, 'avatar');
if (!loaded.bytes.length) throw new Error('avatar file is empty');
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0));
}
/**
* Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar:
* - same highway HTTP upload as personal avatar
* - cmdId 3000 (instead of 90)
* - GroupAvatarExtra proto carried as the `extend` blob, with the
* four protocol-prescribed constants (type=101, field5=3, field6=1,
* field3.field1=1) and the target groupUin.
*
* Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar.
*/
export async function setGroupAvatar(
bridge: Bridge,
groupId: number,
source: string,
): Promise<void> {
const loaded = await loadBinarySource(source, 'group-avatar');
if (!loaded.bytes.length) throw new Error('group avatar file is empty');
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
const extra = protoEncode({
type: 101,
groupUin: groupId,
field3: { field1: 1 },
field5: 3,
field6: 1,
}, GroupAvatarExtraSchema);
await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra);
}
// ─────────────── queries on me / my contacts ───────────────
export async function getProfileLike(
bridge: Bridge,
userId?: number,
start: number = 0,
limit: number = 10,
) {
const isSelf = !userId;
const targetUid = isSelf
? await resolveSelfUid(bridge)
: await bridge.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
}
const req = {
targetUid: targetUid,
basic: 1,
vote: 1,
favorite: 1,
start: start,
limit: limit,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x7ed_12',
oidbCmd: 0x7ED, subCmd: 12,
request: { schema: Oidb0x7edReqSchema, value: req },
response: { schema: Oidb0x7edRespSchema },
});
const data = result?.userLikeInfos?.[0];
if (!data) {
throw new Error('get profile like info empty');
}
return {
uid: data.uid,
time: Number(data.time),
favoriteInfo: {
total_count: data.favoriteInfo?.totalCount || 0,
last_time: Number(data.favoriteInfo?.lastTime || 0),
today_count: data.favoriteInfo?.newCount || 0,
userInfos: [],
},
voteInfo: {
total_count: data.voteInfo?.totalCount || 0,
new_count: data.voteInfo?.newCount || 0,
new_nearby_count: 0,
last_visit_time: Number(data.voteInfo?.lastTime || 0),
userInfos: [],
},
};
}
export async function getUnidirectionalFriendList(
bridge: Bridge,
) {
const reqObj = {
uint64_uin: String(bridge.identity.uin),
uint64_top: 0,
uint32_req_num: 99,
bytes_cookies: '',
};
const req = {
jsonBody: JSON.stringify(reqObj),
};
const result = await runOidb<any>(bridge, {
cmd: 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
oidbCmd: 0xE17, subCmd: 0,
request: { schema: Oidb0xe17ReqSchema, value: req },
response: { schema: Oidb0xe17RespSchema },
});
if (!result || !result.jsonBody) {
throw new Error('get unidirectional friend list empty');
}
const parsed = JSON.parse(result.jsonBody);
return parsed.rpt_block_list || [];
}
export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise<string[]> {
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(bridge.identity.uin),
field3: 1,
field6: 1,
};
const request = protoEncode(req, FaceroamOpReqSchema);
const result = await bridge.sendRawPacket('Faceroam.OpReq', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
}
const resp = protoDecode(result.responseData, FaceroamOpRespSchema);
if (!resp || (resp as any).retCode !== 0) {
throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`);
}
const faceIds = (resp as any).item?.faceIds || [];
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${bridge.identity.uin}/${id}/0`);
}

View File

@@ -1,6 +1,14 @@
// Shared private helpers for the action modules. None of this is part
// of the public Bridge API; keeping it here avoids re-importing the
// same five-line utility from every themed file.
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
import type { Bridge } from '../bridge';
/**
* Coerce numbers, strings, and bigints to a plain integer.
* Returns 0 for anything we can't interpret — every action that
* threads this through OIDB has an explicit `<=0` validation later.
*/
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
@@ -32,7 +40,7 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown
* `selfProfile`; forward/profile actions need this fast path before
* warmup completes.
*/
export async function resolveSelfUid(bridge: BridgeContext): Promise<string> {
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
let selfUid = bridge.identity.selfUid;
if (selfUid) return selfUid;

View File

@@ -0,0 +1,352 @@
// Contact / info-fetching operations extracted from Bridge.
import type { Bridge } from './bridge';
import type { DownloadRKeyInfo } from './bridge';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { protoDecode } from '../protobuf/decode';
import { runOidb } from './bridge-oidb';
import {
OidbSvcTrpcTcp0xFD4_1ResponseSchema,
OidbSvcTrpcTcp0xFE5_2ResponseSchema,
OidbSvcTrpcTcp0xFE7_3ResponseSchema,
OidbSvcTrpcTcp0x10C0ResponseSchema,
} from './proto/oidb';
import {
OidbFriendListRequestSchema,
OidbGroupListRequestSchema,
OidbGroupMemberListRequestSchema,
OidbUserInfoRequestSchema,
OidbUserInfoResponseSchema,
AvatarInfoSchema,
OidbGroupRequestListSchema,
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
} from './proto/oidb-action';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
export function buildFriendProperties(raw: any): Map<number, string> {
const props = new Map<number, string>();
for (const additional of raw.additional ?? []) {
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
for (const property of additional.layer1.properties ?? []) {
props.set(property.code ?? 0, property.value ?? '');
}
}
return props;
}
export function permissionToRole(permission: number): string {
switch (permission) {
case 1: return 'owner';
case 2: return 'admin';
default: return 'member';
}
}
// ---------------------------------------------------------------------------
// Friend list
// ---------------------------------------------------------------------------
export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
const friends: FriendInfo[] = [];
let nextUin: number | null = null;
do {
const body: any = {
friendCount: 300,
field4: 0,
field6: 1,
field7: 0x7FFFFFFF,
body: [
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
{ type: 4, number: { numbers: [100, 101, 102] } },
],
field10002: [13578, 13579, 13573, 13572, 13568],
field10003: 4051,
};
if (nextUin !== null) {
body.nextUin = { uin: nextUin };
}
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfd4_1',
oidbCmd: 0xFD4, subCmd: 1,
request: { schema: OidbFriendListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFD4_1ResponseSchema },
});
if (resp?.friends) {
for (const raw of resp.friends) {
const props = buildFriendProperties(raw);
friends.push({
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
});
}
}
nextUin = resp?.next?.uin ?? null;
if (nextUin === 0) nextUin = null;
} while (nextUin !== null);
bridge.identity.rememberFriends(friends);
return friends;
}
// ---------------------------------------------------------------------------
// Group list
// ---------------------------------------------------------------------------
export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
const allTrue = true;
const body = {
config: {
config1: {
groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue,
groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue,
field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue,
field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue,
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: allTrue,
},
config2: {
field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue,
field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue,
},
config3: { field5: allTrue, field6: allTrue },
},
};
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe5_2',
oidbCmd: 0xFE5, subCmd: 2,
request: { schema: OidbGroupListRequestSchema, value: body, isUid: true },
response: { schema: OidbSvcTrpcTcp0xFE5_2ResponseSchema },
});
const groups: QQGroupInfo[] = [];
if (resp?.groups) {
for (const raw of resp.groups) {
groups.push({
groupId: raw.groupUin ?? 0,
groupName: raw.info?.groupName ?? '',
remark: raw.customInfo?.remark ?? '',
memberCount: raw.info?.memberCount ?? 0,
memberMax: raw.info?.memberMax ?? 0,
members: new Map(),
});
}
}
bridge.identity.rememberGroups(groups);
return groups;
}
// ---------------------------------------------------------------------------
// Group member list
// ---------------------------------------------------------------------------
export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Promise<GroupMemberInfo[]> {
const members: GroupMemberInfo[] = [];
let token = '';
do {
const body: any = {
groupUin: groupId,
field2: 5,
field3: 2,
body: {
memberName: true, memberCard: true, level: true, field13: true,
field16: true, specialTitle: true, field18: true, field20: true,
field21: true, joinTimestamp: true, lastMsgTimestamp: true,
shutUpTimestamp: true, field103: true, field104: true, field105: true,
field106: true, permission: true, field200: true, field201: true,
},
};
if (token) body.token = token;
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe7_3',
oidbCmd: 0xFE7, subCmd: 3,
request: { schema: OidbGroupMemberListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFE7_3ResponseSchema },
});
if (resp?.members) {
for (const raw of resp.members) {
members.push({
uin: raw.uin?.uin ?? 0,
uid: raw.uin?.uid ?? '',
nickname: raw.memberName ?? '',
card: raw.memberCard?.memberCard ?? '',
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
});
}
}
token = resp?.token ?? '';
} while (token);
bridge.identity.rememberGroupMembers(groupId, members);
return members;
}
// ---------------------------------------------------------------------------
// User profile
// ---------------------------------------------------------------------------
export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<UserProfileInfo> {
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
const body = {
uin,
field2: 0,
keys: keys.map(k => ({ key: k })),
};
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: { schema: OidbUserInfoRequestSchema, value: body },
response: { schema: OidbUserInfoResponseSchema },
});
if (!resp?.body) throw new Error('user info response body missing');
const info: UserProfileInfo = {
uin: resp.body.uin ?? uin,
uid: resp.body.uid ?? '',
nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
};
if (resp.body.properties) {
const bytesMap = new Map<number, Uint8Array>();
const numMap = new Map<number, number>();
for (const bp of resp.body.properties.bytesProperties ?? []) {
bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0));
}
for (const np of resp.body.properties.numberProperties ?? []) {
numMap.set(np.number1 ?? 0, np.number2 ?? 0);
}
const getString = (code: number) => {
const b = bytesMap.get(code);
return b ? Buffer.from(b).toString('utf8') : '';
};
info.nickname = getString(20002);
info.remark = getString(103);
info.qid = getString(27394);
info.sign = getString(102);
const avatarBytes = bytesMap.get(101);
if (avatarBytes) {
const av = protoDecode(avatarBytes, AvatarInfoSchema);
if (av?.url) info.avatar = av.url + '640';
}
const sexNum = numMap.get(20009) ?? 0;
info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown';
info.age = numMap.get(20037) ?? 0;
}
bridge.identity.rememberUserProfile(info);
return info;
}
// ---------------------------------------------------------------------------
// Group requests
// ---------------------------------------------------------------------------
export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise<GroupRequestInfo[]> {
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
const resp = await runOidb<any>(bridge, {
cmd,
oidbCmd: 0x10C0, subCmd,
request: { schema: OidbGroupRequestListSchema, value: { count: 20, field2: 0 } },
response: { schema: OidbSvcTrpcTcp0x10C0ResponseSchema },
});
const requests: GroupRequestInfo[] = [];
for (const raw of resp?.requests ?? []) {
requests.push({
groupId: raw.group?.groupUin ?? 0,
groupName: raw.group?.groupName ?? '',
targetUid: raw.target?.uid ?? '',
targetUin: 0,
targetName: raw.target?.name ?? '',
invitorUid: raw.invitor?.uid ?? '',
invitorUin: 0,
invitorName: raw.invitor?.name ?? '',
operatorUid: raw.operatorUser?.uid ?? '',
operatorUin: 0,
operatorName: raw.operatorUser?.name ?? '',
sequence: Number(raw.sequence ?? 0),
state: raw.state ?? 0,
eventType: raw.eventType ?? 0,
comment: raw.comment ?? '',
filtered,
});
}
bridge.identity.rememberGroupRequests(requests);
return requests;
}
// ---------------------------------------------------------------------------
// Download RKeys
// ---------------------------------------------------------------------------
export async function fetchDownloadRKeys(bridge: Bridge): Promise<DownloadRKeyInfo[]> {
const PRIVATE_IMAGE = 10;
const GROUP_IMAGE = 20;
const FALLBACK_IMAGE = 2;
const body = {
reqHead: {
common: { requestId: 1, command: 202 },
scene: { requestType: 2, businessType: 1, sceneType: 0 },
client: { agentType: 2 },
},
downloadRkey: {
types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE],
},
};
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x9067_202',
oidbCmd: 0x9067, subCmd: 202,
request: { schema: NTV2RichMediaReqSchema, value: body, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
}
const result: DownloadRKeyInfo[] = [];
for (const entry of resp?.downloadRkey?.rkeys ?? []) {
const rkey = entry.rkey ?? '';
const type = entry.type ?? 0;
if (rkey && type) {
result.push({
rkey,
ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
storeId: entry.storeId ?? 0,
createTime: entry.rkeyCreateTime ?? 0,
type,
});
}
}
return result;
}

View File

@@ -0,0 +1,147 @@
// BridgeInterface — the surface OneBot (and any other external consumer)
// is allowed to see. The concrete Bridge class additionally exposes raw
// protocol primitives (sendRawPacket, packet dispatch, PID management)
// used by the in-tree action / contacts / highway modules; those internal
// methods deliberately do NOT appear here so that callers depending on
// the interface stay decoupled from the wire format.
//
// Every method below has a matching signature on Bridge; `Bridge
// implements BridgeInterface` is the compile-time enforcement.
import type { BridgeEventBus } from './event-bus';
import type { IdentityService } from './identity-service';
import type {
FriendInfo, QQGroupInfo, GroupMemberInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import type { MessageElement, ForwardNodePayload } from './events';
import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import type { WebHonorType } from './web/group-honor';
import type {
SendMessageReceipt,
DownloadRKeyInfo,
ClientKeyInfo,
} from './bridge';
import type { SendPacketResult } from '../protocol/packet-sender';
export interface BridgeInterface {
// ─── Shared state ───
readonly identity: IdentityService;
readonly events: BridgeEventBus;
readonly activePid: number | null;
// ─── Resolution ───
resolveUserUid(uin: number, groupId?: number): Promise<string>;
// ─── Raw packet (deliberate escape hatch for `send_packet` action) ───
// OneBot clients use this to debug or invoke commands SnowLuma has no
// typed wrapper for. Every other method on this interface eventually
// routes through here.
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
// ─── Send (messages) ───
sendGroupMessage(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
// ─── Fetch (contacts / profile / system) ───
fetchFriendList(): Promise<FriendInfo[]>;
fetchGroupList(): Promise<QQGroupInfo[]>;
fetchGroupMemberList(groupId: number, options?: { force?: boolean }): Promise<GroupMemberInfo[]>;
fetchUserProfile(uin: number): Promise<UserProfileInfo>;
fetchGroupRequests(filtered?: boolean): Promise<GroupRequestInfo[]>;
fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]>;
// ─── Group admin ───
muteGroupMember(groupId: number, userId: number, duration: number): Promise<void>;
muteGroupAll(groupId: number, enable: boolean): Promise<void>;
setGroupAddOption(groupId: number, addType: number): Promise<void>;
setGroupSearch(groupId: number): Promise<void>;
setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason?: string, filtered?: boolean): Promise<void>;
kickGroupMember(groupId: number, userId: number, reject: boolean, reason?: string): Promise<void>;
kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise<void>;
leaveGroup(groupId: number): Promise<void>;
setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise<void>;
setGroupCard(groupId: number, userId: number, card: string): Promise<void>;
setGroupName(groupId: number, name: string): Promise<void>;
setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise<void>;
setGroupRemark(groupId: number, remark: string): Promise<void>;
setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void>;
setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void>;
// ─── Friend ───
setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise<void>;
deleteFriend(userId: number, block?: boolean): Promise<void>;
setFriendRemark(userId: number, remark: string): Promise<void>;
// ─── Files ───
uploadGroupFile(groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
uploadPrivateFile(userId: number, file: string, name?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
fetchGroupFiles(groupId: number, folderId?: string): Promise<GroupFilesResult>;
fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise<string>;
fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string>;
fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise<string>;
fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string>;
fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string>;
fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string>;
deleteGroupFile(groupId: number, fileId: string): Promise<void>;
moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void>;
createGroupFileFolder(groupId: number, name: string, parentId?: string): Promise<void>;
deleteGroupFileFolder(groupId: number, folderId: string): Promise<void>;
renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void>;
fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>;
// ─── Forward ───
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string>;
fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]>;
// ─── Message ops ───
recallGroupMessage(groupId: number, sequence: number): Promise<void>;
recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise<void>;
markGroupMsgAsRead(groupId: number, sequence: number): Promise<void>;
markPrivateMsgAsRead(userId: number, sequence: number): Promise<void>;
// ─── Interaction ───
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void>;
sendLike(userId: number, count: number): Promise<void>;
getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }>;
// ─── Web-backed ───
getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any>;
forceFetchClientKey(): Promise<ClientKeyInfo>;
getGroupEssence(groupId: number, pageStart?: number, pageLimit?: number): Promise<any>;
getGroupEssenceAll(groupId: number): Promise<any>;
sendGroupNotice(groupId: number, content: string, options?: any): Promise<any>;
getGroupNotice(groupId: number): Promise<any>;
deleteGroupNotice(groupId: number, fid: string): Promise<boolean>;
getCookiesStr(domain: string): Promise<string>;
getCsrfToken(): Promise<number>;
getCredentials(domain: string): Promise<any>;
// ─── Personal profile ───
setOnlineStatus(status: number, extStatus?: number, batteryStatus?: number): Promise<void>;
setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void>;
setProfile(nickname?: string, personalNote?: string): Promise<void>;
setSelfLongNick(longNick: string): Promise<any>;
setInputStatus(userId: number, eventType: number): Promise<any>;
setAvatar(source: string): Promise<void>;
setGroupAvatar(groupId: number, source: string): Promise<void>;
fetchCustomFace(count?: number): Promise<string[]>;
getProfileLike(userId?: number, start?: number, limit?: number): Promise<any>;
getUnidirectionalFriendList(): Promise<any>;
getGroupAtAllRemain(groupId: number): Promise<any>;
// ─── Misc ───
translateEn2Zh(words: string[]): Promise<any>;
getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<any>;
clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number): Promise<any>;
sendGroupSign(groupId: number): Promise<any>;
// ─── Tier-2 napcat parity extras ───
setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
getStrangerStatus(uin: number): Promise<{ status: number; ext_status: number } | null>;
fetchAiVoiceList(groupId: number, chatType: number): Promise<Array<{ category: string; voices: Array<{ voiceId: string; voiceDisplayName: string; voiceExampleUrl: string }> }>>;
fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: number): Promise<MediaIndexNode>;
}

View File

@@ -0,0 +1,90 @@
// One deep entry point for a single OIDB round-trip: build the envelope,
// dispatch via Bridge.sendRawPacket, validate the response status, and
// optionally decode the body. Replaces the three positional helpers
// (makeOidbRequest / sendOidbAndCheck / sendOidbAndDecode) that used to
// scatter the same five-step pattern across every action file.
import type { Bridge } from './bridge';
import type { ProtoSchema } from '../protobuf/decode';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { makeOidbBaseSchema } from './proto/oidb';
export interface OidbCall<TResp = void> {
/** Service-cmd string sent on the wire, e.g. 'OidbSvcTrpcTcp.0x1253_1'. */
cmd: string;
/** OIDB command number, e.g. 0x1253. */
oidbCmd: number;
/** OIDB sub-command, e.g. 1. */
subCmd: number;
request: {
schema: ProtoSchema;
value: any;
/**
* Sets the OIDB envelope `reserved` field to 1 when true. A handful
* of commands (group/friend list, rkey download) operate on
* UID-keyed data and require this flag — the wire format is
* otherwise identical.
*/
isUid?: boolean;
};
/** Omit to skip decoding the response body (fire-and-check). */
response?: {
schema: ProtoSchema;
};
}
/**
* Issue one OIDB request. Without `response`, returns void after
* verifying the envelope's retCode. With `response`, decodes the
* envelope, validates retCode, and returns the inner body.
*
* Throws on transport failure, missing response, decode failure, or any
* non-zero envelope retCode. Action modules layer their own retCode
* checks (on inner sub-replies like `upload.retCode`) on top of this.
*/
export function runOidb(bridge: Bridge, call: OidbCall<void> & { response?: undefined }): Promise<void>;
export function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp> & { response: { schema: ProtoSchema } }): Promise<TResp>;
export async function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp>): Promise<TResp | void> {
const envelope = encodeOidbEnvelope(call);
const result = await bridge.sendRawPacket(call.cmd, envelope);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (call.response) {
if (!result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'no response');
}
const baseSchema = makeOidbBaseSchema(call.response.schema);
const resp = protoDecode(result.responseData, baseSchema);
if (!resp) throw new Error('failed to decode OIDB response');
throwIfOidbError(resp);
return (resp as any).body as TResp;
}
// Fire-and-check: response data is optional, but if present we still
// peek at the envelope so a server-side retCode doesn't silently slip past.
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
if (result.responseData && result.responseData.length > 0) {
const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } });
const resp = protoDecode(result.responseData, emptyBase);
if (resp) throwIfOidbError(resp);
}
}
function encodeOidbEnvelope(call: OidbCall<unknown>): Uint8Array {
const baseSchema = makeOidbBaseSchema(call.request.schema);
return protoEncode({
command: call.oidbCmd,
subCommand: call.subCmd,
errorCode: 0,
body: call.request.value,
errorMsg: '',
reserved: call.request.isUid ? 1 : 0,
}, baseSchema);
}
function throwIfOidbError(resp: unknown): void {
const code = (resp as any).errorCode;
if (code && code !== 0) {
throw new Error(`OIDB error ${code}: ${(resp as any).errorMsg ?? ''}`);
}
}

View File

@@ -0,0 +1,575 @@
// Bridge — per-UIN session: handler registration, packet dispatch, event routing.
// Supports packet sending via native addon.
// Heavy OIDB / contact / action logic is split into bridge-oidb, bridge-contacts, bridge-actions.
import type { PacketInfo } from '../protocol/types';
import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push';
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { buildSendElems } from './element-builder';
import { IdentityService } from './identity-service';
import type { BridgeInterface } from './bridge-interface';
import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline';
import { createLogger } from '../utils/logger';
import {
SendMessageRequestSchema,
SendMessageResponseSchema,
} from './proto/action';
// Delegated modules
import {
fetchFriendList as fetchFriendList_,
fetchGroupList as fetchGroupList_,
fetchGroupMemberList as fetchGroupMemberList_,
fetchUserProfile as fetchUserProfile_,
fetchGroupRequests as fetchGroupRequests_,
fetchDownloadRKeys as fetchDownloadRKeys_,
} from './bridge-contacts';
import type { WebHonorType } from './web/group-honor';
import {
muteGroupMember as muteGroupMember_,
muteGroupAll as muteGroupAll_,
setGroupAddOption as setGroupAddOption_,
setGroupSearch as setGroupSearch_,
setGroupAddRequest as setGroupAddRequest_,
kickGroupMember as kickGroupMember_,
kickGroupMembers as kickGroupMembers_,
leaveGroup as leaveGroup_,
setGroupAdmin as setGroupAdmin_,
setGroupCard as setGroupCard_,
setGroupName as setGroupName_,
setGroupSpecialTitle as setGroupSpecialTitle_,
setGroupRemark as setGroupRemark_,
getGroupAtAllRemain as getGroupAtAllRemain_,
} from './actions/group-admin';
import {
uploadGroupFile as uploadGroupFile_,
uploadPrivateFile as uploadPrivateFile_,
fetchGroupFiles as fetchGroupFiles_,
fetchGroupFileUrl as fetchGroupFileUrl_,
fetchPrivateFileUrl as fetchPrivateFileUrl_,
fetchGroupPttUrlByNode as fetchGroupPttUrlByNode_,
fetchPrivatePttUrlByNode as fetchPrivatePttUrlByNode_,
fetchGroupVideoUrlByNode as fetchGroupVideoUrlByNode_,
fetchPrivateVideoUrlByNode as fetchPrivateVideoUrlByNode_,
deleteGroupFile as deleteGroupFile_,
moveGroupFile as moveGroupFile_,
createGroupFileFolder as createGroupFileFolder_,
deleteGroupFileFolder as deleteGroupFileFolder_,
renameGroupFileFolder as renameGroupFileFolder_,
fetchGroupFileCount as fetchGroupFileCount_,
} from './actions/group-file';
import {
recallGroupMessage as recallGroupMessage_,
recallPrivateMessage as recallPrivateMessage_,
markPrivateMessageRead as markGroupMsgAsRead_,
markGroupMessageRead as markPrivateMsgAsRead_,
setGroupEssence as setGroupEssence_,
} from './actions/group-message';
import {
sendPoke as sendPoke_,
sendLike as sendLike_,
setGroupReaction as setGroupReaction_,
getEmojiLikes as getEmojiLikes_,
} from './actions/interaction';
import {
uploadForwardNodes as uploadForwardNodes_,
fetchForwardNodes as fetchForwardNodes_,
} from './actions/forward';
import {
setFriendAddRequest as setFriendAddRequest_,
deleteFriend as deleteFriend_,
setFriendRemark as setFriendRemark_,
} from './actions/friend';
import {
setOnlineStatus as setOnlineStatus_,
setDiyOnlineStatus as setDiyOnlineStatus_,
setProfile as setProfile_,
setSelfLongNick as setSelfLongNick_,
setInputStatus as setInputStatus_,
setAvatar as setAvatar_,
setGroupAvatar as setGroupAvatar_,
fetchCustomFace as fetchCustomFace_,
getProfileLike as getProfileLike_,
getUnidirectionalFriendList as getUnidirectionalFriendList_,
} from './actions/profile';
import {
translateEn2Zh as translateEn2Zh_,
getMiniAppArk as getMiniAppArk_,
clickInlineKeyboardButton as clickInlineKeyboardButton_,
sendGroupSign as sendGroupSign_,
} from './actions/misc';
import {
setGroupTodo as setGroupTodo_,
completeGroupTodo as completeGroupTodo_,
cancelGroupTodo as cancelGroupTodo_,
getStrangerStatus as getStrangerStatus_,
fetchAiVoiceList as fetchAiVoiceList_,
fetchAiVoice as fetchAiVoice_,
AiVoiceChatType,
type AiVoiceCategory,
type AiVoiceChatType as AiVoiceChatTypeT,
type StrangerStatus,
} from './actions/extras';
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
import {
getGroupHonorInfo as getGroupHonorInfo_,
forceFetchClientKey as forceFetchClientKey_,
getGroupEssence as getGroupEssence_,
getGroupEssenceAll as getGroupEssenceAll_,
sendGroupNotice as sendGroupNotice_,
getGroupNotice as getGroupNotice_,
deleteGroupNoticeByFid as deleteGroupNotice_,
getCookiesStr as getCookiesStr_,
getCsrfToken as getCsrfToken_,
getCredentials as getCredentials_,
} from './web-actions';
import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import { BridgeEventBus } from './event-bus';
export interface SendMessageReceipt {
messageId: number;
sequence: number;
clientSequence: number;
random: number;
timestamp: number;
}
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
storeId: number;
createTime: number;
type: number;
}
export interface ClientKeyInfo {
clientKey: string;
expireTime: string;
keyIndex: string
}
const log = createLogger('Bridge');
export class Bridge implements BridgeInterface {
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
readonly identity: IdentityService;
private pids_ = new Set<number>();
/**
* Per-kind event subscription. Replaces the legacy single-callback
* firehose: downstream consumers now register exactly the kinds they
* care about and the pipeline fans out in parallel.
*/
readonly events = new BridgeEventBus();
private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
// Throttle for fetchGroupMemberList(groupId): coalesces in-flight calls
// and serves a fresh result for `kMemberListTtlMs` to all callers.
// Without this, a busy OneBot client (e.g. MaiBot calling
// get_group_member_info(no_cache=true) per inbound message) would
// trigger one OIDB 0xfe7_3 per chat message per group; sustained rate
// (>1k/h) is detected by Tencent risk-control and gets the account
// banned for 7 days.
private memberListInflight_ = new Map<number, Promise<GroupMemberInfo[]>>();
private memberListLastFetch_ = new Map<number, { at: number; data: GroupMemberInfo[] }>();
// Sequence and random generators for outgoing messages
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
constructor(identity: IdentityService) {
this.identity = identity;
this.identity.setFetcher({
fetchProfile: (uin) => this.fetchUserProfile(uin),
fetchGroupMemberList: (gid) => this.fetchGroupMemberList(gid),
});
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
});
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
}
dispose(): void {
this.identity.close();
this.events.clear();
}
setPacketClient(client: PacketSender): void {
this.packetClient_ = client;
}
registerCmd(cmd: string, parser: CmdParser): void {
this.pipeline.registerCmd(cmd, parser);
}
handlesCmd(cmd: string): boolean {
return this.pipeline.handlesCmd(cmd);
}
// --- PID management ---
attachPid(pid: number): void {
this.pids_.add(pid);
}
detachPid(pid: number): void {
this.pids_.delete(pid);
}
hasPid(pid: number): boolean { return this.pids_.has(pid); }
get empty(): boolean { return this.pids_.size === 0; }
get activePid(): number | null {
for (const pid of this.pids_) return pid;
return null;
}
// --- Packet dispatch ---
onPacket(pkt: PacketInfo): void {
this.pipeline.process(pkt);
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.identity.findGroup(groupId)) return false;
await this.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
// --- Sequence / random generators ---
private nextClientSequence(): number {
return ++this.clientSeq_;
}
private nextMessageRandom(): number {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
// --- Send packet (raw) ---
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.packetClient_) {
return {
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'no packet sender attached', responseData: null,
};
}
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
}
// --- Send message (high-level) ---
async sendGroupMessage(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
const protoElems = await buildSendElems(elements, { bridge: this, groupId });
const random = this.nextMessageRandom();
const request = protoEncode({
routingHead: {
grp: { groupCode: BigInt(groupId) },
} as any,
contentHead: {
type: 1,
} as any,
messageBody: {
richText: {
elems: protoElems,
},
} as any,
clientSequence: 0,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
multiSendSeq: 0,
}, SendMessageRequestSchema);
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`);
}
const response = protoDecode(result.responseData, SendMessageResponseSchema);
if (!response) {
throw new Error('failed to decode SendMessageResponse');
}
if (response.result !== undefined && response.result !== 0) {
throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.groupSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return {
messageId,
sequence: seq,
clientSequence: 0,
random,
timestamp,
};
}
async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
// Resolve UID for media upload and the final c2c routing head.
let userUid = '';
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
if (hasMedia) {
userUid = await this.resolveUserUid(userUin);
}
const protoElems = await buildSendElems(elements, { bridge: this, userUid });
const random = this.nextMessageRandom();
const clientSeq = this.nextClientSequence();
const request = protoEncode({
routingHead: {
c2c: {
uin: userUin,
...(userUid ? { uid: userUid } : {}),
},
} as any,
contentHead: {
type: 1,
subType: 0,
c2cCmd: 11,
} as any,
messageBody: {
richText: {
elems: protoElems,
},
} as any,
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: {
msgFlag: Math.floor(Date.now() / 1000),
} as any,
multiSendSeq: 0,
}, SendMessageRequestSchema);
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`);
}
const response = protoDecode(result.responseData, SendMessageResponseSchema);
if (!response) {
throw new Error('failed to decode SendMessageResponse');
}
if (response.result !== undefined && response.result !== 0) {
throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.privateSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return {
messageId,
sequence: seq,
clientSequence: clientSeq,
random,
timestamp,
};
}
// --- Delegated: OIDB helpers ---
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
// --- Delegated: Contact / info queries ---
async fetchFriendList(): Promise<FriendInfo[]> { return fetchFriendList_(this); }
async fetchGroupList(): Promise<QQGroupInfo[]> { return fetchGroupList_(this); }
async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise<GroupMemberInfo[]> {
const kMemberListTtlMs = 60_000;
const now = Date.now();
const last = this.memberListLastFetch_.get(groupId);
if (!options.force && last && now - last.at < kMemberListTtlMs) {
return last.data;
}
const inflight = this.memberListInflight_.get(groupId);
if (inflight) return inflight;
const task = (async () => {
try {
const data = await fetchGroupMemberList_(this, groupId);
this.memberListLastFetch_.set(groupId, { at: Date.now(), data });
return data;
} finally {
this.memberListInflight_.delete(groupId);
}
})();
this.memberListInflight_.set(groupId, task);
return task;
}
async fetchUserProfile(uin: number): Promise<UserProfileInfo> { return fetchUserProfile_(this, uin); }
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> { return fetchGroupRequests_(this, filtered); }
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> { return fetchDownloadRKeys_(this); }
// --- Delegated: Admin / action methods ---
async muteGroupMember(groupId: number, userId: number, duration: number): Promise<void> { return muteGroupMember_(this, groupId, userId, duration); }
async muteGroupAll(groupId: number, enable: boolean): Promise<void> { return muteGroupAll_(this, groupId, enable); }
async setGroupAddOption(groupId: number, addType: number): Promise<void> { return setGroupAddOption_(this, groupId, addType); }
async setGroupSearch(groupId: number): Promise<void> { return setGroupSearch_(this, groupId); }
async kickGroupMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> { return kickGroupMember_(this, groupId, userId, reject, reason); }
async kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> { return kickGroupMembers_(this, groupId, userIds, reject); }
async leaveGroup(groupId: number): Promise<void> { return leaveGroup_(this, groupId); }
async setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise<void> { return setGroupAdmin_(this, groupId, userId, enable); }
async setGroupCard(groupId: number, userId: number, card: string): Promise<void> { return setGroupCard_(this, groupId, userId, card); }
async setGroupName(groupId: number, name: string): Promise<void> { return setGroupName_(this, groupId, name); }
async setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise<void> { return setGroupSpecialTitle_(this, groupId, userId, title); }
async setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise<void> { return setFriendAddRequest_(this, uidOrFlag, approve); }
async deleteFriend(userId: number, block = false): Promise<void> { return deleteFriend_(this, userId, block); }
async uploadGroupFile(groupId: number, file: string, name = '', folderId = '/', uploadFile = true): Promise<{ fileId: string | null }> {
return uploadGroupFile_(this, groupId, file, name, folderId, uploadFile);
}
async uploadPrivateFile(userId: number, file: string, name = '', uploadFile = true): Promise<{ fileId: string | null }> {
return uploadPrivateFile_(this, userId, file, name, uploadFile);
}
async fetchGroupFiles(groupId: number, folderId = '/'): Promise<GroupFilesResult> { return fetchGroupFiles_(this, groupId, folderId); }
async fetchGroupFileUrl(groupId: number, fileId: string, busId = 102): Promise<string> { return fetchGroupFileUrl_(this, groupId, fileId, busId); }
async fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string> { return fetchPrivateFileUrl_(this, userId, fileId, fileHash); }
async fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupPttUrlByNode_(this, groupId, node); }
async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivatePttUrlByNode_(this, node); }
async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupVideoUrlByNode_(this, groupId, node); }
async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivateVideoUrlByNode_(this, node); }
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId); }
async fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]> { return fetchForwardNodes_(this, resId); }
async deleteGroupFile(groupId: number, fileId: string): Promise<void> { return deleteGroupFile_(this, groupId, fileId); }
async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); }
async createGroupFileFolder(groupId: number, name: string, parentId = '/'): Promise<void> { return createGroupFileFolder_(this, groupId, name, parentId); }
async deleteGroupFileFolder(groupId: number, folderId: string): Promise<void> { return deleteGroupFileFolder_(this, groupId, folderId); }
async renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> { return renameGroupFileFolder_(this, groupId, folderId, newFolderName); }
async setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason = '', filtered = false): Promise<void> { return setGroupAddRequest_(this, groupId, sequence, eventType, approve, reason, filtered); }
async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> { return sendPoke_(this, isGroup, peerUin, targetUin); }
async sendLike(userId: number, count: number): Promise<void> { return sendLike_(this, userId, count); }
async setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> { return setGroupEssence_(this, groupId, sequence, random, enable); }
async setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> { return setGroupReaction_(this, groupId, sequence, code, isSet); }
async recallGroupMessage(groupId: number, sequence: number): Promise<void> { return recallGroupMessage_(this, groupId, sequence); }
async recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise<void> { return recallPrivateMessage_(this, userUin, clientSeq, msgSeq, random, timestamp); }
async markGroupMsgAsRead(groupId: number, sequence: number): Promise<void> { return markGroupMsgAsRead_(this, groupId, sequence); }
async markPrivateMsgAsRead(userId: number, sequence: number): Promise<void> { return markPrivateMsgAsRead_(this, userId, sequence); }
async setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
async setGroupRemark(groupId: number, remark: string): Promise<void> { return setGroupRemark_(this, groupId, remark); }
async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
return getGroupHonorInfo_(this, groupId, type);
}
async forceFetchClientKey(): Promise<ClientKeyInfo> { return forceFetchClientKey_(this)}
async getGroupEssence(groupId: number, pageStart: number = 0, pageLimit: number = 50): Promise<any> {
return getGroupEssence_(this, groupId, pageStart, pageLimit);
}
async getGroupEssenceAll(groupId: number): Promise<any> {
return getGroupEssenceAll_(this, groupId);
}
async sendGroupNotice(groupId: number, content: string, options?: any) {
return sendGroupNotice_(this, groupId, content, options);
}
async getGroupNotice(groupId: number) {
return getGroupNotice_(this, groupId);
}
async deleteGroupNotice(groupId: number, fid: string): Promise<boolean> {
return deleteGroupNotice_(this, groupId, fid);
}
async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); }
async getGroupAtAllRemain(groupId: number) {
return getGroupAtAllRemain_(this, groupId);
}
// extend
async setOnlineStatus(status: number, extStatus: number = 0, batteryStatus: number = 100): Promise<void> {
return setOnlineStatus_(this, status, extStatus, batteryStatus);
}
async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void> {
return setDiyOnlineStatus_(this, faceId, wording, faceType);
}
async setProfile(nickname?: string, personalNote?: string): Promise<void> {
return setProfile_(this, nickname, personalNote);
}
async getCookiesStr(domain: string): Promise<string> { return getCookiesStr_(this, domain); }
async getCsrfToken(): Promise<number> { return getCsrfToken_(this); }
async getCredentials(domain: string) { return getCredentials_(this, domain); }
async getProfileLike(userId?: number, start?: number, limit?: number) {
return getProfileLike_(this, userId, start, limit);
}
async getUnidirectionalFriendList() {
return getUnidirectionalFriendList_(this);
}
async setSelfLongNick(longNick: string) {
return setSelfLongNick_(this, longNick);
}
async setInputStatus(userId: number, eventType: number) {
return setInputStatus_(this, userId, eventType);
}
async translateEn2Zh(words: string[]) {
return translateEn2Zh_(this, words);
}
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string) {
return getMiniAppArk_(this, type, title, desc, picUrl, jumpUrl);
}
async clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number) {
return clickInlineKeyboardButton_(this, groupId, botAppid, buttonId, callbackData, msgSeq);
}
async sendGroupSign(groupId: number) {
return sendGroupSign_(this, groupId);
}
async setAvatar(source: string): Promise<void> {
return setAvatar_(this, source);
}
async setGroupAvatar(groupId: number, source: string): Promise<void> {
return setGroupAvatar_(this, groupId, source);
}
async fetchCustomFace(count?: number): Promise<string[]> {
return fetchCustomFace_(this, count);
}
async getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) {
return getEmojiLikes_(this, groupId, sequence, emojiId, emojiType, count, cookie);
}
// --- Tier-2 napcat-parity extras (group todo, stranger status, AI voice) ---
async setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return setGroupTodo_(this, groupId, BigInt(msgSeq));
}
async completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return completeGroupTodo_(this, groupId, BigInt(msgSeq));
}
async cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return cancelGroupTodo_(this, groupId, BigInt(msgSeq));
}
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
return getStrangerStatus_(this, uin);
}
async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatTypeT): Promise<AiVoiceCategory[]> {
return fetchAiVoiceList_(this, groupId, chatType);
}
async fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: AiVoiceChatTypeT) {
return fetchAiVoice_(this, groupId, voiceId, text, chatType);
}
}

View File

@@ -1,47 +1,39 @@
import type {
MarkdownData,
MentionExtraSend,
} from '@snowluma/proto-defs/action';
import type { Elem, GroupFileExtra } from '@snowluma/proto-defs/element';
import { protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { deflateSync } from 'zlib';
import type { BridgeContext } from './bridge-context';
// Element Builder — converts internal MessageElement[] into proto Elem objects
// for encoding with protoEncode(SendMessageRequestSchema).
// Port of src/bridge/src/bridge_messages.cpp build_send_elems()
import type { Bridge } from './bridge';
import type { MessageElement } from './events';
import type { ProtoDecoded } from '../protobuf/decode';
import { protoEncode } from '../protobuf/decode';
import {
ElemSchema,
} from './proto/element';
import {
MentionExtraSendSchema,
MarkdownDataSchema,
} from './proto/action';
import { uploadImageMsgInfo } from './highway/image-upload';
import { hexToBytes } from './highway/pipeline';
import { uploadPttMsgInfo } from './highway/ptt-upload';
import { uploadVideoMsgInfo } from './highway/video-upload';
type ProtoElem = Partial<Elem>;
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
export interface SendContext {
bridge: BridgeContext;
bridge: Bridge;
groupId?: number;
userUid?: string;
/**
* Set by the forward-message upload path. When `true`, file segments
* are encoded as receive-side wire shapes (group → `transElem(24)`,
* c2c → caller writes `body.msgContent` separately) instead of being
* dropped. The QQ-NT server rejects outgoing PbSendMsg with
* `transElem(24)` (result=79), but the long-msg upload service does
* NOT — it stores the gzipped protobuf verbatim, so the receiver
* can walk it back through the regular decoder. Mirrors NapCat's
* `PacketMsgFileElement.buildElement` + `buildContent` split (see
* `dev/napcatQQ/.../packet/message/element.ts:530-610`).
*/
forwardFake?: boolean;
}
function makeTextElem(text: string): ProtoElem {
return {
text: { str: text },
text: { str: text } as any,
};
}
function makeFaceElem(faceId: number): ProtoElem {
return {
face: { index: faceId },
face: { index: faceId } as any,
};
}
@@ -59,12 +51,12 @@ function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem
const mentionAll = element.uid === 'all' || element.targetUin === 0;
const targetUin = element.targetUin ?? 0;
const extra = protobuf_encode<MentionExtraSend>({
const extra = protoEncode({
type: mentionAll ? 1 : 2,
uin: mentionAll ? 0 : targetUin,
field5: 0,
uid: mentionAll ? 'all' : (element.uid ?? ''),
});
}, MentionExtraSendSchema);
// Prefer an explicit display string from the caller; otherwise look the
// target up in the roster so QQ renders `@昵称` instead of `@QQ号`.
@@ -83,17 +75,17 @@ function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem
text: {
str,
pbReserve: extra,
},
} as any,
};
}
function makeReplyElem(element: MessageElement): ProtoElem {
const seq = element.replySeq! & 0xFFFFFFFF;
const srcMsg: NonNullable<Elem['srcMsg']> = {
const srcMsg: any = {
origSeqs: [seq],
};
// Add additional fields if available for better reply display
if (element.replySenderUin) {
srcMsg.senderUin = BigInt(element.replySenderUin);
@@ -101,7 +93,7 @@ function makeReplyElem(element: MessageElement): ProtoElem {
if (element.replyTime) {
srcMsg.time = element.replyTime;
}
return { srcMsg };
}
@@ -116,7 +108,7 @@ function makeJsonElem(element: MessageElement): ProtoElem {
richMsg: {
serviceId: 1,
template1: payload,
},
} as any,
};
}
@@ -131,22 +123,30 @@ function makeXmlElem(element: MessageElement): ProtoElem {
richMsg: {
serviceId: element.subType === 0 ? 35 : (element.subType ?? 35),
template1: payload,
},
} as any,
};
}
function makeMarkdownElem(element: MessageElement): ProtoElem {
const data = protobuf_encode<MarkdownData>({ content: element.text ?? '' });
const data = protoEncode({ content: element.text ?? '' }, MarkdownDataSchema);
return {
commonElem: {
serviceType: 45,
pbElem: data,
businessType: 1,
},
} as any,
};
}
function escapeXml(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
function makeForwardElem(element: MessageElement): ProtoElem {
const resId = (element.resId ?? '').trim();
@@ -154,12 +154,10 @@ function makeForwardElem(element: MessageElement): ProtoElem {
throw new Error('forward resId is required');
}
// `uniseq` MUST round-trip between the preview JSON and the outer
// upload's piggyback `actionCommand` for nested forwards to resolve
// without an extra server hit. Generate one fresh if absent (flat
// forwards don't piggyback anyway, so the value is cosmetic there).
const uniseq = (element.forwardUuid ?? '').trim() || randomUUID();
// Multi-msg preview bubble — modelled on the go-cqhttp / NapCat XML.
// `source` becomes the bold header (e.g. "群聊的聊天记录"), `news`
// entries become per-line previews ("nick: text"), `summary` is the
// grey footer ("查看 N 条转发消息"), `prompt` is the chat-list brief.
const source = element.forwardSource && element.forwardSource.length > 0
? element.forwardSource
: '聊天记录';
@@ -174,49 +172,36 @@ function makeForwardElem(element: MessageElement): ProtoElem {
? element.forwardTSum
: Math.max(news.length, 1);
// LightApp / `com.tencent.multimsg` is the modern wire shape both
// QQ-NT, Lagrange.Core, and NapCat emit and decode. The older
// `richMsg serviceID=35 m_resid=…` XML still renders on mobile QQ
// but it doesn't carry `uniseq`, so nested forwards lose the link
// between the inner preview and the piggybacked actions on the
// outer's LongMsgResult — cross-checked against
// `dev/Lagrange.Core/.../Message/Entity/MultiMsgEntity.cs:43-115`
// and `dev/NapCatQQ/.../helper/forward-msg-builder.ts:52-122`.
const lightApp = {
app: 'com.tencent.multimsg',
config: {
autosize: 1,
forward: 1,
round: 1,
type: 'normal',
width: 300,
},
desc: prompt,
extra: JSON.stringify({ filename: uniseq, tsum: tSum }),
meta: {
detail: {
news: news.map(n => ({ text: n.text ?? '' })),
resid: resId,
source,
summary,
uniseq,
},
},
prompt,
ver: '0.0.0.5',
view: 'contact',
};
const newsTitles = news
.map(n => `<title size="26" color="#777777">${escapeXml(n.text ?? '')}</title>`)
.join('');
const json = JSON.stringify(lightApp);
const deflated = deflateSync(Buffer.from(json, 'utf8'));
const payload = new Uint8Array(deflated.length + 1);
payload[0] = 0x01; // 0x01 prefix = deflated JSON (vs 0x00 = uncompressed XML)
payload.set(deflated, 1);
const resIdAttr = escapeXml(resId);
const xml =
`<?xml version="1.0" encoding="utf-8"?>` +
`<msg templateID="1" action="viewMultiMsg" serviceID="35"` +
` brief="${escapeXml(prompt)}"` +
` m_resid="${resIdAttr}" m_fileName="${resIdAttr}" actionData="${resIdAttr}"` +
` tSum="${tSum}" sourceMsgId="0" flag="3" adverSign="0" multiMsgFlag="0">` +
`<item layout="1">` +
`<title size="34" color="#000000">${escapeXml(source)}</title>` +
newsTitles +
`<hr hidden="false" style="0"/>` +
`<summary size="26" color="#808080">${escapeXml(summary)}</summary>` +
`</item>` +
`<source name="${escapeXml(source)}" icon="" action="" appid="-1"/>` +
`</msg>`;
const encodedXml = new TextEncoder().encode(xml);
const payload = new Uint8Array(encodedXml.length + 1);
payload[0] = 0x00;
payload.set(encodedXml, 1);
return {
lightApp: {
data: payload,
},
richMsg: {
serviceId: 35,
template1: payload,
} as any,
};
}
@@ -234,7 +219,7 @@ async function makeImageElem(ctx: SendContext, element: MessageElement): Promise
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 20 : 10,
},
} as any,
};
}
@@ -255,76 +240,7 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise<P
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 22 : 12,
},
};
}
/**
* Receive-side group file element shape — `transElem(elemType=24,
* elemValue: 0x01 | BE16(len) | GroupFileExtra)`.
*
* NOT used for outgoing PbSendMsg (the QQ-NT server rejects that with
* result=79); the group-file send-side flow goes through dedicated
* OIDB 0x6d9_4 via `bridge.apis.groupFile.publish`. This shape IS used
* inside the long-msg upload (forward / multi-msg) — the long-msg
* service stores the gzipped protobuf verbatim, and the receiver
* decodes file entities from `transElem(24)` (see
* `msg-push/rich-body-decoder.ts:169-187`).
*
* `ctx` is consulted to fill in size/name/md5/sha1 from the upload
* metadata cache when the caller only threaded the file_id through.
* Mirrors the c2c forward path in `apis/forward.ts::buildForwardPushBody`
* which already does this lookup — without it the receiver sees a
* "0 B" file with no name (OneBot11 `{type:'file', file_id}` segments
* typically omit the metadata since the upload action returned only
* the id).
*/
function makeGroupFileElem(element: MessageElement, ctx?: SendContext): ProtoElem {
if (!element.fileId) throw new Error('file element missing fileId');
const cached = ctx?.bridge.recallUploadedFile(element.fileId);
const fileSize = element.fileSize ?? cached?.fileSize ?? 0;
const fileName = element.fileName ?? cached?.fileName ?? '';
const md5 = element.md5Hex
? hexToBytes(element.md5Hex)
: (cached?.fileMd5 ?? new Uint8Array(0));
const sha1 = element.sha1Hex
? hexToBytes(element.sha1Hex)
: (cached?.fileSha1 ?? new Uint8Array(0));
// Outer field1 is hardcoded to 6 in NapCat's encoder
// (`packet/message/element.ts:589`). Inner GroupFileExtraInfo carries
// busId=102 + the file_id + name + size + sha1/md5 hashes.
const extraBytes = protobuf_encode<GroupFileExtra>({
field1: 6,
fileName,
inner: {
info: {
busId: 102,
fileId: element.fileId,
fileSize: BigInt(fileSize),
fileName,
fileSha: sha1,
extInfoString: '',
fileMd5: md5,
},
},
});
if (extraBytes.length > 0xFFFF) {
// The 16-bit length prefix caps the payload at 64 KiB; even the
// densest GroupFileExtra (fileId/name/two hashes) is well under.
throw new Error(`group file extra too large (${extraBytes.length} > 65535)`);
}
const elemValue = new Uint8Array(3 + extraBytes.length);
elemValue[0] = 0x01;
elemValue[1] = (extraBytes.length >> 8) & 0xff;
elemValue[2] = extraBytes.length & 0xff;
elemValue.set(extraBytes, 3);
return {
transElem: {
elemType: 24,
elemValue,
},
} as any,
};
}
@@ -345,7 +261,7 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 21 : 11,
},
} as any,
};
}
@@ -415,42 +331,6 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
}
break;
case 'file':
// Files split into two routes depending on whether this is a
// live send or a forward-message fake-send:
//
// 1. LIVE send (PbSendMsg / OIDB 0x6d9_4) — never carried on
// elems[]. The OneBot layer splits file segments off before
// calling buildSendElems:
// * c2c (private): split → `bridge.sendC2cFileMessage`
// (routingHead.trans0x211 + msgContent FileExtra).
// * group: split → `bridge.sendGroupFileMessage`
// (OIDB 0x6d9_4 publish).
// The QQ-NT server REJECTS outgoing PbSendMsg with a
// transElem(24) (result=79), so an element reaching here
// in live-send mode is a routing bug — drop with a warn.
//
// 2. FORWARD-FAKE upload (long-msg) — `ctx.forwardFake===true`.
// The long-msg service stores the gzipped protobuf verbatim
// and the receiver decodes file entities from transElem(24)
// + msgContent FileExtra. Mirror NapCat's split (see
// `dev/napcatQQ/.../packet/message/element.ts:530-610`):
// * group → emit transElem(24) via makeGroupFileElem
// * c2c → emit NOTHING here; the forward-builder pulls
// the file segment off and writes msgContent
// separately (because RichText.notOnlineFile +
// FileExtra both live outside elems[]).
if (ctx && ctx.forwardFake) {
if (ctx.groupId !== undefined) {
result.push(makeGroupFileElem(elem, ctx));
}
// c2c forwardFake intentionally falls through — handled by
// the forward-builder at the msgContent level.
} else {
console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)');
}
break;
default:
console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`);
break;

View File

@@ -1,5 +1,16 @@
import { createLogger } from '@snowluma/common/logger';
// Typed, per-kind pub/sub for bridge-level events.
//
// Replaces the single-callback firehose where every consumer received every
// event variant and had to switch on `event.kind`. Now each downstream
// concern (OneBot dispatch, member cache refresh, etc.) registers exactly
// the kinds it cares about, much closer to NapCat's per-listener pattern.
//
// `emit` is fire-and-forget: subscribers can be sync or async; async
// rejections are surfaced via `Promise.allSettled` and reported through the
// optional `onError` hook so one buggy handler never starves the others.
import type { QQEventVariant } from './events';
import { createLogger } from '../utils/logger';
type EventKind = QQEventVariant['kind'];
type EventOf<K extends EventKind> = Extract<QQEventVariant, { kind: K }>;

View File

@@ -1,3 +1,6 @@
// Bridge event types and MessageElement.
// Port of src/bridge/include/bridge/events.h
export interface MessageElement {
type: string; // 'text'|'at'|'face'|'mface'|'image'|'video'|'record'|'file'|'json'|'xml'|'reply'|'poke'|'forward'
text?: string;
@@ -24,8 +27,8 @@ export interface MessageElement {
flash?: boolean;
resId?: string;
fileHash?: string;
// Preview-bubble metadata for the `forward` element. Drives the
// `com.tencent.multimsg` LightApp JSON the recipient renders before
// Preview-bubble metadata for the `forward` element. Drives the XML
// template (brief/title/news/summary/tSum) the recipient renders before
// they tap to expand. When unset, the element builder falls back to
// generic defaults so old call sites keep working.
forwardSource?: string;
@@ -33,14 +36,6 @@ export interface MessageElement {
forwardPrompt?: string;
forwardNews?: Array<{ text: string }>;
forwardTSum?: number;
/** `uniseq` baked into the preview's LightApp JSON. For a nested
* forward, the *outer* upload uses this same uuid as the
* `actionCommand` for the piggyback entry carrying the inner
* layer's msgBody — so receivers (Mobile QQ / QQ-NT clients) can
* resolve the inner layer from the outer's single fetch instead of
* hitting the server again. Defaults to a fresh UUID on send when
* omitted (i.e. for non-nested forwards). */
forwardUuid?: string;
// Server-side fingerprints carried from receive side so a forward can do a
// pure md5/sha1 fast-upload without re-downloading the original bytes.
// Set together with `noByteFallback: true` to make the upload modules throw
@@ -88,18 +83,6 @@ export interface ForwardNodePayload {
groupId?: number;
senderCard?: string;
messageType?: 'group' | 'private';
// When set, this node's `content` is a nested forward chain. The
// upload pipeline (see `actions/forward.ts::uploadForwardNodes`)
// recursively uploads the inner chain and replaces this node's
// `elements` with an ARK preview element pointing at the inner
// res_id. We also piggyback the inner chain's msgBody onto the
// outer long-msg upload as an extra `actionCommand` slot so the
// NapCat-compatible receiver can walk the whole tree from one
// server fetch without resolving each layer's res_id separately
// (modelled after `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`).
// Caller never sets this on top-level OneBot input — `parseForward
// Nodes` synthesises it when it detects a nested-node array.
innerForward?: ForwardNodePayload[];
}
export interface QQEvent {
@@ -247,22 +230,6 @@ export interface FriendAddEvent extends QQEvent {
userUin: number;
}
export interface GroupMsgEmojiLikeEvent extends QQEvent {
kind: 'group_msg_emoji_like';
groupId: number;
operatorUin: number;
operatorUid: string;
/** Sequence of the message that was reacted to (server-assigned msg_seq). */
msgSeq: number;
/** Emoji ID. QQ system faces are short numeric strings; market faces
* are alphanumeric. We keep the wire string verbatim. */
emojiId: string;
/** Multiplicity of the reaction event. Usually 1. */
count: number;
/** True when the reaction is being added; false when removed. */
isAdd: boolean;
}
export type QQEventVariant =
| FriendMessage
| GroupMessage
@@ -279,5 +246,4 @@ export type QQEventVariant =
| GroupPokeEvent
| GroupEssenceEvent
| GroupFileUploadEvent
| FriendAddEvent
| GroupMsgEmojiLikeEvent;
| FriendAddEvent;

View File

@@ -1,7 +1,14 @@
import crypto from 'crypto';
// FFmpeg native addon wrapper — port of NapCat's FFmpegAddonAdapter.
// No fallback: throws if the addon isn't available on this platform/arch.
//
// The addon is shipped under `native/ffmpeg/ffmpegAddon.<platform>.<arch>.node`
// to match the layout used by the upstream NapCat build so the binaries
// can be dropped in as-is.
import fs from 'fs';
import os from 'os';
import path from 'path';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));

View File

@@ -1,17 +1,18 @@
import type {
HighwayMsgInfoBody,
HttpConn0x6FF501Request,
HttpConn0x6FF501Response,
NTV2IPv4,
NTV2RichMediaHighwayExt,
NTV2UploadRespMsgInfo,
ReqDataHighwayHead,
RespDataHighwayHead,
} from '@snowluma/proto-defs/highway';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
// Highway HTTP client: session fetch and chunked binary upload.
// Port of src/bridge/src/highway_client.cpp
import net from 'net';
import type { BridgeContext } from '../bridge-context';
import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
import type { Bridge } from '../bridge';
import { protoEncode, protoDecode } from '../../protobuf/decode';
import {
HttpConn0x6FF501RequestSchema,
HttpConn0x6FF501ResponseSchema,
ReqDataHighwayHeadSchema,
RespDataHighwayHeadSchema,
NTV2RichMediaHighwayExtSchema,
HighwayMsgInfoBodySchema,
} from '../proto/highway';
import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from './utils';
const HIGHWAY_APP_ID = 1600001604;
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
@@ -30,21 +31,21 @@ function ipv4ToString(value: number): string {
return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`;
}
export async function fetchHighwaySession(bridge: BridgeContext): Promise<HighwaySession> {
const request = protobuf_encode<HttpConn0x6FF501Request>({
export async function fetchHighwaySession(bridge: Bridge): Promise<HighwaySession> {
const request = protoEncode({
httpConn: {
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
serviceTypes: [1, 5, 10, 21],
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
},
});
}, HttpConn0x6FF501RequestSchema);
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'HttpConn request failed');
}
const resp = protobuf_decode<HttpConn0x6FF501Response>(result.responseData);
const resp = protoDecode(result.responseData, HttpConn0x6FF501ResponseSchema);
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
throw new Error('HttpConn response missing sig_session');
@@ -77,7 +78,7 @@ function makeHighwayHead(
uin: string, commandId: number, fileSize: number, offset: number, length: number,
chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array,
): Uint8Array {
return protobuf_encode<ReqDataHighwayHead>({
return protoEncode({
msgBaseHead: {
version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0,
appId: HIGHWAY_APP_ID, dataFlag: 16, commandId,
@@ -89,13 +90,13 @@ function makeHighwayHead(
bytesReqExtendInfo: extend,
timestamp: 0n,
msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID },
});
}, ReqDataHighwayHeadSchema);
}
export function buildHighwayExtend(
uKey: string,
msgInfo: NTV2UploadRespMsgInfo,
ipv4s: NTV2IPv4[],
msgInfo: any,
ipv4s: any[],
sha1: Uint8Array | Uint8Array[],
fileIndex = 0,
): Uint8Array {
@@ -103,7 +104,7 @@ export function buildHighwayExtend(
if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body');
const selected = msgInfoBody[fileIndex] ?? msgInfoBody[0];
const networkIpv4s: NonNullable<NonNullable<NTV2RichMediaHighwayExt['network']>['ipv4s']> = [];
const networkIpv4s: any[] = [];
for (const ipv4 of ipv4s ?? []) {
const ip = ipv4.outIp ?? 0;
const port = ipv4.outPort ?? 0;
@@ -112,16 +113,16 @@ export function buildHighwayExtend(
}
}
return protobuf_encode<NTV2RichMediaHighwayExt>({
return protoEncode({
fileUuid: selected?.index?.fileUuid ?? '',
uKey,
network: { ipv4s: networkIpv4s },
msgInfoBody: msgInfoBody.map((b: HighwayMsgInfoBody) => ({
msgInfoBody: msgInfoBody.map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
})),
blockSize: HIGHWAY_BLOCK_SIZE,
hash: { fileSha1: Array.isArray(sha1) ? sha1 : [sha1] },
});
}, NTV2RichMediaHighwayExtSchema);
}
// --- TCP-based HTTP highway upload ---
@@ -221,7 +222,7 @@ async function httpPostFrame(
}
export async function uploadHighwayHttp(
bridge: BridgeContext, session: HighwaySession, commandId: number,
bridge: Bridge, session: HighwaySession, commandId: number,
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
): Promise<void> {
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
@@ -240,22 +241,9 @@ export async function uploadHighwayHttp(
const frame = packHighwayFrame(head, chunk);
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
const { head: respHead } = unpackHighwayFrame(responseBody);
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
const resp = protoDecode(respHead, RespDataHighwayHeadSchema);
if (resp?.errorCode && resp.errorCode !== 0) {
// Surface every diagnostic the highway response carries so
// user reports of `error_code=921` and friends include the
// server-side context (segHead.retCode, chunk size, file md5)
// — without these we can't tell apart a malformed-payload
// reject, a session-ticket mismatch, or a per-account rate-
// limit.
const segRetCode = resp.msgSegHead?.retCode ?? 0;
const fileMd5Hex = Buffer.from(fileMd5).toString('hex');
throw new Error(
`highway upload error_code=${resp.errorCode}` +
` (cmdId=${commandId} chunk=${chunkSize}/${bytes.length}` +
` offset=${offset} segRetCode=${segRetCode}` +
` fileMd5=${fileMd5Hex.slice(0, 16)}…)`,
);
throw new Error(`highway upload error_code=${resp.errorCode}`);
}
offset += chunkSize;
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);

View File

@@ -1,5 +1,11 @@
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
// Image upload: load the source, run NTV2 upload + (optional) Highway PUT,
// return the encoded MsgInfo for the outgoing commonElem.
//
// Shared OIDB envelope + response handling + Highway PUT live in
// pipeline.ts; this file just supplies the image-specific bits (format
// detection, picFormat, bizType, command ids).
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
import {
@@ -10,14 +16,6 @@ import {
} from './pipeline';
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
const moduleLog = createLogger('Highway.Image');
function loggerFor(bridge: BridgeContext) {
const raw = bridge.identity?.uin;
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
}
interface ImageData {
/** Empty when the caller is forwarding from cached fingerprints. */
bytes: Uint8Array;
@@ -46,14 +44,7 @@ function imageDataFromFingerprint(element: MessageElement): ImageData {
sha1Hex: element.sha1Hex ?? '',
fileName: element.fileName || `${element.md5Hex ?? 'image'}.jpg`,
fileSize: element.fileSize ?? 0,
// QQ ecosystem convention — mobile QQ + Lagrange.Core + NapCat all
// surface these exact Chinese strings as the chat-list bubble
// preview text. English fallbacks would render `[image]` /
// `[sticker]` in QQ users' chat lists instead of the expected
// `[图片]` / `[动画表情]`. Cross-checked against:
// dev/NapCatQQ/.../packet/message/element.ts:367-371
// dev/Lagrange.Core/.../Message/Entity/ImageEntity.cs:186-192
summary: element.summary || (element.subType === 1 ? '[动画表情]' : '[图片]'),
summary: element.summary || (element.subType === 0 ? '[image]' : '[sticker]'),
subType: element.subType ?? 0,
width: element.width ?? 0,
height: element.height ?? 0,
@@ -96,7 +87,7 @@ async function loadImageFromSource(source: string, fileName: string, subType: nu
sha1Hex: hashes.sha1Hex,
fileName: finalName,
fileSize: loaded.bytes.length,
summary: summary || (subType === 1 ? '[动画表情]' : '[图片]'),
summary: summary || (subType === 0 ? '[image]' : '[sticker]'),
subType,
width: fmt.width,
height: fmt.height,
@@ -110,18 +101,12 @@ async function loadImageFromSource(source: string, fileName: string, subType: nu
* commonElem.
*/
export async function uploadImageMsgInfo(
bridge: BridgeContext,
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const log = loggerFor(bridge);
const image = await loadImage(element);
log.debug('uploading %d bytes md5=%s... → %s %s',
image.fileSize,
image.md5Hex.slice(0, 8),
isGroup ? 'group' : 'c2c',
String(targetIdOrUid));
const uploads: MediaSubFileUpload[] = [{
source: 'top',

View File

@@ -1,21 +1,30 @@
import { createLogger } from '@snowluma/common/logger';
import type {
EncodableMediaMsgInfo,
HighwayMsgInfoBody,
NTV2ExtBizInfo,
NTV2UploadInfo,
NTV2UploadRespBody,
NTV2UploadRichMediaReq,
NTV2UploadRichMediaResp,
} from '@snowluma/proto-defs/highway';
import { OidbBase } from '@snowluma/proto-defs/oidb';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import crypto from 'crypto';
import type { BridgeContext } from '../bridge-context';
import { makeOidbEnvelope } from '../bridge-oidb';
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
// Shared NTV2 rich-media upload pipeline.
//
// Image, PTT, and video all follow the same three-step shape:
// 1. send a NTV2UploadRichMediaReq OIDB packet describing the file(s),
// 2. for any sub-file the server signals it wants (uKey present in the
// response), do a Highway HTTP PUT of the bytes,
// 3. encode the returned msgInfo into the bytes that go inside a
// commonElem on the outgoing message.
//
// The per-format files (image-upload, ptt-upload, video-upload) used to
// each implement steps 1 / 2 / 3 inline with subtle drift between them.
// This module pulls the envelope, response decoding, error handling, and
// the Highway PUT loop into one place, leaving each format file with
// only: how to load the file, how to fill the type-specific fileInfo +
// extBizInfo, and which command ids to use.
const moduleLog = createLogger('Highway');
import crypto from 'crypto';
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { makeOidbBaseSchema } from '../proto/oidb';
import {
EncodableMediaMsgInfoSchema,
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
} from '../proto/highway';
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
// ─────────────── public types ───────────────
@@ -54,7 +63,7 @@ export interface MediaSubFileUpload {
}
export interface NtV2UploadParams {
bridge: BridgeContext;
bridge: Bridge;
isGroup: boolean;
/** Group uin when isGroup, otherwise the recipient's uid string. */
targetIdOrUid: string | number;
@@ -68,11 +77,11 @@ export interface NtV2UploadParams {
/** `reqHead.scene.businessType` (1=image, 3=voice, 2=video). */
businessType: number;
/** `upload.uploadInfo` array. Each entry is `{ fileInfo, subFileType }`. */
uploadInfo: NTV2UploadInfo[];
uploadInfo: unknown[];
/** `upload.compatQmsgSceneType`. */
compatQmsgSceneType: number;
/** `upload.extBizInfo` — type-specific bytes/flags. */
extBizInfo: NTV2ExtBizInfo;
extBizInfo: unknown;
/** Sub-file Highway PUTs to perform after the OIDB response. */
uploads: MediaSubFileUpload[];
/** Used in error messages. Defaults to 'media'. */
@@ -111,18 +120,13 @@ export function hexToBytes(hex: string): Uint8Array {
* Sessions are cached across sub-file uploads — video does two PUTs but
* only fetches the Highway session once.
*/
export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2UploadRespBody> {
export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
const label = params.label ?? 'media';
const raw = bridge.identity?.uin;
const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
const log = Number.isFinite(uinNum) && uinNum > 0
? moduleLog.child({ uin: uinNum })
: moduleLog;
// Build the full body once. Pulling this in here means each format file
// only specifies the seven fields that actually vary.
const body: NTV2UploadRichMediaReq = {
const body: any = {
reqHead: {
common: { requestId: params.requestId, command: 100 },
scene: {
@@ -147,15 +151,18 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
},
};
const env = makeOidbEnvelope<NTV2UploadRichMediaReq>(oidbCmd, 100, body, true);
const requestBytes = protobuf_encode<OidbBase<NTV2UploadRichMediaReq>>(env);
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const request = protoEncode({
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
}, baseSchema);
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || `${label} upload request failed`);
}
const resp = protobuf_decode<OidbBase<NTV2UploadRichMediaResp>>(result.responseData);
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
const resp: any = protoDecode(result.responseData, respBaseSchema);
if (!resp) throw new Error(`failed to decode ${label} upload response`);
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
@@ -177,7 +184,6 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
return session;
};
let didPut = false;
for (const sub of uploads) {
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
const uKey = target?.uKey ?? '';
@@ -190,24 +196,14 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
continue;
}
if (!target) continue;
const extend = buildHighwayExtend(
uKey,
upload.msgInfo,
target.ipv4s ?? [],
sub.sha1,
sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both
sub.subFileIndex ?? 0,
);
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source));
const t0 = Date.now();
await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend);
log.debug('%s PUT done in %dms', label, Date.now() - t0);
didPut = true;
}
if (!didPut) {
log.debug('%s fast-upload hit (server already had bytes)', label);
}
return upload;
@@ -224,16 +220,16 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
* pic alone unless the server populates it.
*/
export function finalizeMediaMsgInfo(
upload: NTV2UploadRespBody,
upload: any,
defaultPic?: { bizType: number; textSummary: string },
): Uint8Array {
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: HighwayMsgInfoBody) => ({
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
}));
const extBizInfo: NonNullable<EncodableMediaMsgInfo['extBizInfo']> = {};
const extBizInfo: any = {};
if (upload.msgInfo.extBizInfo?.pic) {
extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic };
if (defaultPic) {
@@ -249,5 +245,5 @@ export function finalizeMediaMsgInfo(
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
}
return protobuf_encode<EncodableMediaMsgInfo>({ msgInfoBody, extBizInfo });
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
}

View File

@@ -1,26 +1,28 @@
import crypto from 'crypto';
// Voice (PTT) upload: stage the audio bytes (convert to NT silk if
// necessary), run NTV2 upload + (optional) Highway PUT, return the
// encoded MsgInfo for the outgoing commonElem.
//
// Shared OIDB envelope + response handling + Highway PUT live in
// pipeline.ts; this file owns the silk transcoding, the temp-file
// cleanup hooks, and the PTT-specific OIDB fields.
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils';
import { defaultPttTempDir, encodeSilk } from './ffmpeg-addon';
import { createLogger } from '../../utils/logger';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils';
const moduleLog = createLogger('Highway.Ptt');
function loggerFor(bridge: BridgeContext) {
const raw = bridge.identity?.uin;
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
}
const log = createLogger('Ptt');
export const PRIVATE_PTT_CMD_ID = 1007;
export const GROUP_PTT_CMD_ID = 1008;
@@ -103,7 +105,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
const silk = await encodeSilk(inputPath, tempDir);
if (silk.converted) {
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
moduleLog.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
log.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
}
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
@@ -134,20 +136,13 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
* a `commonElem { serviceType: 48, businessType: 22 }`.
*/
export async function uploadPttMsgInfo(
bridge: BridgeContext,
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const log = loggerFor(bridge);
const tempDir = defaultPttTempDir();
const ptt = await loadPtt(element, tempDir);
log.debug('uploading %d bytes md5=%s... → %s %s duration=%ds',
ptt.fileSize,
ptt.md5Hex.slice(0, 8),
isGroup ? 'group' : 'c2c',
String(targetIdOrUid),
ptt.duration);
try {
const uploads: MediaSubFileUpload[] = [{
source: 'top',

View File

@@ -1,3 +1,6 @@
// Highway utilities: binary source loading, hashing, image format detection, frame packing.
// Port of src/bridge/src/highway_utils.h/.cpp
import { createHash } from 'crypto';
import fs from 'fs';
import path from 'path';
@@ -190,7 +193,7 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
// PNG
if (bytes.length >= 24 &&
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
width = readBE32(bytes, 16);
height = readBE32(bytes, 20);
return { format: 1001, width, height };
@@ -198,8 +201,8 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
// GIF
if (bytes.length >= 10 &&
bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 &&
(bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 &&
(bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
width = readLE16(bytes, 6);
height = readLE16(bytes, 8);
return { format: 2000, width, height };
@@ -214,8 +217,8 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
// WebP
if (bytes.length >= 30 &&
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x20) {
width = readLE16(bytes, 26);
height = readLE16(bytes, 28);
@@ -248,7 +251,7 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
// (DAC). The previous `(marker & 0xFC) === 0xC0` check accepted DHT
// and friends, then misread Huffman table bytes as image dimensions.
const isSof = marker >= 0xC0 && marker <= 0xCF
&& marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC;
&& marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC;
if (isSof && segLen >= 7 && offset + 9 <= bytes.length) {
height = readBE16(bytes, offset + 5);
width = readBE16(bytes, offset + 7);

View File

@@ -1,31 +1,35 @@
import crypto from 'crypto';
// Video upload: stage the source video and a thumbnail (extracted via
// ffmpeg if not supplied), run NTV2 upload + (optional) Highway PUTs for
// both files, return the encoded MsgInfo for the outgoing commonElem.
//
// Shared OIDB envelope + response handling + Highway PUT loop live in
// pipeline.ts; this file owns the ffmpeg thumb extraction, the 1 MB
// streaming sha1 used by main-video Highway uploads, and the
// video-specific OIDB fields (uploadInfo has TWO entries — main + thumb).
import fs from 'fs';
import os from 'os';
import path from 'path';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
import crypto from 'crypto';
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { getFFmpegAddon } from './ffmpeg-addon';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
import {
computeHashes,
detectImageFormat,
loadBinarySource,
resolveLocalFilePath,
} from './utils';
import { getFFmpegAddon } from './ffmpeg-addon';
import { createLogger } from '../../utils/logger';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
const moduleLog = createLogger('Highway.Video');
function loggerFor(bridge: BridgeContext) {
const raw = bridge.identity?.uin;
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
}
const log = createLogger('Video');
export const PRIVATE_VIDEO_CMD_ID = 1001;
export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002;
@@ -319,7 +323,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{
try {
thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes;
} catch (err) {
moduleLog.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
log.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
}
}
@@ -333,7 +337,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{
thumbBytes = new Uint8Array(info.image);
}
} catch (err) {
moduleLog.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
log.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
}
}
@@ -421,18 +425,12 @@ async function loadVideo(element: MessageElement): Promise<VideoPayload> {
* (with per-1MB-block sha1) and a thumb (read off `upload.subFileInfos[0]`).
*/
export async function uploadVideoMsgInfo(
bridge: BridgeContext,
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const log = loggerFor(bridge);
const video = await loadVideo(element);
log.debug('uploading %d bytes md5=%s... → %s %s',
video.fileSize,
video.md5Hex.slice(0, 8),
isGroup ? 'group' : 'c2c',
String(targetIdOrUid));
try {
const uploads: MediaSubFileUpload[] = [
{
@@ -470,24 +468,14 @@ export async function uploadVideoMsgInfo(
fileHash: video.md5Hex,
fileSha1: video.sha1Hex,
fileName: 'nya.mp4',
// NapCat sends type.videoFormat=0 and width/height/time=0
// for the main video sub-file (only the thumb carries
// dimensions). The QQ NT server treats non-zero values
// here as a schema mismatch on c2c sends.
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
// Width/height kept at 0 — NapCat does the same and the QQ-NT
// server has been observed to reject non-zero dimensions
// here on c2c sends with a schema-mismatch error. acidify
// *does* fill them (`payload.videoWidth/Height`) but we
// leave that alone until c2c regression coverage exists.
height: 0,
width: 0,
// `time` MUST be the real duration in seconds, otherwise
// every receiving client renders "00:00" on the video.
// NapCat ships `time: 0` because it sits on top of QQ-NT's
// IPC layer, which the desktop client patches up before
// the wire message goes out. We're a protocol-direct
// client (same position as acidify), so we own this field.
// acidify writes `payload.videoDuration` here for the same
// reason — verified against `RichMediaUpload.kt::
// buildVideoUploadInfoList` (2026-04 refactor).
time: video.duration,
time: 0,
original: 0,
},
subFileType: 0,

View File

@@ -1,16 +1,14 @@
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import { DatabaseSync } from 'node:sqlite';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type {
FriendInfo, GroupMemberInfo,
GroupRequestInfo,
QQGroupInfo,
UserProfileInfo,
FriendInfo, GroupMemberInfo, QQGroupInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import { createLogger } from '../utils/logger';
const moduleLogger = createLogger('Identity');
const log = createLogger('Identity');
/**
* Hooks Identity uses when its read methods miss every cache layer. Wired in
@@ -112,23 +110,11 @@ export class IdentityService {
// ─── Persistence + fetcher ───
private readonly db: DatabaseSync | null;
// Prepared-statement cache. Every `.prepare(sql)` call in this
// service re-parses the SQL — that's the SQLite anti-pattern
// RoadMap #5 is fixing. We memoize by the SQL string itself so the
// call sites stay readable (no need to enumerate 20+ named fields
// upfront); the Map lookup is O(1) hash + string-eq, which is
// negligible next to the SQL parse it replaces.
private readonly stmtCache_ = new Map<string, StatementSync>();
private inTransaction = false;
private fetcher: IdentityFetcher | null = null;
private readonly log: Logger;
constructor(uin: string, dbPath: string | null) {
this.uin_ = uin;
const uinNum = Number.parseInt(uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0
? moduleLogger.child({ uin: uinNum })
: moduleLogger;
if (!dbPath) {
this.db = null;
@@ -143,16 +129,6 @@ export class IdentityService {
this.loadSnapshot();
}
/** Cached `prepare(sql)`. First call per unique SQL parses; later
* calls reuse the same `Statement` object. See `stmtCache_`. */
private pstmt(sql: string): StatementSync {
let cached = this.stmtCache_.get(sql);
if (cached !== undefined) return cached;
cached = this.db!.prepare(sql);
this.stmtCache_.set(sql, cached);
return cached;
}
static openForUin(uin: string, dataRoot = 'data'): IdentityService {
return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db'));
}
@@ -257,7 +233,7 @@ export class IdentityService {
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.pstmt(
const row = this.db.prepare(
`SELECT uin FROM group_members
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
ORDER BY active DESC, updated_at DESC
@@ -267,7 +243,7 @@ export class IdentityService {
if (uin !== null) return uin;
}
const row = this.pstmt(
const row = this.db.prepare(
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
).get(normalized) as { uin: number | null } | undefined;
return normalizeUin(row?.uin);
@@ -286,7 +262,7 @@ export class IdentityService {
if (!this.db) return null;
if (groupId !== undefined) {
const row = this.pstmt(
const row = this.db.prepare(
`SELECT uid FROM group_members
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
ORDER BY active DESC, updated_at DESC
@@ -296,7 +272,7 @@ export class IdentityService {
if (uid) return uid;
}
const row = this.pstmt(
const row = this.db.prepare(
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
).get(normalized) as { uid: string | null } | undefined;
return normalizeUid(row?.uid) || null;
@@ -308,7 +284,7 @@ export class IdentityService {
this.friends_ = friends;
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
this.runWrite('friends', () => this.transaction(() => {
this.pstmt('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
this.db!.prepare('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
.run(nowSeconds());
for (const friend of friends) {
this.upsertUser({
@@ -326,7 +302,7 @@ export class IdentityService {
rememberGroups(groups: QQGroupInfo[]): void {
this.setGroupsInMemory(groups);
this.runWrite('groups', () => this.transaction(() => {
this.pstmt('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
.run(nowSeconds());
for (const group of groups) {
this.upsertGroup({
@@ -346,7 +322,7 @@ export class IdentityService {
for (const member of members) this.rememberUidUin(member.uid, member.uin);
this.runWrite('group members', () => this.transaction(() => {
this.upsertGroup({ groupId, memberCount: members.length });
this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?')
this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?')
.run(nowSeconds(), groupId);
for (const member of members) {
this.upsertGroupMember({
@@ -451,7 +427,7 @@ export class IdentityService {
const updatedAt = nowSeconds();
this.transaction(() => {
for (const row of rows) {
this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
.run(updatedAt, row.id);
}
});
@@ -560,7 +536,7 @@ export class IdentityService {
}
private loadSnapshot(): void {
const friendRows = this.pstmt(
const friendRows = this.db!.prepare(
`SELECT uid, uin, nickname, remark
FROM users
WHERE is_friend = 1 AND uin IS NOT NULL`,
@@ -573,7 +549,7 @@ export class IdentityService {
}));
for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin);
const groups = this.pstmt(
const groups = this.db!.prepare(
`SELECT group_id, group_name, remark, member_count, member_max
FROM groups
WHERE active = 1`,
@@ -598,7 +574,7 @@ export class IdentityService {
private hydrateActiveMembersForGroups(groupIds: number[]): void {
if (!this.db || groupIds.length === 0) return;
const select = this.pstmt(
const select = this.db.prepare(
`SELECT group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time
FROM group_members
@@ -645,9 +621,9 @@ export class IdentityService {
if (primary) {
for (const duplicate of rows.slice(1)) {
this.pstmt('DELETE FROM users WHERE id = ?').run(duplicate.id);
this.db.prepare('DELETE FROM users WHERE id = ?').run(duplicate.id);
}
this.pstmt(
this.db.prepare(
`UPDATE users
SET uid = ?, uin = ?, nickname = ?, remark = ?, is_friend = ?, source = ?, updated_at = ?
WHERE id = ?`,
@@ -664,7 +640,7 @@ export class IdentityService {
return;
}
this.pstmt(
this.db.prepare(
`INSERT INTO users (uid, uin, nickname, remark, is_friend, source, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
).run(
@@ -681,7 +657,7 @@ export class IdentityService {
private upsertGroup(input: GroupInput): void {
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
const existing = this.pstmt(
const existing = this.db.prepare(
'SELECT group_name, remark, member_count, member_max FROM groups WHERE group_id = ?',
).get(input.groupId) as {
group_name: string;
@@ -690,7 +666,7 @@ export class IdentityService {
member_max: number;
} | undefined;
this.pstmt(
this.db.prepare(
`INSERT INTO groups (group_id, group_name, remark, member_count, member_max, active, updated_at)
VALUES (?, ?, ?, ?, ?, 1, ?)
ON CONFLICT(group_id) DO UPDATE SET
@@ -744,9 +720,9 @@ export class IdentityService {
if (primary) {
for (const duplicate of rows.slice(1)) {
this.pstmt('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
this.db.prepare('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
}
this.pstmt(
this.db.prepare(
`UPDATE group_members
SET uid = ?, uin = ?, nickname = ?, card = ?, role = ?, level = ?, title = ?,
join_time = ?, last_sent_time = ?, shut_up_time = ?, active = ?, updated_at = ?
@@ -769,7 +745,7 @@ export class IdentityService {
return;
}
this.pstmt(
this.db.prepare(
`INSERT INTO group_members
(group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active, updated_at)
@@ -794,17 +770,17 @@ export class IdentityService {
private findUserRows(uid: string, uin: number | null): UserRow[] {
if (!this.db) return [];
if (uid && uin !== null) {
return this.pstmt(
return this.db.prepare(
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? OR uin = ? ORDER BY id',
).all(uid, uin) as unknown as UserRow[];
}
if (uid) {
return this.pstmt(
return this.db.prepare(
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? ORDER BY id',
).all(uid) as unknown as UserRow[];
}
if (uin !== null) {
return this.pstmt(
return this.db.prepare(
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uin = ? ORDER BY id',
).all(uin) as unknown as UserRow[];
}
@@ -814,7 +790,7 @@ export class IdentityService {
private findMemberRows(groupId: number, uid: string, uin: number | null): MemberRow[] {
if (!this.db) return [];
if (uid && uin !== null) {
return this.pstmt(
return this.db.prepare(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
FROM group_members
@@ -823,7 +799,7 @@ export class IdentityService {
).all(groupId, uid, uin) as unknown as MemberRow[];
}
if (uid) {
return this.pstmt(
return this.db.prepare(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
FROM group_members
@@ -832,7 +808,7 @@ export class IdentityService {
).all(groupId, uid) as unknown as MemberRow[];
}
if (uin !== null) {
return this.pstmt(
return this.db.prepare(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
FROM group_members
@@ -864,7 +840,7 @@ export class IdentityService {
try {
fn();
} catch (err) {
this.log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
}
}
}

View File

@@ -0,0 +1,122 @@
// BridgeManager — manages per-UIN Bridge sessions.
// onPacket() is the single entry point for parsed hook packets;
// HookManager wires it as the default packet sink for every HookSession.
// Port of src/bridge/include/bridge/manager.h + src/bridge/src/manager.cpp
import type { PacketInfo } from '../protocol/types';
import { Bridge } from './bridge';
import { IdentityService } from './identity-service';
import type { PacketSender } from '../protocol/packet-sender';
import { createLogger } from '../utils/logger';
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string) => void;
interface QQSession {
bridge: Bridge;
}
const log = createLogger('Bridge');
export class BridgeManager {
private sessions_ = new Map<string, QQSession>();
private pidToUin_ = new Map<number, string>();
private pidPacketClients_ = new Map<number, PacketSender>();
private onSessionStarted_: SessionStartedCallback | null = null;
private onSessionClosed_: SessionClosedCallback | null = null;
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
onPidDisconnected(pid: number): void {
this.pidPacketClients_.delete(pid);
const uin = this.pidToUin_.get(pid);
if (!uin) return;
this.pidToUin_.delete(pid);
const session = this.sessions_.get(uin);
if (!session) return;
session.bridge.detachPid(pid);
if (session.bridge.empty) {
this.sessions_.delete(uin);
log.debug('session closed: UIN=%s', uin);
if (this.onSessionClosed_) this.onSessionClosed_(uin);
session.bridge.dispose();
}
}
private static isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (!BridgeManager.isRealUin(uin)) return;
this.pidPacketClients_.set(pid, packetClient);
const { session, created } = this.ensureSession(uin);
session.bridge.attachPid(pid);
session.bridge.setPacketClient(packetClient);
this.pidToUin_.set(pid, uin);
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.bridge);
}
}
}
onPacket(pkt: PacketInfo): void {
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
const uin = pkt.uin;
// Ensure session exists
const { session, created } = this.ensureSession(uin);
// Attach PID if known
if (pkt.pid && this.pidPacketClients_.has(pkt.pid)) {
session.bridge.attachPid(pkt.pid);
this.pidToUin_.set(pkt.pid, uin);
const client = this.pidPacketClients_.get(pkt.pid);
if (client) session.bridge.setPacketClient(client);
}
// Notify session started on first real packet
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.bridge);
}
}
// Dispatch packet to bridge
session.bridge.onPacket(pkt);
}
private ensureSession(uin: string): { session: QQSession; created: boolean } {
let session = this.sessions_.get(uin);
if (session) return { session, created: false };
const bridge = new Bridge(IdentityService.openForUin(uin));
session = { bridge };
this.sessions_.set(uin, session);
// Each downstream consumer (e.g. OneBotInstance) subscribes to
// `bridge.events` directly via the per-kind bus — there is no longer a
// generic firehose to wire here.
return { session, created: true };
}
getSession(uin: string): QQSession | null {
return this.sessions_.get(uin) ?? null;
}
get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_;
}
}

View File

@@ -1,11 +1,18 @@
import { protobuf_decode } from '@snowluma/proton';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { IdentityService } from '../identity-service';
import type { ContentHead, MessageBody, PushMsg, ResponseHead } from '@snowluma/proto-defs/message';
// MsgPushContext — the decoded envelope fields every decoder may need.
// One unified shape: notice decoders pick from `content`, message decoders
// pick from `body` / `responseHead`. Decoders ignore fields they don't need.
export type PushMsgBody = MessageBody;
export type PushMsgResponseHead = ResponseHead;
export type PushMsgContentHead = ContentHead;
import { protoDecode } from '../../protobuf/decode';
import type { ProtoDecoded } from '../../protobuf/decode';
import {
PushMsgSchema, MessageBodySchema, ResponseHeadSchema, ContentHeadSchema,
} from '../proto/message';
import type { PacketInfo } from '../../protocol/types';
import type { IdentityService } from '../identity-service';
export type PushMsgBody = ProtoDecoded<typeof MessageBodySchema>;
export type PushMsgResponseHead = ProtoDecoded<typeof ResponseHeadSchema>;
export type PushMsgContentHead = ProtoDecoded<typeof ContentHeadSchema>;
export interface MsgPushHead {
readonly msgType: number;
@@ -29,12 +36,7 @@ export interface MsgPushContext {
export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPushContext | null {
if (pkt.body.length === 0) return null;
// `pkt.body` is already a `Uint8Array` (see `PacketInfo` in
// @snowluma/common/protocol-types). The legacy `Buffer.from(uint8)`
// wrap was a no-op copy — Buffer is a Uint8Array subclass and
// proton's decoder accepts the parent type directly. Dropping the
// wrap saves one allocation per incoming push packet.
const push = protobuf_decode<PushMsg>(pkt.body);
const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema);
if (!push?.message) return null;
const msg = push.message;

View File

@@ -0,0 +1,73 @@
// Handles Event0x210 wrapper (528). Internal switch on subType dispatches
// to FriendRequest (35) / FriendRecall (138) / FriendPoke (290).
import { protoDecode } from '../../../protobuf/decode';
import {
FriendRequestSchema, FriendRecallSchema, GeneralGrayTipInfoSchema,
} from '../../proto/notify';
import type {
FriendRequestEvent, FriendRecall, FriendPokeEvent, QQEventVariant,
} from '../../events';
import type { MsgPushDecoder } from '../registry';
import type { MsgPushContext } from '../context';
import { Event0x210SubType } from '../enums';
import {
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
} from '../helpers';
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx);
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
}
return [];
};
function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
const request = protoDecode(ctx.content, FriendRequestSchema);
if (!request?.info) return [];
const sourceUid = request.info.newSource || request.info.sourceUid || '';
const ev: FriendRequestEvent = {
kind: 'friend_request',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
fromUin: resolveUidToUin(ctx.identity, 0, sourceUid, ctx.fromUin),
fromUid: sourceUid,
message: request.info.message ?? '',
flag: sourceUid,
};
return [ev];
}
function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] {
const recall = protoDecode(ctx.content, FriendRecallSchema);
if (!recall?.info) return [];
const ev: FriendRecall = {
kind: 'friend_recall',
time: recall.info.time ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, recall.info.fromUid ?? '', ctx.fromUin),
msgSeq: recall.info.clientSequence ?? 0,
};
return [ev];
}
function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] {
const grayTip = protoDecode(ctx.content, GeneralGrayTipInfoSchema);
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: FriendPokeEvent = {
kind: 'friend_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(ctx.identity, 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}

View File

@@ -1,44 +1,34 @@
import { protobuf_decode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
// Handles Event0x2DC wrapper (732). Internal switch on subType dispatches
// to GroupMute (12) / GroupRecall (17) / GroupGreyTip (20) / GroupEssence (21).
import { protoDecode } from '../../../protobuf/decode';
import {
GroupMuteSchema, NotifyMessageBodySchema,
} from '../../proto/notify';
import type {
GroupEssenceEvent,
GroupMsgEmojiLikeEvent,
GroupMuteEvent,
GroupPokeEvent,
GroupRecallEvent,
GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent,
QQEventVariant,
} from '../../events';
import type {
GroupMute,
GroupReactNotify,
NotifyMessageBody,
} from '@snowluma/proto-defs/notify';
import type { MsgPushDecoder } from '../registry';
import type { MsgPushContext } from '../context';
import { Event0x2DCSubType } from '../enums';
import {
buildTemplateMap, findTemplateValue,
parseU64OrZero,
resolveUidToUin,
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
unwrapGroupNotifyPayload,
} from '../helpers';
import type { MsgPushDecoder } from '../registry';
const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x2DCSubType) {
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx);
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
}
unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType);
return [];
};
function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] {
const mute = protobuf_decode<GroupMute>(ctx.content);
const mute = protoDecode(ctx.content, GroupMuteSchema);
if (!mute?.data?.state) return [];
const duration = mute.data.state.duration ?? 0;
const ev: GroupMuteEvent = {
@@ -56,7 +46,7 @@ function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] {
function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protobuf_decode<NotifyMessageBody>(payload);
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
const recalled = notify.recall.recallMessages[0];
const ev: GroupRecallEvent = {
@@ -75,7 +65,7 @@ function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] {
function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protobuf_decode<NotifyMessageBody>(payload);
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
@@ -97,7 +87,7 @@ function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] {
function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protobuf_decode<NotifyMessageBody>(payload);
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.essenceMessage) return [];
const essence = notify.essenceMessage;
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
@@ -114,51 +104,3 @@ function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
};
return [ev];
}
// Magic prefix QQ prepends to the GroupReactNotify payload inside
// body.msgContent for Event0x2DC subType=16. Same value NapCat strips
// (see api/group.ts: `msgContent?.slice(7)`).
const GROUP_REACT_PREFIX_BYTES = 7;
// Discriminator on GroupReactNotify.field13 — same subType is reused
// for other notify variants, only 35 means "emoji react". Anything
// else falls through to MsgPush.Unknown for protocol-drift visibility.
const GROUP_REACT_DISCRIMINATOR = 35;
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
const notify = protobuf_decode<GroupReactNotify>(payload);
if (!notify) return [];
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
notify.field13 ?? 0, GROUP_REACT_DISCRIMINATOR);
return [];
}
const content = notify.groupReactionData?.data?.data?.groupReactionDataContent;
const target = notify.groupReactionData?.data?.data?.groupReactionTarget;
if (!content) return [];
const groupId = Number(notify.groupUin ?? 0n);
const operatorUid = content.operatorUid ?? '';
const emojiId = content.code ?? '';
const count = content.count ?? 1;
// type is QQ's add/remove discriminator: 1 = react added, 2 = react
// removed. Older payloads occasionally omit it; default to "add"
// since most clients can only generate add events.
const isAdd = (content.type ?? 1) === 1;
const msgSeq = Number(target?.seq ?? 0n);
const ev: GroupMsgEmojiLikeEvent = {
kind: 'group_msg_emoji_like',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, ctx.fromUin),
operatorUid,
msgSeq,
emojiId,
count,
isAdd,
};
return [ev];
}

View File

@@ -1,3 +1,9 @@
// Handles the four PkgTypes that produce a FriendMessage event:
// PrivateMessage (166), ForwardFakePrivateMessage (9),
// PrivateRecordMessage (208), PrivateFileMessage (529). The PkgType
// difference only affects which proto-level elements show up in the
// body — decodeRichBody handles all of them uniformly.
import type { FriendMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';

View File

@@ -1,11 +1,14 @@
import { protobuf_decode } from '@snowluma/proton';
// Handles GroupAdminChangedNotice (44). extraEnable / extraDisable
// distinguishes set vs. unset.
import { protoDecode } from '../../../protobuf/decode';
import { GroupAdminSchema } from '../../proto/notify';
import type { GroupAdminEvent } from '../../events';
import type { GroupAdmin } from '@snowluma/proto-defs/notify';
import { resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
import { resolveUidToUin } from '../helpers';
export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
const admin = protobuf_decode<GroupAdmin>(ctx.content);
const admin = protoDecode(ctx.content, GroupAdminSchema);
if (!admin?.body) return [];
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
if (!extra) return [];

View File

@@ -1,29 +1,24 @@
import { protobuf_decode } from '@snowluma/proton';
// Handles GroupRequestJoinNotice (84) + GroupRequestInvitationNotice (525)
// + GroupInviteNotice (87). All three produce GroupInviteEvent with
// different subType ('add' / 'invite') and flag prefixes.
import { protoDecode } from '../../../protobuf/decode';
import {
GroupJoinSchema, GroupInvitationSchema, GroupInviteSchema,
} from '../../proto/notify';
import type { GroupInviteEvent } from '../../events';
import type {
GroupInvitation, GroupInvite,
GroupJoin,
} from '@snowluma/proto-defs/notify';
import { resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
import { resolveUidToUin } from '../helpers';
export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
const join = protobuf_decode<GroupJoin>(ctx.content);
const join = protoDecode(ctx.content, GroupJoinSchema);
if (!join) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: join.groupUin ?? 0,
// Strangers (not in our cache, not yet group members) won't resolve
// here — pass 0 instead of ctx.fromUin (which on a group-scoped push
// IS the group's own uin, so falling back to it produces a bogus
// `fromUin === groupId` collision). The packet-pipeline's pre-
// dispatch hook does an async UID-form FetchUserProfile lookup to
// fill in the uin + nickname before the event is emitted — same
// shape as Lagrange's flow at
// `dev/Lagrange.Core/.../MessagingLogic.cs:215-224`.
fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? '', 0),
fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? '', ctx.fromUin),
fromUid: join.targetUid ?? '',
subType: 'add',
message: '',
@@ -33,7 +28,7 @@ export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
};
export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
const invitation = protobuf_decode<GroupInvitation>(ctx.content);
const invitation = protoDecode(ctx.content, GroupInvitationSchema);
if (!invitation?.info?.inner) return [];
const inner = invitation.info.inner;
const ev: GroupInviteEvent = {
@@ -41,7 +36,7 @@ export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: inner.groupUin ?? 0,
fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? '', 0),
fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? '', ctx.fromUin),
fromUid: inner.invitorUid ?? '',
subType: 'invite',
message: '',
@@ -51,14 +46,14 @@ export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
};
export const decodeGroupInvite: MsgPushDecoder = (ctx) => {
const invite = protobuf_decode<GroupInvite>(ctx.content);
const invite = protoDecode(ctx.content, GroupInviteSchema);
if (!invite) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: invite.groupUin ?? 0,
fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? '', 0),
fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? '', ctx.fromUin),
fromUid: invite.invitorUid ?? '',
subType: 'invite',
message: '',

View File

@@ -1,11 +1,15 @@
import { protobuf_decode } from '@snowluma/proton';
// Handles GroupMemberIncreaseNotice (33) + GroupMemberDecreaseNotice (34).
// Both share GroupChangeSchema; the decreaseType field distinguishes kick vs
// voluntary leave (dt != 0 && dt != 130 means kicked).
import { protoDecode } from '../../../protobuf/decode';
import { GroupChangeSchema } from '../../proto/notify';
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify';
import { decodeOperatorUid, resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
import { decodeOperatorUid, resolveUidToUin } from '../helpers';
export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
const change = protobuf_decode<GroupChange>(ctx.content);
const change = protoDecode(ctx.content, GroupChangeSchema);
if (!change) return [];
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
@@ -24,7 +28,7 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
};
export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
const change = protobuf_decode<GroupChange>(ctx.content);
const change = protoDecode(ctx.content, GroupChangeSchema);
if (!change) return [];
const dt = change.decreaseType ?? 0;
const groupId = change.groupUin ?? 0;
@@ -43,29 +47,3 @@ export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
};
return [ev];
};
export const decodeGroupSelfJoined: MsgPushDecoder = (ctx) => {
const joined = protobuf_decode<SelfJoinInGroup>(ctx.content);
if (!joined) return [];
// groupUin is uint_64 on the wire (bigint). Real group IDs fit in
// uint32 (≤ 10 digits in practice), so Number() conversion is safe
// — saturate to 0 on the unlikely overflow rather than letting
// BigInt propagate downstream where consumers expect a number.
const groupUinBig = joined.groupUin ?? 0n;
const groupId = groupUinBig > 0n && groupUinBig <= 0x7FFFFFFFn ? Number(groupUinBig) : 0;
const operatorUid = joined.operatorUid ?? '';
// We're the one joining — surface the bot's own identity as userUin
// so the existing converter's `notice.group_increase` shape works
// unchanged.
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: ctx.selfUin,
userUid: ctx.identity.selfUid ?? '',
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
operatorUid,
};
return [ev];
};

View File

@@ -1,3 +1,6 @@
// Handles GroupMessage (82). Resolves senderCard / senderRole from the
// group member roster when present.
import type { GroupMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';

View File

@@ -1,3 +1,6 @@
// Handles TempMessage (141). Pulls senderNick from group hint first
// then falls back to friend roster.
import type { TempMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';

View File

@@ -0,0 +1,33 @@
// MsgPush PkgType taxonomy. The top-level msgType field in PushMsg.contentHead
// names a QQ-protocol-defined packet shape; Event0x210 / Event0x2DC are wrapper
// PkgTypes whose payload is further dispatched by subType.
export enum PkgType {
ForwardFakePrivateMessage = 9,
PrivateMessage = 166,
GroupMessage = 82,
TempMessage = 141,
Event0x210 = 528,
Event0x2DC = 732,
PrivateRecordMessage = 208,
PrivateFileMessage = 529,
GroupRequestInvitationNotice = 525,
GroupRequestJoinNotice = 84,
GroupInviteNotice = 87,
GroupAdminChangedNotice = 44,
GroupMemberIncreaseNotice = 33,
GroupMemberDecreaseNotice = 34,
}
export enum Event0x2DCSubType {
GroupMuteNotice = 12,
GroupRecallNotice = 17,
GroupGreyTipNotice = 20,
GroupEssenceNotice = 21,
}
export enum Event0x210SubType {
FriendRequestNotice = 35,
FriendRecallNotice = 138,
FriendPokeNotice = 290,
}

View File

@@ -1,7 +1,10 @@
import { protobuf_decode } from '@snowluma/proton';
// MsgPush decode helpers — pure functions shared across PkgType decoders
// and the rich-body decoder. No state, no I/O.
import { inflateSync } from 'zlib';
import { protoDecode } from '../../protobuf/decode';
import { OperatorInfoSchema } from '../proto/notify';
import type { IdentityService } from '../identity-service';
import type { OperatorInfo } from '@snowluma/proto-defs/notify';
export function makeImageUrl(origUrl: string): string {
if (!origUrl) return '';
@@ -49,12 +52,12 @@ export function resolveUidToUin(identity: IdentityService, groupId: number, uid:
export function decodeOperatorUid(bytes: Uint8Array): string {
if (!bytes || bytes.length === 0) return '';
const info = protobuf_decode<OperatorInfo>(bytes);
const info = protoDecode(bytes, OperatorInfoSchema);
if (info?.operatorField?.uid) return info.operatorField.uid;
return Buffer.from(bytes).toString('utf8');
}
export function buildTemplateMap(params: Array<{ name?: string; value?: string }>): Map<string, string> {
export function buildTemplateMap(params: Array<{name?: string; value?: string}>): Map<string, string> {
const map = new Map<string, string>();
for (const p of params) {
if (p.name !== undefined) map.set(p.name, p.value ?? '');

View File

@@ -1,29 +1,31 @@
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { QQEventVariant } from '../events';
// MsgPush entry point — assembles the PkgType registry and exposes
// `parseMsgPush(pkt, identity)` as the single CmdParser registered against
// `MSG_PUSH_CMD` on the IncomingPacketPipeline.
import type { PacketInfo } from '../../protocol/types';
import type { IdentityService } from '../identity-service';
import type { QQEventVariant } from '../events';
import { buildContext } from './context';
import { decodeEvent0x210 } from './decoders/event-0x210';
import { decodeEvent0x2DC } from './decoders/event-0x2dc';
import { decodeFriendMessage } from './decoders/friend-message';
import { MsgPushRegistry } from './registry';
import { PkgType } from './enums';
import {
decodeGroupMemberJoin, decodeGroupMemberLeave,
} from './decoders/group-member-change';
import { decodeGroupAdmin } from './decoders/group-admin';
import {
decodeGroupInvitation, decodeGroupInvite,
decodeGroupJoinRequest,
decodeGroupJoinRequest, decodeGroupInvitation, decodeGroupInvite,
} from './decoders/group-join-request';
import {
decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined,
} from './decoders/group-member-change';
import { decodeEvent0x210 } from './decoders/event-0x210';
import { decodeEvent0x2DC } from './decoders/event-0x2dc';
import { decodeGroupMessage } from './decoders/group-message';
import { decodeTempMessage } from './decoders/temp-message';
import { PkgType } from './enums';
import { MsgPushRegistry } from './registry';
import { decodeFriendMessage } from './decoders/friend-message';
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
const registry = new MsgPushRegistry();
registry.register(PkgType.GroupMemberIncreaseNotice, decodeGroupMemberJoin);
registry.register(PkgType.GroupMemberDecreaseNotice, decodeGroupMemberLeave);
registry.register(PkgType.GroupSelfJoinedNotice, decodeGroupSelfJoined);
registry.register(PkgType.GroupAdminChangedNotice, decodeGroupAdmin);
registry.register(PkgType.GroupRequestJoinNotice, decodeGroupJoinRequest);
registry.register(PkgType.GroupRequestInvitationNotice, decodeGroupInvitation);

View File

@@ -1,10 +1,14 @@
import { createLogger } from '@snowluma/common/logger';
// MsgPushRegistry — per-PkgType dispatch table. Each PkgType maps to a single
// decoder; double-registration is a programming error (throws at register time).
// Decoder errors are caught and logged with the PkgType so a single bad decoder
// can never silently take down sibling decoders sharing the cmd.
import { createLogger } from '../../utils/logger';
import type { QQEventVariant } from '../events';
import type { MsgPushContext } from './context';
import type { PkgType } from './enums';
const log = createLogger('MsgPush');
const unknownLog = createLogger('MsgPush.Unknown');
export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[];
@@ -23,13 +27,7 @@ export class MsgPushRegistry {
decode(ctx: MsgPushContext): QQEventVariant[] {
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
if (!decoder) {
// Unrecognized PkgType: either we don't care about this notify, or
// the QQ NT client added a new variant. Surface at debug so a
// protocol change can be spotted without spamming production logs.
unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType);
return [];
}
if (!decoder) return [];
try {
return decoder(ctx);
} catch (e) {

View File

@@ -1,21 +1,26 @@
import { protobuf_decode } from '@snowluma/proton';
import { toHexUpper } from '@snowluma/common/hex';
// Rich body decoder — turns the proto MessageBody (richText.elems +
// richText.ptt/notOnlineFile + msgContent) of a MsgPush message into
// the bridge-internal MessageElement[] sequence. Pure, no identity
// lookups, no I/O. The single small interface `decodeRichBody` hides
// ~400 lines of per-element-type decoding behind it.
import { protoDecode } from '../../protobuf/decode';
import type { ProtoDecoded } from '../../protobuf/decode';
import { ElemSchema } from '../proto/element';
import {
MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema,
MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema,
} from '../proto/element';
import {
MessageBodySchema, RichTextSchema, FileExtraSchema,
} from '../proto/message';
import type { MessageElement } from '../events';
import type {
Elem,
GroupFileExtra,
MentionExtra,
MsgInfo,
NotOnlineImage,
QFaceExtra,
QSmallFaceExtra,
} from '@snowluma/proto-defs/element';
import type { FileExtra, MessageBody, RichText } from '@snowluma/proto-defs/message';
import { toHexUpper } from '../../utils/hex';
import { decompressData, makeImageUrl } from './helpers';
type ElemDecoded = Elem;
type RichTextDecoded = RichText;
export type PushMsgBody = MessageBody;
type ElemDecoded = ProtoDecoded<typeof ElemSchema>;
type RichTextDecoded = ProtoDecoded<typeof RichTextSchema>;
export type PushMsgBody = ProtoDecoded<typeof MessageBodySchema>;
export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] {
const elements: MessageElement[] = [];
@@ -45,9 +50,9 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
// Text (with possible @ detection)
if (elem.text) {
const t = elem.text;
let mention: MentionExtra | null = null;
let mention: ProtoDecoded<typeof MentionExtraSchema> | null = null;
if (t.pbReserve && t.pbReserve.length > 0) {
mention = protobuf_decode<MentionExtra>(t.pbReserve);
mention = protoDecode(t.pbReserve, MentionExtraSchema);
}
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
const hasMention = mention && (mention.type === 1 || mention.type === 2);
@@ -97,11 +102,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
width: img.picWidth ?? 0,
height: img.picHeight ?? 0,
subType: img.pbRes?.subType ?? 0,
// `[图片]` / `[动画表情]` are the QQ-ecosystem default
// bubble texts; mobile QQ + Lagrange.Core + NapCat all
// expect these literal Chinese strings when the wire
// doesn't carry a per-image override.
summary: img.pbRes?.summary || (img.pbRes?.subType === 1 ? '[动画表情]' : '[图片]'),
summary: img.pbRes?.summary ?? '[image]',
md5Hex: toHexUpper(img.picMd5),
});
}
@@ -119,7 +120,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
width: img.width ?? 0,
height: img.height ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary || (img.pbRes?.subType === 1 ? '[动画表情]' : '[图片]'),
summary: img.pbRes?.summary ?? '[image]',
md5Hex: toHexUpper(img.md5),
});
}
@@ -171,7 +172,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
const val = te.elemValue;
const len = (val[1] << 8) | val[2];
if (val.length >= 3 + len) {
const extra = protobuf_decode<GroupFileExtra>(val.subarray(3, 3 + len));
const extra = protoDecode(val.subarray(3, 3 + len), GroupFileExtraSchema);
if (extra?.inner?.info) {
const info = extra.inner.info;
result.push({
@@ -217,33 +218,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
const la = elem.lightApp;
if (la.data && la.data.length > 0) {
const content = decompressData(la.data);
if (content) {
// `com.tencent.multimsg` is the multi-msg / forward preview
// LightApp (the modern replacement for the XML serviceID=35
// shape). Parse out resid + uniseq so downstream callers can
// both render a `[聊天记录]` placeholder and walk into the
// forward chain via `fetch(resId)` — the uniseq is what links
// the inner layer to its piggybacked actions on the outer's
// LongMsgResult. Other LightApp messages fall through to the
// generic `{type: 'json'}` path.
try {
const parsed = JSON.parse(content);
if (parsed && parsed.app === 'com.tencent.multimsg') {
const detail = parsed.meta?.detail ?? {};
const resId = typeof detail.resid === 'string' ? detail.resid : '';
const uniseq = typeof detail.uniseq === 'string' ? detail.uniseq : '';
if (resId) {
result.push({
type: 'forward',
resId,
forwardUuid: uniseq || undefined,
});
continue;
}
}
} catch { /* fall through to generic json element */ }
result.push({ type: 'json', text: content });
}
if (content) result.push({ type: 'json', text: content });
}
}
@@ -268,7 +243,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
if ((b & 0x80) === 0) break;
}
if (pos + length <= pb.length) {
const img = protobuf_decode<NotOnlineImage>(pb.subarray(pos, pos + length));
const img = protoDecode(pb.subarray(pos, pos + length), NotOnlineImageSchema);
if (img) {
const me: MessageElement = {
type: 'image', fileId: img.filePath ?? '',
@@ -285,7 +260,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
skipNext = true;
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
// NTQQ new protocol image/record/video
const info = protobuf_decode<MsgInfo>(ce.pbElem);
const info = protoDecode(ce.pbElem, MsgInfoSchema);
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
const body = info.msgInfoBody[0];
if (body.index?.info) {
@@ -315,8 +290,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
if (fi.type?.picFormat) me.picFormat = fi.type.picFormat;
if (info.extBizInfo?.pic) {
me.subType = info.extBizInfo.pic.bizType ?? 0;
me.summary = info.extBizInfo.pic.textSummary
|| (me.subType === 1 ? '[动画表情]' : '[图片]');
me.summary = info.extBizInfo.pic.textSummary || '[image]';
}
result.push(me);
} else if (bizType === 12 || bizType === 22) {
@@ -394,11 +368,11 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
}
} else if (svcType === 33 && ce.pbElem) {
// Small face
const extra = protobuf_decode<QSmallFaceExtra>(ce.pbElem);
const extra = protoDecode(ce.pbElem, QSmallFaceExtraSchema);
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
} else if (svcType === 37 && ce.pbElem) {
// Big face
const extra = protobuf_decode<QFaceExtra>(ce.pbElem);
const extra = protoDecode(ce.pbElem, QFaceExtraSchema);
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
skipNext = true;
}
@@ -460,24 +434,14 @@ function extractRichtextExtras(
}
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
// `MessageBody.msgContent` is where the QQ-NT server actually puts
// c2c file metadata — serialised `FileExtra { file: NotOnlineFile }`
// bytes. The previous schema (`FileExtraInfoSchema` with fileSize=1/
// fileName=2/fileMd5=3/fileUuid=4/fileHash=5) didn't match the wire
// shape — every field landed at the wrong tag, so the four-field
// truthiness check below filtered out every real c2c file push as
// "incomplete metadata". After consolidating FileExtra to wrap
// `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`),
// this reads the right tags.
const extra = protobuf_decode<FileExtra>(msgContent);
const extra = protoDecode(msgContent, FileExtraSchema);
if (!extra?.file) return;
const f = extra.file;
if (!f.fileUuid) return;
elements.push({
type: 'file',
fileId: f.fileUuid,
fileName: f.fileName ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash ?? '',
});
if (f.fileSize !== undefined && f.fileName && f.fileMd5 && f.fileUuid && f.fileHash) {
elements.push({
type: 'file', fileName: f.fileName, fileId: f.fileUuid,
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash,
});
}
}

View File

@@ -0,0 +1,275 @@
// Incoming packet pipeline — the chain that turns a single PacketInfo
// arriving from the hook layer into a stream of QQEventVariant
// emissions on the typed event bus. Replaces the inline orchestration
// that previously lived on Bridge.onPacket / triggerMemberCacheRefresh /
// rememberEventIdentity / dispatchAfterIdentityRefresh / etc.
//
// Stage chain per parser output:
// parse → enrich identity (sync, or async refresh)
// → side-effects (remember UID/UIN + schedule roster refresh)
// → log
// → emit on bus
//
// The pipeline owns its cmd handler map and its per-group coalesce table
// for background member-list refreshes. It does NOT own protocol calls
// — `refreshMemberCache` is injected by Bridge because it ultimately
// dispatches OIDB packets through Bridge.fetchGroupList /
// Bridge.fetchGroupMemberList.
import type { PacketInfo } from '../protocol/types';
import type { QQEventVariant } from './events';
import type { IdentityService } from './identity-service';
import type { BridgeEventBus } from './event-bus';
import { createLogger } from '../utils/logger';
const log = createLogger('Bridge');
const eventLog = createLogger('Event');
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
export type CmdParser = (pkt: PacketInfo, identity: IdentityService) => QQEventVariant[];
export interface PacketPipelineDeps {
identity: IdentityService;
events: BridgeEventBus;
/**
* Refresh group + member roster as a side-effect. Resolves with
* whether any refresh actually ran (false when the group is unknown
* and `refreshGroupList` was false).
*/
refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean>;
}
export class IncomingPacketPipeline {
private cmdHandlers_ = new Map<string, CmdParser[]>();
private memberRefreshTasks_ = new Map<number, Promise<void>>();
constructor(private readonly deps: PacketPipelineDeps) {}
registerCmd(cmd: string, parser: CmdParser): void {
const arr = this.cmdHandlers_.get(cmd) ?? [];
arr.push(parser);
this.cmdHandlers_.set(cmd, arr);
}
handlesCmd(cmd: string): boolean {
return this.cmdHandlers_.has(cmd);
}
process(pkt: PacketInfo): void {
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) return;
for (const handler of handlers) {
try {
const events = handler(pkt, this.deps.identity);
for (const event of events) {
if (this.needsPreDispatchIdentityRefresh(event)) {
void this.dispatchAfterIdentityRefresh(event);
} else {
this.handleSideEffects(event);
printEvent(event);
this.emit(event);
}
}
} catch (e) {
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
private emit(event: QQEventVariant): void {
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
// own onError hook so one bad listener never blocks the others.
void this.deps.events.emit(event);
}
private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_member_join' }> {
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
}
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
let refreshed = false;
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
}
this.handleSideEffects(event, refreshed);
printEvent(event);
this.emit(event);
}
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
this.resolveMemberIdentityFromCache(event);
if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false;
const refreshed = await this.deps.refreshMemberCache(
event.groupId,
!this.deps.identity.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
true,
);
this.resolveMemberIdentityFromCache(event);
return refreshed;
}
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
if (event.groupId <= 0) return;
if (event.userUin <= 0 && event.userUid) {
const uin = this.deps.identity.findUinByUid(event.userUid, event.groupId);
if (uin !== null) event.userUin = uin;
}
if (event.operatorUin <= 0 && event.operatorUid) {
const uin = this.deps.identity.findUinByUid(event.operatorUid, event.groupId);
if (uin !== null) event.operatorUin = uin;
}
}
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
const selfUin = Number(this.deps.identity.uin);
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.deps.identity.selfUid);
}
private handleSideEffects(event: QQEventVariant, alreadyRefreshed = false): void {
this.rememberEventIdentity(event);
if (alreadyRefreshed) return;
let groupId = 0;
let reason = '';
let refreshGroupList = false;
switch (event.kind) {
case 'group_member_join':
groupId = event.groupId;
reason = 'group_member_join';
refreshGroupList = this.isSelfMemberIdentity(event.userUin, event.userUid);
break;
case 'group_member_leave':
groupId = event.groupId;
reason = 'group_member_leave';
break;
case 'group_admin':
groupId = event.groupId;
reason = 'group_admin';
break;
default:
return;
}
if (groupId <= 0) return;
if (this.memberRefreshTasks_.has(groupId)) return;
if (event.kind === 'group_member_join' && !this.deps.identity.findGroup(groupId)) {
refreshGroupList = true;
}
const task = (async () => {
try {
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
groupId, reason, e instanceof Error ? e.message : String(e));
} finally {
this.memberRefreshTasks_.delete(groupId);
}
})();
this.memberRefreshTasks_.set(groupId, task);
}
private rememberEventIdentity(event: QQEventVariant): void {
switch (event.kind) {
case 'group_member_join':
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_member_leave':
this.deps.identity.markGroupMemberInactive(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_admin':
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uin: event.userUin,
});
break;
case 'friend_request':
this.deps.identity.rememberRequestIdentity({
uid: event.fromUid,
uin: event.fromUin,
source: 'friend_request',
});
break;
case 'group_invite':
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.fromUid,
uin: event.fromUin,
source: 'group_request',
});
break;
default:
break;
}
}
}
function formatEventUser(uin: number, uid?: string): string {
if (uin > 0) return String(uin);
return uid || '未知用户';
}
function printEvent(event: QQEventVariant): void {
switch (event.kind) {
case 'group_message':
case 'friend_message':
case 'temp_message':
// Message logging is handled by OneBot layer with message ID
break;
case 'group_recall':
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
break;
case 'friend_recall':
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
break;
case 'group_member_join':
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
break;
case 'group_member_leave':
eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId);
break;
case 'group_mute':
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
break;
case 'group_admin':
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
break;
case 'friend_poke':
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
break;
case 'group_poke':
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
break;
case 'friend_request':
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
break;
case 'group_invite':
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
break;
case 'group_essence':
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
break;
}
}

View File

@@ -0,0 +1,89 @@
// Proto schemas for outgoing message actions.
// Port of src/bridge/include/bridge/proto/action.h
import type { ProtoSchema } from '../../protobuf/decode';
import { ElemSchema } from './element';
// --- Routing ---
export const RoutingC2CSchema = {
uin: { field: 1, type: 'uint32' as const },
uid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const RoutingGroupSchema = {
groupCode: { field: 1, type: 'uint64' as const },
} satisfies ProtoSchema;
export const RoutingHeadSchema = {
c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema },
grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema },
} satisfies ProtoSchema;
// --- Content Head (for send) ---
export const SendContentHeadSchema = {
type: { field: 1, type: 'uint32' as const },
subType: { field: 2, type: 'uint32' as const },
c2cCmd: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- Message Control ---
export const MessageControlSchema = {
msgFlag: { field: 1, type: 'int32' as const },
} satisfies ProtoSchema;
// --- RichText (for send — only elems) ---
export const SendRichTextSchema = {
elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
} satisfies ProtoSchema;
// --- MessageBody (for send) ---
export const SendMessageBodySchema = {
richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema },
} satisfies ProtoSchema;
// --- SendMessageRequest ---
export const SendMessageRequestSchema = {
routingHead: { field: 1, type: 'message' as const, schema: RoutingHeadSchema },
contentHead: { field: 2, type: 'message' as const, schema: SendContentHeadSchema },
messageBody: { field: 3, type: 'message' as const, schema: SendMessageBodySchema },
clientSequence: { field: 4, type: 'uint32' as const },
random: { field: 5, type: 'uint32' as const },
syncCookie: { field: 6, type: 'bytes' as const },
via: { field: 8, type: 'uint32' as const },
dataStatist: { field: 9, type: 'uint32' as const },
ctrl: { field: 12, type: 'message' as const, schema: MessageControlSchema },
multiSendSeq: { field: 14, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- SendMessageResponse ---
export const SendMessageResponseSchema = {
result: { field: 1, type: 'int32' as const },
errMsg: { field: 2, type: 'string' as const },
timestamp1: { field: 3, type: 'uint32' as const },
field10: { field: 10, type: 'uint32' as const },
groupSequence: { field: 11, type: 'uint32' as const },
timestamp2: { field: 12, type: 'uint32' as const },
privateSequence: { field: 14, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- MentionExtra (for building @mention text element) ---
export const MentionExtraSendSchema = {
type: { field: 3, type: 'int32' as const },
uin: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'int32' as const },
uid: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
// --- MarkdownData ---
export const MarkdownDataSchema = {
content: { field: 1, type: 'string' as const },
} satisfies ProtoSchema;

View File

@@ -0,0 +1,418 @@
// Proto schemas for QQ message elements.
// Port of src/bridge/include/bridge/proto/element.h
import type { ProtoSchema } from '../../protobuf/decode';
// --- Nested / helper schemas ---
export const CustomFacePbReserveSchema = {
subType: { field: 1, type: 'int32' as const },
summary: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
export const NotOnlineImagePbReserve2Schema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'int32' as const },
field4: { field: 4, type: 'int32' as const },
field5: { field: 5, type: 'int32' as const },
field7: { field: 7, type: 'string' as const },
} satisfies ProtoSchema;
export const NotOnlineImagePbReserveSchema = {
subType: { field: 1, type: 'int32' as const },
field3: { field: 3, type: 'int32' as const },
field4: { field: 4, type: 'int32' as const },
summary: { field: 8, type: 'string' as const },
field10: { field: 10, type: 'int32' as const },
field20: { field: 20, type: 'message' as const, schema: NotOnlineImagePbReserve2Schema },
url: { field: 30, type: 'string' as const },
md5Str: { field: 31, type: 'string' as const },
} satisfies ProtoSchema;
// --- Core element schemas ---
export const TextElemSchema = {
str: { field: 1, type: 'string' as const },
link: { field: 2, type: 'string' as const },
attr6Buf: { field: 3, type: 'bytes' as const },
attr7Buf: { field: 4, type: 'bytes' as const },
buf: { field: 11, type: 'bytes' as const },
pbReserve: { field: 12, type: 'bytes' as const },
} satisfies ProtoSchema;
export const FaceElemSchema = {
index: { field: 1, type: 'int32' as const },
oldData: { field: 2, type: 'bytes' as const },
buf: { field: 11, type: 'bytes' as const },
} satisfies ProtoSchema;
export const OnlineImageSchema = {
guid: { field: 1, type: 'bytes' as const },
filePath: { field: 2, type: 'bytes' as const },
oldVerSendFile: { field: 3, type: 'bytes' as const },
} satisfies ProtoSchema;
export const NotOnlineImageSchema = {
filePath: { field: 1, type: 'string' as const },
fileLen: { field: 2, type: 'uint32' as const },
downloadPath: { field: 3, type: 'string' as const },
oldVerSendFile: { field: 4, type: 'bytes' as const },
imgType: { field: 5, type: 'int32' as const },
previewsImage: { field: 6, type: 'bytes' as const },
picMd5: { field: 7, type: 'bytes' as const },
picHeight: { field: 8, type: 'uint32' as const },
picWidth: { field: 9, type: 'uint32' as const },
resId: { field: 10, type: 'string' as const },
flag: { field: 11, type: 'bytes' as const },
thumbUrl: { field: 12, type: 'string' as const },
original: { field: 13, type: 'int32' as const },
bigUrl: { field: 14, type: 'string' as const },
origUrl: { field: 15, type: 'string' as const },
bizType: { field: 16, type: 'int32' as const },
result: { field: 17, type: 'int32' as const },
index: { field: 18, type: 'int32' as const },
opFaceBuf: { field: 19, type: 'bytes' as const },
oldPicMd5: { field: 20, type: 'bool' as const },
thumbWidth: { field: 21, type: 'int32' as const },
thumbHeight: { field: 22, type: 'int32' as const },
fileId: { field: 23, type: 'int32' as const },
showLen: { field: 24, type: 'uint32' as const },
downloadLen: { field: 25, type: 'uint32' as const },
x400Url: { field: 26, type: 'string' as const },
x400Width: { field: 27, type: 'int32' as const },
x400Height: { field: 28, type: 'int32' as const },
pbRes: { field: 29, type: 'message' as const, schema: NotOnlineImagePbReserveSchema },
} satisfies ProtoSchema;
export const TransElemSchema = {
elemType: { field: 1, type: 'int32' as const },
elemValue: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
export const MarketFaceSchema = {
faceName: { field: 1, type: 'string' as const },
itemType: { field: 2, type: 'uint32' as const },
faceInfo: { field: 3, type: 'uint32' as const },
faceId: { field: 4, type: 'bytes' as const },
tabId: { field: 5, type: 'uint32' as const },
subType: { field: 6, type: 'uint32' as const },
key: { field: 7, type: 'bytes' as const },
param: { field: 8, type: 'bytes' as const },
mediaType: { field: 9, type: 'uint32' as const },
imageWidth: { field: 10, type: 'uint32' as const },
imageHeight: { field: 11, type: 'uint32' as const },
mobileParam: { field: 12, type: 'bytes' as const },
pbReserve: { field: 13, type: 'bytes' as const },
} satisfies ProtoSchema;
export const CustomFaceSchema = {
guid: { field: 1, type: 'bytes' as const },
filePath: { field: 2, type: 'string' as const },
shortcut: { field: 3, type: 'string' as const },
buffer: { field: 4, type: 'bytes' as const },
flag: { field: 5, type: 'bytes' as const },
oldData: { field: 6, type: 'bytes' as const },
fileId: { field: 7, type: 'uint32' as const },
serverIp: { field: 8, type: 'int32' as const },
serverPort: { field: 9, type: 'int32' as const },
fileType: { field: 10, type: 'int32' as const },
signature: { field: 11, type: 'bytes' as const },
useful: { field: 12, type: 'int32' as const },
md5: { field: 13, type: 'bytes' as const },
thumbUrl: { field: 14, type: 'string' as const },
bigUrl: { field: 15, type: 'string' as const },
origUrl: { field: 16, type: 'string' as const },
bizType: { field: 17, type: 'int32' as const },
repeatIndex: { field: 18, type: 'int32' as const },
repeatImage: { field: 19, type: 'int32' as const },
imageType: { field: 20, type: 'int32' as const },
index: { field: 21, type: 'int32' as const },
width: { field: 22, type: 'int32' as const },
height: { field: 23, type: 'int32' as const },
source: { field: 24, type: 'int32' as const },
size: { field: 25, type: 'uint32' as const },
origin: { field: 26, type: 'int32' as const },
thumbWidth: { field: 27, type: 'int32' as const },
thumbHeight: { field: 28, type: 'int32' as const },
showLen: { field: 29, type: 'int32' as const },
downloadLen: { field: 30, type: 'int32' as const },
x400Url: { field: 31, type: 'string' as const },
x400Width: { field: 32, type: 'int32' as const },
x400Height: { field: 33, type: 'int32' as const },
pbRes: { field: 34, type: 'message' as const, schema: CustomFacePbReserveSchema },
} satisfies ProtoSchema;
export const RichMsgSchema = {
template1: { field: 1, type: 'bytes' as const },
serviceId: { field: 2, type: 'int32' as const },
msgResId: { field: 3, type: 'bytes' as const },
rand: { field: 4, type: 'int32' as const },
seq: { field: 5, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GroupFileElemSchema = {
filename: { field: 1, type: 'string' as const },
fileSize: { field: 2, type: 'uint64' as const },
fileId: { field: 3, type: 'string' as const },
batchId: { field: 4, type: 'string' as const },
fileKey: { field: 5, type: 'string' as const },
mark: { field: 6, type: 'bytes' as const },
sequence: { field: 7, type: 'uint64' as const },
batchItemId: { field: 8, type: 'bytes' as const },
feedMsgTime: { field: 9, type: 'int32' as const },
pbReserve: { field: 10, type: 'bytes' as const },
} satisfies ProtoSchema;
export const ExtraInfoSchema = {
nick: { field: 1, type: 'bytes' as const },
groupCard: { field: 2, type: 'bytes' as const },
level: { field: 3, type: 'int32' as const },
flags: { field: 4, type: 'int32' as const },
groupMask: { field: 5, type: 'int32' as const },
msgTailId: { field: 6, type: 'int32' as const },
senderTitle: { field: 7, type: 'bytes' as const },
apnsTips: { field: 8, type: 'bytes' as const },
uin: { field: 9, type: 'uint64' as const },
msgStateFlag: { field: 10, type: 'int32' as const },
apnsSoundType: { field: 11, type: 'int32' as const },
newGroupFlag: { field: 12, type: 'int32' as const },
} satisfies ProtoSchema;
export const VideoFileSchema = {
fileUuid: { field: 1, type: 'string' as const },
fileMd5: { field: 2, type: 'bytes' as const },
fileName: { field: 3, type: 'string' as const },
fileFormat: { field: 4, type: 'int32' as const },
fileTime: { field: 5, type: 'int32' as const },
fileSize: { field: 6, type: 'int32' as const },
thumbWidth: { field: 7, type: 'int32' as const },
thumbHeight: { field: 8, type: 'int32' as const },
thumbFileMd5: { field: 9, type: 'bytes' as const },
source: { field: 10, type: 'bytes' as const },
thumbFileSize:{ field: 11, type: 'int32' as const },
busiType: { field: 12, type: 'int32' as const },
fromChatType: { field: 13, type: 'int32' as const },
toChatType: { field: 14, type: 'int32' as const },
supportProgressive: { field: 15, type: 'bool' as const },
fileWidth: { field: 16, type: 'int32' as const },
fileHeight: { field: 17, type: 'int32' as const },
subBusiType: { field: 18, type: 'int32' as const },
videoAttr: { field: 19, type: 'int32' as const },
pbReserve: { field: 24, type: 'bytes' as const },
} satisfies ProtoSchema;
export const SrcMsgSchema = {
origSeqs: { field: 1, type: 'repeated_uint32' as const },
senderUin: { field: 2, type: 'uint64' as const },
time: { field: 3, type: 'int32' as const },
flag: { field: 4, type: 'int32' as const },
elemsRaw: { field: 5, type: 'repeated_bytes' as const },
type: { field: 6, type: 'int32' as const },
richMsg: { field: 7, type: 'bytes' as const },
pbReserve: { field: 8, type: 'bytes' as const },
sourceMsg: { field: 9, type: 'bytes' as const },
toUin: { field: 10, type: 'uint64' as const },
troopName: { field: 11, type: 'bytes' as const },
} satisfies ProtoSchema;
export const LightAppElemSchema = {
data: { field: 1, type: 'bytes' as const },
msgResid: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
export const CommonElemSchema = {
serviceType: { field: 1, type: 'int32' as const },
pbElem: { field: 2, type: 'bytes' as const },
businessType: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GeneralFlagsSchema = {
bubbleDiyTextId: { field: 1, type: 'int32' as const },
groupFlagNew: { field: 2, type: 'int32' as const },
uin: { field: 3, type: 'uint64' as const },
longTextFlag: { field: 6, type: 'int32' as const },
longTextResId: { field: 7, type: 'string' as const },
} satisfies ProtoSchema;
// --- Elem (union of all element types) ---
export const ElemSchema = {
text: { field: 1, type: 'message' as const, schema: TextElemSchema },
face: { field: 2, type: 'message' as const, schema: FaceElemSchema },
onlineImage: { field: 3, type: 'message' as const, schema: OnlineImageSchema },
notOnlineImage: { field: 4, type: 'message' as const, schema: NotOnlineImageSchema },
transElem: { field: 5, type: 'message' as const, schema: TransElemSchema },
marketFace: { field: 6, type: 'message' as const, schema: MarketFaceSchema },
customFace: { field: 8, type: 'message' as const, schema: CustomFaceSchema },
richMsg: { field: 12, type: 'message' as const, schema: RichMsgSchema },
groupFile: { field: 13, type: 'message' as const, schema: GroupFileElemSchema },
extraInfo: { field: 16, type: 'message' as const, schema: ExtraInfoSchema },
videoFile: { field: 19, type: 'message' as const, schema: VideoFileSchema },
generalFlags: { field: 37, type: 'message' as const, schema: GeneralFlagsSchema },
srcMsg: { field: 45, type: 'message' as const, schema: SrcMsgSchema },
lightApp: { field: 51, type: 'message' as const, schema: LightAppElemSchema },
commonElem: { field: 53, type: 'message' as const, schema: CommonElemSchema },
} satisfies ProtoSchema;
// --- Extra decode types (for CommonElem.pbElem sub-messages) ---
export const MentionExtraSchema = {
type: { field: 3, type: 'int32' as const },
uin: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'int32' as const },
uid: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
export const QFaceExtraSchema = {
packId: { field: 1, type: 'string' as const },
stickerId: { field: 2, type: 'string' as const },
qsid: { field: 3, type: 'int32' as const },
sourceType: { field: 4, type: 'int32' as const },
stickerType: { field: 5, type: 'int32' as const },
resultId: { field: 6, type: 'string' as const },
text: { field: 7, type: 'string' as const },
randomType: { field: 9, type: 'int32' as const },
} satisfies ProtoSchema;
export const QSmallFaceExtraSchema = {
faceId: { field: 1, type: 'uint32' as const },
preview: { field: 2, type: 'string' as const },
preview2: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
// --- NTQQ MsgInfo types (CommonElem service_type 48) ---
export const FileTypeSchema = {
type: { field: 1, type: 'uint32' as const },
picFormat: { field: 2, type: 'uint32' as const },
videoFormat: { field: 3, type: 'uint32' as const },
voiceFormat: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const FileInfoSchema = {
fileSize: { field: 1, type: 'uint32' as const },
fileHash: { field: 2, type: 'string' as const },
fileSha1: { field: 3, type: 'string' as const },
fileName: { field: 4, type: 'string' as const },
type: { field: 5, type: 'message' as const, schema: FileTypeSchema },
width: { field: 6, type: 'uint32' as const },
height: { field: 7, type: 'uint32' as const },
time: { field: 8, type: 'uint32' as const },
original: { field: 9, type: 'uint32' as const },
} satisfies ProtoSchema;
export const IndexNodeSchema = {
info: { field: 1, type: 'message' as const, schema: FileInfoSchema },
fileUuid: { field: 2, type: 'string' as const },
storeId: { field: 3, type: 'uint32' as const },
uploadTime: { field: 4, type: 'uint32' as const },
ttl: { field: 5, type: 'uint32' as const },
subType: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;
export const PicUrlExtInfoSchema = {
originalParameter: { field: 1, type: 'string' as const },
bigParameter: { field: 2, type: 'string' as const },
thumbParameter: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const PictureInfoSchema = {
urlPath: { field: 1, type: 'string' as const },
ext: { field: 2, type: 'message' as const, schema: PicUrlExtInfoSchema },
domain: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const PicExtDataSchema = {
subType: { field: 1, type: 'uint32' as const },
textSummary: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
export const PicExtBizInfoSchema = {
bizType: { field: 1, type: 'uint32' as const },
textSummary: { field: 2, type: 'string' as const },
bytesPbReserveC2c: { field: 11, type: 'bytes' as const },
extData: { field: 12, type: 'message' as const, schema: PicExtDataSchema },
fromScene: { field: 1001, type: 'uint32' as const },
toScene: { field: 1002, type: 'uint32' as const },
oldFileId: { field: 1003, type: 'uint32' as const },
} satisfies ProtoSchema;
export const VideoExtBizInfoSchema = {
fromScene: { field: 1, type: 'uint32' as const },
toScene: { field: 2, type: 'uint32' as const },
bytesPbReserve: { field: 3, type: 'bytes' as const },
} satisfies ProtoSchema;
export const PttExtBizInfoSchema = {
srcUin: { field: 1, type: 'uint64' as const },
pttScene: { field: 2, type: 'uint32' as const },
pttType: { field: 3, type: 'uint32' as const },
changeVoice: { field: 4, type: 'uint32' as const },
waveform: { field: 5, type: 'bytes' as const },
autoConvertText: { field: 6, type: 'uint32' as const },
bytesReserve: { field: 11, type: 'bytes' as const },
bytesPbReserve: { field: 12, type: 'bytes' as const },
bytesGeneralFlags: { field: 13, type: 'bytes' as const },
} satisfies ProtoSchema;
export const ExtBizInfoSchema = {
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
busiType: { field: 10, type: 'uint32' as const },
} satisfies ProtoSchema;
export const C2cSourceSchema = {
friendUid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const TroopSourceSchema = {
groupUin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const HashSumSchema = {
bytesPbReserveC2c: { field: 201, type: 'message' as const, schema: C2cSourceSchema },
troopSource: { field: 202, type: 'message' as const, schema: TroopSourceSchema },
} satisfies ProtoSchema;
export const MsgInfoBodySchema = {
index: { field: 1, type: 'message' as const, schema: IndexNodeSchema },
picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema },
fileExist: { field: 5, type: 'bool' as const },
hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema },
} satisfies ProtoSchema;
export const MsgInfoSchema = {
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: MsgInfoBodySchema },
extBizInfo: { field: 2, type: 'message' as const, schema: ExtBizInfoSchema },
} satisfies ProtoSchema;
// --- GroupFileExtra (TransElem type=24) ---
export const GroupFileInfoSchema = {
busId: { field: 1, type: 'uint32' as const },
fileId: { field: 2, type: 'string' as const },
fileSize: { field: 3, type: 'uint64' as const },
fileName: { field: 4, type: 'string' as const },
fileSha: { field: 5, type: 'bytes' as const },
extInfoString: { field: 6, type: 'string' as const },
fileMd5: { field: 7, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupFileExtraInnerSchema = {
info: { field: 2, type: 'message' as const, schema: GroupFileInfoSchema },
} satisfies ProtoSchema;
export const GroupFileExtraSchema = {
inner: { field: 7, type: 'message' as const, schema: GroupFileExtraInnerSchema },
} satisfies ProtoSchema;
// --- Preserve (for message receipt info) ---
export const PreserveSchema = {
messageId: { field: 3, type: 'uint64' as const },
senderUid: { field: 6, type: 'string' as const },
receiverUid: { field: 7, type: 'string' as const },
clientSequence: { field: 8, type: 'uint32' as const },
} satisfies ProtoSchema;

View File

@@ -0,0 +1,336 @@
// Proto schemas for highway upload protocol.
// Port of src/bridge/include/bridge/proto/highway.h + action.h (HttpConn)
import type { ProtoSchema } from '../../protobuf/decode';
import {
IndexNodeSchema,
PictureInfoSchema,
HashSumSchema,
PicExtBizInfoSchema,
VideoExtBizInfoSchema,
PttExtBizInfoSchema,
} from '../proto/element';
// --- DataHighwayHead ---
export const DataHighwayHeadSchema = {
version: { field: 1, type: 'uint32' as const },
uin: { field: 2, type: 'string' as const },
command: { field: 3, type: 'string' as const },
seq: { field: 4, type: 'uint32' as const },
retryTimes:{ field: 5, type: 'uint32' as const },
appId: { field: 6, type: 'uint32' as const },
dataFlag: { field: 7, type: 'uint32' as const },
commandId: { field: 8, type: 'uint32' as const },
} satisfies ProtoSchema;
export const SegHeadSchema = {
serviceId: { field: 1, type: 'uint32' as const },
filesize: { field: 2, type: 'uint64' as const },
dataOffset: { field: 3, type: 'uint64' as const },
dataLength: { field: 4, type: 'uint32' as const },
retCode: { field: 5, type: 'uint32' as const },
serviceTicket: { field: 6, type: 'bytes' as const },
flag: { field: 7, type: 'uint32' as const },
md5: { field: 8, type: 'bytes' as const },
fileMd5: { field: 9, type: 'bytes' as const },
cacheAddr: { field: 10, type: 'uint32' as const },
cachePort: { field: 13, type: 'uint32' as const },
} satisfies ProtoSchema;
export const LoginSigHeadSchema = {
loginSigType: { field: 1, type: 'uint32' as const },
appId: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const ReqDataHighwayHeadSchema = {
msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema },
msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema },
bytesReqExtendInfo: { field: 3, type: 'bytes' as const },
timestamp: { field: 4, type: 'uint64' as const },
msgLoginSigHead: { field: 5, type: 'message' as const, schema: LoginSigHeadSchema },
} satisfies ProtoSchema;
export const RespDataHighwayHeadSchema = {
msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema },
msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema },
errorCode: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- Highway extend (NTV2RichMediaHighwayExt) ---
export const HighwayDomainSchema = {
isEnable: { field: 1, type: 'bool' as const },
ip: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const HighwayIPv4Schema = {
domain: { field: 1, type: 'message' as const, schema: HighwayDomainSchema },
port: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const HighwayNetworkSchema = {
ipv4s: { field: 1, type: 'repeated_message' as const, schema: HighwayIPv4Schema },
} satisfies ProtoSchema;
export const HighwayHashSchema = {
fileSha1: { field: 1, type: 'repeated_bytes' as const },
} satisfies ProtoSchema;
export const HighwayMsgInfoBodySchema = {
index: { field: 1, type: 'message' as const, schema: IndexNodeSchema },
picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema },
fileExist: { field: 5, type: 'bool' as const },
hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema },
} satisfies ProtoSchema;
export const NTV2RichMediaHighwayExtSchema = {
fileUuid: { field: 1, type: 'string' as const },
uKey: { field: 2, type: 'string' as const },
network: { field: 5, type: 'message' as const, schema: HighwayNetworkSchema },
msgInfoBody: { field: 6, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
blockSize: { field: 10, type: 'uint32' as const },
hash: { field: 11, type: 'message' as const, schema: HighwayHashSchema },
} satisfies ProtoSchema;
// --- File upload extend (group/private file highway) ---
export const FileUploadUrlSchema = {
unknown: { field: 1, type: 'int32' as const },
host: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const FileUploadHostSchema = {
url: { field: 1, type: 'message' as const, schema: FileUploadUrlSchema },
port: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const FileUploadHostConfigSchema = {
hosts: { field: 200, type: 'repeated_message' as const, schema: FileUploadHostSchema },
} satisfies ProtoSchema;
export const FileUploadNameInfoSchema = {
fileName: { field: 100, type: 'string' as const },
} satisfies ProtoSchema;
export const FileUploadClientInfoSchema = {
clientType: { field: 100, type: 'int32' as const },
appId: { field: 200, type: 'string' as const },
terminalType: { field: 300, type: 'int32' as const },
clientVer: { field: 400, type: 'string' as const },
unknown: { field: 600, type: 'int32' as const },
} satisfies ProtoSchema;
export const FileUploadFileEntrySchema = {
fileSize: { field: 100, type: 'uint64' as const },
md5: { field: 200, type: 'bytes' as const },
checkKey: { field: 300, type: 'bytes' as const },
md5S2: { field: 400, type: 'bytes' as const },
fileId: { field: 600, type: 'string' as const },
uploadKey: { field: 700, type: 'bytes' as const },
} satisfies ProtoSchema;
export const FileUploadBusiInfoSchema = {
busId: { field: 1, type: 'int32' as const },
senderUin: { field: 100, type: 'uint64' as const },
receiverUin: { field: 200, type: 'uint64' as const },
groupCode: { field: 400, type: 'uint64' as const },
} satisfies ProtoSchema;
export const FileUploadEntrySchema = {
busiBuff: { field: 100, type: 'message' as const, schema: FileUploadBusiInfoSchema },
fileEntry: { field: 200, type: 'message' as const, schema: FileUploadFileEntrySchema },
clientInfo: { field: 300, type: 'message' as const, schema: FileUploadClientInfoSchema },
fileNameInfo: { field: 400, type: 'message' as const, schema: FileUploadNameInfoSchema },
host: { field: 500, type: 'message' as const, schema: FileUploadHostConfigSchema },
} satisfies ProtoSchema;
export const FileUploadExtSchema = {
unknown1: { field: 1, type: 'int32' as const },
unknown2: { field: 2, type: 'int32' as const },
unknown3: { field: 3, type: 'int32' as const },
entry: { field: 100, type: 'message' as const, schema: FileUploadEntrySchema },
unknown200: { field: 200, type: 'int32' as const },
} satisfies ProtoSchema;
// --- Encodable MsgInfo (for embedding in message element) ---
export const EncodableMediaExtBizInfoSchema = {
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
busiType: { field: 10, type: 'uint32' as const },
} satisfies ProtoSchema;
export const EncodableMediaMsgInfoSchema = {
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
extBizInfo: { field: 2, type: 'message' as const, schema: EncodableMediaExtBizInfoSchema },
} satisfies ProtoSchema;
// --- HttpConn.0x6ff_501 (highway session) ---
export const HttpConnSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'int32' as const },
field3: { field: 3, type: 'int32' as const },
field4: { field: 4, type: 'int32' as const },
field6: { field: 6, type: 'int32' as const },
serviceTypes: { field: 7, type: 'repeated_uint32' as const },
field9: { field: 9, type: 'int32' as const },
field10: { field: 10, type: 'int32' as const },
field11: { field: 11, type: 'int32' as const },
ver: { field: 15, type: 'string' as const },
} satisfies ProtoSchema;
export const HttpConn0x6FF501RequestSchema = {
httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnSchema },
} satisfies ProtoSchema;
export const ServerAddrSchema = {
type: { field: 1, type: 'uint32' as const },
ip: { field: 2, type: 'uint32' as const }, // fixed32 as uint32
port: { field: 3, type: 'uint32' as const },
area: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const ServerInfoSchema = {
serviceType: { field: 1, type: 'uint32' as const },
serverAddrs: { field: 2, type: 'repeated_message' as const, schema: ServerAddrSchema },
} satisfies ProtoSchema;
export const HttpConnResponseSchema = {
sigSession: { field: 1, type: 'bytes' as const },
sessionKey: { field: 2, type: 'bytes' as const },
serverInfos: { field: 3, type: 'repeated_message' as const, schema: ServerInfoSchema },
} satisfies ProtoSchema;
export const HttpConn0x6FF501ResponseSchema = {
httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnResponseSchema },
} satisfies ProtoSchema;
// --- NTV2 Upload Request (for OIDB 0x11C4/0x11C5) ---
export const NTV2FileTypeSchema = {
type: { field: 1, type: 'uint32' as const },
picFormat: { field: 2, type: 'uint32' as const },
videoFormat: { field: 3, type: 'uint32' as const },
voiceFormat: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2FileInfoSchema = {
fileSize: { field: 1, type: 'uint32' as const },
fileHash: { field: 2, type: 'string' as const },
fileSha1: { field: 3, type: 'string' as const },
fileName: { field: 4, type: 'string' as const },
type: { field: 5, type: 'message' as const, schema: NTV2FileTypeSchema },
width: { field: 6, type: 'uint32' as const },
height: { field: 7, type: 'uint32' as const },
time: { field: 8, type: 'uint32' as const },
original: { field: 9, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadInfoSchema = {
fileInfo: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema },
subFileType: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
// The NTV2 upload request + response carry the same ExtBizInfo shape that
// element-side incoming-message decoding uses. Pulling those schemas in
// directly (instead of redefining stub copies) keeps the round-trip
// `server response → finalizeMediaMsgInfo → commonElem.pbElem` from
// silently dropping fields the QQ NT server later validates against —
// the video `fromScene`/`toScene` drop was already responsible for c2c
// `result=79` rejections on `send_private_msg [{type:'video'}]`.
export const NTV2ExtBizInfoSchema = {
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
busiType: { field: 10, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadReqSchema = {
uploadInfo: { field: 1, type: 'repeated_message' as const, schema: NTV2UploadInfoSchema },
tryFastUploadCompleted: { field: 2, type: 'bool' as const },
srvSendMsg: { field: 3, type: 'bool' as const },
clientRandomId: { field: 4, type: 'uint64' as const },
compatQmsgSceneType: { field: 5, type: 'uint32' as const },
extBizInfo: { field: 6, type: 'message' as const, schema: NTV2ExtBizInfoSchema },
clientSeq: { field: 7, type: 'uint32' as const },
noNeedCompatMsg: { field: 8, type: 'bool' as const },
} satisfies ProtoSchema;
export const NTV2C2CUserInfoSchema = {
accountType: { field: 1, type: 'uint32' as const },
targetUid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const NTV2GroupInfoSchema = {
groupUin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadSceneInfoSchema = {
requestType: { field: 101, type: 'uint32' as const },
businessType: { field: 102, type: 'uint32' as const },
sceneType: { field: 200, type: 'uint32' as const },
c2c: { field: 201, type: 'message' as const, schema: NTV2C2CUserInfoSchema },
group: { field: 202, type: 'message' as const, schema: NTV2GroupInfoSchema },
} satisfies ProtoSchema;
export const NTV2CommonHeadSchema = {
requestId: { field: 1, type: 'uint32' as const },
command: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2ClientMetaSchema = {
agentType: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadReqHeadSchema = {
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
scene: { field: 2, type: 'message' as const, schema: NTV2UploadSceneInfoSchema },
client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema },
} satisfies ProtoSchema;
export const NTV2UploadRichMediaReqSchema = {
reqHead: { field: 1, type: 'message' as const, schema: NTV2UploadReqHeadSchema },
upload: { field: 2, type: 'message' as const, schema: NTV2UploadReqSchema },
} satisfies ProtoSchema;
// --- NTV2 Upload Response ---
export const NTV2IPv4Schema = {
outIp: { field: 1, type: 'uint32' as const },
outPort: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2SubFileInfoRespSchema = {
subType: { field: 1, type: 'uint32' as const },
uKey: { field: 2, type: 'string' as const },
uKeyTtl: { field: 3, type: 'uint32' as const },
ipv4s: { field: 4, type: 'repeated_message' as const, schema: NTV2IPv4Schema },
} satisfies ProtoSchema;
export const NTV2UploadRespMsgInfoSchema = {
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
extBizInfo: { field: 2, type: 'message' as const, schema: NTV2ExtBizInfoSchema },
} satisfies ProtoSchema;
export const NTV2UploadRespBodySchema = {
uKey: { field: 1, type: 'string' as const },
uKeyTtl: { field: 2, type: 'uint32' as const },
ipv4s: { field: 3, type: 'repeated_message' as const, schema: NTV2IPv4Schema },
msgSeq: { field: 5, type: 'uint64' as const },
msgInfo: { field: 6, type: 'message' as const, schema: NTV2UploadRespMsgInfoSchema },
subFileInfos: { field: 10, type: 'repeated_message' as const, schema: NTV2SubFileInfoRespSchema },
} satisfies ProtoSchema;
export const NTV2UploadRespHeadSchema = {
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
retCode: { field: 2, type: 'uint32' as const },
message: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const NTV2UploadRichMediaRespSchema = {
respHead: { field: 1, type: 'message' as const, schema: NTV2UploadRespHeadSchema },
upload: { field: 2, type: 'message' as const, schema: NTV2UploadRespBodySchema },
} satisfies ProtoSchema;

View File

@@ -0,0 +1,68 @@
import type { ProtoSchema } from '../../protobuf/decode';
import { PushMsgBodySchema } from './message';
export const LongMsgUidSchema = {
uid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const LongMsgSettingsSchema = {
field1: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
field4: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const SendLongMsgInfoSchema = {
type: { field: 1, type: 'uint32' as const },
uid: { field: 2, type: 'message' as const, schema: LongMsgUidSchema },
groupUin: { field: 3, type: 'uint32' as const },
payload: { field: 4, type: 'bytes' as const },
} satisfies ProtoSchema;
export const SendLongMsgReqSchema = {
info: { field: 2, type: 'message' as const, schema: SendLongMsgInfoSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const SendLongMsgRespResultSchema = {
resId: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const SendLongMsgRespSchema = {
result: { field: 2, type: 'message' as const, schema: SendLongMsgRespResultSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const RecvLongMsgInfoSchema = {
uid: { field: 1, type: 'message' as const, schema: LongMsgUidSchema },
resId: { field: 2, type: 'string' as const },
acquire: { field: 3, type: 'bool' as const },
} satisfies ProtoSchema;
export const RecvLongMsgReqSchema = {
info: { field: 1, type: 'message' as const, schema: RecvLongMsgInfoSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const RecvLongMsgRespResultSchema = {
resId: { field: 3, type: 'string' as const },
payload: { field: 4, type: 'bytes' as const },
} satisfies ProtoSchema;
export const RecvLongMsgRespSchema = {
result: { field: 1, type: 'message' as const, schema: RecvLongMsgRespResultSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const LongMsgContentSchema = {
msgBody: { field: 1, type: 'repeated_message' as const, schema: PushMsgBodySchema },
} satisfies ProtoSchema;
export const LongMsgActionSchema = {
actionCommand: { field: 1, type: 'string' as const },
actionData: { field: 2, type: 'message' as const, schema: LongMsgContentSchema },
} satisfies ProtoSchema;
export const LongMsgResultSchema = {
action: { field: 2, type: 'repeated_message' as const, schema: LongMsgActionSchema },
} satisfies ProtoSchema;

View File

@@ -0,0 +1,113 @@
// Proto schemas for message envelopes (PushMsg).
// Port of src/bridge/include/bridge/proto/message.h
import type { ProtoSchema } from '../../protobuf/decode';
import { ElemSchema } from './element';
// --- ResponseHead.Grp ---
export const ResponseGrpSchema = {
groupUin: { field: 1, type: 'uint32' as const },
memberName: { field: 2, type: 'string' as const },
groupName: { field: 4, type: 'string' as const },
} satisfies ProtoSchema;
export const ResponseForwardSchema = {
friendName: { field: 6, type: 'string' as const },
} satisfies ProtoSchema;
// --- ResponseHead ---
export const ResponseHeadSchema = {
fromUin: { field: 1, type: 'uint32' as const },
fromUid: { field: 2, type: 'string' as const },
type: { field: 3, type: 'uint32' as const },
sigMap: { field: 4, type: 'uint32' as const },
toUin: { field: 5, type: 'uint32' as const },
toUid: { field: 6, type: 'string' as const },
forward: { field: 7, type: 'message' as const, schema: ResponseForwardSchema },
grp: { field: 8, type: 'message' as const, schema: ResponseGrpSchema },
} satisfies ProtoSchema;
// --- ContentHead ---
export const ContentHeadSchema = {
msgType: { field: 1, type: 'uint32' as const },
subType: { field: 2, type: 'uint32' as const },
divSeq: { field: 3, type: 'uint32' as const },
msgId: { field: 4, type: 'uint32' as const },
sequence: { field: 5, type: 'uint32' as const },
timestamp: { field: 6, type: 'uint32' as const },
field7: { field: 7, type: 'uint64' as const },
newId: { field: 12, type: 'uint64' as const },
} satisfies ProtoSchema;
// --- Ptt (voice) ---
export const PttSchema = {
fileType: { field: 1, type: 'uint32' as const },
fileId: { field: 2, type: 'uint64' as const },
fileUuid: { field: 3, type: 'bytes' as const },
fileMd5: { field: 4, type: 'bytes' as const },
fileName: { field: 5, type: 'string' as const },
fileSize: { field: 6, type: 'uint32' as const },
groupFileKey: { field: 10, type: 'string' as const },
fileKey: { field: 14, type: 'bytes' as const },
time: { field: 19, type: 'uint32' as const },
format: { field: 29, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- NotOnlineFile (C2C file) ---
export const NotOnlineFileSchema = {
fileType: { field: 1, type: 'uint32' as const },
fileUuid: { field: 3, type: 'string' as const },
fileMd5: { field: 4, type: 'bytes' as const },
fileName: { field: 5, type: 'string' as const },
fileSize: { field: 6, type: 'uint64' as const },
fileHash: { field: 57, type: 'string' as const },
} satisfies ProtoSchema;
// --- RichText ---
export const RichTextSchema = {
elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
notOnlineFile: { field: 3, type: 'message' as const, schema: NotOnlineFileSchema },
ptt: { field: 4, type: 'message' as const, schema: PttSchema },
} satisfies ProtoSchema;
// --- MessageBody ---
export const MessageBodySchema = {
richText: { field: 1, type: 'message' as const, schema: RichTextSchema },
msgContent: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
// --- FileExtra (for C2C file in msg_content) ---
export const FileExtraInfoSchema = {
fileSize: { field: 1, type: 'uint64' as const },
fileName: { field: 2, type: 'string' as const },
fileMd5: { field: 3, type: 'bytes' as const },
fileUuid: { field: 4, type: 'string' as const },
fileHash: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
export const FileExtraSchema = {
file: { field: 1, type: 'message' as const, schema: FileExtraInfoSchema },
} satisfies ProtoSchema;
// --- PushMsgBody ---
export const PushMsgBodySchema = {
responseHead: { field: 1, type: 'message' as const, schema: ResponseHeadSchema },
contentHead: { field: 2, type: 'message' as const, schema: ContentHeadSchema },
body: { field: 3, type: 'message' as const, schema: MessageBodySchema },
} satisfies ProtoSchema;
// --- PushMsg (top-level) ---
export const PushMsgSchema = {
message: { field: 1, type: 'message' as const, schema: PushMsgBodySchema },
status: { field: 3, type: 'int32' as const },
} satisfies ProtoSchema;

View File

@@ -0,0 +1,207 @@
// Proto schemas for notification types.
// Port of src/bridge/include/bridge/proto/notify.h
import type { ProtoSchema } from '../../protobuf/decode';
export const OperatorField1Schema = {
uid: { field: 1, type: 'string' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'bytes' as const },
field4: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'bytes' as const },
} satisfies ProtoSchema;
export const OperatorInfoSchema = {
operatorField: { field: 1, type: 'message' as const, schema: OperatorField1Schema },
} satisfies ProtoSchema;
export const GroupChangeSchema = {
groupUin: { field: 1, type: 'uint32' as const },
flag: { field: 2, type: 'uint32' as const },
memberUid: { field: 3, type: 'string' as const },
decreaseType: { field: 4, type: 'uint32' as const },
operatorBytes: { field: 5, type: 'bytes' as const },
increaseType: { field: 6, type: 'uint32' as const },
field7: { field: 7, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupAdminExtraSchema = {
adminUid: { field: 1, type: 'string' as const },
isPromote: { field: 2, type: 'bool' as const },
} satisfies ProtoSchema;
export const GroupAdminBodySchema = {
extraDisable: { field: 1, type: 'message' as const, schema: GroupAdminExtraSchema },
extraEnable: { field: 2, type: 'message' as const, schema: GroupAdminExtraSchema },
} satisfies ProtoSchema;
export const GroupAdminSchema = {
groupUin: { field: 1, type: 'uint32' as const },
flag: { field: 2, type: 'uint32' as const },
isPromote: { field: 3, type: 'bool' as const },
body: { field: 4, type: 'message' as const, schema: GroupAdminBodySchema },
} satisfies ProtoSchema;
export const InvitationInnerSchema = {
groupUin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
field4: { field: 4, type: 'uint32' as const },
targetUid: { field: 5, type: 'string' as const },
invitorUid: { field: 6, type: 'string' as const },
field7: { field: 7, type: 'uint32' as const },
field9: { field: 9, type: 'uint32' as const },
field10: { field: 10, type: 'bytes' as const },
field11: { field: 11, type: 'uint32' as const },
field12: { field: 12, type: 'string' as const },
} satisfies ProtoSchema;
export const InvitationInfoSchema = {
inner: { field: 1, type: 'message' as const, schema: InvitationInnerSchema },
} satisfies ProtoSchema;
export const GroupInvitationSchema = {
cmd: { field: 1, type: 'int32' as const },
info: { field: 2, type: 'message' as const, schema: InvitationInfoSchema },
} satisfies ProtoSchema;
export const GroupInviteSchema = {
groupUin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
field4: { field: 4, type: 'uint32' as const },
invitorUid: { field: 5, type: 'string' as const },
hashes: { field: 6, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupJoinSchema = {
groupUin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
targetUid: { field: 3, type: 'string' as const },
field4: { field: 4, type: 'uint32' as const },
field6: { field: 6, type: 'uint32' as const },
field7: { field: 7, type: 'string' as const },
field8: { field: 8, type: 'uint32' as const },
field9: { field: 9, type: 'bytes' as const },
} satisfies ProtoSchema;
export const FriendRequestInfoSchema = {
targetUid: { field: 1, type: 'string' as const },
sourceUid: { field: 2, type: 'string' as const },
newSource: { field: 5, type: 'string' as const },
message: { field: 10, type: 'string' as const },
source: { field: 11, type: 'string' as const },
} satisfies ProtoSchema;
export const FriendRequestSchema = {
info: { field: 1, type: 'message' as const, schema: FriendRequestInfoSchema },
} satisfies ProtoSchema;
export const FriendRecallTipInfoSchema = {
tip: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const FriendRecallInfoSchema = {
fromUid: { field: 1, type: 'string' as const },
toUid: { field: 2, type: 'string' as const },
clientSequence: { field: 3, type: 'uint32' as const },
newId: { field: 4, type: 'uint64' as const },
time: { field: 5, type: 'uint32' as const },
random: { field: 6, type: 'uint32' as const },
pkgNum: { field: 7, type: 'uint32' as const },
pkgIndex: { field: 8, type: 'uint32' as const },
divSeq: { field: 9, type: 'uint32' as const },
tipInfo: { field: 13, type: 'message' as const, schema: FriendRecallTipInfoSchema },
} satisfies ProtoSchema;
export const FriendRecallSchema = {
info: { field: 1, type: 'message' as const, schema: FriendRecallInfoSchema },
instId: { field: 2, type: 'uint32' as const },
appId: { field: 3, type: 'uint32' as const },
longMessageFlag: { field: 4, type: 'uint32' as const },
reserved: { field: 5, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupMuteStateSchema = {
targetUid: { field: 1, type: 'string' as const },
duration: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GroupMuteDataSchema = {
timestamp: { field: 1, type: 'uint32' as const },
type: { field: 2, type: 'uint32' as const },
state: { field: 3, type: 'message' as const, schema: GroupMuteStateSchema },
} satisfies ProtoSchema;
export const GroupMuteSchema = {
groupUin: { field: 1, type: 'uint32' as const },
subType: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
operatorUid: { field: 4, type: 'string' as const },
data: { field: 5, type: 'message' as const, schema: GroupMuteDataSchema },
} satisfies ProtoSchema;
export const RecallMessageSchema = {
sequence: { field: 1, type: 'uint32' as const },
time: { field: 2, type: 'uint32' as const },
random: { field: 3, type: 'uint32' as const },
type: { field: 4, type: 'uint32' as const },
flag: { field: 5, type: 'uint32' as const },
authorUid: { field: 6, type: 'string' as const },
} satisfies ProtoSchema;
export const GroupRecallTipInfoSchema = {
tip: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const GroupRecallSchema = {
operatorUid: { field: 1, type: 'string' as const },
recallMessages: { field: 3, type: 'repeated_message' as const, schema: RecallMessageSchema },
userDef: { field: 5, type: 'bytes' as const },
groupType: { field: 6, type: 'int32' as const },
opType: { field: 7, type: 'int32' as const },
tipInfo: { field: 9, type: 'message' as const, schema: GroupRecallTipInfoSchema },
} satisfies ProtoSchema;
export const TemplParamSchema = {
name: { field: 1, type: 'string' as const },
value: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const GeneralGrayTipInfoSchema = {
busiType: { field: 1, type: 'uint64' as const },
busiId: { field: 2, type: 'uint64' as const },
ctrlFlag: { field: 3, type: 'uint32' as const },
c2cType: { field: 4, type: 'uint32' as const },
serviceType: { field: 5, type: 'uint32' as const },
templId: { field: 6, type: 'uint64' as const },
msgTemplParam: { field: 7, type: 'repeated_message' as const, schema: TemplParamSchema },
content: { field: 8, type: 'string' as const },
} satisfies ProtoSchema;
export const EssenceMessageSchema = {
groupUin: { field: 1, type: 'uint32' as const },
msgSequence: { field: 2, type: 'uint32' as const },
random: { field: 3, type: 'uint32' as const },
setFlag: { field: 4, type: 'uint32' as const },
memberUin: { field: 5, type: 'uint32' as const },
operatorUin: { field: 6, type: 'uint32' as const },
timestamp: { field: 7, type: 'uint32' as const },
msgSequence2: { field: 8, type: 'uint32' as const },
operatorNickname: { field: 9, type: 'string' as const },
memberNickname: { field: 10, type: 'string' as const },
setFlag2: { field: 11, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NotifyMessageBodySchema = {
type: { field: 1, type: 'uint32' as const },
groupUin: { field: 4, type: 'uint32' as const },
eventParam: { field: 5, type: 'bytes' as const },
recall: { field: 11, type: 'message' as const, schema: GroupRecallSchema },
field13: { field: 13, type: 'uint32' as const },
operatorUid: { field: 21, type: 'string' as const },
generalGrayTip: { field: 26, type: 'message' as const, schema: GeneralGrayTipInfoSchema },
essenceMessage: { field: 33, type: 'message' as const, schema: EssenceMessageSchema },
msgSequence: { field: 37, type: 'uint32' as const },
field39: { field: 39, type: 'uint32' as const },
} satisfies ProtoSchema;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,161 @@
// Proto schemas for OidbSvc service types.
// Port of src/bridge/include/bridge/proto/oidb.h
import type { ProtoSchema } from '../../protobuf/decode';
// --- OidbSvcTrpcTcpBase wrapper ---
export const OidbPropertySchema = {
key: { field: 1, type: 'string' as const },
value: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
// Factory for OidbSvcTrpcTcpBase<T>
export function makeOidbBaseSchema(bodySchema: ProtoSchema): ProtoSchema {
return {
command: { field: 1, type: 'uint32' as const },
subCommand: { field: 2, type: 'uint32' as const },
errorCode: { field: 3, type: 'uint32' as const },
body: { field: 4, type: 'message' as const, schema: bodySchema },
errorMsg: { field: 5, type: 'string' as const },
properties: { field: 11, type: 'repeated_message' as const, schema: OidbPropertySchema },
reserved: { field: 12, type: 'int32' as const },
};
}
// --- Friend list (0xFD4_1) ---
export const OidbFriendPropertySchema = {
code: { field: 1, type: 'uint32' as const },
value: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbFriendLayer1Schema = {
properties: { field: 2, type: 'repeated_message' as const, schema: OidbFriendPropertySchema },
} satisfies ProtoSchema;
export const OidbFriendAdditionalSchema = {
type: { field: 1, type: 'uint32' as const },
layer1: { field: 2, type: 'message' as const, schema: OidbFriendLayer1Schema },
} satisfies ProtoSchema;
export const OidbFriendSchema = {
uid: { field: 1, type: 'string' as const },
customGroup:{ field: 2, type: 'uint32' as const },
uin: { field: 3, type: 'uint32' as const },
additional: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendAdditionalSchema },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFD4_1ResponseUinSchema = {
uin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFD4_1ResponseSchema = {
next: { field: 2, type: 'message' as const, schema: OidbSvcTrpcTcp0xFD4_1ResponseUinSchema },
displayFriendCount: { field: 3, type: 'uint32' as const },
timestamp: { field: 6, type: 'uint32' as const },
selfUin: { field: 7, type: 'uint32' as const },
friends: { field: 101, type: 'repeated_message' as const, schema: OidbFriendSchema },
groups: { field: 102, type: 'repeated_message' as const, schema: OidbFriendPropertySchema },
} satisfies ProtoSchema;
// --- Group list (0xFE5_2) ---
export const OidbSvcTrpcTcp0xFE5_2MemberSchema = {
uid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2GroupInfoSchema = {
groupOwner: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2MemberSchema },
createdTime: { field: 2, type: 'uint32' as const },
memberMax: { field: 3, type: 'uint32' as const },
memberCount: { field: 4, type: 'uint32' as const },
groupName: { field: 5, type: 'string' as const },
description: { field: 18, type: 'string' as const },
question: { field: 19, type: 'string' as const },
announcement: { field: 30, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2CustomInfoSchema = {
remark: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2GroupSchema = {
groupUin: { field: 3, type: 'uint32' as const },
info: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupInfoSchema },
customInfo: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2CustomInfoSchema },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2ResponseSchema = {
groups: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupSchema },
} satisfies ProtoSchema;
// --- Group member list (0xFE7_3) ---
export const OidbSvcTrpcTcp0xFE7_3UinSchema = {
uid: { field: 2, type: 'string' as const },
uin: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3CardSchema = {
memberCard: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3LevelSchema = {
infos: { field: 1, type: 'repeated_uint32' as const },
level: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3MemberSchema = {
uin: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3UinSchema },
memberName: { field: 10, type: 'string' as const },
specialTitle: { field: 17, type: 'string' as const },
memberCard: { field: 11, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3CardSchema },
level: { field: 12, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3LevelSchema },
joinTimestamp: { field: 100, type: 'uint32' as const },
lastMsgTimestamp: { field: 101, type: 'uint32' as const },
shutUpTimestamp: { field: 102, type: 'uint32' as const },
permission: { field: 107, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3ResponseSchema = {
groupUin: { field: 1, type: 'uint32' as const },
members: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE7_3MemberSchema },
field3: { field: 3, type: 'uint32' as const },
memberChangeSeq: { field: 5, type: 'uint32' as const },
memberCardChangeSeq:{ field: 6, type: 'uint32' as const },
token: { field: 15, type: 'string' as const },
} satisfies ProtoSchema;
// --- Group request (0x10C0) ---
export const OidbSvcTrpcTcp0x10C0ResponseUserSchema = {
uid: { field: 1, type: 'string' as const },
name: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0x10C0ResponseGroupSchema = {
groupUin: { field: 1, type: 'uint32' as const },
groupName: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0x10C0ResponseRequestSchema = {
sequence: { field: 1, type: 'uint64' as const },
eventType: { field: 2, type: 'uint32' as const },
state: { field: 3, type: 'uint32' as const },
group: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseGroupSchema },
target: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
invitor: { field: 6, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
operatorUser: { field: 7, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
field9: { field: 9, type: 'string' as const },
comment: { field: 10, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0x10C0ResponseSchema = {
requests: { field: 1, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseRequestSchema },
field2: { field: 2, type: 'uint64' as const },
newLatestSeq: { field: 3, type: 'uint64' as const },
field4: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'uint64' as const },
field6: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;

Some files were not shown because too many files have changed in this diff Show More